117 Commits
Author SHA1 Message Date
yuanyuanxiang e99092ca70 Release v1.4.2 2026-10-31 18:24:54 +01:00
yuanyuanxianganddeepseek-flash ebc2d03290 fix(web): keep the IME bar still and the pointer honest in portrait
Two separate faults showed up once the "I" shortcut was in use in portrait: the
phone input bar would not stay put, and the pointer stopped being where it
claimed to be.

#ime-bar was the last flex child of #screen-page, so it sat at the bottom of the
page, and the only thing keeping it above the keyboard was adjustImeBar()
writing padding-bottom on #screen-page -- the bar chased the keyboard height
frame by frame through visualViewport. The keyboard animation is asynchronous
and the events lag behind it, so while it rose the bar was still low with the
keyboard already covering everything from y=544. A later attempt clamped it
against keyboardTopY() and reserved the last measured keyboard height before the
keyboard arrived. That kept it visible, but the bar still moved whenever the
keyboard changed height -- switching input method, the QuickType row, the
AutoFill Contact chip appearing or going away -- and that is what "the input box
keeps getting pushed up" actually was.

The bar is now a fixed overlay at the bottom edge of the picture, placed by the
same formula the shortcut row already used: picture bottom + 4px. In portrait
adjustImeBar() has nothing left to chase -- it only clears the padding that
landscape may have left behind, and recomputes when the keyboard top changes.
That recompute is idempotent and the style is only written when the value
differs, so in the normal case it produces no movement at all. lastKbHeight,
KB_HEIGHT_GUESS, noteKeyboardHeight() and the old keyboard-top tracking are gone
with it.

One clamp survives, as a safety net: if the picture bottom is itself inside the
keyboard block -- a remote machine that is portrait, where the picture is taller
than the space above the keyboard -- the bar falls back to the keyboard top,
because there is nowhere else to put it. That case also has to follow the
keyboard, which is why the recompute above still exists. For a landscape/16:9
remote the clamp never fires and the position is a constant.

Getting that constant right needed a coordinate fix. #ime-bar hangs off
#screen-page while #input-shortcuts lives inside .canvas-container, so the two
have different containing blocks. Reusing the shortcut formula
(canvas.offsetTop + ...) put the bar a whole toolbar height too high -- 279
against a picture that ends at 319 -- which is why it always looked like it was
floating above the shortcut row. The bar's position now comes from the canvas
rect minus the #screen-page rect, so the containing block is whatever the bar
actually resolves against; that subtraction also cancels the translateY
compensation, since both rects are inside the translated element. It lands at
323..382, 4px under the picture.

Landscape keeps the flex behaviour via (orientation: landscape). That is not
just tidiness: an absolutely positioned child does not take padding into
account, because bottom: 0 resolves against the padding box, which includes the
padding. Left as an overlay, the bar would have stayed at the very bottom of the
screen and been covered by the keyboard instead of being pushed up by
padding-bottom.

Opening the keyboard must not move the picture either, and two things were
moving it:

- #screen-page had no overflow guard. #term-page already carries one for exactly
  this reason ("stop iOS from quietly adding a scroll to body and lifting the
  whole page"). Without it iOS hands the page a scroll and then scrolls it once
  the keyboard comes up.
- Even with the page locked, iOS moves the *visual* viewport up when the keyboard
  appears (visualViewport.offsetTop > 0). #screen-page is position: fixed and is
  therefore pinned to the layout viewport, so the entire page -- picture
  included -- was pushed off the top of the screen.

So #screen-page gets overflow: hidden + overscroll-behavior: contain, and
syncVisualOffset() translates it by exactly visualViewport.offsetTop to cancel
the shift. It is driven by the IME rAF loop and the viewport scroll event, and
clears the transform once the offset returns to 0. Nothing downstream has to
compensate for it: the picture, the pointer overlay and the bar are all
descendants of #screen-page, so they move with it.

The pointer overlay was the one thing that did not accept that. .cursor-overlay
was position: fixed, placed by taking the canvas's getBoundingClientRect() and
then subtracting whatever translateY the page currently carried -- two
independent sources of truth that have to agree exactly, the browser's idea of
where the canvas is and our own idea of how far we moved it. They do agree in
desktop Chrome, which is why the harness never saw the fault, but on the phone
they did not: once the IME was open the overlay was drawn off by the
compensation amount while taps still landed correctly, and closing the input box
-- offsetTop back to 0, transform gone -- put it back. The overlay is now
position: absolute inside .canvas-container, the same containing block the canvas
resolves against, and style.left/top hold canvas-local CSS pixels (bx/kx, by/ky).
No viewport rect, no compensation term: whatever an ancestor does to the picture,
it does to the pointer. pageShiftY() is gone with it.

The overlay also has to follow a re-fit, not just a move. resizeScreenCanvas()
keeps the last remote coordinate the overlay was placed at and replays it once
the bitmap has been resized, so the keyboard shrinking the layout viewport, a
rotation or a fullscreen toggle no longer leaves the pointer where the previous
geometry put it.

The touch mapping and the drawing path have to stay exact inverses --
positionCursorOverlay() turns remote coordinates into a position on the canvas,
screenToCanvas() turns a finger position back into remote coordinates -- otherwise
the cursor is drawn where nobody tapped. It was only after the keyboard had been
up for a while that this broke: switching the input method changes the keyboard
height, iOS pans the visual viewport to keep the focused textarea visible, and
from then on offsetTop is non-zero.

iOS also stacks a row of its own directly above the keyboard: the QuickType
predictions and, when Safari decides the field looks like it can take contact
info, an "AutoFill Contact" chip. The textarea gets the full set of suppression
attributes (autocomplete, autocorrect and autocapitalize off, spellcheck off,
inputmode text). That lowers the odds of the chip showing up at all, but iOS
does not promise to honour it -- the only guaranteed off switch is Settings >
Safari > Autofill > Use Contact Info, which is a per-device setting.

With the bar no longer able to hide under the keyboard, the shortcut row below
the picture is only in the way: that row exists to be tapped *before* the IME
opens, and while the IME is open the bar takes its place. Opening the IME now
hides it, so the bar sits 4px under the picture instead of queuing up below the
row. The class lives on #screen-page rather than being stripped off .visible,
because updateUIForOrientation() recomputes .visible from keyboardOpen and would
put the row straight back. Closing the IME -- the bar's own collapse button does
that -- or disconnecting restores it. The key buttons it holds stay reachable by
reopening the mobile keyboard, which is what showed the row in the first place.

The bar also has to exist only while the keyboard does. Tapping it is what wakes
the keyboard in the first place, and iOS then scrolls the page to keep the
focused field visible -- which is the "tap the input box and it shoves itself up"
report. updateImePresence() runs in the IME rAF loop and puts .ime-waiting on the
bar the moment the keyboard is not up -- opacity 0, so it is not there to touch
-- and closeIme() 450ms later once the keyboard has really gone. Two deliberate
choices in that CSS: it is opacity, not display or visibility, because the
textarea has to stay in the document and focusable or the keyboard never comes
up at all; and there is no pointer-events: none, because that would let touches
on that strip fall through to the canvas and become stray clicks on the remote
machine. The wait for the keyboard to appear is capped at 3000ms, after which the
IME is abandoned rather than left invisible forever. It is generous on purpose:
iOS sometimes does not update visualViewport until something scrolls, and a short
timeout would close a perfectly good IME on a slow device.

The RDP reset button redraws the whole frame, but it left the IME open. The bar
stayed on screen, so touching its textarea brought the keyboard back up -- and the
page got shoved again, with the pointer going with it. Reset now closes the IME
first. Since "close the IME" was being spelled out in three places (the I button,
the keyboard toggle, disconnect) and each copy had drifted a little, it is now one
closeIme() that toggleIme(), toggleKeyboard(), sendRdpReset() and disconnect()
all call. The cleanup half runs unconditionally -- imeMode and the DOM can fall out
of sync and a half-closed state is exactly what leaves a bar that pops the
keyboard -- while updateKeyboardButtons(false) is guarded by whether the IME was
actually open, so resetting with only the mobile keyboard up does not close it.
disconnect() additionally keeps its own updateKeyboardButtons(false), because
there the keyboard should close regardless, and it no longer needs to reset
imeMode by hand -- which also stops imeWatcher's rAF loop from spinning on after
a disconnect.

Deselecting the mouse (the control toggle) now drops the keyboard and the IME as
well, for the same reason: leaving the bar on screen means the next touch on its
textarea brings the keyboard back up and shoves the page. Closing only the IME
would not be enough here -- the mobile keyboard is a separate focus -- so
closeKeyboardAndIme() blurs both and is what the control toggle and disconnect()
now share.

Verified with visualViewport.height mocked so the keyboard arrives after the bar
has been placed, on 390x844 and 375x667, with a 16:9 and a portrait remote, at
keyboard heights 0/216/260/300/304/344. For the 16:9 remote the bar is 323..382
at every single step -- zero jump across the whole sweep, where the portrait
remote used to jump 300px. For a portrait remote it tracks the keyboard top
(485..544 at 300px), the only position available to it. No case leaves the bar
under the keyboard, and every measured position equals min(picture bottom + 4,
keyboard top - bar height) to 0.0px.

The bar is present exactly when the keyboard is, checked at every step: on tap
(before the keyboard rises) opacity 0; keyboard up, opacity 1; keyboard down 60ms,
opacity 0 again; 580ms, imeMode false and display none. Reopening with the keyboard
never arriving keeps it at opacity 0 and gives up after 3s. No page errors.
Picture placement across all five layouts is byte-identical to before the change.
Cursor accuracy is dx=dy=0 over portrait/landscape x scale 1/2/3 x offsetTop
0/150/200/300, and the round-trip test -- positionCursorOverlay() asked where to
draw, that screen position fed back through screenToCanvas() -- returns the
original remote point for all nine cases; before the inverse fix six of them were
off, by exactly offsetTop scaled into remote pixels (739 at offsetTop 150 for the
(1800,1000) point).

Tapping RDP reset with the IME open (keyboard mocked at 544, visualViewport
offsetTop at 200) leaves imeMode false, the bar display:none, the transform
cleared, visualOffsetY 0 and the watcher stopped, with the picture still at
y=100..319.4 instead of being shoved up; disconnect() from the same state clears
it identically. Deselecting the mouse from that same state (control on, mobile
keyboard focused, IME open, keyboard mocked at 544 and offsetTop at 180) leaves
controlEnabled false, imeMode false, neither element focused, the bar
display:none, the transform cleared and the watcher stopped, with the picture
still at y=100..319.4. Opening the IME moves the bar from the shortcut row's slot
to 323..382 and closing it puts the row back at 321..369, through both toggleIme()
and a direct class toggle. In landscape the flex path still works: with a 200px
padding the bar goes from 331..390 to 131..190, i.e. just above the keyboard.

The pointer was a second, unrelated bug, and a worse one. screenToCanvas() added
visualViewport.offsetTop on top of a clientX/clientY that is
already expressed in the same coordinate space as getBoundingClientRect(), i.e.
after the translateY compensation. Both quantities include the pan, so subtracting
them already cancels it; adding offsetTop counted it twice. That pushed every
computed remote y down by offsetTop scaled into remote pixels -- 492 remote pixels
at offsetTop 100 on a 16:9 remote -- so everything below the middle of the picture
overshot streamH and was clamped to streamH-1. The symptom is exactly what it
looks like: the pointer can only be moved in the upper part of the picture, a
fixed horizontal band cannot be crossed downwards, and clicking inside that band
lands on the remote taskbar. At offsetTop 300 the whole picture mapped past the
bottom, so every touch landed on the taskbar. The pinch origin had the same
mistake, and so did the cursor recomputation at the end of a pinch, which fed the
overlay's style.top -- a pre-compensation coordinate -- back into screenToCanvas.

Neither direction may add the compensation, and neither does: clientX/clientY and
getBoundingClientRect() are already in the same space, and the overlay no longer
works in screen coordinates at all. The round-trip test had been written against
the wrong premise -- it fed style.top straight into screenToCanvas() -- so it
kept passing while the absolute mapping was wrong. It now converts the overlay's
style values back through the canvas rect on the way in.

Verified against the picture's own rect rather than against the other function:
for points at 10/30/50/70/90/99% of the picture height, screenToCanvas() must
return the remote pixel that sits under that point. At offsetTop 0/100/300 all
eighteen cases are exact (error 0,0); before the fix, offsetTop 100 was off by
+492 on every point and the lower half clamped to 1079, and offsetTop 300 clamped
the entire picture to 1079. The overlay still renders where it should -- for a
pointer driven to the remote bottom it lands 4px above the picture's bottom edge,
the constant hotspot offset, at offsetTop 0 and 300 alike -- and the round-trip
test still returns the original remote point for all nine cases once the
transform is accounted for. With the overlay anchored to the canvas it holds that
alignment through the whole IME lifecycle: dx=dy=0 at offsetTop 0, 200 and 300, on
both a 16:9 remote in portrait and after rotating to landscape and back, and the
pointer lands back on the picture after the IME closes. The rotation case also
covers the re-fit path: the container changes size, the canvas is resized, and
the overlay is replayed at the new geometry instead of staying where the old one
put it.

Co-Authored-By: deepseek-flash
2026-10-31 13:37:27 +01:00
yuanyuanxianganddeepseek-flash 0a6cbbbf06 fix(web): draw the remote screen inside a fixed canvas to kill the iOS ghost lines
On an iPhone in landscape, panning the picture to the left with two fingers left
a stack of 1px vertical lines along the right edge. It only showed up after
zooming in, and every pan added more lines.

The cause is the old render model, not the panning code. #screen-canvas was
sized to the remote resolution and then moved/scaled with a CSS transform
(`canvas.style.transform = scale(s) translate(tx, ty)`). iOS Safari caches the
raster of a transformed canvas layer and does not repaint the strip the layer
uncovers when it moves, so whatever sat at the old right edge -- one column of
the picture -- got stretched across the newly exposed band. Pan again and the
next column repeats it: the lines accumulate.

An earlier attempt clamped the pan range so the uncovered band could not appear.
That was wrong twice over: it did not remove the ghosting (the clamp still moved
the layer, so the edge was still repainted from a stale raster), and it put hard
limits on dragging, which is not how the page is used.

So the canvas element now never moves. It is pinned to the container
(bitmap = viewport x devicePixelRatio, driven by a ResizeObserver), and every
frame is drawn into it with ctx.setTransform. There is no CSS transform, no CSS
scaling, and no layer movement left to cache, so there is nothing to leave a
stale edge behind.

- renderFrame(): paints black, then draws the latest frame with the fit-to-view
  and pinch-zoom/pan transform applied via setTransform.
- initDecoder(): keeps the remote-resolution frame in an offscreen frameCanvas.
  The isTopDown flip is applied to that canvas only, so the visible canvas is
  always upright and no longer needs a flipped transform.
- positionCursorOverlay() / screenToCanvas(): rewritten as exact inverses of the
  new transform chain, so the cursor overlay and touch coordinates still land on
  the right remote pixel.
- applyZoomTransform(): drops the CSS transform and every pan clamp. Dragging
  past the picture just shows the canvas' own black background, with no boundary
  at all -- the free panning feel is unchanged.
- Touch/mouse deltas are converted with remotePerScreenPx() instead of assuming
  the old element size.

The picture also has to land exactly where it used to. In the old model the
canvas element *was* the picture, so the flex container positioned it: portrait
CSS sets `.canvas-container { align-items: flex-start; padding-top: 56px }` to
pin it to the top and keep the on-screen keyboard off it, landscape leaves it
centred. Now that the picture is drawn inside a full-bleed canvas, flex no
longer positions it, and hard-coding "centre" dropped it 262px in portrait --
straight into the keyboard's path. So renderFrame takes its vertical placement
from the container's computed align-items and padding-top, and the canvas covers
the padding box so a zoomed picture panned upwards still reaches the top of the
container the way it used to.

The zoom anchor had the same problem: originX/originY were read as percentages
of the canvas, while the old transform-origin sat on the canvas element, i.e. on
the picture. They are percentages of the picture now, so pinch-zoom keeps the
point under the fingers fixed instead of drifting towards the canvas centre.

Two smaller details have to be right for the mapping to stay exact, and both are
fixed here rather than left for later:

- resizeScreenCanvas() takes its scale factor from the bitmap it just allocated
  divided by the measured CSS width, not from devicePixelRatio. The bitmap is
  rounded, so with a fractional CSS width or a non-integer ratio the two drift
  apart -- 843.5px at dpr 2.625 lands 2.2e-3 apart -- and translateX, which
  reaches a few hundred px, turns that into a ~1px mismatch between the picture
  and the cursor overlay. getViewMetrics().d is now identically equal to the
  kx reported by canvasPixelRatio().
- updateInputShortcutsPosition() divides the picture height out of streamH, which
  is 0 before the first frame; it now bails out instead of placing the shortcuts
  bar in the middle of the canvas box.

Nothing else reads the canvas dimensions, so the semantic change from "remote
resolution" to "viewport x dpr" does not reach any other feature: there is no
toDataURL/getImageData anywhere, the wall tiles own their own canvases and go
through wallHandleFrame, the cursor overlay is a fixed 24x24 element that never
scaled with the old CSS transform either, and the wheel/dblclick handlers only
forward coordinates. The overlays that sit on top of the canvas (quick controls
100, shortcuts 101, android navbar 102, cursor 1002) all carry a z-index, so
making the canvas positioned does not push it over them.

Verified in a browser harness built from the same functions the page uses:
drawing position vs cursor position over 90 fully-visible cases is off by at
most 0.42px, the screen->remote->screen round trip over 1500 points is exact to
0.000px, a real two-finger gesture chain (scale 1 -> 2.5, translateX -145) moves
the picture correctly with no page errors, and across dpr 1.5/2/2.625/2.75/3 the
bitmap ratio matches the CSS ratio exactly (round-trip error 7e-4px, float
noise). Picture placement was diffed against the previous build in five layouts
(portrait, portrait fullscreen, Android immersive, landscape, landscape
fullscreen) and matches to 0.0px in every one; a portrait zoom of 2x panned up
by 150px shows the same visible band (y 44..128) as before; with the viewport
shortened to simulate the keyboard the picture stays at y 100..319 and is not
covered; pinch anchors at 25%/50%/80% of the picture stay put to 0px across
scale 1.5/2/3. The user confirmed on the device that the lines are gone.

Co-Authored-By: deepseek-flash
2026-10-31 10:28:10 +01:00
yuanyuanxianganddeepseek-flash 36ae4b3057 fix(client): stop the reconnect loops from spinning when the master restarts
On a master restart the client receives SERVER_EXIT and KernelManager sets
g_bExit = S_SERVER_EXIT. IsClientAppRunning() compares against S_CLIENT_NORMAL,
so it flips to false immediately and the worker starts tearing down -- but
g_bThreadExit is only cleared at the very end of StartClient. Throughout that
window TestRun() still sees IsThreadRun() == TRUE and takes its early-return
path.

The loader's reconnect loop deliberately does not wait in the S_SERVER_EXIT case
("reconnect immediately, do not wait for share instances"), and its else branch
was empty, so it re-entered TestRun() with no delay whatsoever. Measured on a
live host: 919 identical "TestRun SetServer[91.99.165.207:443]" lines inside a
single second, 960 on its second instance. The client ring buffer holds 1000
lines, so that burst erased the entire history -- which is why nothing from
before the restart could be inspected afterwards. IsStoped() cannot gate this:
it returns true unconditionally while g_bExit == S_SERVER_EXIT, conflating
"worker exited" with "master restarted".

- test.cpp: sleep 20ms in the S_SERVER_EXIT branch. The sleep runs concurrently
  with the worker's teardown rather than after it, so reconnecting is delayed by
  at most one 20ms tick.
- ClientDll.cpp TestRun(): log only when SetServer() reports the address really
  changed. It returns false for a null address, which also silences AutoRun's
  TestRun(NULL, 0) calls. Nothing is lost: the restart itself is already logged
  as "======> Server exit" in KernelManager.
- ClientDll.cpp AutoRun(): its do/while had no sleep either. Gate it on "still
  in S_SERVER_EXIT and a worker is still running" so the normal path stays
  zero-delay.

Together these turn a burst that wiped the log buffer into silence, and cap the
loop at 50 iterations per second instead of roughly 900. A worker that hangs
during teardown still burns a core; curing that needs the thread-alive state
exposed separately from IsStoped(), which is an interface change and is left out.

Co-Authored-By: deepseek-flash
2026-10-30 23:39:05 +01:00
yuanyuanxianganddeepseek-flash cbb84809d8 fix(server): bind context-menu commands to the hosts the menu was opened for
The host list is a virtual list (LVS_OWNERDATA), so its selection is stored as
row indices. m_HostList is reordered underneath those indices: ApplySort() sorts
it in place on every TIMER_REFRESH_LIST tick, and RemoveFromHostList() erases
entries as hosts go offline. TrackPopupMenu runs its own modal loop, which keeps
dispatching WM_TIMER, so by the time the user clicks an item the row numbers
have already shifted. Every command handler resolves its targets at click time
with GetFirstSelectedItemPosition() + GetContextByListIndex(), a pure row lookup
(m_HostList[m_FilteredIndices[row]]), so a menu opened for host A could act on
whichever host now occupied that row.

Snapshot the selected clientIDs before the popup and restore the selection to
their current rows when it returns, dispatching the command ourselves through
TPM_RETURNCMD so the restore happens first. CMenu::TrackPopupMenu is not used
for this because its return type is BOOL, which would truncate the command ID.

Restoring the selection alone is not enough. A dozen handlers pop a confirmation
or input dialog before resolving their targets, and that modal pumps WM_TIMER
too, so the selection drifts a second time. Keep the same clientID snapshot in
m_CtxMenuTargets for the duration of the dispatch and let ResolveCommandTargets()
prefer it over re-reading the selection. Every lookup revalidates GetClientID()
against the row it landed on, so a stale index skips the host instead of acting
on a different one, and hosts that went offline while the menu was open are
dropped rather than guessed at. The snapshot is saved and restored around the
dispatch so a nested popup cannot clobber the outer one.

SendSelectedCommand, ShouldRemoteControl, SwitchSelectedProtocol, OnOnlineDelete,
OnOnlineUninstall, OnOnlineHostnote, OnOnlineRunAsAdmin, MachineManage and
ProxyClientTcpPort now resolve through it. Handlers that show no dialog before
resolving (OnMainProxy, OnOnlineAddWatch, OnOnlineInjNotepad, OnOnlineLoginNotify,
OnOnlineActiveWnd) keep reading the selection directly.

Co-Authored-By: deepseek-flash
2026-10-30 23:07:48 +01:00
yuanyuanxianganddeepseek-flash 96f1bacd43 fix(client): use GDI capture when the session has no interactive desktop
A host whose DXGI initialisation hangs never opens the remote desktop window at
all. WorkThreadProc runs InitScreenSpy() and SendBitMapInfo() back to back, so a
capturer that never finishes constructing means TOKEN_BITMAPINFO is never sent,
and the master - which only opens the window on that token - waits forever. On
the affected Server 2022 box the screen thread stopped right after logging its
type and algorithm, printing neither the DXGI init summary nor the existing
"DXGI SPY init failed" fallback, so it was stuck inside the capturer
constructor; a healthy machine on the same build reaches the summary in under a
second. Six clicks left six stuck threads, each holding a D3D device.

DXGI desktop duplication needs a display to duplicate. With no interactive
desktop it can return no frames at best, and on some drivers it never returns
from the initialisation calls at all. BitBlt has no such dependency and keeps
working, which is why switching the screen type to GDI made the same host
connect. Detect that up front and pick GDI instead of relying on a hang to be
survivable:

- IsWorkstationLocked() - the input desktop is Winlogon. Moved out of
  CKernelManager into Manager.cpp so the capturer can use it too; the manager
  keeps its private wrapper for the "Locked:"/"Inactive:" activity string.
- IsCurrentSessionDisconnected() - the process's own session is
  WTSDisconnected. That is the state the reported host was actually in: its
  client runs in session 2, which was disconnected, and the desktop only came
  back after the master's "RDP session reset" ran tscon. Session 0 has no
  disconnected state and is left alone.

Either condition means the same thing for capture, so both route to the plain
GDI capturer. An active session keeps DXGI untouched, so hosts that work today
are unaffected; the new log line names which condition fired.

Co-Authored-By: deepseek-flash
2026-10-30 22:36:01 +01:00
yuanyuanxianganddeepseek-flash 6a3d536d38 fix(server): keep the build dialog's default protocol at TCP
Commit 46f4bf2 swapped InsertString for AddString on IDC_COMBO_PROTO while
attaching protocol values as item data. That combo carries CBS_SORT, and the two
messages differ there: CB_ADDSTRING inserts in alphabetical order and returns
the sorted position, while CB_INSERTSTRING ignores CBS_SORT entirely. The list
went from TCP/UDP/HTTP/random/KCP/WebSocket/WS+TLS to HTTP/KCP/TCP/UDP/...,
so SetCurSel(0) landed on HTTP and every newly opened build dialog defaulted to
the wrong protocol.

Revert both hunks of that commit for this dialog. The items are appended with
InsertStringL like every other combo on the form, and OnBnClickedOk reads
GetCurSel() again: with no item data attached GetItemData returns 0 for every
row, so the previous guard (0 != CB_ERR) would have written TCP no matter what
the user picked. PROTO_TCP..PROTO_WSS are 0..6 without gaps and PROTO_HTTPS
sits outside the list, so the index still equals the protocol value.

Co-Authored-By: deepseek-flash
2026-10-30 22:18:17 +01:00
yuanyuanxiang 389de9d456 fix(client): fall back to GDI capture when DXGI duplication yields no frames
Some environments never deliver a frame from
IDXGIOutputDuplication::AcquireNextFrame: headless or virtual displays, Session 0
desktops, and drivers that do not push duplication notifications. It returns
DXGI_ERROR_WAIT_TIMEOUT forever, even while the desktop is changing.

Consequences:
- The first screen could not be captured, so the server kept showing
  "Please wait..." because m_bIsFirst was never cleared.
- Adding a GDI fallback for the first screen alone was not enough: the picture
  appeared but then froze, because ScanNextScreen still polled DXGI and always
  got nothing back, leaving the encoder without input.

Fixes:
- Add CaptureByGDI(), which grabs a frame with GetDC(NULL) + CreateDIBSection +
  BitBlt. GDI does not depend on desktop changes, which is why the plain GDI
  capture path always worked in these environments.
- When the first screen cannot be obtained from DXGI, capture it with GDI and
  mark the whole session as GDI (m_bGDIFallback = true), releasing the
  duplication object. All later frames then go through GDI so the picture keeps
  updating.
- Normal machines are unaffected: if DXGI delivers the probe frame or the first
  screen, the flag stays false and the GDI path is never entered. This also
  avoids mis-detecting a momentarily static desktop as a broken duplication,
  which a plain timeout counter would do.
- Create the GDI offscreen DIB lazily and reuse it (m_hGdiMemDC, m_hGdiBmp,
  m_pGdiBits). The fallback is a per-frame path, so allocating and freeing about
  15MB every frame would cause visible jitter.
- Reuse m_BitmapInfor_Full for CreateDIBSection instead of building a second
  BITMAPINFO: it is already 32bpp BI_RGB with a positive height (bottom-up) and
  matches the surface size.
- Guard the GDI buffer readiness check. If CreateCompatibleDC or SelectObject
  fails, drop the bitmap so the next call does not mistake a half-initialized
  state for a usable one; otherwise BitBlt would silently write nowhere and
  memcpy would read uninitialized memory.
- Restore the previous bitmap before DeleteDC and check for HGDI_ERROR,
  otherwise DeleteObject on the still-selected bitmap fails and leaks it.

The fallback matches the plain GDI capture path (full-size BitBlt plus
ScaleBitmap), so a downgraded session performs the same as GDI mode. The only
added cost versus DXGI is one BitBlt per frame.
2026-10-30 21:57:39 +01:00
yuanyuanxiang bc75e1ae99 fix(client): fix DXGI black screen on rotated displays and slow first frame
1. Black screen on rotated displays

Root cause: with DXGI Desktop Duplication on a rotated output,
DXGI_OUTDUPL_DESC.ModeDesc reports the logical desktop size (e.g. 1440x2560)
while the surface returned by AcquireNextFrame is the unrotated landscape
bitmap (2560x1440). The old code created cpuTexture from the ModeDesc size.
On a mismatch ID3D11DeviceContext::CopyResource returns void and silently
copies nothing, leaving the destination texture all zeros, so the first
screen and every H.264 frame were fully black (IDR was only 5KB).
The GDI path does not go through DXGI and was unaffected; the web client uses
the DIFF algorithm and was hit too, but looked different.

Fixes:
- Create cpuTexture from the real D3D11_TEXTURE2D_DESC; when the probe fails,
  derive the real surface size from Rotation instead of falling back to
  ModeDesc, which would reintroduce the black screen
- Add BlitRotated() to upright the image for ROTATE90/180/270, with a whole-row
  memcpy fast path for IDENTITY; m_ulFullWidth/Height now hold the upright
  logical size
- Treat DXGI_ERROR_WAIT_TIMEOUT as "no new frame" instead of a failure, so a
  static desktop reuses the previous frame instead of always returning nullptr
- GetFirstScreenData: fix the write offset (start at +1, previously the color
  channels were all wrong) and report the scaled size instead of the full size,
  which used to send about 8.5MB of garbage
- Validate the frame format against a whitelist; fall back to BGRA and warn for
  formats that are not 4 bytes per pixel

2. Slow first frame (the probe frame consumed the initial frame)

Root cause: the probe frame AcquireNextFrame(500), added to read the real
texture description, was released right after use and therefore discarded.
But the frame DXGI pushes after DuplicateOutput is often the only frame
available on a static desktop. After discarding it, the first-screen
AcquireNextFrame always timed out (and that timeout was 1000ms at the time),
ScreenManager had already set m_SendFirst = TRUE so it never retried, and the
encoder had no input to produce an IDR, so the picture only appeared once the
desktop changed. Symptom: MDLL/EXE builds with this fix took a long time to
show the remote desktop, while the old build without the probe frame was fast.

Fixes:
- Keep the probe frame: stash it in m_probeRes without calling ReleaseFrame and
  let the new ConsumeProbeFrame() fill the first screen once the buffers are
  allocated, so the first screen no longer depends on the desktop changing
- Probe timeout 500 -> 200ms; verify both size and format of the probe frame
  against cpuTexture and skip consumption on mismatch, otherwise a silently
  failed CopyResource would be taken as a valid all-black first screen
- CaptureFrame: drop "reuseOk ? 100 : 1000" and use a fixed 100ms timeout. The
  AcquireNextFrame timeout is an upper bound rather than a fixed wait, and
  blocking on a static desktop only slowed the capture loop down to 1Hz
- Retry the first screen up to 3 times on "no new frame" (100ms timeout plus a
  20ms gap); skip the capture entirely when the probe frame already filled it
- Release m_probeRes in CleanupDXGI and ReinitDuplication so the duplication
  object can be released

3. Incomplete picture

- Add ScreenCapture::FitDefaultSendSize(), which scales proportionally so the
  long edge stays at or below 1920 and the short edge at or below 1080, for
  both landscape and portrait. The old min(1920,w) and min(1080,h) clamped the
  axes independently and broke the aspect ratio: a 1440x2560 portrait desktop
  was squeezed to 1440x1080, keeping only 42% of the height
- Use the same helper for both the GDI and DXGI paths; common landscape
  resolutions (1920x1080, 2560x1440, 3840x2160, 1280x720) are unchanged

4. Incidental fixes

- CaptureFrame leaked desktopResource when QueryInterface failed, one DXGI
  resource per failure
- Drop the frame and warn when the surface size changes, for example after the
  user changed the resolution, so BlitRotated does not read out of bounds using
  stale sizes
2026-10-30 21:18:57 +01:00
yuanyuanxianganddeepseek-flash 46f4bf2dfb Fix: Make the WebSocket transport reachable and bounded on every platform
The POSIX clients were built without a connection config - Linux, macOS and
Android all construct IOCPClient without the injected CONNECT_ADDRESS - so
ConnectServer saw protoType -1 and quietly dialled the master port in plain
TCP. Setting protoType to WS in their settings did nothing and logged nothing,
and since CLIENT_CAP_PROTO_SWITCH is Windows-only the server could not move
them either. Give the client a SetDefaultProto() for that construction path
and call it from all three mains before the reconnect loop, with a one-shot
log when neither a conn nor a default protocol is available so the silent
fallback becomes visible next time.

Bound what a peer can make the client read. ReadHeader accepted the 8-byte
extended length and rejected only the sign bit, so a frame length of nearly
2^63 kept the connection streaming into a frame that would never end - alive
but never delivering another packet. Cap single frames at 256 MB, the same
value ServerWsSession already applies to client frames, and drop the
connection past it; real traffic is far below that.

Stop Reset() from writing the receive thread's frame state. Disconnect() can
run from the heartbeat or command thread, not just the receive thread, so
Reset() now only flips the atomic ready flag and a new ResetFrames() clears
m_remaining, m_masked and m_maskPos from Handshake() alone, before the
receive thread starts reading the socket. Those fields keep a single owner
without adding a lock to the receive hot path.

Finish a dead WS session instead of leaving it to the keepalive timer. When
the session had closed but wsState was still WS_Ready, sends were dropped and
nothing woke the pending recv, so a peer that closed and then went quiet held
the context for the 3-minute keepalive. shutdown() the socket there so the
recv returns zero bytes and the normal -2 teardown runs; RemoveStaleContext
would deadlock against the caller's own IoRefCount and can hand back a reused
context.

That shutdown only finishes the connection if a zero-byte read still tears it
down, and on the plain path it no longer did. DispatchPlain answers an empty
buffer with "handled", so a peer's FIN left the connection in CLOSE_WAIT
until keepalive - holding an IOCP context, a pending WSARecv and a rate-limit
slot - where the pre-WS code called ParseReceivedData and tore down at once.
Restore that teardown on the TLS_Plain branch, matching the other two. Checked
against a Debug server: a plain socket that half-closes used to sit in
CLOSE_WAIT with the peer's recv timing out, and now disappears immediately
with recv returning zero.

Two smaller cleanups from the same review. Give the WS upgrade its own prefix
buffer (wsPreClassify) instead of borrowing the TLS sniffer's, which was
serially reused for two state machines and read as if it were one. And stop
deriving the build dialog's protoType from the combo box index: items now
carry the protocol value as item data, keyed off the index AddString returns,
so inserting an option in the middle can no longer write the wrong number into
the generated client without any error. ApplyProtoSwitch loses its bool
return, which contradicted its own side effects and was ignored by every
caller.

Co-Authored-By: deepseek-flash
2026-10-30 19:15:14 +01:00
yuanyuanxianganddeepseek-flash 50a489e316 Fix: Close the gaps the WebSocket transport review found
Three of the findings only bite in deployment. First, the client's TLS and
WebSocket handshakes run synchronously on the reconnect thread with no socket
timeout, so a peer that accepts TCP and then goes quiet (black-holed proxy
upstream, middlebox that only receives) blocks recv() forever and stalls the
reconnect loop until the process is restarted. Set a 15 s SO_RCVTIMEO and
SO_SNDTIMEO for the handshake window - the same value both server handshake
threads use - and clear them once the connection is up so the worker thread's
select plus blocking recv keeps working as before.

Second, per-IP rate limiting counted the getpeername address before the real
device was known. Behind a same-host reverse proxy that address is loopback,
which IPWhitelist always trusts, so WS traffic was neither counted nor banned;
behind a remote proxy every device shares one bucket, and tripping the
threshold disconnected all of them. Count and ban by the forwarded device IP
once the upgrade resolves it, mirroring the Go server's limitDirectPeer and
handleConnection split. Direct connections keep their accept-time count and
are not counted twice.

Third, the protocol switch disarmed its five-minute auto-revert as soon as the
new entry connected, which only proves TCP/TLS/WS handshaking finished. If
login is never accepted there (wrong backend, reverse proxy pointing at some
other WS service), the revert could never fire and the client would keep
retrying a dead entry. Disarm on the first CMD_MASTERSETTING instead, which
the server only sends after adding the host to its online list, and re-check
it on every heartbeat so a late one still counts.

The smaller items came along: free the handshake parameter when CreateThread
fails in both handshake starters, move the WS_Handshaking fail-closed guard
ahead of the TLS branch so it also covers WSS (where tlsState is already
TLS_Ready), generate the frame mask from a per-channel PRNG inside the send
lock instead of an unseeded global rand(), make the transport flags and the WS
session's ready flag atomic, drop rather than send unframed application bytes
when a WS session has closed, and abort a protocol switch whose PEM fails to
load instead of moving to an entry that cannot connect.

The Go server now bounds the upgrade sniff even when ReadTimeout is zero, and
the design doc records the two-stage limiter, the login-based disarm and the
review items that stay as known limits.

The protocol switch's input prompt is cut down to "reverse-proxy entry
(host:port)" - the label static is only 81 dialog units wide, and the old
sentence ran to roughly three times that.

The three language files follow: en_US and zh_TW gain the shortened prompt and drop
the long key it replaced, the German file gains the protocol-switch block it never
had, and its WebSocket tip key is corrected - it had picked up a Go-server clause
the source string never carried, so the tip was never translated at all.

Co-Authored-By: deepseek-flash
2026-10-30 18:11:34 +01:00
yuanyuanxiang 99db28e2e2 Feature: Let the operator switch a live client's transport from the online list 2026-10-30 17:22:36 +01:00
yuanyuanxiang cc891e3670 Feature: Sniff WebSocket upgrades on the MFC server's device port 2026-10-30 17:22:17 +01:00
yuanyuanxiang d4f312c9d8 Feature: Tunnel the device protocol through a reverse proxy over WebSocket 2026-10-30 17:21:42 +01:00
yuanyuanxiang de621aa555 Compliance: Audit third-party dependencies and complete the license notices
Dependencies.md only covered compress/ and the injection libraries. Everything
else in the tree was undocumented, and LICENSE-THIRD-PARTY.txt was missing
three components that Dependencies.md already listed.

Added to Dependencies.md (23 entries):

  vendored source  KCP/ikcp, xxHash 0.8.3, tiny-AES-c, skCrypter,
                   cpp-httplib 0.14.3
  runtime / data   OpenSSL (Linux/macOS TLS and libsign.a HMAC), FRP
                   (Bin/res/frpc.dll, frps.dll), ip2region xdb v4, QQWry,
                   Microsoft DirectX SDK headers
  server-go        jwt 5.3.1, gorilla/websocket 1.5.3, klauspost/compress
                   1.18.2, zerolog 1.34.0, x/sync, x/text, lumberjack 2.2.1
                   plus 3 indirect modules
  android          androidx core-ktx 1.13.1, appcompat 1.7.0, Kotlin stdlib
                   2.1.21
  test             GoogleTest 1.14.0 (CMake FetchContent)

LICENSE-THIRD-PARTY.txt grows from 278 to 633 lines and 22 sections. Full text
is embedded for the short licenses (MIT, BSD, zlib, Unlicense); the Apache,
LGPL and GPL entries follow the file's existing style of terms + obligations +
where to obtain the text, rather than reproducing legal text by hand.

Three findings worth recording:

- x264 is GPL-2.0 and is linked statically (client/X264Encoder.cpp). The old
  file only stated that FFmpeg was built without GPL plugins, and never
  mentioned that x264 is linked separately. Section 21 now spells out the
  consequence: a binary containing x264 is a GPL-2.0 work unless covered by a
  commercial x264 license.

- FFmpeg is linked STATICALLY, not dynamically as the old text claimed. There
  is no av*.dll anywhere in the tree; the pragmas reference libavcodec_x64.lib
  and friends. Section 19 is rewritten around LGPL-2.1 section 6 and quotes the
  configure line recovered from libavutil, which also shows the build is
  decode-only (--disable-encoders). That means x264 is the product's only
  H.264 encoder, so DISABLE_X264_FOR_TEST=1 leaves no encoder at all and the
  client degrades to RGB565.

- The FRP binaries report buildinfo v0.69.2-...+d58c00d0332c+dirty. The "+dirty"
  means the FRP sources were modified locally, and Apache-2.0 section 4(b)
  requires modified files to carry a prominent change notice.
2026-10-30 11:04:54 +01:00
yuanyuanxiang 82f59b2469 Fix: Make the x264 opt-out real, and unchain libyuv from it
DISABLE_X264_FOR_TEST never actually removed the x264 dependency. Two
separate reasons:

1. X264Encoder.h included <x264/x264.h> unconditionally and only pulled in
   common/config.h afterwards, so the macro was not even visible at the point
   where it mattered. The class also carried x264_t / x264_picture_t /
   x264_param_t members, so the header was required to compile regardless of
   the switch. Moving the config.h include to the top and splitting the class
   declaration in two fixes it: with the switch on, the class is a stub with
   no x264 types at all, and open() returns false so EncoderFactory falls
   through. The open(x264_param_t*) overload is dropped in that branch; it had
   no callers outside X264Encoder.cpp.

2. libyuv was collateral damage. Its only #pragma comment(lib) lived inside
   the #else branch of the x264 switch, but CFFmpegAV1Encoder.cpp and
   CFFmpegH264Encoder.cpp both call libyuv::RGB24ToI420 / ARGBToNV12 /
   I420ToNV12 without carrying a pragma of their own. Turning x264 off
   therefore dropped libyuv too and the link failed with LNK2001 on those
   three symbols. libyuv is BSD-3 and unrelated to x264: the pragma is now
   unconditional in X264Encoder.cpp, and CFFmpegH264Encoder.cpp declares it
   alongside its ffmpeg libs so the encoder pair is self-sufficient.

Verified with Release x64 builds of both ServerDll and ghost:

  switches 0/0, compress/ intact          -> builds
  switch x264=1, compress/x264 deleted    -> builds (was LNK2001 before)
  switches 1/1, both dirs deleted         -> builds

So a compliant build needs neither the x264 library nor its headers.

Note for anyone flipping these switches: do a full rebuild, not an
incremental one. config.h reaches X264Encoder.cpp indirectly through
X264Encoder.h, which the .tlog dependency tracking does not record, so an
incremental build happily links a stale object against a freshly compiled one
and reports bogus LNK2001 errors.
2026-10-30 11:04:44 +01:00
yuanyuanxianganddeepseek-flash 1d875ddbd1 Feature: Add a "Copy Name" item to the online host context menu
The online list already lets an operator copy everything about a host
through "Copy Client Info", but there was no quick way to grab just the
names, which is what people actually paste into a chat or a ticket. The
new menu item sits directly below "Edit Group" and copies the names of
all selected hosts to the clipboard, separated by semicolons.

"Name" means what the first column of the list shows: the remark when one
has been set, otherwise the computer name. The column text is CP_ACP, so
the handler decodes it the same way OnGetdispinfo does; that keeps the
copied text identical to what is on screen, including for Chinese remarks.
Clipboard writing reuses the existing UTF-8 based SetClipboardText helper
instead of growing a third copy of the same CF_UNICODETEXT code.

The item also gets its own 16x16 icon (two stacked cards with text bars,
drawn on the usual 240,240,240 background) loaded into a newly added
m_bmOnline[75] slot, and translations were added for English, German and
Traditional Chinese so the item does not fall back to simplified Chinese
when another UI language is active. The user manual and the resource
README were updated to match.

Co-Authored-By: deepseek-flash
2026-10-29 22:06:33 +01:00
yuanyuanxiang dcb5ae25c6 Fix: Paginate get_activity_history results
The tool was the only list-type tool without pagination. The client keeps
ACTIVITY_HISTORY_MAX=500 records and Dump() prepends the in-progress window,
so a single call returned up to 501 lines of "[time] [title] duration" --
enough to blow up the caller's context, especially since titles carry
personal browsing history.

Records come back newest-first (m_records uses push_front and the current
window is prepended), so the standard limit/offset window applies directly:
offset=0 is the most recent page, no need to read total first and count
backwards. That ordering is now stated in the tool description so the model
can rely on it.

- inputSchema: BuildGetHostDetailInputSchema -> BuildPagedHostListInputSchema
  (adds limit, default 100 / max 1000, and offset)
- outputSchema: append AppendPageOutputProps plus truncated
- implementation: rename the full split to `all`, slice via ResolvePageWindow
  and ApplyPageWindow, write back with WritePageFields
- activityHistory is rebuilt from the window instead of returning the whole
  Dump() text -- otherwise the raw copy would bypass pagination entirely
- 64 KB byte budget (same as get_client_log), trimmed from the end so the
  newest records survive; hasMore is computed as offset+kept < total rather
  than hardcoded true, since a single oversized tail record must not claim
  there is another page

Batch calls need no extra work: the tool is already in IsBatchReadOnlyTool,
and BuildBatchCall forwards limit/offset to each host, so ids + limit means
"the latest N records of every host".

Compiles clean; not yet exercised against a running server (the exe was
locked by the live instance). Verification cases are listed in
docs/Mcp_Test_Report_2026-10-29.md section 8.
2026-10-29 21:37:02 +01:00
yuanyuanxianganddeepseek-flash 56a937fabb Fix: Three blocking defects found by the MCP tool survey
The survey in docs/Mcp_Test_Report_2026-10-29.md turned up three P0s, each
of which stopped a whole capability rather than degrading it. Two of them
were the same mistake: the input schema promised something the output
schema then rejected. The third was an output with no size limit, plus a
client that never implemented the command at all.

Batch calls could never succeed. A call carrying ids[] goes through
BuildBatchCall, which returns {tool, total, succeeded, failed, skipped,
results[]}; every tool declares only the single-host shape. The client
validates structuredContent against that declaration, so any batch call
failed with -32602: data must have required property 'host' - the input
schema advertises ids, the output schema kills it. Tools/call cannot fix
this one call at a time, so ApplyBatchOutputSchema runs at the end of
tools/list, next to ApplyToolAnnotations, and rewrites the schema of every
tool in the batch list to {type: object, anyOf: [single, batch]}. Placing
it at the end is what makes it cover all three registration points
(inline, McpMachine, McpChat) and any tool added later. IsBatchReadOnlyTool
moved from McpServer.cpp to McpInternal.cpp for the same reason: the list
is now read by tools/call and tools/list, and the two must not drift.

list_registry failed whenever path was omitted. The root-key branch
returns keys only, while the output schema listed values in required as
well, so the first usage the documentation describes - omit path, get the
five root keys - could not work. values is no longer required and the
schema says it is absent in that branch. The root branch also returns
path: "" now, so both branches carry the same field set and callers need
not branch.

get_client_log was unusable on both platforms, for two unrelated reasons.
Windows returned the whole 1000-line ring buffer, 90,473 characters, over
the client's result limit: fetched, then not deliverable. Linux and macOS
timed out because their clients never handled COMMAND_QUERY_LOG at all -
only client/ClientLogManager.cpp does - so TOKEN_REPORT_LOG never arrived.
Adding a limit alone would have left Linux broken; fixing the client alone
would have left Windows over the limit.

The server now takes limit (default 200, max 2000) and filter, and reads
backwards from the end: troubleshooting wants the last thing that happened,
not the first line after boot. A 64 KB byte budget sits under the line
count, because one line can be a stack dump; when the final line alone
exceeds it, the tail is returned and truncated says so. Responses carry
lines_total, lines_matched, lines_returned and truncated. The timeout
message now names the likely cause and two ways around it instead of
saying only "Timeout waiting for client log".

The POSIX clients get common/ClientLogHandler.h, a counterpart to the
Windows CClientLogManager, and one line each in linux/main.cpp and
macos/main.mm. It must open a sub-connection: MessageHandle's
TOKEN_REPORT_LOG branch takes the first packet and then calls CancelIO on
that connection, so answering on the main connection would close the main
connection and drop the client offline.

Verified against a server built at 21:17:21 with both clients rebuilt. A
batch get_host_detail over the two A6 records returns succeeded=2 with
per-host data; host_list_processes with ids returns 2 of 2, which exercises
the McpMachine registration point rather than the inline one; a mixed
Windows/Linux batch of get_client_log returns 2 of 2. list_registry with
no path returns the five root keys and path ""; with a path it still
returns its values. get_client_log on Windows goes from 1000 lines to 200
with truncated=true, and limit=3 with filter=ConnAuth yields 28 matched and
3 returned. On Ubuntu 24.04 it returns logs at all, and the client's own
log shows Enter ClientLogThread, TOKEN_REPORT_LOG, then Leave about a
second later when the server cancels the connection - paired, no leak.

The connector still caches an old input schema for get_client_log, so
limit and filter are rejected locally until it reconnects; the defaults
already cover the P0, and this is the same cache problem as the
copy_files_c2c.overwrite entry in the report's P1 list.

docs/Mcp_Design.md section 18 records the implementation and the reasoning;
section 7 of the test report carries the verification table.

Co-Authored-By: deepseek-flash
2026-10-29 21:22:43 +01:00
yuanyuanxianganddeepseek-flash dc4fd792f6 Feature: Implement the Linux screen preview response
The Linux client now answers COMMAND_SCREEN_PREVIEW_REQ, so a host with
an X11 desktop gets a thumbnail when it is double-clicked in the online
list, a frame in the list's Preview column, and an image from the MCP
get_screenshot tool. Previously only Windows clients advertised the
capability and Linux hosts showed "预览不可用" after a four second wait.

The client does not encode JPEG. Stock desktops ship libjpeg.so.8 whose
struct layout is the distribution's ABI (JPEG_LIB_VERSION 80), while the
in-tree jpeglib.h is libjpeg-turbo 3.1.1 (62), and libturbojpeg is not
installed by default; dlopening the system library against that header
fails with "Wrong JPEG library version: library is 80, caller expects
62". Instead the client sends raw pixels in a new screen preview format,
SCREEN_PREVIEW_FMT_BGRX: top-down rows of B,G,R,X with no row padding,
already scaled to the requested width. The server re-encodes to JPEG at
the single ingress point, so the preview popup, the list thumbnail cache
and the MCP tool keep consuming JPEG only.

Capture follows the path ScreenHandler already uses: root window copied
into an offscreen pixmap with an IncludeInferiors GC, then XGetImage,
which avoids BadMatch under compositing window managers. The X11 type
declarations and the dlopen loader moved out of ScreenHandler.h into
linux/X11Loader.h so both users share one dlsym table. The full-size
image is never materialized: a box filter reads straight from the
XImage rows (honouring bytes_per_line) into the output buffer, scales to
maxWidth without upscaling, and clamps the height to 1080 so a portrait
4K desktop cannot produce a 26 MB packet. Rows and columns come out
even, which they are for JPEG anyway.

The capability bit is now honest about the runtime. LOGIN_INFOR grows
DefaultCaps()/SetCaps(), and the client recomputes the bits before every
login and re-login: CLIENT_CAP_SCREEN_PREVIEW is set only when DISPLAY is
present and the X server actually opens. A headless host therefore gets
-32005 "Host does not support screen preview" from MCP instead of a
timeout, and a host whose session appears after boot picks it up on the
next reconnect. Requests are handled on a detached worker thread behind
a single-flight guard (matching the Windows client), so a slow XGetImage
never stalls the receive thread and a burst of requests degrades to "no
preview" rather than queueing. If the worker thread cannot be created,
the guard is released again, so one failure cannot leave every later
request rejected as busy until the client restarts.

The MCP design note claimed the capability was declared by Windows only,
and the get_screenshot tool description said the same; both now say what
the code does (Windows always, Linux when a display is reachable).

Server side, NormalizeScreenPreviewPacket runs in MessageHandle before
the MCP handoff and the PostMessage to the UI thread. It validates that
width/height are within the values the server itself can ask for and
that bytes equals width*height*4, converts with a stack Gdiplus::Bitmap
over the packet's own pixels (no copy, and no DEBUG_NEW trouble), and
rewrites the header to JPEG. The encoder output is read back by seeking
the stream rather than GlobalSize, so the packet carries no heap-block
padding after the EOI marker. Malformed packets are dropped; failure
statuses pass through untouched so the existing code can report them.

Tested against a Debug server with the WSL Ubuntu 24.04 build as the
client. get_screenshot returned valid JPEGs at max_width 480 (480x142,
1.7 KB) and 1920 (1920x570, 17.9 KB), repeatably; the list showed a
thumbnail for the GUI client and N/A for a second copy started without
DISPLAY, which also answered -32005. The box filter and the BGRX to JPEG
conversion were checked separately with quadrant fixtures: the browser
over the synthetic B,G,R,X buffer recovers red/green/blue/white in the
right channels and the downscale averages, handles non-integer ratios
and row padding, and rejects 24bpp and upscaling. The captured frames
come out black under WSLg because Xwayland keeps no root pixmap there;
that is the compositor, not this code, and Xorg sessions capture
normally.

Co-Authored-By: deepseek-flash
2026-10-29 18:12:15 +01:00
yuanyuanxianganddeepseek-flash 5bff9df3fc Improve: Harden the self-implemented SOCKS5 proxy listener
Follow-up to the HP-Socket replacement: the four items the first pass
deliberately left out, plus two defects that the new tests turned up.

The listener now binds 127.0.0.1 instead of INADDR_ANY. The dialog only
ever points the user (and the Chrome shortcut) at 127.0.0.1, and an
unauthenticated SOCKS5 port open on every interface is an open proxy.

The SOCKS5 handshake is parsed as a byte stream. The previous code
assumed one callback carried exactly one message, which happens to hold
for curl and Chrome but not in general: a greeting split across segments
was answered twice, and a CONNECT request followed by tunnel data in the
same read dropped the trailing bytes. Each connection now keeps a pending
buffer and a four-state machine (greeting, request, connecting, tunnel),
and bytes that arrive before CONNECT_RESULT are replayed to the client
once the tunnel opens, after the SOCKS5 reply.

Flow control: the listener takes a PROXYCANRECVPROC callback that is
consulted before each recv. The dialog answers it from the main
connection's send queue, so a download that outruns the client link
pauses the local read instead of growing the server's buffer. A 300MB
transfer through the tunnel peaks 150KB above the idle working set.

Handshake watchdog: sessions that stall in greeting/request/connecting
are dropped after 30 seconds; established tunnels are left alone.

Two defects in the log path, both surfaced by the watchdog test. Logging
every 32KB chunk produced roughly 9000 posted messages for a 300MB
transfer, which starved the UI thread's timers (the first watchdog run
never fired) and could overflow the message queue; and every line re-set
the whole 256KB text into the read-only edit. Transfers now log
cumulative progress once per second and a per-connection total at
teardown, panes are refreshed at most every 100ms from a dirty flag, and
a failed PostMessage no longer leaks its CString.

Localization: the new session-log strings were also added to en_US.ini,
zh_TW.ini and de_DE.ini (16 keys each, GBK, kept in the existing
FormatL section). Two of the lines were reworded instead of translated
as-is: the close notice now says what happened (the client asked to
close, or the downlink send failed) rather than printing the protocol
token name, and the throughput arrows are now << and >> because
CIniParser splits an entry at the first '=', so the old <== and ==>
could never have served as keys.

Testing: curl IPv4 and hostname tunnels, 4MB and 300MB transfers
byte-identical, byte-at-a-time and pipelined handshakes, refused target
(REP=5), SOCKS client killed mid-transfer, client process killed
mid-transfer (dialog closes, port released), 20 parallel connections,
five open/close cycles with no handle or thread growth, and the 30s
handshake timeout. The dialog log was checked at runtime with
Language=en_US and renders in English only.

Co-Authored-By: deepseek-flash
2026-10-29 16:12:14 +01:00
yuanyuanxianganddeepseek-flash 45e1dd9f6c Feature: Implement the proxy mapping listener without HP-Socket
The proxy mapping dialog ("代理映射") depended on HP-Socket: three vendored
SDK headers (4787 lines) plus #pragma comment(lib) lines pulling in four
prebuilt lib/DLL variants, all guarded by ENABLE_HPSOCKET, which has been 0
since the initial commit -- so the feature was dead code that only answered
"This feature is unavailable due to HPSocket disabled" and no build of this
repository ever ran it.

Replace that dependency with a small listener built on blocking sockets and
select, which is the same approach the client's CProxyManager and the
server's own SimpleWebSocket already take. The accept loop polls every
200 ms so Shutdown can return without closing a socket another thread is
selecting on, and each accepted connection gets a relay thread that only
has to recv and hand bytes to the dialog. Connection sockets are closed by
their relay thread alone; Disconnect only raises a stop flag and calls
shutdown() under the same lock the relay thread takes before closesocket,
so a recycled handle is never shut down by mistake. Finished threads are
parked in a graveyard and joined by the accept thread, which keeps the
thread handle count flat across open/close cycles.

ProxyMapDlg keeps the SOCKS5 state machine it had, but now stores its
per-connection state in a map keyed by the connection id instead of
relying on HP-Socket's GetConnectionExtra, and it logs through a posted
window message rather than touching CEdit from worker threads. The two log
panes in IDD_PROXY are ES_READONLY, so EM_REPLACESEL was silently ignored
(the original code had the same latent bug); the dialog now keeps the pane
text itself and writes it with SetWindowText, bounded to 256 KB per pane.

The vcxproj and filters lose the three SDK headers, and the dialog gate in
OnOpenProxyDialog loses its ENABLE_HPSOCKET check.

Tested against a Debug server with a Debug Windows client on the same
host: curl through the listener succeeds over both the IPv4 and the
hostname ATYP paths, a 4 MB transfer arrives byte-identical, a refused
target maps to SOCKS5 reply 5, killing the client mid-transfer closes the
dialog and releases the port, and five open/close cycles leave the server's
handle and thread counts unchanged.

Co-Authored-By: deepseek-flash
2026-10-29 15:37:16 +01:00
yuanyuanxianganddeepseek-flash 13c02fe50b Feature: Skip already-present targets in copy_files_c2c
The destination writes every chunk unconditionally, so a second call with
the same arguments re-sent the whole file and returned exactly the same
result as the first. Measured on an 11 MB log: the target's mtime moved
and the entry count did not, and the caller had no way to tell a real
transfer from a repeat. upload_file and download_file already answer this
with overwrite/skipped; copy_files_c2c was the one that did not.

The skip decision has to be made on the server, because the receiving end
does not check whether the file exists. Before opening the transfer, a
default call now lists one level of dst_dir through ListRemoteTopLevelNames
- the helper upload_file already uses - and drops the paths whose basename
is already there. If everything is dropped the call returns success
without creating a transfer id at all, so no host is occupied and nothing
is sent. overwrite=true restores the old unconditional behaviour.

Name comparison follows the destination filesystem: folded on Windows,
exact on POSIX. That needed a foldCase parameter on the helper, defaulted
to true so upload_file keeps its behaviour.

dst_dir is handed to the listing without its trailing separator, because
the client concatenates "%s\*.*" and a trailing one produces "C://*.*",
which FindFirstFile rejects. search_file hit the same thing.

No protocol change and no client change: the packet layout, the receiver
and both client platforms are untouched.

Verified against a real server (build 2026-10-29 14:34:33) with a Windows
11 source and both an Ubuntu 24.04 and a Windows 11 destination. A second
default call returns file_count=0, skipped=1, an empty transfer_id and
skip_check_failed=false with the target's mtime unchanged; overwrite=true
advances the mtime (1793276909 -> 1793281657) and reports skipped=0; a
call into a non-existent directory creates it and lands the file flat; a
Windows destination folds case, so a placeholder SETTINGS.INI makes a
later settings.ini skip, while a POSIX destination leaves both files side
by side.

One documented case does not hold, and the expectation was mine rather
than the code's. "Destination occupied by another tool" was supposed to
fail the pre-check and still transfer with skip_check_failed=true, but
BeginC2CTransfer consults the same m_Pending registry for src_id and
dst_id, so the transfer is refused with -32003 before the fallback can
carry it. The other door - a directory that can be written but not listed
- showed the pre-check succeeding instead of failing: the Linux client
reports EACCES as an empty directory rather than TOKEN_FILE_LIST_ERROR,
so the call goes on to overwrite. skip_check_failed is therefore a
timeout backstop that is hard to reach deliberately; the field stays, and
14.9.2 no longer claims that a busy host reaches the fallback.

Section 14.9 of the design doc records the contract, those results, and
one wrong turn worth keeping: an earlier round concluded that single-file
C2C nested the whole absolute path under dst_dir, and added receiver-side
hardening for it. The nesting came from the ad-hoc JSON-RPC test harness,
which passed JSON on the command line where the shell folded \\ into \/
before Python parsed it, so the source client received a path with no
backslashes left and its basename fallback - which looks for a backslash
- returned the whole path. The same file sent through the real MCP client
produces a clean basename. That hardening has been reverted; the defect
was in the test, not the product.

Co-Authored-By: deepseek-flash
2026-10-29 15:03:32 +01:00
yuanyuanxianganddeepseek-flash cd10d0cc1b Docs: Bring the MCP plan up to date after P10 and P11
The plan was written when the server had 54 tools in eight families, and
every batch since then changed the facts it states: P10-B added the three
file-write tools, P10-C the input lock, P11 the two session tools and the
protocol work. Read as-is, the plan would send the next person looking for
work that is already done, so the numbers, the family table and the batch
table now describe the 60 tools that actually exist.

The family table was rebuilt from the registration sites rather than from
the previous table: nine families, and the gating column now separates
"appears in tools/list" from "callable", which the old table conflated.
That distinction also fixes the default-config figure - 19 tools, not the
20 stated earlier: get_keylog needs McpKeylog, download_file needs
McpFileTransfer, and list_network_connections lives in the McpMachine
family, so with a default of read-only and every switch off only the
nine server-local read tools, eight read tools on the host and the two
remark/watch tools remain.

Section 5.10's field list for mcp_list_sessions was a guess written
before the tool existed; it now carries the eight fields that D.5
actually returns, with the original guess kept so the change is visible.
The two stale rows in 5.14 and the outdated header comment in 5.13 are
marked done against the commits that did them - bb55f52 bumped the
comment from 53 to 54, 3d388f8 dropped the number altogether when it
added remote_block_input, and every hash cited here was checked to be an
ancestor of HEAD so none of them points at the merged-away history.
Sections 5.1 to 5.10 gained completion markers, with 5.7 marked partial
because verified landed and verify_hint did not.

Everything in this diff is bookkeeping; no code, no behaviour, and no
claim in section 5.11 or the tools/list volume discussion changed.

Co-Authored-By: deepseek-flash
2026-10-28 23:39:13 +01:00
yuanyuanxianganddeepseek-flash 1c832ff7f2 Feature: Add MCP cancellation, progress notifications and dry runs
P11 closes the plan's last batch, entirely on the server side: no client
change is required for any of it.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: deepseek-flash
2026-10-28 18:50:53 +01:00
yuanyuanxianganddeepseek-flash 106ac2ff0f Fix: Resolve the Desktop, Downloads and home shortcuts on Unix clients
The file manager's remote shortcut buttons send "%USERPROFILE%\Desktop\" and
friends, which the Windows client expands with ExpandEnvironmentStringsA. Unix
clients had no such expansion, so the literal %USERPROFILE% was taken as a
directory name: opendir() failed and the Desktop, Downloads and home buttons
listed nothing at all.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

The smoke test gains the three reproducible negatives.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

While auditing the device-port logging surface:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: deepseek-v4-pro
2026-10-07 21:19:04 +02:00
214 changed files with 40319 additions and 7494 deletions

No files matched your search

+1
View File
@@ -93,6 +93,7 @@ Bin/*
nul
server/go/web/assets/index.html
server/go/users.json
server/go/devices.json
server/go/build/
server/go/.claude/settings.json
android/app/.cxx/
+85 -8
View File
@@ -2,28 +2,105 @@
## compress
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)
- [x264 v0.164.3194](https://github.com/corecodec/x264)
- [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)
- [ffmpeg 7.1](https://git.ffmpeg.org/ffmpeg.git) — LGPL-2.1, linked statically, see note below
- [jsoncpp v1.9.6](https://github.com/open-source-parsers/jsoncpp)
- [jpeg v3.1.1](https://github.com/libjpeg-turbo/libjpeg-turbo)
- [opus-1.6.1](https://opus-codec.org/release/stable/2026/01/14/libopus-1_6_1.html)
- [libpeconv c7d1e48](https://github.com/hasherezade/libpeconv)
- [libvpl v2.16.0](https://github.com/intel/libvpl)
- [dav1d 62501cc](https://github.com/videolan/dav1d)
- [libpeconv c7d1e48](https://github.com/hasherezade/libpeconv) — `server/2015Remote/libpeconv/`
- [libvpl v2.16.0](https://github.com/intel/libvpl) — `compress/ffmpeg/vpl_x64*.lib`
- [dav1d 62501cc](https://github.com/videolan/dav1d) — `compress/ffmpeg/dav1d_x64.lib`
## execution
- [MemoryModule](https://github.com/fancycode/MemoryModule.git)
- [MemoryModule](https://github.com/fancycode/MemoryModule.git) — `client/MemoryModule.c`
- [sRDI](https://github.com/Drewsif/sRDI.git)
- [pe_to_shellcode](https://github.com/hasherezade/pe_to_shellcode.git)
## vendored source
Single-file libraries compiled into the product as source.
- [KCP (ikcp)](https://github.com/skywind3000/kcp) — `common/ikcp.c`, `common/ikcp.h`
- [xxHash v0.8.3](https://github.com/Cyan4973/xxHash) — `common/xxhash.h`
- [tiny-AES-c](https://github.com/kokke/tiny-AES-c) — `common/aes.c`, `common/aes.h`
- [skCrypter](https://github.com/skadro-official/skCrypter) — `common/skCrypter.h`
- [cpp-httplib v0.14.3](https://github.com/yhirose/cpp-httplib) — `server/2015Remote/httplib.h`
## runtime / data
Shipped with the product or linked by the Linux/macOS builds.
- [OpenSSL](https://github.com/openssl/openssl) — Linux/macOS client TLS (`client/TlsChannelLinux.cpp`) and `libsign.a` HMAC; version follows the system/package OpenSSL 3.x
- [FRP (frpc / frps) v0.69.2-0.20260605064132-d58c00d0332c](https://github.com/fatedier/frp) — `Bin/res/frpc.dll`, `Bin/res/frps.dll`
- [ip2region (xdb v4)](https://github.com/lionsoul2014/ip2region) — `Bin/ip2region_v4.xdb`
- [QQWry / 纯真 IP 库](https://www.cz88.net/) — `Bin/qqwry.dat`
- Microsoft DirectX SDK headers — `client/d3d/`, included by `client/dxtrans.h` for legacy D3D texture formats; used under the DirectX SDK EULA, not open source
## server-go
`server/go/`, shipped as `Bin/YAMAGo_x64.exe`.
- [github.com/golang-jwt/jwt/v5 v5.3.1](https://github.com/golang-jwt/jwt)
- [github.com/gorilla/websocket v1.5.3](https://github.com/gorilla/websocket)
- [github.com/klauspost/compress v1.18.2](https://github.com/klauspost/compress)
- [github.com/rs/zerolog v1.34.0](https://github.com/rs/zerolog)
- [golang.org/x/sync v0.20.0](https://pkg.go.dev/golang.org/x/sync)
- [golang.org/x/text v0.32.0](https://pkg.go.dev/golang.org/x/text)
- [gopkg.in/natefinch/lumberjack.v2 v2.2.1](https://github.com/natefinch/lumberjack)
- indirect: [mattn/go-colorable v0.1.13](https://github.com/mattn/go-colorable), [mattn/go-isatty v0.0.19](https://github.com/mattn/go-isatty), [golang.org/x/sys v0.12.0](https://pkg.go.dev/golang.org/x/sys)
## android
`android/`, shipped as `Bin/ghost.apk`.
- [androidx.core:core-ktx 1.13.1](https://developer.android.com/jetpack/androidx/releases/core)
- [androidx.appcompat:appcompat 1.7.0](https://developer.android.com/jetpack/androidx/releases/appcompat)
- [Kotlin standard library 2.1.21](https://kotlinlang.org/)
## test
Build/test only, not shipped.
- [GoogleTest v1.14.0](https://github.com/google/googletest) — fetched via CMake `FetchContent`
## *Note*
The proper operation of the program depends on the above library files.
The proper operation of the program depends on the above library files.
Some libraries are not open source, please contact author for details.
These libraries are all compiled personally by the author and can be used with confidence.
These libraries are all compiled personally by the author and can be used with confidence.
If you use libraries from other sources, there may be compilation risks.
### Private libraries (not third-party)
`lib/` ships `FileUpload_Lib`, `PrivateDesktop_Lib` and `shrink` as prebuilt
binaries; `linux/lib/libsign.a`, `macos/lib/libsign.a` and
`android/.../lib/<abi>/libsign.a` are likewise the author's own. They are part
of the multi-layer licensing architecture and are **not** covered by the
open-source notices above.
### GPL note
`x264` is GPL-2.0 and `ffmpeg` is LGPL-2.1; both are linked **statically** on
Windows. `common/config.h` exposes `DISABLE_X264_FOR_TEST` and
`DISABLE_FFMPEG_FOR_TEST` (both default `0`, i.e. enabled) to build without
them. With `DISABLE_X264_FOR_TEST=1` neither the x264 library nor its headers
are needed — the whole `compress/x264/` directory can be deleted. The same
holds for `DISABLE_FFMPEG_FOR_TEST=1` and `compress/ffmpeg/`.
Binaries that include x264 are subject to GPL-2.0 unless covered by a
commercial x264 license.
**Important:** the bundled FFmpeg is a decode-only build (`--disable-encoders`,
see the configure line in `LICENSE-THIRD-PARTY.txt` section 19), so it provides
no encoder. x264 is therefore the product's *only* H.264 encoder, and
`DISABLE_X264_FOR_TEST=1` means no H.264 at all — the client falls back to raw
RGB565 frames. Keeping H.264 while staying GPL-free needs a different encoder
or a commercial x264 license. See `LICENSE-THIRD-PARTY.txt` for the full text
and the obligations that come with static LGPL linking.
+403 -25
View File
@@ -1,15 +1,15 @@
THIRD-PARTY SOFTWARE NOTICES AND LICENSES
This document contains intellectual property notices and license information for
This document contains intellectual property notices and license information for
third-party software components used in this product.
================================================================================
SUMMARY OF LICENSE TYPES
================================================================================
The third-party components included in this software are governed by the following
open-source licenses. For complete compliance, ensure that any modifications to
LGPL and MPL covered components are made available under their respective terms,
and this text file is distributed with your software product.
The third-party components included in this software are governed by the following
open-source licenses. For complete compliance, ensure that any modifications to
LGPL, MPL and GPL covered components are made available under their respective
terms, and this text file is distributed with your software product.
1. Zlib License
- zlib v1.3.2
@@ -18,16 +18,47 @@ and this text file is distributed with your software product.
- libyuv v190
- jpeg (libjpeg-turbo) v3.1.1
- opus-1.6.1
- GoogleTest v1.14.0
- github.com/klauspost/compress v1.18.2
- golang.org/x/sync, golang.org/x/text, golang.org/x/sys
3. BSD 2-Clause License
- libpeconv c7d1e48
- pe_to_shellcode
- dav1d 62501cc
- xxHash v0.8.3
- github.com/gorilla/websocket v1.5.3
4. MIT License
- jsoncpp v1.9.6
- sRDI
5. GNU Lesser General Public License v2.1 (LGPL v2.1)
- ffmpeg v7.1 (Compiled in shared, non-GPL mode)
6. Mozilla Public License v2.0 (MPL 2.0)
- libvpl v2.16.0
- KCP (ikcp)
- skCrypter
- cpp-httplib v0.14.3
- github.com/golang-jwt/jwt/v5 v5.3.1
- github.com/rs/zerolog v1.34.0
- gopkg.in/natefinch/lumberjack.v2 v2.2.1
- github.com/mattn/go-colorable v0.1.13
- github.com/mattn/go-isatty v0.0.19
5. The Unlicense (public domain dedication)
- tiny-AES-c
6. Apache License 2.0
- OpenSSL (Linux / macOS builds only)
- FRP (frpc.dll / frps.dll)
- ip2region (xdb v4)
- androidx.core:core-ktx 1.13.1
- androidx.appcompat:appcompat 1.7.0
- Kotlin standard library 2.1.21
7. GNU Lesser General Public License v2.1 (LGPL v2.1)
- ffmpeg v7.1 (statically linked, non-GPL build)
8. Mozilla Public License v2.0 (MPL 2.0)
- MemoryModule
9. GNU General Public License v2.0 (GPL v2.0)
- x264 v0.164.3194 (Windows builds only, opt-out available)
10. Custom terms
- QQWry / 纯真 IP database (qqwry.dat)
IMPORTANT: items 7 and 9 carry copyleft obligations. See the corresponding
sections at the end of this file before distributing a build.
================================================================================
1. zlib v1.3.2 (Zlib License)
@@ -217,7 +248,7 @@ The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
@@ -240,7 +271,7 @@ The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
@@ -248,32 +279,379 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================================================
9. ffmpeg v7.1 (GNU Lesser General Public License v2.1)
9. libvpl v2.16.0 (MIT License)
================================================================================
This software uses libraries from the FFmpeg project (v7.1), licensed under the
Copyright (c) 2021 Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================================================
10. dav1d 62501cc (BSD 2-Clause License)
================================================================================
Copyright (c) 2018-2024, VideoLAN and dav1d authors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
11. xxHash v0.8.3 (BSD 2-Clause License)
================================================================================
Copyright (c) 2012-2023 Yann Collet
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================================================
12. KCP / ikcp (MIT License)
================================================================================
Copyright (c) 2010-2011 skywind3000 (at) gmail.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================================================
13. skCrypter (MIT License)
================================================================================
Copyright (c) 2020 skadro
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================================================
14. cpp-httplib v0.14.3 (MIT License)
================================================================================
Copyright (c) 2023 Yuji Hirose. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================================================
15. tiny-AES-c (The Unlicense)
================================================================================
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
================================================================================
16. Go module dependencies (MIT / BSD)
================================================================================
The Go server (server/go, shipped as YAMAGo_x64.exe) depends on the following
modules. Each is distributed under the license noted next to it; the full text
of each license is available in the corresponding module repository.
github.com/golang-jwt/jwt/v5 v5.3.1 MIT
github.com/gorilla/websocket v1.5.3 BSD 2-Clause
github.com/klauspost/compress v1.18.2 BSD 3-Clause
github.com/rs/zerolog v1.34.0 MIT
golang.org/x/sync v0.20.0 BSD 3-Clause
golang.org/x/text v0.32.0 BSD 3-Clause
gopkg.in/natefinch/lumberjack.v2 v2.2.1 MIT
github.com/mattn/go-colorable v0.1.13 MIT (indirect)
github.com/mattn/go-isatty v0.0.19 MIT (indirect)
golang.org/x/sys v0.12.0 BSD 3-Clause (indirect)
MIT License text: see section 7 above.
BSD 2-Clause License text: see section 6 above.
BSD 3-Clause License text: see section 2 above.
================================================================================
17. GoogleTest v1.14.0 (BSD 3-Clause License)
================================================================================
Copyright 2008, Google Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Google Inc. nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
GoogleTest is used only to build and run the unit tests under test/; it is not
shipped with the product.
================================================================================
18. Apache License 2.0 components
================================================================================
The following components are licensed under the Apache License, Version 2.0
(https://www.apache.org/licenses/LICENSE-2.0). A copy of the license is
available at that URL and will be provided on request.
OpenSSL (Linux / macOS builds only)
Copyright (c) 1998-2024 The OpenSSL Project Authors
Used by the Linux/macOS client for TLS (client/TlsChannelLinux.cpp) and
by libsign.a for HMAC. OpenSSL 3.x is Apache-2.0; builds against OpenSSL
1.1.1 or earlier fall under the original OpenSSL/SSLeay license, which is
included with that distribution.
FRP (frpc / frps)
Copyright 2016-2024 fatedier, fatedier@gmail.com, and The FRP Authors
Bundled as Bin/res/frpc.dll and Bin/res/frps.dll.
Version: v0.69.2-0.20260605064132-d58c00d0332c (commit d58c00d0332c).
NOTE: the bundled binaries report a "+dirty" build, i.e. the FRP sources
were modified locally. Apache-2.0 section 4(b) requires modified files to
carry prominent notices stating that they were changed.
ip2region (xdb v4)
Copyright 2019-2024 lionsoul2014 and contributors
Data file: Bin/ip2region_v4.xdb
androidx.core:core-ktx 1.13.1
androidx.appcompat:appcompat 1.7.0
Copyright (C) 2005-2024 The Android Open Source Project
Used by the Android client (Bin/ghost.apk).
Kotlin standard library 2.1.21
Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language
contributors
Used by the Android client (Bin/ghost.apk).
================================================================================
19. ffmpeg v7.1 (GNU Lesser General Public License v2.1)
================================================================================
This software uses libraries from the FFmpeg project (v7.1), licensed under the
GNU Lesser General Public License (LGPL) version 2.1.
FFmpeg is a trademark of Fabrice Bellard, originator of the FFmpeg project.
Our product links to FFmpeg dynamically as a shared library (.dll/.so/.dylib)
and does NOT enable any GPL-licensed plugins (such as x264).
The FFmpeg libraries were built WITHOUT any GPL-licensed components, so the
FFmpeg binaries themselves are covered by LGPL v2.1 and not by the GPL. The
configure line embedded in libavutil is:
The source code of FFmpeg v7.1 can be obtained from the official FFmpeg
website (https://ffmpeg.org). If you require the exact build script and build
configuration used by our product to build the FFmpeg binary, please contact
our open-source compliance team.
--toolchain=msvc --arch=x86_64 --target-os=win64 --enable-static
--disable-shared --extra-cflags=-MT --extra-cxxflags=-MT --disable-everything
--disable-all --enable-avcodec --enable-avutil --enable-swresample
--enable-decoder=h264 --enable-decoder=aac --enable-decoder=aac_latm
--enable-decoder=pcm_s16le --enable-decoder=pcm_s16be --enable-decoder=pcm_f32le
--enable-parser=h264 --enable-parser=aac --enable-parser=aac_latm
--disable-iconv --disable-zlib --disable-bzlib --disable-lzma --disable-sdl2
--disable-doc --disable-programs --disable-network --disable-encoders
--disable-muxers --disable-demuxers --disable-filters --disable-devices
--disable-bsfs --disable-debug --enable-small --prefix=./install-win64
Note that this build is DECODE ONLY (--disable-encoders): it provides the
H.264/AAC/PCM decoders used to display remote screens, and contains no
encoder of any kind. The hardware-encoder paths in the client therefore cannot
be satisfied by these libraries, and software H.264 encoding is provided
exclusively by x264 (section 21).
HOW IT IS LINKED: on Windows the FFmpeg libraries (libavcodec, libavutil,
libswresample) are linked STATICALLY into the client and server executables
(see the #pragma comment(lib, "ffmpeg/...") directives in
client/CFFmpegH264Encoder.cpp, client/CFFmpegAV1Encoder.cpp and
server/2015Remote/ScreenSpyDlg.h). No FFmpeg DLL is shipped.
Because the linking is static, LGPL v2.1 section 6 applies: recipients are
entitled to modify FFmpeg and relink it with this product. To satisfy that,
the following are available on request from the author:
- the exact FFmpeg build scripts and configuration used (quoted above);
- the object files of the product sufficient to relink it against a
modified FFmpeg.
To build without FFmpeg entirely, set DISABLE_FFMPEG_FOR_TEST to 1 in
common/config.h; the encoder implementations and the FFmpeg include paths are
then removed from the build, and the compress/ffmpeg/ directory is no longer
needed at all.
The source code of FFmpeg v7.1 can be obtained from the official FFmpeg
website (https://ffmpeg.org).
================================================================================
10. MemoryModule (Mozilla Public License v2.0)
20. MemoryModule (Mozilla Public License v2.0)
================================================================================
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at
http://mozilla.org/MPL/2.0/.
MemoryModule is Copyright (c) Joachim Bauch.
Under the terms of the MPL 2.0, you may distribute this component as part of
your commercial/proprietary application without being required to open-source
Under the terms of the MPL 2.0, you may distribute this component as part of
your commercial/proprietary application without being required to open-source
your own proprietary code, provided that:
1. MemoryModule source files remain unmodified, or if modified, those modifications
1. MemoryModule source files remain unmodified, or if modified, those modifications
are made available under the MPL 2.0.
2. Users are informed that MemoryModule is used and where they can find its source.
2. Users are informed that MemoryModule is used and where they can find its source.
================================================================================
21. x264 v0.164.3194 (GNU General Public License v2.0)
================================================================================
The Windows build links libx264 statically for software H.264 encoding, used as
the CPU fallback when hardware encoders are unavailable (see
client/X264Encoder.cpp, client/EncoderFactory.h).
x264 is Copyright (C) 2003-2024 x264 project (Laurent Aimar, Loren Merritt,
Fiona Glaser, Jason Garrett-Glaser, Steven Walters and contributors) and is
licensed under the GNU General Public License version 2.0, not the LGPL.
Commercial licenses for x264 are available from x264 LLC
(https://www.x264licensing.com).
CONSEQUENCE: a binary that statically links x264 is, as a whole, a work
covered by the GPL v2.0 and must be distributed under GPL v2.0 terms
(accompanying complete corresponding source code, or a written offer valid for
three years), unless it is covered by a commercial x264 license.
To build without x264, set DISABLE_X264_FOR_TEST to 1 in common/config.h. The
x264 header is then no longer included and libx264 is no longer linked, so a
compliant build needs neither the x264 library nor its headers; the
compress/x264/ directory can be deleted outright.
IMPORTANT CONSEQUENCE: because the bundled FFmpeg is a decode-only build (see
section 19), x264 is the ONLY H.264 encoder in the product. A build with
DISABLE_X264_FOR_TEST=1 therefore has no H.264 encoder at all, and the client
falls back to raw RGB565 frames (client/ScreenCapture.h). Keeping H.264 while
staying GPL-free requires replacing x264 with an LGPL-compatible or licensed
encoder, or obtaining a commercial x264 license.
The text of the GPL v2.0 is available at https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
and is provided with any binary that includes x264.
================================================================================
22. QQWry / 纯真 IP database (custom terms)
================================================================================
Bin/qqwry.dat is the QQWry (纯真) IP geolocation database, published by
cz88.net (https://www.cz88.net/). It is not open source and is not covered by
any of the licenses above. The publisher's terms permit free use for
non-commercial purposes; redistribution inside a commercial product requires
the publisher's permission.
The product does not require this file. IP geolocation is selected at runtime
by the settings key settings/IPLocType: 1 uses qqwry.dat, 2 uses the ip2region
database (Bin/ip2region_v4.xdb, Apache-2.0). If the selected database cannot be
loaded, the server logs "IP数据库加载: failed" and falls back to a built-in
converter that returns no location, so shipping without qqwry.dat is supported
as long as IPLocType is set to 2.
================================================================================
END OF NOTICES
================================================================================
+61 -1
View File
@@ -378,6 +378,66 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
## 更新日志
### v1.4.2 (2026.10.31)
**MCP 运维套件 & WebSocket 传输 & 抓屏健壮性**
**新功能:**
- **MCP 工具集 27 → 60**:新增主机 / 连接 / 服务 / 计划任务管理(16 个,写操作执行前后复核,受 McpMachine / McpMachineDangerous 双开关)、远程交谈(4 个,McpChat)、文件系统写操作 delete_path / move_path / create_folder(McpFileWrite)、remote_block_input(带截止时间与看门狗)、copy_files_c2c(客户端间直传,服务端只中继)、search_file、get_server_status、get_keylog 扩展、mcp_list_sessions / mcp_cancel_session;离线主机查询、批量只读调用(ids ≤ 50)、列表过滤器与分页
- **MCP 协议**:initialize instructions、能力上报(platform / remoteControl / fileTransferV2 / c2cPaths / registry 等)、工具注解(readOnly / destructive / idempotent / openWorld)、结构化结果二次文本块、通知取消(-32800)与 progress 进度、dry-run 预演、客户端结构化失败令牌(170–173:失败与空结果可区分)、错误码收敛(参数错误 -32012、写入失败 -32011)、超时经 `McpToolTimeoutMs` 可调
- **MCP 端点**:内置 HTTPS(Schannel 同端口按首字节嗅探,RSA / ECDSA、支持 fullchain、不可用时 fail-closed)、请求体 2 MB 上限、Bearer 失败按源 IP 限流(1 分钟 10 次封 15 分钟)、`logs\mcp_audit.log` 审计
- **WebSocket 传输**:新增 PROTO_WS(5) / PROTO_WSS(6),升级路径 `/api/ws`,仅放行 80/443 的网络也能接入;MFC 与 Go 服务端同一设备端口三路嗅探(明文 / TLS / WS);在线列表右键「协议切换」把已在线客户端在 直连 TCP / WS / WSS 之间远程切换(COMMAND_SET_PROTO 177,WSS 下发反代信任锚,5 分钟未登录自动回退)
- **Windows 抓屏健壮性**:旋转显示器按真实纹理描述分配并直立图像(原首屏与每帧全黑)、DXGI 无帧自动切 GDI(无头 / Session 0)、工作站锁定与断开会话直接选 GDI(避免初始化卡死)、探测帧保留以便静态桌面首帧即出图、发送尺寸改为长边 ≤1920 / 短边 ≤1080 等比缩放
- **Web 控制台**:非控制模式显示真实远端光标(形状变化即时、位置 ≤50 ms/次);iOS 幽灵竖线(画布固定 + `ctx.setTransform` 绘制);竖屏输入法下指针与画面错位(覆盖层与画布同包含块、坐标用画布局部像素);输入条固定在画面下沿不再随键盘跳动;Go 端滚轮小数 delta 导致彻底失灵
- **Linux / macOS 客户端能力补齐**:MCP 一级工具(kill_process / exec_command / 终端 / 远控 / 剪贴板)支持 Linux、文件上传下载与 C2C 目标支持 POSIX、Linux 远程升级(COMMAND_UPDATE 校验 + 原子替换 + execv 回滚)、TLS 切换立即生效、屏幕预览(服务端统一转 JPEG)、桌面 / 下载 / 主目录快捷方式按 `user-dirs.dirs` 展开、运行时长按北京时间换算
- **客户端与主控**:在线列表右键「复制名称」、高级菜单与免责声明补 16×16 图标、SOCKS5 代理映射移除 HP-Socket 依赖并重写(阻塞 socket + select、仅绑回环、SOCKS5 握手按字节流解析、按主连接队列背压、30 秒握手看门狗)
**改进:**
- 依赖清单扩充至 23 项 / LICENSE-THIRD-PARTY 至 657 行(10 类许可证、33 项组件),并更正 x264(GPL-2.0 静态链接)、FFmpeg(静态链接、仅解码)、FRP(本地修改)三处
- `DISABLE_X264_FOR_TEST` 真正生效(此前既没前置 config.h 也仍引用 x264 类型),libyuv 从该开关解绑
- `build.ps1` 按 `atlmfc` 库存在与否挑选 MSBuild 实例(修复挑到无 ATL 的 BuildTools 时 `LNK1104 atls.lib`)
- 协议切换、SOCKS5 会话日志、复制名称、MCP 新开关等字符串补齐 en_US / zh_TW / de_DE
**Bug 修复:**
- 主控重启后客户端重连空转(一秒 919 行重复日志刷爆环形缓冲)
- 右键菜单作用于错误主机(虚拟列表行号在菜单模态循环期间被排序 / 下线挪动)
- 构建对话框默认协议错位(`CBS_SORT` + `AddString` 致 `SetCurSel(0)` 落在 HTTP)
- 在线列表表头偶发闪烁(缺 `WS_CLIPCHILDREN`,改为只擦最后一列右侧空带)
- 加壳客户端收不到即时消息 / 远程交谈对话框创建失败(资源段为空,改内嵌模板)、非 936 系统标题与正文乱码、多显示器居中偏移、窗口与线程泄漏
- 键盘记录饿死快捷键转发(钩子线程不泵消息被系统摘除)
- 锁定聊天时 Win 键不转发(未 `CallNextHookEx` 挡住后续钩子)
- 聊天消息以 e 开头被丢弃(首个字节 101 被心跳守卫吞掉)
- 文件搜索栈溢出(`wsprintf` 无界拼 MAX_PATH,深目录必崩)
- 空目录下载超时;文件传输会话子连接悬空指针(超时后 `CancelIO` 到已回收连接)
- 连接列表地址反序(`192.168.0.55` → `55.0.168.192`)与宽窄字符格式化塌缩
- macOS 合盖外接屏鼠标偏移(取被抓显示器的 `CGDisplayBounds`,另加按主机保存的校准)
- 任务与机器管理一批缺陷(计划任务命令组装、解冻只恢复一个线程、窗口列表空指针、服务枚举句柄泄漏、删除进程 PID 判断与句柄、IE 历史时间戳翻转等)
### v1.4.1 (2026.10.20)
**Web 运维控制台 & 安全加固 & 单向 TLS**
**新功能:**
- **Web 屏幕墙**:同一标签页以 1×1 ~ 5×5 布局同时监控多台设备,桌面 9 路 / 触控 4 路实时解码,超出预算暂停并自动晋升;点击 tile 进入单画面控制;同一设备可重复添加并共享一路流;MFC 与 Go 服务端同步支持(旧前端 / 旧服务端自动降级)
- **安全审计日志**:登录 / 授权拒绝 / WS 生命周期 / 屏幕与终端会话 / 剪贴板(仅字节数)/ 设备认证 / 管理变更;Go 端持久化 `logs/audit.log`,MFC 端保留最近 1000 条内存环形缓冲;Web 新增审计日志查询页(时间 / 事件 / 操作者 / IP / 设备 / 关键字 / 告警过滤 + 分页)
- **离线设备历史(Go)**:`devices.json` 持久化所有登录过的设备,设备列表可按需显示离线记录;管理员可删除记录或对在线设备执行远程卸载
- **单向 TLS 传输**:设备端口同一端口嗅探 ClientHello,TLS 1.2 客户端加密、旧明文客户端不受影响;MFC「扩展 > TLS证书」运行时配置;在线列表新增 TLS 列,右键可远程启用 / 取消(客户端下次启动生效)
- **Web 远程桌面增强**:Ctrl+C/X/V 双向文本剪贴板同步、手机「I」输入框(经剪贴板桥注入)、登录会话跨标签页共享、管理员 SSO 桥接
- **客户端安装位置选择**:ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
- **Go Web UI 白标**:`YAMA_WEB_BRAND_NAME` 替换产品名并移除安全提示与外链
- **安全加固**:每 IP 连接与登录限流、单连接入站缓冲上限、屏幕 / 终端子连接绑定源 IP、可选 ConnAuth HMAC 校验
- **克隆机 ID 去重**:V2 `client_id` 折叠主机名,撞 ID 时服务端下发 `COMMAND_REGEN_CLIENT_ID` 让客户端重算重连
**改进:**
- 文件传输速度改由 MasterSettings 下发(修复重复弹窗),传输对话框标题实时显示速度
- 客户端聊天关闭仅隐藏;日志右键新增白名单;MCP 勾选即时刷新;Web 原生 alert/confirm 全部替换为主题化应用内对话框
- 非中文系统统一按 GBK / UTF-8 解码(对话框 / 进程列表 / 文件列表 / 路径 / 地理位置 / 主机管理 / 剪贴板)
**Bug 修复:**
- 共享 / 转移主机后重启主控不重连;分享 / 转移权限误判
- 已过期授权续期从今天起算,提示与日志显示实际到期日
- V2 上传快捷目录未展开 `%USERPROFILE%`;无摄像头主机发送 0×0 画面信息;列切换残留像素;Go 设备端口日志刷屏;审计页最小化后跳回设备页
### v1.4.0 (2026.10.7)
**SimplePlugins 功能迁移 & 远程交互增强 & MCP 扩展 & 国际化**
@@ -390,7 +450,7 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
- **主机管理**:迁移 CMachineManager(进程 / 窗口 / 网络 / 软件 / IE 历史 / 收藏夹 / 服务 / 任务 / hosts 枚举 + 进程注入),COMMAND_MACHINE_MANAGE 162
- **授权失败触发器**:新增 TRIGGER_AUTH_FAILED 触发类型(与主机上线触发独立),授权失败时下发插件 DLL,受 ShouldLogAuth 去重约束
- **iPhone 远程音频**:WebAudio + 自托管 opus-decoder WASM 解码,修复 iOS 无 MSE 静音
- **画质与传输控制**:远程桌面 / 屏幕预览质量等级菜单(各 6 档可配置)+ 文件传输速度对话框(7 档 + 无限档,CMD_FILE_SPEED 252)
- **画质与传输控制**:远程桌面 / 屏幕预览质量等级菜单(各 6 档可配置)+ 文件传输速度对话框(7 档 + 无限档,经 MasterSettings 下发)
- **Shine/HELL 协议选择**:分享 / 传输主机时可选协议,尾随冒号字段透传,旧客户端兼容
- **Go Web UI 子路径部署**:YAMA_WEB_BASE_PATH 挂载整个 Web UI 到 URL 前缀
- **国际化**:德语(de_DE)第 4 种语言、语言切换工具栏按钮、剩余字符串翻译补齐;远程桌面剪贴板按钮(全屏可达)
+61 -1
View File
@@ -378,6 +378,66 @@ Valid : 2026-02-01 to 2028-02-01
## Changelog
### v1.4.2 (2026.10.31)
**MCP operations suite & WebSocket transport & capture robustness**
**New features:**
- **MCP tool count grew from 27 to 60**: host / connection / service / scheduled-task management (16 tools, writes re-read state before and re-verify after, gated by both McpMachine and McpMachineDangerous), remote chat (4 tools, McpChat), filesystem writes delete_path / move_path / create_folder (McpFileWrite), remote_block_input (with a deadline and a watchdog), copy_files_c2c (client-to-client delivery relayed without touching server disk), search_file, an extended get_keylog, get_server_status, mcp_list_sessions / mcp_cancel_session; offline-host queries, batched read-only calls (ids up to 50), list filters and paging
- **MCP protocol**: initialize instructions, capability reporting (platform / remoteControl / fileTransferV2 / c2cPaths / registry and more), tool annotations (readOnly / destructive / idempotent / openWorld), a second text block carrying the structured result, notification-based cancellation (-32800) and progress, dry-run previews, structured client failure tokens (170-173, so failure is distinguishable from an empty result), consolidated error codes (parameter errors -32012, write failures -32011), and a tunable timeout via `McpToolTimeoutMs`
- **MCP endpoint**: built-in HTTPS (Schannel sniffing on the same port, RSA / ECDSA, fullchain support, fail-closed when the certificate is unusable), a 2 MB request-body cap, per-source-IP rate limiting of Bearer failures (10 in a minute blocks for 15 minutes), and an audit trail in `logs\mcp_audit.log`
- **WebSocket transport**: new PROTO_WS(5) / PROTO_WSS(6) with upgrade path `/api/ws`, so clients on networks that only allow 80/443 can connect; both MFC and Go servers sniff plaintext / TLS / WS on the same device port; a new "Protocol switch" context-menu action moves an already-online client between direct TCP / WS / WSS (COMMAND_SET_PROTO 177, WSS carries the reverse-proxy trust anchor, automatic rollback if login does not succeed within 5 minutes)
- **Windows capture robustness**: rotated displays allocate by the real texture description and orient the image (previously fully black first and every frame), DXGI falls back to GDI when no frame arrives (headless / Session 0), locked workstations and disconnected sessions select GDI up front (avoiding a stuck initialisation), the probe frame is kept so a static desktop paints on first connect, and the send size is scaled proportionally to long edge <= 1920 / short edge <= 1080
- **Web console**: the real remote cursor is shown outside control mode (shape changes immediately, position at most every 50 ms); iOS ghost vertical lines (canvas pinned, drawn with `ctx.setTransform`); pointer misalignment with the IME open in portrait (overlay shares the canvas containing block and uses canvas-local pixels); the input bar sits at the bottom of the picture instead of following the keyboard; fractional wheel deltas on the Go server no longer break scrolling entirely
- **Linux / macOS client parity**: MCP tier-one tools (kill_process / exec_command / terminal / remote control / clipboard) now accept Linux hosts; upload, download and C2C targets support POSIX paths; Linux remote upgrade (COMMAND_UPDATE with verification, atomic replace and execv rollback); TLS switches take effect immediately; screen preview (the server converts to JPEG in one place); Desktop / Downloads / Home shortcuts expand through `user-dirs.dirs`; uptime is converted from Beijing time
- **Client and master**: "Copy name" in the online-list context menu; 16x16 icons for the advanced menu and the disclaimer item; the SOCKS5 proxy mapping drops the HP-Socket dependency and is rewritten (blocking socket + select, byte-level SOCKS5 parsing, back-pressure against the master send queue, 30-second handshake watchdog)
**Improvements:**
- The dependency inventory grew to 23 items and LICENSE-THIRD-PARTY to 657 lines (10 license classes, 33 components), with corrections for x264 (GPL-2.0, statically linked), FFmpeg (static, decoders only) and FRP (locally modified)
- `DISABLE_X264_FOR_TEST` now actually works (config.h was not included first and the class still referenced x264 types), and libyuv is no longer tied to that switch
- `build.ps1` picks the MSBuild instance that has the `atlmfc` libraries, fixing `LNK1104 atls.lib` when a BuildTools install without ATL was chosen first
- Strings added by protocol switching, SOCKS5 session logging, "Copy name" and the new MCP switches are translated in en_US / zh_TW / de_DE
**Bug fixes:**
- Clients spun in a reconnect loop after a master restart (919 identical log lines per second flushed the 1000-line ring buffer)
- The context menu could act on the wrong host (virtual-list row indices shift while the menu's modal loop keeps dispatching timers)
- The build dialog defaulted to the wrong protocol (`CBS_SORT` plus `AddString` made `SetCurSel(0)` land on HTTP)
- Occasional header flicker in the online list (missing `WS_CLIPCHILDREN`; erasure now limited to the empty band right of the last column)
- Packed clients never showed instant messages / could not create the chat dialog (empty resource section, now an embedded template), with garbled titles and text on non-936 systems, off-centre placement on multi-monitor hosts, and window and thread leaks
- The keylogger hook starved hotkey forwarding (its thread never pumped messages and Windows removed the hook)
- Win-key forwarding stopped while chat was locked (`CallNextHookEx` was skipped, shadowing later hooks)
- Chat messages starting with "e" were dropped (byte 101 was swallowed by the heartbeat guard)
- Stack overflow in recursive file search (`wsprintf` into a `MAX_PATH` buffer with no bound)
- Downloading an empty directory timed out; file-transfer sessions kept dangling sub-connection pointers (`CancelIO` against a recycled connection after a timeout)
- Connection-list addresses were byte-reversed (`192.168.0.55` shown as `55.0.168.192`) and collapsed by a mixed wide/narrow format string
- macOS mouse offset in clamshell mode (now uses the captured display's `CGDisplayBounds`, plus a per-host calibration)
- A batch of machine and task-management defects (scheduled-task command assembly, thawing only one thread, a null dereference on an empty window list, leaked service-enumeration handles, PID truncation and handle leaks when deleting processes, flipped IE history timestamps)
### v1.4.1 (2026.10.20)
**Web operations console & security hardening & one-way TLS**
**New features:**
- **Web screen wall**: monitor several devices in one tab with 1x1 to 5x5 layouts; desktop decodes up to 9 live streams and touch devices 4, tiles over budget show Paused and are promoted automatically; click a tile for single-screen control; the same device can be added repeatedly and shares one stream; supported by both the MFC and Go servers (old frontends / old servers degrade automatically)
- **Security audit log**: login attempts, authorization denials, WebSocket lifecycle, screen / terminal sessions, clipboard (byte counts only), device authentication and admin mutations; the Go server persists to `logs/audit.log`, the MFC server keeps the newest 1000 events in an in-memory ring; new Audit Log page with time / event / actor / IP / device / keyword / warn filters and paging
- **Offline device history (Go)**: `devices.json` persists every device that has ever logged in, and the device list can show offline records; admins can delete a record or remotely uninstall an online device
- **One-way TLS transport**: the device port sniffs ClientHello on the same port, so TLS 1.2 clients are encrypted while legacy plaintext clients keep working; "Extensions > TLS Certificate" configures the MFC server at runtime; a TLS column and a per-client remote enable / disable action (effective on the client's next start)
- **Web remote desktop enhancements**: bidirectional Ctrl+C/X/V text clipboard sync, a phone "I" input box that injects text through the clipboard bridge, login sessions shared across tabs, and an admin-only SSO bridge
- **Client install location**: ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
- **White-label Go web UI**: `YAMA_WEB_BRAND_NAME` replaces the product name and removes the security notice and external links
- **Security hardening**: per-IP connection and login rate limits, a per-connection inbound buffer cap, source-IP binding for screen / terminal sub-connections, and optional ConnAuth HMAC verification
- **Clone ID deduplication**: the V2 `client_id` folds in the hostname; on a collision the server sends `COMMAND_REGEN_CLIENT_ID` so the client recomputes and reconnects
**Improvements:**
- File-transfer speed is delivered via MasterSettings (fixes duplicate dialogs), and the transfer dialog title shows live speed
- Closing the client chat now hides it; whitelist action in the log context menu; MCP checkmark refreshes immediately; native browser alert/confirm replaced with themed in-app dialogs
- GBK / UTF-8 decoding across non-Chinese systems (dialogs, process list, file lists, paths, geolocation, machine management, clipboard)
**Bug fixes:**
- Hosts did not reconnect after a master restart following share / transfer; share / transfer permission misjudgment
- Expired licenses now renew from today, and prompts and logs show the actually issued date
- V2 quick-folder uploads did not expand `%USERPROFILE%`; webcam-less hosts sent 0x0 bitmap info; stale pixels after column toggles; Go device-port log flood; audit page reset after minimizing the browser
### v1.4.0 (2026.10.7)
**SimplePlugins Feature Migration & Remote Interaction Enhancements & MCP Expansion & i18n**
@@ -390,7 +450,7 @@ Valid : 2026-02-01 to 2028-02-01
- **Machine management**: CMachineManager migrated (process / window / network / software / IE history / favorites / service / task / hosts enumeration plus process injection), COMMAND_MACHINE_MANAGE 162
- **Auth-failed trigger**: new TRIGGER_AUTH_FAILED type (independent of the host-online trigger) pushes plugin DLLs on authorization failure, gated by ShouldLogAuth dedup
- **iPhone remote audio**: Web Audio API + self-hosted opus-decoder WASM decoding fixes silent audio on iOS without MSE
- **Quality & transfer controls**: configurable remote-desktop / screen-preview quality-level menus (six presets each) plus a file-transfer speed dialog (seven presets + unlimited, CMD_FILE_SPEED 252)
- **Quality & transfer controls**: configurable remote-desktop / screen-preview quality-level menus (six presets each) plus a file-transfer speed dialog (seven presets + unlimited, delivered via MasterSettings)
- **Shine/HELL protocol selection**: choose the protocol when sharing / transferring a host, passed as a trailing colon field, backward compatible
- **Go web UI subpath deployment**: YAMA_WEB_BASE_PATH mounts the whole web UI under a URL prefix
- **i18n**: German (de_DE) as the fourth language, a language-switch toolbar button, remaining string translations; remote-desktop clipboard buttons (reachable in fullscreen)
+61 -1
View File
@@ -378,6 +378,66 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
## 更新日誌
### v1.4.2 (2026.10.31)
**MCP 維運套件 & WebSocket 傳輸 & 擷取畫面健壯性**
**新功能:**
- **MCP 工具集 27 → 60**:新增主機 / 連線 / 服務 / 排程工作管理(16 個,寫入操作執行前後複核,受 McpMachine / McpMachineDangerous 雙開關)、遠端交談(4 個,McpChat)、檔案系統寫入 delete_path / move_path / create_folder(McpFileWrite)、remote_block_input(帶截止時間與看門狗)、copy_files_c2c(用戶端間直傳,伺服端只中繼不落地)、search_file、get_keylog 擴充、get_server_status、mcp_list_sessions / mcp_cancel_session;離線主機查詢、批次唯讀呼叫(ids ≤ 50)、列表過濾與分頁
- **MCP 協定**:initialize instructions、能力上報(platform / remoteControl / fileTransferV2 / c2cPaths / registry 等)、工具註解(readOnly / destructive / idempotent / openWorld)、結構化結果二次文字區塊、通知取消(-32800)與 progress 進度、dry-run 預演、用戶端結構化失敗權杖(170–173,失敗與空結果可區分)、錯誤碼收斂(參數錯誤 -32012、寫入失敗 -32011)、逾時可經 `McpToolTimeoutMs` 調整
- **MCP 端點**:內建 HTTPS(Schannel 同連接埠依首位元組嗅探,RSA / ECDSA、支援 fullchain、不可用時 fail-closed)、請求本文 2 MB 上限、Bearer 失敗依來源 IP 限流(1 分鐘 10 次封 15 分鐘)、`logs\mcp_audit.log` 稽核
- **WebSocket 傳輸**:新增 PROTO_WS(5) / PROTO_WSS(6),升級路徑 `/api/ws`,只放行 80/443 的網路也能接入;MFC 與 Go 伺服端同一裝置連接埠三路嗅探(明文 / TLS / WS);線上列表右鍵「協定切換」把已線上用戶端在 直連 TCP / WS / WSS 之間遠端切換(COMMAND_SET_PROTO 177,WSS 下發反代信任錨,5 分鐘未登入自動回退)
- **Windows 擷取畫面健壯性**:旋轉顯示器依真實紋理描述配置並直立影像(原首屏與每幀全黑)、DXGI 無幀自動切 GDI(無頭 / Session 0)、工作站鎖定與中斷工作階段直接選 GDI(避免初始化卡死)、保留探測幀讓靜態桌面首幀即出圖、傳送尺寸改為長邊 ≤1920 / 短邊 ≤1080 等比縮放
- **Web 控制台**:非控制模式顯示真實遠端游標(形狀變化即時、位置 ≤50 ms/次);iOS 幽靈豎線(畫布固定 + `ctx.setTransform` 繪製);豎屏輸入法下指標與畫面錯位(覆蓋層與畫布同包含區塊、座標用畫布局部像素);輸入列固定在畫面下緣不再隨鍵盤跳動;Go 端滾輪小數 delta 導致徹底失靈
- **Linux / macOS 用戶端能力補齊**:MCP 一級工具(kill_process / exec_command / 終端 / 遠控 / 剪貼簿)支援 Linux、檔案上傳下載與 C2C 目標支援 POSIX、Linux 遠端升級(COMMAND_UPDATE 校驗 + 原子替換 + execv 回退)、TLS 切換立即生效、螢幕預覽(伺服端統一轉 JPEG)、桌面 / 下載 / 主目錄捷徑依 `user-dirs.dirs` 展開、執行時間依北京時間換算
- **用戶端與主控**:線上列表右鍵「複製名稱」、進階選單與免責聲明補 16×16 圖示、SOCKS5 代理映射移除 HP-Socket 依賴並重寫(阻塞 socket + select、位元組級 SOCKS5 解析、依主連線佇列背壓、30 秒握手看門狗)
**改進:**
- 依賴清單擴充至 23 項 / LICENSE-THIRD-PARTY 至 657 行(10 類授權、33 項元件),並更正 x264(GPL-2.0 靜態連結)、FFmpeg(靜態連結、僅解碼)、FRP(本機修改)三處
- `DISABLE_X264_FOR_TEST` 真正生效(先前既未前置 config.h 也仍引用 x264 型別),libyuv 從該開關解綁
- `build.ps1` 依 `atlmfc` 函式庫存在與否挑選 MSBuild 實例(修復挑到無 ATL 的 BuildTools 時 `LNK1104 atls.lib`)
- 協定切換、SOCKS5 工作階段日誌、複製名稱、MCP 新開關等字串補齊 en_US / zh_TW / de_DE
**Bug 修復:**
- 主控重啟後用戶端重連空轉(一秒 919 行重複日誌刷爆環形緩衝)
- 右鍵選單作用於錯誤主機(虛擬列表列號在選單模態迴圈期間被排序 / 離線挪動)
- 建置對話框預設協定錯位(`CBS_SORT` + `AddString` 致 `SetCurSel(0)` 落在 HTTP)
- 線上列表表頭偶發閃爍(缺 `WS_CLIPCHILDREN`,改為只擦最後一欄右側空帶)
- 加殼用戶端收不到即時訊息 / 遠端交談對話框建立失敗(資源區段為空,改內嵌模板)、非 936 系統標題與本文亂碼、多螢幕居中偏移、視窗與執行緒洩漏
- 鍵盤記錄餓死快速鍵轉發(掛鉤執行緒不泵訊息被系統摘除)
- 鎖定聊天時 Win 鍵不轉發(未 `CallNextHookEx` 擋住後續掛鉤)
- 聊天訊息以 e 開頭被丟棄(首位元組 101 被心跳守衛吞掉)
- 檔案搜尋堆疊溢位(`wsprintf` 無界拼 MAX_PATH,深目錄必崩)
- 空目錄下載逾時;檔案傳輸工作階段子連線懸空指標(逾時後 `CancelIO` 到已回收連線)
- 連線列表位址反序(`192.168.0.55` → `55.0.168.192`)與寬窄字元格式化塌縮
- macOS 合蓋外接螢幕滑鼠偏移(取被抓螢幕的 `CGDisplayBounds`,另加依主機儲存的校準)
- 工作與機器管理一批缺陷(排程工作命令組裝、解凍只恢復一個執行緒、視窗列表空指標、服務列舉控制代碼洩漏、刪除處理程序 PID 判斷與控制代碼、IE 歷程時間戳翻轉等)
### v1.4.1 (2026.10.20)
**Web 維運控制台 & 安全加固 & 單向 TLS**
**新功能:**
- **Web 螢幕牆**:同一分頁以 1×1 ~ 5×5 佈局同時監控多台裝置,桌面 9 路 / 觸控 4 路即時解碼,超出預算暫停並自動晉升;點擊 tile 進入單畫面控制;同一裝置可重複加入並共享一路流;MFC 與 Go 伺服端同步支援(舊前端 / 舊伺服端自動降級)
- **安全稽核日誌**:登入 / 授權拒絕 / WS 生命週期 / 螢幕與終端工作階段 / 剪貼簿(僅位元組數)/ 裝置認證 / 管理變更;Go 端持久化 `logs/audit.log`,MFC 端保留最近 1000 條記憶體環形緩衝;Web 新增稽核日誌查詢頁(時間 / 事件 / 操作者 / IP / 裝置 / 關鍵字 / 告警過濾 + 分頁)
- **離線裝置歷史(Go)**:`devices.json` 持久化所有登入過的裝置,裝置列表可依需顯示離線記錄;管理員可刪除記錄或對線上裝置執行遠端解除安裝
- **單向 TLS 傳輸**:裝置連接埠同一連接埠嗅探 ClientHello,TLS 1.2 用戶端加密、舊明文用戶端不受影響;MFC「擴充 > TLS憑證」執行時設定;線上列表新增 TLS 欄,右鍵可遠端啟用 / 取消(用戶端下次啟動生效)
- **Web 遠端桌面增強**:Ctrl+C/X/V 雙向文字剪貼簿同步、手機「I」輸入框(經剪貼簿橋注入)、登入工作階段跨分頁共享、管理員 SSO 橋接
- **用戶端安裝位置選擇**:ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
- **Go Web UI 白標**:`YAMA_WEB_BRAND_NAME` 取代產品名稱並移除安全提示與外部連結
- **安全加固**:每 IP 連線與登入限流、單連線入站緩衝上限、螢幕 / 終端子連線綁定來源 IP、可選 ConnAuth HMAC 校驗
- **複製機 ID 去重**:V2 `client_id` 納入主機名稱,撞 ID 時伺服端下發 `COMMAND_REGEN_CLIENT_ID` 讓用戶端重算重連
**改進:**
- 檔案傳輸速度改由 MasterSettings 下發(修復重複彈窗),傳輸對話框標題即時顯示速度
- 用戶端聊天關閉僅隱藏;日誌右鍵新增白名單;MCP 勾選即時重新整理;Web 原生 alert/confirm 全部替換為主題化應用內對話框
- 非中文系統統一按 GBK / UTF-8 解碼(對話框 / 處理程序列表 / 檔案列表 / 路徑 / 地理位置 / 主機管理 / 剪貼簿)
**Bug 修復:**
- 分享 / 轉移主機後重啟主控不重連;分享 / 轉移權限誤判
- 已過期授權續期從今天起算,提示與日誌顯示實際到期日
- V2 上傳快捷目錄未展開 `%USERPROFILE%`;無攝影機主機傳送 0×0 畫面資訊;欄切換殘留像素;Go 裝置連接埠日誌刷屏;稽核頁最小化後跳回裝置頁
### v1.4.0 (2026.10.7)
**SimplePlugins 功能遷移 & 遠端互動增強 & MCP 擴充 & 國際化**
@@ -390,7 +450,7 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
- **主機管理**:遷移 CMachineManager(處理程序 / 視窗 / 網路 / 軟體 / IE 歷史 / 收藏夾 / 服務 / 排程工作 / hosts 列舉 + 處理程序注入),COMMAND_MACHINE_MANAGE 162
- **授權失敗觸發器**:新增 TRIGGER_AUTH_FAILED 觸發類型(與主機上線觸發獨立),授權失敗時下發外掛程式 DLL,受 ShouldLogAuth 去重約束
- **iPhone 遠端音訊**:WebAudio + 自託管 opus-decoder WASM 解碼,修復 iOS 無 MSE 靜音
- **品質與傳輸控制**:遠端桌面 / 螢幕預覽品質等級選單(各 6 檔可設定)+ 檔案傳輸速度對話框(7 檔 + 無限檔,CMD_FILE_SPEED 252)
- **品質與傳輸控制**:遠端桌面 / 螢幕預覽品質等級選單(各 6 檔可設定)+ 檔案傳輸速度對話框(7 檔 + 無限檔,經 MasterSettings 下發)
- **Shine/HELL 協定選擇**:分享 / 傳輸主機時可選協定,尾隨冒號欄位透傳,舊用戶端相容
- **Go Web UI 子路徑部署**:YAMA_WEB_BASE_PATH 掛載整個 Web UI 到 URL 前綴
- **國際化**:德語(de_DE)第 4 種語言、語言切換工具列按鈕、剩餘字串翻譯補齊;遠端桌面剪貼簿按鈕(全螢幕可達)
+2
View File
@@ -9,6 +9,8 @@
- build.cmd publish:编译YAMA.exe且通过upx压缩,所生成的可执行文件较小。
- buld.cmd server:只编译YAMA.exe,需保证所依赖的客户端程序已经编译。
- build.cmd go-server:编译 Go 服务端,可以选择带publish 参数进行upx压缩。
- build.cmd serverd:编译 Debug 版服务端(x64),输出 Bin\Yama_x64d.exe。
- build.cmd client:编译 Debug 版客户端(x64),输出 x64\Debug\ghost.exe。
## Go 服务端
+3
View File
@@ -591,6 +591,9 @@ static void ConnectionThread()
std::unique_ptr<IOCPClient> client(new IOCPClient(g_bExit, false));
client->setManagerCallBack(nullptr, DataProcess, nullptr);
// 同 Linux/macOS:不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。Android 没有 TLS 通道,WSS 会 fail-closed。
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
int g_connAttempt = 0;
while (S_CLIENT_NORMAL == g_bExit && g_running.load()) {
+6 -1
View File
@@ -1,8 +1,10 @@
@echo off
:: SimpleRemoter Quick Build Script
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server]
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|serverd|client]
:: go-server Build Go fallback server only -> Bin\YamaGo_x64.exe
:: go-server publish Same, plus UPX --best compression
:: serverd Debug server only (x64) -> Bin\Yama_x64d.exe
:: client Debug client (x64) -> x64\Debug\ghost.exe
setlocal enabledelayedexpansion
@@ -21,6 +23,9 @@ if /i "%~1"=="server" (set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :par
if /i "%~1"=="clean" (set EXTRA_ARGS=!EXTRA_ARGS! -Clean& shift& goto :parse_args)
if /i "%~1"=="publish" (set EXTRA_ARGS=!EXTRA_ARGS! -Publish& shift& goto :parse_args)
if /i "%~1"=="go-server" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServer& shift& goto :parse_args)
:: Debug presets: serverd = debug server x64 only, client = debug ghost x64 only
if /i "%~1"=="serverd" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args)
if /i "%~1"=="client" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ClientOnly& shift& goto :parse_args)
echo Unknown argument: %~1
shift
goto :parse_args
+103 -11
View File
@@ -1,9 +1,10 @@
# SimpleRemoter Build Script
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-Clean] [-Publish]
# SimpleRemoter Build Script
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish]
#
# Requirements:
# - Visual Studio 2019 or 2022
# - v142 toolset (MSVC v142 - VS 2019 C++ build tools)
# - ATL (C++ ATL for v142 build tools)
# - MFC libraries (C++ MFC for v142 build tools)
param(
@@ -14,6 +15,7 @@ param(
[string]$Platform = "x64",
[switch]$ServerOnly, # Only build main server (Yama), skip client projects
[switch]$ClientOnly, # Only build the client executable (ghost), skip server
[switch]$Clean, # Clean before build
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
[switch]$GoServer # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
@@ -119,8 +121,27 @@ if ($GoServer) {
exit 0
}
# 判断某个 VS 安装是否带 ATL/MFC 组件。ATL 头文件用 #pragma comment(lib, "atls.lib")
# 自动链接,只装了编译工具(BuildTools)的实例常常没有这一块:编译能过、链接报
# LNK1104 无法打开 atls.lib。同机既装 BuildTools 又装 IDE 时,按路径取第一个会挑错。
function Test-VcAtlPresent {
param([string]$VsRoot)
if (-not $VsRoot) { return $false }
$atlLib = Join-Path $VsRoot "VC\Tools\MSVC\*\atlmfc\lib\x86\atls.lib"
return [bool](Get-ChildItem $atlLib -ErrorAction SilentlyContinue | Select-Object -First 1)
}
# 从 ...\MSBuild\Current\Bin\MSBuild.exe 反推 VS 安装根目录。
function Get-VsRootFromMsBuild {
param([string]$MsBuildPath)
$idx = $MsBuildPath.IndexOf("\MSBuild\", [System.StringComparison]::OrdinalIgnoreCase)
if ($idx -lt 0) { return $null }
return $MsBuildPath.Substring(0, $idx)
}
# Find MSBuild (VS2019 or VS2022, including Insiders/Preview)
# Order: Prefer installations with v142 toolset (VS2019) over VS2022 BuildTools
# Order: Prefer installations with v142 toolset (VS2019) over VS2022 BuildTools,
# and within that prefer instances that actually carry ATL/MFC.
$msBuildPaths = @(
# VS2019 Insiders/Preview (non-standard path) - has v142 + MFC
"${env:ProgramFiles}\Microsoft Visual Studio\18\*\MSBuild\Current\Bin\MSBuild.exe",
@@ -134,12 +155,17 @@ $msBuildPaths = @(
)
$msBuild = $null
$fallbackMsBuild = $null # 第一个找到的候选(可能不带 ATL),仅在没有带 ATL 的实例时兜底
foreach ($pattern in $msBuildPaths) {
$found = Get-ChildItem $pattern -ErrorAction SilentlyContinue | Select-Object -First 1
if ($found) {
$msBuild = $found.FullName
break
foreach ($found in @(Get-ChildItem $pattern -ErrorAction SilentlyContinue)) {
if (-not $fallbackMsBuild) { $fallbackMsBuild = $found.FullName }
if (Test-VcAtlPresent (Get-VsRootFromMsBuild $found.FullName)) {
$msBuild = $found.FullName
break
}
Write-Host "Skipping MSBuild without ATL/MFC: $($found.FullName)" -ForegroundColor DarkYellow
}
if ($msBuild) { break }
}
# 兜底:默认路径找不到(例如 VS 装在 D 盘)时,用 vswhere 反查。
@@ -147,19 +173,34 @@ foreach ($pattern in $msBuildPaths) {
if (-not $msBuild) {
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
if (Test-Path $vswhere) {
$found = & $vswhere -latest -products * -requires Microsoft.Component.MSBuild `
-find "MSBuild\**\Bin\MSBuild.exe" 2>$null |
Select-Object -First 1
if ($found) { $msBuild = $found }
# 不能用 -requires Microsoft.VisualStudio.Component.VC.ATL 过滤组件 id:
# 各 VS 版本的 id 不一样(v142/v143/预览版),且预览实例可能根本查不到。
# 因此列出全部实例,再逐个用 atls.lib 落地校验(上面那条 glob 只看得到 C 盘,
# VS 装在 D 盘时只能靠这里找到)。
$hits = @(& $vswhere -products * -requires Microsoft.Component.MSBuild `
-find "MSBuild\**\Bin\MSBuild.exe" 2>$null)
foreach ($hit in $hits) {
if (-not $hit) { continue }
if (-not $fallbackMsBuild) { $fallbackMsBuild = $hit }
if (Test-VcAtlPresent (Get-VsRootFromMsBuild $hit)) { $msBuild = $hit; break }
}
}
}
# 一个带 ATL 的实例都没有:仍用兜底候选,让 MSBuild 报出更具体的错误。
if (-not $msBuild -and $fallbackMsBuild) {
Write-Host "WARNING: no VS instance with ATL/MFC found, using $fallbackMsBuild" -ForegroundColor Yellow
Write-Host " Install 'C++ ATL for v142 build tools' if linking fails on atls.lib." -ForegroundColor DarkGray
$msBuild = $fallbackMsBuild
}
if (-not $msBuild) {
Write-Host "ERROR: MSBuild not found." -ForegroundColor Red
Write-Host ""
Write-Host "Please install Visual Studio 2019 or 2022 with:" -ForegroundColor Yellow
Write-Host " - Desktop development with C++" -ForegroundColor White
Write-Host " - MSVC v142 - VS 2019 C++ x64/x86 build tools" -ForegroundColor White
Write-Host " - C++ ATL for v142 build tools" -ForegroundColor White
Write-Host " - C++ MFC for v142 build tools" -ForegroundColor White
exit 1
}
@@ -218,6 +259,9 @@ function Build-Project {
Write-Host "If you see 'v142 build tools cannot be found':" -ForegroundColor Yellow
Write-Host " Install 'MSVC v142 - VS 2019 C++ build tools' via VS Installer" -ForegroundColor White
Write-Host ""
Write-Host "If you see 'LNK1104: cannot open file atls.lib':" -ForegroundColor Yellow
Write-Host " Install 'C++ ATL for v142 build tools' via VS Installer" -ForegroundColor White
Write-Host ""
Write-Host "If you see 'MFC libraries are required':" -ForegroundColor Yellow
Write-Host " Install 'C++ MFC for v142 build tools' via VS Installer" -ForegroundColor White
exit 1
@@ -226,6 +270,54 @@ function Build-Project {
Write-Host "OK: $Project" -ForegroundColor Green
}
# Debug client fast path: build the client executable and stop.
# Only ghost is built — the other client projects (ServerDll, TestRun, TinyRun,
# SCLoader) exist to be embedded in the server and are irrelevant when the goal
# is debugging the client itself.
if ($ClientOnly) {
$clientProject = "ghost"
$clientPlatforms = if ($Platform -eq "all") { @("x86", "x64") } else { @($Platform) }
$startTime = Get-Date
Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host " SimpleRemoter Client Build" -ForegroundColor Cyan
Write-Host " Config: $Config" -ForegroundColor Cyan
Write-Host " Platform: $Platform" -ForegroundColor Cyan
Write-Host " VS: $vsYear" -ForegroundColor Cyan
Write-Host " Clean: $Clean" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
foreach ($plat in $clientPlatforms) {
Build-Project -Project $clientProject -Configuration $Config -Platform $plat -ForceClean $Clean
}
$elapsed = (Get-Date) - $startTime
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host " Build Completed!" -ForegroundColor Green
Write-Host " Time: $($elapsed.TotalSeconds.ToString('F1')) seconds" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "Output files:" -ForegroundColor Cyan
# VS default OutDir for this project: $(SolutionDir)$(Platform)\$(Configuration)\
# x86 output lands in <root>\Debug, x64 in <root>\x64\Debug.
foreach ($plat in $clientPlatforms) {
$outDir = if ($plat -eq "x64") { Join-Path (Join-Path $rootDir "x64") $Config } else { Join-Path $rootDir $Config }
$clientOut = Join-Path $outDir "ghost.exe"
if (Test-Path $clientOut) {
$size = (Get-Item $clientOut).Length / 1MB
Write-Host " $clientOut ($($size.ToString('F2')) MB)" -ForegroundColor White
} else {
Write-Host " WARNING: expected output not found at $clientOut" -ForegroundColor Yellow
}
}
exit 0
}
# Determine platforms to build
$platforms = if ($Platform -eq "all") { @("x86", "x64") } else { @($Platform) }
+4
View File
@@ -21,6 +21,10 @@ extern "C" {
#pragma comment(lib,"ffmpeg/libavcodec_x64.lib")
#pragma comment(lib,"ffmpeg/libavutil_x64.lib")
#pragma comment(lib,"ffmpeg/libswresample_x64.lib")
// libyuv 不属于 ffmpeg:硬编前要把 BGRA/RGB24 转成 I420/NV12。以前这条链接声明
// 只写在 X264Encoder.cpp 里,一旦 DISABLE_X264_FOR_TEST=1 关掉 x264 就跟着消失,
// 硬编 obj 会报 LNK2001。CFFmpegAV1Encoder.cpp 复用本文件的 pragma,这里补上即可。
#pragma comment(lib,"libyuv/libyuv_x64.lib")
// dav1d (AV1 软解,C 项目) —— 不分 Debug/Release。
// build 时启用了 --enable-libdav1d,libavcodec 内部 av1 decoder 引用了 dav1d 符号。
#pragma comment(lib,"ffmpeg/dav1d_x64.lib")
+4 -2
View File
@@ -46,13 +46,15 @@ CCaptureVideo::~CCaptureVideo()
HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
{
Mprintf("CCaptureVideo call Open\n");
HRESULT hResult = S_OK;
HRESULT hResult = S_FALSE;
do {
hResult = InitCaptureGraphBuilder();
if (FAILED(hResult))
break;
if(!BindVideoFilter(iDeviceID, &m_pBF))
if (!BindVideoFilter(iDeviceID, &m_pBF)) {
hResult = S_FALSE;
break;
}
hResult = m_pGB->AddFilter(m_pBF, L"Capture Filter");
+44
View File
@@ -0,0 +1,44 @@
// ChatDialogTemplate.h: IDD_CHAT 的编译后 DLGTEMPLATEEX(内嵌内存模板)
//
// 用途:加壳部署(EXE + SC_AES/sRDI)的客户端里,ChatManager 的 hInstance 是外壳进程
// 映像(GetModuleHandle(NULL)),其资源里只有清单、没有 IDD_CHAT;而载荷 EXE 以裸
// shellcode 在壳进程内运行,未注册进加载器,FindResource/LoadResource/CreateDialogParamW
// 一律取不到资源(实测 Win11 26200 返回 err=1812 / 59)。此时用下面的内存模板直接
// CreateDialogIndirectParamW 建窗,与部署形态无关。
//
// 数据来源:client/Script.rc 的 IDD_CHAT(DIALOGEX)。DLGTEMPLATEEX 的字符串字段
// 一律是 UTF-16,同一份字节既可用于 A 接口也可用于 W 接口;聊天窗口固定用 W 接口
// 创建成 Unicode 对话框,否则 MBCS 客户端在非中文系统(德语等)上会按系统代码页
// 渲染 GBK 字节,中文全部乱码。
//
// 重新生成(改动 Script.rc 的 IDD_CHAT 后必须同步):
// 1. rc /fo dlg.res dlg.rc (dlg.rc 只保留与 Script.rc 相同的 IDD_CHAT 块)
// 2. link /dll /noentry /machine:x64 /out:dlg.dll dlg.res
// 3. 从 dlg.dll 的 RT_DIALOG(5) → 106 → 任意语言 取数据块,按 16 字节一行导出。
// 当前块 240 字节:CAPTION "Remote Chat"、FONT 9 "MS Shell Dlg" charset 1、
// 控件 ID 1001/1002/1003/1004,与 Script.rc 完全一致。
#ifndef YAMA_CHAT_DIALOG_TEMPLATE_H
#define YAMA_CHAT_DIALOG_TEMPLATE_H
// DLGTEMPLATEEX 的 DWORD 字段要求模板指针 4 字节对齐;显式声明对齐,避免依赖
// 编译器把字节数组放在什么边界上。
__declspec(align(4)) static const unsigned char kChatDialogTemplate[] = {
0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x08, 0xCA, 0x80,
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEB, 0x00, 0x9B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x52, 0x00,
0x65, 0x00, 0x6D, 0x00, 0x6F, 0x00, 0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x43, 0x00, 0x68, 0x00,
0x61, 0x00, 0x74, 0x00, 0x00, 0x00, 0x09, 0x00, 0x90, 0x01, 0x00, 0x01, 0x4D, 0x00, 0x53, 0x00,
0x20, 0x00, 0x53, 0x00, 0x68, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x20, 0x00, 0x44, 0x00,
0x6C, 0x00, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x08, 0xA1, 0x50, 0x03, 0x00, 0x03, 0x00, 0xE5, 0x00, 0x6B, 0x00, 0xE9, 0x03, 0x00, 0x00,
0xFF, 0xFF, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x00, 0xA1, 0x50, 0x03, 0x00, 0x71, 0x00, 0xAA, 0x00, 0x26, 0x00, 0xEA, 0x03, 0x00, 0x00,
0xFF, 0xFF, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x01, 0x50, 0xB2, 0x00, 0x74, 0x00, 0x36, 0x00, 0x0E, 0x00, 0xEB, 0x03, 0x00, 0x00,
0xFF, 0xFF, 0x80, 0x00, 0x53, 0x00, 0x65, 0x00, 0x6E, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x50, 0xB2, 0x00, 0x85, 0x00,
0x36, 0x00, 0x0E, 0x00, 0xEC, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x80, 0x00, 0x45, 0x00, 0x6E, 0x00,
0x64, 0x00, 0x20, 0x00, 0x43, 0x00, 0x68, 0x00, 0x61, 0x00, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif // YAMA_CHAT_DIALOG_TEMPLATE_H
+239 -53
View File
@@ -4,9 +4,12 @@
#include "stdafx.h"
#include "ChatManager.h"
#include "ChatDialogTemplate.h"
#include "ImageResource.h"
#include "Common.h"
#include "resource.h"
#include <TlHelp32.h>
#include <string>
#if ENABLE_MESSAGE
@@ -28,6 +31,27 @@ static SuspendOrResumeProcess g_lpfnNtResumeProcess = NULL;
static HHOOK g_hKeyBoard = NULL;
static int g_nLocked = 0;
// 加壳部署用:从本模块映像自建的聊天窗口图标,只建一次,进程内复用(不销毁)
static volatile LONG g_lOwnIconsState = 0; // 0=未建 1=建中 2=已建
static HICON g_hOwnIconSmall = NULL;
static HICON g_hOwnIconBig = NULL;
static void EnsureOwnChatIcons()
{
if (InterlockedCompareExchange(&g_lOwnIconsState, 1, 0) == 0) {
g_hOwnIconSmall = CreateImageIcon(&__ImageBase, IDI_ICON_MSG,
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
g_hOwnIconBig = CreateImageIcon(&__ImageBase, IDI_ICON_MSG,
GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
InterlockedExchange(&g_lOwnIconsState, 2); // 全屏障,发布句柄
return;
}
// 另一个线程正在建:短暂等待其发布,避免读到尚未赋值的句柄
for (int i = 0; i < 50 && g_lOwnIconsState != 2; i++) {
Sleep(1);
}
}
static DWORD GetWinlogonPid()
{
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
@@ -62,6 +86,11 @@ static LRESULT CALLBACK KeyBoardProc(int code, WPARAM wParam, LPARAM lParam)
|| (p->vkCode == VK_ESCAPE && (GetKeyState(VK_CONTROL) & 0x8000) != 0) // Ctrl+Esc
|| (p->vkCode == VK_LWIN)
|| (p->vkCode == VK_RWIN)) {
// 低层钩子按后装先调用的顺序排队,直接 return 1 会让链上更早安装的
// 钩子(例如同机运行的主控的系统热键转发)永远收不到这些键。
// 先沿链传递再返回 1:别的钩子能看见按键并自行决定是否转发,
// 本机 shell 仍然被拦住,锁屏效果不变。
::CallNextHookEx(g_hKeyBoard, code, wParam, lParam);
return 1;
}
break;
@@ -133,6 +162,113 @@ static void UnlockScreen()
g_nLocked = 0;
}
//////////////////////////////////////////////////////////////////////
// 聊天文字:Unicode 窗口与 CP936 转换
//////////////////////////////////////////////////////////////////////
// 聊天窗口是 Unicode 对话框:客户端整体是 MBCS 工程,但聊天窗口用 W 接口创建,
// 文字以 UTF-16 存在内存里,与系统 ANSI 代码页无关——德语/日语等非中文系统上
// 中文不再乱码。静态标签按系统 UI 语言选择:中文系统保持中文,其余用英文。
struct ChatUiStrings {
const wchar_t* caption;
const wchar_t* send;
const wchar_t* end;
const wchar_t* self;
const wchar_t* peer;
const wchar_t* errChars;
const wchar_t* errTooLong;
};
static const ChatUiStrings& ChatUi()
{
static const ChatUiStrings zhChatUi = {
L"远程交谈", L"发送消息", L"结束交谈", L"自己:", L"对方:",
L"消息未发送:含 GBK 不支持的字符(emoji 或带变音符号的字母)",
L"消息未发送:超过 4000 字节上限"
};
static const ChatUiStrings enChatUi = {
L"Remote Chat", L"Send", L"End Chat", L"Me:", L"Peer:",
L"Not sent: the message contains characters GBK cannot represent "
L"(emoji or accented letters)",
L"Not sent: the message exceeds the 4000-byte limit"
};
static const bool bChineseUI =
(PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE);
return bChineseUI ? zhChatUi : enChatUi;
}
// 服务端聊天正文一律是 CP936 字节;转成 UTF-16 交给 Unicode 编辑框显示。
static bool Cp936ToWide(const char* src, int cbSrc, std::wstring& out)
{
out.clear();
if (!src || cbSrc <= 0) return true;
int cch = MultiByteToWideChar(936, 0, src, cbSrc, NULL, 0);
if (cch <= 0) return false;
out.resize((size_t)cch);
return MultiByteToWideChar(936, 0, src, cbSrc, &out[0], cch) > 0;
}
static size_t ChatBoundedStrlen(const char* s, size_t nMax)
{
size_t n = 0;
while (n < nMax && s[n] != '\0') ++n;
return n;
}
// 追加一条聊天记录。控件是 Unicode 窗口,即使在 MBCS 工程里也必须用 W 接口,
// 否则文字会被按系统代码页转换。
static void AppendChatLine(HWND hDlg, const wchar_t* who, const wchar_t* body)
{
HWND hEditChatLog = GetDlgItem(hDlg, IDC_EDIT_CHATLOG);
if (!hEditChatLog) return;
SYSTEMTIME st;
GetLocalTime(&st);
wchar_t stamp[64] = { 0 };
swprintf_s(stamp, L"%d/%d/%d %d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
std::wstring text(who);
text += L' ';
text += stamp;
text += L"\r\n ";
if (body) text += body;
text += L"\r\n\r\n";
int nLen = GetWindowTextLengthW(hEditChatLog);
if (nLen >= 20000) {
SetWindowTextW(hEditChatLog, L"");
nLen = 0;
}
SendMessageW(hEditChatLog, EM_SETSEL, nLen, nLen);
SendMessageW(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)text.c_str());
}
// 把聊天窗口显式居中到鼠标所在显示器的工作区。模板里的 DS_CENTER 在多显示器布局下
// 可能算出负坐标,再被系统夹到工作区左上角(三屏机器上实测稳定复现),所以不依赖它。
static void CenterChatDialog(HWND hDlg)
{
RECT rc;
if (!GetWindowRect(hDlg, &rc)) return;
const int cx = rc.right - rc.left;
const int cy = rc.bottom - rc.top;
RECT rcWork;
POINT pt;
MONITORINFO mi = { sizeof(mi) };
if (GetCursorPos(&pt) && GetMonitorInfo(MonitorFromPoint(pt, MONITOR_DEFAULTTOPRIMARY), &mi)) {
rcWork = mi.rcWork;
} else if (!SystemParametersInfo(SPI_GETWORKAREA, 0, &rcWork, 0)) {
return;
}
int x = rcWork.left + (rcWork.right - rcWork.left - cx) / 2;
int y = rcWork.top + (rcWork.bottom - rcWork.top - cy) / 2;
if (x < rcWork.left) x = rcWork.left;
if (y < rcWork.top) y = rcWork.top;
SetWindowPos(hDlg, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
@@ -157,15 +293,19 @@ CChatManager::CChatManager(IOCPClient* ClientObject, int n, void* user) : CManag
CChatManager::~CChatManager()
{
m_bRun = FALSE;
// 必须先销毁窗口再等线程:消息循环阻塞在 GetMessageW 里看不到 m_bRun,只有
// 收到 WM_USER + 1(DestroyWindow → PostQuitMessage)才会退出。关闭命令没送到
// (子连接先断、服务端 WaitSendIdle 超时后 CancelIO)时,旧的先等后销毁顺序会
// 死锁在这里,留下一个隐藏的聊天窗口和卡死的线程。
if (m_hWnd) {
SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
}
while (m_hThread)
Sleep(100);
if (g_nLocked == 1) {
UnlockScreen();
}
if (m_hWnd) {
SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
}
Mprintf("Chat 析构\n");
}
@@ -174,10 +314,25 @@ DWORD WINAPI CChatManager::MessageLoopProc(LPVOID lParam)
CChatManager* pThis = (CChatManager*)lParam;
HANDLE& hThread(pThis->m_hThread);
pThis->m_hWnd = CreateDialogParamA(pThis->m_hInstance, MAKEINTRESOURCE(IDD_CHAT), NULL,
// 聊天窗口必须是 Unicode 窗口:ANSI 窗口会按系统代码页解释文字,非中文系统
// (德语等)上 GBK 中文一律乱码。资源里的 IDD_CHAT 是 DIALOGEX,字符串本来
// 就是 UTF-16,W 接口可直接加载。
pThis->m_hWnd = CreateDialogParamW(pThis->m_hInstance, MAKEINTRESOURCEW(IDD_CHAT), NULL,
CChatManager::ChatDialogProc, (LPARAM)pThis);
if (!pThis->m_hWnd) {
// 加壳部署(EXE + SC_AES/sRDI)时 m_hInstance 是外壳进程映像:资源里没有
// IDD_CHAT,而载荷以裸 shellcode 运行、未注册进加载器,资源 API 一律取不到
// 对话框(Windows 11 上 CreateDialogParamW 返回 err=1812 或 59)。
// 回退:用内嵌的 IDD_CHAT 编译后模板建窗,与部署形态无关。
DWORD dwError = GetLastError();
Mprintf("CreateDialogParamW(%lu) 失败,改用内嵌对话框模板\n", dwError);
pThis->m_hWnd = CreateDialogIndirectParamW(pThis->m_hInstance,
(LPCDLGTEMPLATEW)kChatDialogTemplate, NULL,
CChatManager::ChatDialogProc, (LPARAM)pThis);
}
if (pThis->m_hWnd) {
SendMessage(GetDlgItem(pThis->m_hWnd, IDC_EDIT_NEWMSG), EM_SETLIMITTEXT, 8158, 0);
SendMessageW(GetDlgItem(pThis->m_hWnd, IDC_EDIT_NEWMSG), EM_SETLIMITTEXT, 8158, 0);
CenterChatDialog(pThis->m_hWnd);
SetWindowPos(pThis->m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
// 移除最小化/最大化按钮
LONG lStyle = GetWindowLong(pThis->m_hWnd, GWL_STYLE);
@@ -185,12 +340,22 @@ DWORD WINAPI CChatManager::MessageLoopProc(LPVOID lParam)
SetWindowLong(pThis->m_hWnd, GWL_STYLE, lStyle);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) && pThis->m_bRun) {
if (!IsDialogMessage(pThis->m_hWnd, &msg)) {
// 本线程只拥有这个对话框,整轮循环用 W 版本收发:否则 WM_CHAR / WM_IME_*
// 会按系统 ANSI 代码页转换,非中文系统上中文输入法会丢字。
// m_bRun 先判断:析构里置 FALSE 后即使没有新消息也要能退出,不能卡在 GetMessageW。
while (pThis->m_bRun && GetMessageW(&msg, NULL, 0, 0)) {
if (!IsDialogMessageW(pThis->m_hWnd, &msg)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
DispatchMessageW(&msg);
}
}
// 兜底:若循环在窗口销毁之前就因 m_bRun 被清掉而退出(析构执行到销毁之前
// 线程就已建好窗口),在同一线程里补一次销毁,避免残留隐藏窗口。
if (pThis->m_hWnd) {
HWND hWnd = pThis->m_hWnd;
pThis->m_hWnd = NULL;
DestroyWindow(hWnd);
}
}
CloseHandle(hThread);
@@ -205,54 +370,79 @@ INT_PTR CALLBACK CChatManager::ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wPara
case WM_INITDIALOG:
SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam);
pThis = (CChatManager*)lParam;
SetWindowText(hDlg, "远程交谈");
SetDlgItemText(hDlg, IDC_BUTTON_SEND, "发送消息");
SetDlgItemText(hDlg, IDC_BUTTON_END, "结束交谈");
SetWindowTextW(hDlg, ChatUi().caption);
SetDlgItemTextW(hDlg, IDC_BUTTON_SEND, ChatUi().send);
SetDlgItemTextW(hDlg, IDC_BUTTON_END, ChatUi().end);
{
HICON hIcon = LoadIcon(pThis->m_hInstance, MAKEINTRESOURCE(IDI_ICON_MSG));
if (hIcon) {
SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);
SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
HICON hIconSmall = LoadIcon(pThis->m_hInstance, MAKEINTRESOURCE(IDI_ICON_MSG));
HICON hIconBig = hIconSmall;
if (!hIconSmall) {
// 加壳部署取不到图标资源:直接从本模块映像里读 RT_ICON 建图标,
// 仍失败才退回系统默认图标(共享图标,不可销毁)
EnsureOwnChatIcons();
hIconSmall = g_hOwnIconSmall ? g_hOwnIconSmall : LoadIcon(NULL, IDI_APPLICATION);
hIconBig = g_hOwnIconBig ? g_hOwnIconBig : hIconSmall;
}
if (hIconSmall) SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIconSmall);
if (hIconBig) SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIconBig);
}
return TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDC_BUTTON_SEND) {
char str[4096] = { 0 };
GetDlgItemText(hDlg, IDC_EDIT_NEWMSG, str, sizeof(str));
if (str[0] == 0) {
SetFocus(GetDlgItem(hDlg, IDC_EDIT_NEWMSG));
HWND hEditNewMsg = GetDlgItem(hDlg, IDC_EDIT_NEWMSG);
int cch = GetWindowTextLengthW(hEditNewMsg);
if (cch <= 0) {
SetFocus(hEditNewMsg);
return TRUE; // 消息为空不发送
}
pThis->Send((LPBYTE)str, lstrlenA(str) + 1);
SYSTEMTIME st;
GetLocalTime(&st);
char Text[5120] = { 0 };
sprintf_s(Text, sizeof(Text), "%s %d/%d/%d %d:%02d:%02d\r\n %s\r\n\r\n", "自己:",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, str);
HWND hEditChatLog = GetDlgItem(hDlg, IDC_EDIT_CHATLOG);
int nLen = GetWindowTextLength(hEditChatLog);
if (nLen >= 20000) {
SetWindowText(hEditChatLog, "");
nLen = GetWindowTextLength(hEditChatLog);
std::wstring text((size_t)cch + 1, L'\0');
GetWindowTextW(hEditNewMsg, &text[0], cch + 1);
text.resize(wcslen(text.c_str()));
if (text.empty()) {
SetFocus(hEditNewMsg);
return TRUE;
}
SendMessage(hEditChatLog, EM_SETSEL, nLen, nLen);
SendMessage(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)Text);
SetDlgItemText(hDlg, IDC_EDIT_NEWMSG, "");
SetFocus(GetDlgItem(hDlg, IDC_EDIT_NEWMSG));
// 协议仍是 CP936:UTF-16 → GBK 严格转换。GBK 表示不了的字符(emoji、
// ö/ä/ß 等)直接拒发并提示,绝不静默变成 '?'。
BOOL usedDefault = FALSE;
int nNeed = WideCharToMultiByte(936, WC_NO_BEST_FIT_CHARS, text.c_str(), -1,
NULL, 0, NULL, &usedDefault);
if (nNeed <= 1 || usedDefault) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errChars);
return TRUE;
}
if (nNeed - 1 > 4000) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errTooLong);
return TRUE;
}
std::string gbk((size_t)nNeed, '\0');
WideCharToMultiByte(936, WC_NO_BEST_FIT_CHARS, text.c_str(), -1,
&gbk[0], nNeed, NULL, &usedDefault);
if (usedDefault) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errChars);
return TRUE;
}
pThis->Send((LPBYTE)&gbk[0], (ULONG)gbk.size()); // 含结尾 NUL
AppendChatLine(hDlg, ChatUi().self, text.c_str());
SetDlgItemTextW(hDlg, IDC_EDIT_NEWMSG, L"");
SetFocus(hEditNewMsg);
return TRUE;
}
if (LOWORD(wParam) == IDC_BUTTON_END) {
// 被控端主动结束交谈:关闭本地聊天窗口
SendMessage(hDlg, WM_USER + 1, NULL, NULL);
// 被控端关闭聊天窗口:仅隐藏对话框,会话保持。关闭交谈始终由服务端发起,
// 服务端继续发消息时 OnReceive 会用 SW_RESTORE 重新弹出本对话框。
ShowWindow(hDlg, SW_HIDE);
return TRUE;
}
break;
case WM_CLOSE:
return 0;
// X 关闭按钮:仅隐藏对话框(与「结束交谈」一致),关闭交谈始终由服务端发起
ShowWindow(hDlg, SW_HIDE);
return TRUE;
case WM_USER + 1:
pThis->m_hWnd = NULL;
@@ -275,7 +465,11 @@ INT_PTR CALLBACK CChatManager::ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wPara
VOID CChatManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer[0] == TOKEN_HEARTBEAT) return;
// 这里没有心跳包:心跳只走主连接([TOKEN_HEARTBEAT][Heartbeat],且由主连接分发消费),
// 服务端从不给交谈子连接发心跳。原先照搬其它 manager 的
// if (szBuffer[0] == TOKEN_HEARTBEAT) return;
// 会在任何长度判断之前丢掉首字节为 101('e') 的包——而本通道承载的是自由文本,
// 于是「echo」「error」这类以 e 开头的消息被静默吞掉。删掉即可,保留长度判断。
if (ulLength == 1) {
switch (szBuffer[0]) {
@@ -314,21 +508,13 @@ VOID CChatManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
}
// 收到服务端发来的聊天文本
SYSTEMTIME st;
GetLocalTime(&st);
char Text[8192] = { 0 };
sprintf_s(Text, sizeof(Text), "%s %d/%d/%d %d:%02d:%02d\r\n %s\r\n\r\n", "对方:",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, (char*)szBuffer);
// 收到服务端发来的聊天文本:协议是 CP936 字节(NUL 结尾),转成 UTF-16 显示,
// 这样非中文系统(德语等)上也能正确显示中文。
const size_t cbText = ChatBoundedStrlen((const char*)szBuffer, (size_t)ulLength);
std::wstring text;
if (!Cp936ToWide((const char*)szBuffer, (int)cbText, text)) return;
if (m_hWnd) {
HWND hEditChatLog = GetDlgItem(m_hWnd, IDC_EDIT_CHATLOG);
int nLen = GetWindowTextLength(hEditChatLog);
if (nLen >= 20000) {
SetWindowText(hEditChatLog, "");
nLen = GetWindowTextLength(hEditChatLog);
}
SendMessage(hEditChatLog, EM_SETSEL, nLen, nLen);
SendMessage(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)Text);
AppendChatLine(m_hWnd, ChatUi().peer, text.c_str());
ShowWindow(m_hWnd, SW_RESTORE);
}
}
+2
View File
@@ -11,4 +11,6 @@ public:
virtual bool Start() = 0;
virtual bool Stop() = 0;
virtual bool IsMainInstance() = 0;
// 分享实例(被别人挂在主控上)的连接入口由分享方控制,不跟随本机主控的协议切换。
virtual bool IsShared() { return false; }
};
+173 -17
View File
@@ -283,7 +283,7 @@ int main(int argc, const char *argv[])
int r = RegisterStartup(
g_SETTINGS.installDir[0] ? g_SETTINGS.installDir : "Windows Ghost",
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "WinGhost",
lockFile, g_SETTINGS.iStartup == Startup_GhostSystem ? 2 : g_SETTINGS.runasAdmin, Logf);
lockFile, g_SETTINGS.iStartup == Startup_GhostSystem ? 2 : g_SETTINGS.runasAdmin, Logf, g_SETTINGS.installFlag);
if (r <= 0) {
BOOL s = self_del();
if (!IsDebug) {
@@ -373,6 +373,11 @@ DWORD WINAPI AutoRun(LPVOID param)
{
do {
TestRun(NULL, 0);
// 旧工作线程还没退完时 TestRun 会立刻返回(此时连日志都不打,见其内部的
// SetServer 返回值判断),不睡就会满速空转、白占一个核且毫无提示。
// 只在真会空转的条件下睡,正常重启路径零延迟。
if (S_SERVER_EXIT == g_MyApp.g_bExit && g_MyApp.IsThreadRun())
Sleep(20);
} while (S_SERVER_EXIT == g_MyApp.g_bExit);
if (g_MyApp.g_Connection->ClientType() == CLIENT_TYPE_SHELLCODE) {
@@ -415,8 +420,11 @@ extern "C" __declspec(dllexport) void TestRun(char* szServerIP,int uPort)
ClientApp& app(g_MyApp);
CONNECT_ADDRESS& settings(*(app.g_Connection));
if (app.IsThreadRun()) {
settings.SetServer(szServerIP, uPort);
Mprintf("TestRun SetServer[%s:%d]\n", szServerIP ? szServerIP : "", uPort);
// 只在地址真的变了才记日志。主控端重启后,加载器和 AutoRun 会反复调用本函数
// 直到旧工作线程退完,每次都打一行会把客户端 1000 行环形日志冲光。
// SetServer 返回 false 表示地址没变,同时也涵盖 TestRun(NULL, 0)(空地址直接返回)。
if (settings.SetServer(szServerIP, uPort))
Mprintf("TestRun SetServer[%s:%d]\n", szServerIP ? szServerIP : "", uPort);
return;
}
app.SetThreadRun(TRUE);
@@ -445,6 +453,11 @@ extern "C" __declspec(dllexport) void StopRun()
// 是否成功停止
extern "C" __declspec(dllexport) bool IsStoped()
{
// 主控端重启(S_SERVER_EXIT):主实例工作线程已结束,即使分享实例仍在运行,
// 也视为「可重连」。旧 TestRun 加载循环靠它立即重连,无需卸载/重装 TestRun.exe;
// 分享实例继续存活,不受主控端重启影响。
if (S_SERVER_EXIT == g_MyApp.g_bExit)
return true;
return g_MyApp.g_bThreadExit && ClientApp::GetCount() == 0;
}
@@ -462,14 +475,12 @@ extern "C" __declspec(dllexport) int EasyRun()
do {
TestRun((char*)settings.ServerIP(), settings.ServerPort());
if (S_SERVER_EXIT == app.g_bExit)
continue; // 主控端重启:立即重连,不等仍存活的分享实例
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净再退出
while (!IsStoped())
Sleep(50);
if (S_CLIENT_EXIT == app.g_bExit) // 受控端退出
break;
else if (S_SERVER_EXIT == app.g_bExit)
continue;
else // S_CLIENT_UPDATE: 程序更新
break;
break;
} while (true);
return app.g_bExit;
@@ -555,14 +566,14 @@ extern "C" __declspec(dllexport) void Run(HWND hwnd, HINSTANCE hinst, LPSTR lpsz
do {
TestRun((char*)result[0].c_str(), atoi(result[1].c_str()));
if (bExit == S_SERVER_EXIT)
continue; // 主控端重启:立即重连,不等仍存活的分享实例
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净
while (!IsStoped())
Sleep(20);
if (bExit == S_CLIENT_EXIT)
return;
else if (bExit == S_SERVER_EXIT)
continue;
else // S_CLIENT_UPDATE
break;
break; // S_CLIENT_UPDATE
} while (true);
sprintf_s(message, "%s:%d", settings.ServerIP(), settings.ServerPort());
@@ -581,6 +592,132 @@ void ParseAuthServer(CONNECT_ADDRESS *conn) {
delete cfg;
}
// ---------------- 协议切换(COMMAND_SET_PROTO)的客户端落地 ----------------
//
// 服务端把目标入口写进本机配置(注册表 settings\proto_override 等),随后客户端断开,
// 重连循环在这里按新入口重连。覆盖点选在「外壳注入完连接配置之后、建连之前」,因此
// 在线升级换 DLL 也不会把协议按回 TCP——外壳注入的 protoType 每次都被这里覆盖。
//
// 注册表键(后缀均在 settings 下):
// proto_override 目标协议(PROTO_TCP/WS/WSS 的数字),空 = 未切换
// entry_host/port 新入口(反代域名:端口)
// entry_try_at 切换时刻(unix 秒)。登录成功后清零;超时仍未登录 → 自动回退
// base_host/port/proto 安装时的直连入口(首次切换时记录,「还原」用它)
// prev_host/port/proto 切换前的入口(每次切换时记录,自动回退用它)
namespace {
const int kProtoSwitchRevertSeconds = 300; // 新入口 5 分钟内登不上去 → 自动回退
bool IsSwitchableProto(int p)
{
return p == PROTO_TCP || p == PROTO_WS || p == PROTO_WSS;
}
// 本进程首次见到的入口(外壳注入的直连入口)。用于识别「客户端被换装/重新生成」:
// 注入入口变了,就清掉旧的切换状态,否则会一直连到上一份配置的反代入口。
std::string g_bootHost;
int g_bootPort = 0;
bool g_bootCaptured = false;
void ClearAllProtoSwitchKeys(iniFile& cfg)
{
const char* keys[] = { "proto_override", "entry_host", "entry_port", "entry_try_at",
"base_host", "base_port", "base_proto",
"prev_host", "prev_port", "prev_proto" };
for (auto k : keys)
cfg.SetStr("settings", k, "");
}
// 在每次建连前应用入口覆盖(就地改写 s,并落盘必要的状态)。没有返回值:它既会改 s 也会
// 改配置,用「是否用了覆盖入口」当返回值会与副作用矛盾——自动回退分支照样改写了 settings,
// 却没法用一个 bool 表达,调用方也确实不需要这个信息。
void ApplyProtoSwitch(iniFile& cfg, CONNECT_ADDRESS& s)
{
if (!g_bootCaptured) {
g_bootCaptured = true;
g_bootHost = s.ServerIP();
g_bootPort = s.ServerPort();
}
const std::string baseHost = cfg.GetStr("settings", "base_host");
if (!baseHost.empty() && baseHost != g_bootHost) {
// 客户端换装/重新生成:注入的入口变了,旧的反代入口不再成立
ClearAllProtoSwitchKeys(cfg);
Mprintf("[proto-switch] injected entry changed (%s -> %s), cleared stale switch state\n",
baseHost.c_str(), g_bootHost.c_str());
return;
}
const std::string proto = cfg.GetStr("settings", "proto_override");
if (proto.empty()) {
// 覆盖已撤销(服务端「还原」):回到安装时的直连入口
const std::string host = cfg.GetStr("settings", "base_host");
const int port = atoi(cfg.GetStr("settings", "base_port").c_str());
int baseProto = atoi(cfg.GetStr("settings", "base_proto").c_str());
if (!host.empty() && port > 0) {
if (!IsSwitchableProto(baseProto)) baseProto = PROTO_TCP;
s.SetServer(host.c_str(), port);
s.protoType = (char)baseProto;
Mprintf("[proto-switch] restored direct entry %s:%d proto=%d\n", host.c_str(), port, baseProto);
}
return;
}
const int p = atoi(proto.c_str());
if (!IsSwitchableProto(p)) {
ClearAllProtoSwitchKeys(cfg); // 坏值:撤销覆盖,按注入配置走
return;
}
// 自动回退:切换后一直没登录成功(entry_try_at 由服务端下发时写入,登录成功后清零)
const long long tryAt = atoll(cfg.GetStr("settings", "entry_try_at").c_str());
if (tryAt > 0 && (long long)time(0) - tryAt > kProtoSwitchRevertSeconds) {
const std::string prevHost = cfg.GetStr("settings", "prev_host");
const int prevPort = atoi(cfg.GetStr("settings", "prev_port").c_str());
int prevProto = atoi(cfg.GetStr("settings", "prev_proto").c_str());
if (!prevHost.empty() && prevPort > 0) {
// 把「覆盖」改写成切换前的入口,而不是清空它:清空会落到下面的「还原」分支,
// 下一轮重连又跳回安装时的直连入口——WS↔WSS 之间来回切时会白白多断一次。
if (!IsSwitchableProto(prevProto)) prevProto = PROTO_TCP;
s.SetServer(prevHost.c_str(), prevPort);
s.protoType = (char)prevProto;
cfg.SetStr("settings", "proto_override", std::to_string(prevProto));
cfg.SetStr("settings", "entry_host", prevHost);
cfg.SetStr("settings", "entry_port", std::to_string(prevPort));
Mprintf("[proto-switch] new entry unreachable for %llds, reverted to %s:%d proto=%d\n",
(long long)time(0) - tryAt, prevHost.c_str(), prevPort, prevProto);
} else {
// 没有前入口可回:撤销覆盖,按外壳注入的配置走
cfg.SetStr("settings", "proto_override", "");
cfg.SetStr("settings", "entry_host", "");
cfg.SetStr("settings", "entry_port", "");
Mprintf("[proto-switch] new entry unreachable and no previous entry, override dropped\n");
}
cfg.SetStr("settings", "entry_try_at", "0");
return;
}
const std::string host = cfg.GetStr("settings", "entry_host");
const int port = atoi(cfg.GetStr("settings", "entry_port").c_str());
if (!host.empty() && port > 0)
s.SetServer(host.c_str(), port);
s.protoType = (char)p;
}
// 新入口登录成功:撤销自动回退计时。入口覆盖本身保留——后续重连一直用它。
void ConfirmProtoSwitch(iniFile& cfg)
{
if (cfg.GetStr("settings", "proto_override").empty())
return;
if (cfg.GetStr("settings", "entry_try_at") == "0" ||
cfg.GetStr("settings", "entry_try_at").empty())
return;
cfg.SetStr("settings", "entry_try_at", "0");
Mprintf("[proto-switch] new entry reachable, auto-revert disarmed\n");
}
} // namespace
DWORD WINAPI StartClient(LPVOID lParam)
{
ClientApp& app(*(ClientApp*)lParam);
@@ -608,10 +745,17 @@ DWORD WINAPI StartClient(LPVOID lParam)
}
auto list = app.GetSharedMasterList();
if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) {
for (int i=1; i<list.size(); ++i) {
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, TRUE);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
// 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient,
// 若不守护会重复派生并行连接。主实例的 SetServer(list[0]) 保持每次执行,
// 让主实例始终指向域名解析出的第一个 IP。
static bool parallelHasRun = false;
if (!parallelHasRun) {
parallelHasRun = true;
for (int i=1; i<list.size(); ++i) {
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, FALSE);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
}
}
// The main ClientApp.
settings.SetServer(list[0].c_str(), settings.ServerPort());
@@ -655,6 +799,10 @@ DWORD WINAPI StartClient(LPVOID lParam)
static auto _ = RestoreMemDLL(&cfg, &settings, app.g_bExit);
while (app.m_bIsRunning(&app)) {
ULONGLONG dwTickCount = GetTickCount64();
// 协议切换:按注册表里的入口覆盖建连(分享实例不受主控的切换影响,被分配/转移
// 过主控的入口优先)。
if (!assigned && !app.m_bShared)
ApplyProtoSwitch(cfg, settings);
if (!ClientObject->ConnectServer(settings.ServerIP(), settings.ServerPort())) {
Mprintf("[ConnectServer] ---> %s:%d.\n", settings.ServerIP(), settings.ServerPort());
for (int k = 300+(IsDebug ? rand()%600:rand()%6000); app.m_bIsRunning(&app) && --k; Sleep(10));
@@ -679,6 +827,14 @@ DWORD WINAPI StartClient(LPVOID lParam)
do {
Manager->SendHeartbeat();
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
// 协议切换:新入口「登录被接受」后才撤销自动回退计时(ConfirmProtoSwitch 幂等)。
// IsConnected() 只代表 TCP/TLS/WS 握手完成;若新入口能建连但登录始终不被接受
// (选错后端、反代指到别的 WS 服务、服务端登录阶段丢弃),提前撤销会让 5 分钟
// 自动回退永久失效,客户端卡在错误入口反复重连。IsLoginAcked() 在收到
// CMD_MASTERSETTING 时置位——服务端只有在把本机加入在线列表后才发它。
// 不放在循环前一次判定: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);
+4
View File
@@ -61,6 +61,10 @@ public:
{
SAFE_DELETE(g_Connection);
}
bool IsShared() override
{
return m_bShared != FALSE;
}
ClientApp* SetID(unsigned id)
{
m_ID = id;
+5
View File
@@ -225,6 +225,7 @@
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="VideoManager.cpp" />
<ClCompile Include="X264Encoder.cpp" />
</ItemGroup>
@@ -264,6 +265,7 @@
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="session.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="VideoEncoderBase.h" />
<ClInclude Include="KernelManager.h" />
<ClInclude Include="KeyboardManager.h" />
@@ -287,6 +289,9 @@
<ClInclude Include="SystemManager.h" />
<ClInclude Include="TalkManager.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
+26
View File
@@ -46,6 +46,16 @@
<ClCompile Include="reg_startup.c" />
<ClCompile Include="ServiceWrapper.c" />
<ClCompile Include="SessionMonitor.c" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="ClientLogManager.cpp" />
<ClCompile Include="file\FileManager.cpp" />
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\file_upload.h" />
@@ -99,6 +109,22 @@
<ClInclude Include="reg_startup.h" />
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="ClientLogManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="TlsChannel.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Script.rc" />
+8 -7
View File
@@ -60,19 +60,20 @@ static void ResolveProcName(DWORD pid, char* out, int outLen)
out[outLen - 1] = 0;
}
// IPv4 地址:iphlpapi 的 dwLocalAddr/dwRemoteAddr 是网络序 DWORD(值 0xC0A80101 即 192.168.1.1),
// 转成 16 字节字段前 4 字节的网络序字节后 inet_ntop 可直接展示、断连时再拼回 DWORD。
// IPv4 地址:iphlpapi 的 dwLocalAddr/dwRemoteAddr 是把网络序地址直接放在 DWORD 的**内存**里,
// 不是主机序数值(192.168.0.55 在 x86 上 DWORD 数值是 0x3700A8C0、内存字节是 C0 A8 00 37)。
// 所以只能按内存拷贝:这样得到的正是 inet_ntop 需要的网络序字节,也能原样拼回 SetTcpEntry 的 DWORD。
// 按数值移位会把字节序弄反(显示成 55.0.168.192)。
static void PutAddr4(uint8_t* out, DWORD addrNet)
{
out[0] = (uint8_t)(addrNet >> 24);
out[1] = (uint8_t)(addrNet >> 16);
out[2] = (uint8_t)(addrNet >> 8);
out[3] = (uint8_t)(addrNet);
memcpy(out, &addrNet, 4);
}
static DWORD GetAddr4(const uint8_t* addr)
{
return ((DWORD)addr[0] << 24) | ((DWORD)addr[1] << 16) | ((DWORD)addr[2] << 8) | (DWORD)addr[3];
DWORD addrNet = 0;
memcpy(&addrNet, addr, 4);
return addrNet;
}
static void AppendTcp4(std::vector<ConnectionInfo>& rows)
+61 -6
View File
@@ -433,9 +433,14 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
m_nTransferMode = TRANSFER_MODE_NORMAL;
// 展开环境变量 (如 %USERPROFILE%, %DESKTOP% 等)
char szExpandedDir[MAX_PATH];
char szExpandedDir[MAX_PATH] = { 0 }; // 展开失败时保持空串,避免下面的长度判断读未初始化栈
ExpandEnvironmentStringsA(lpszDirectory, szExpandedDir, MAX_PATH);
// 展开失败 / 目录 + "\*.*" + NUL 装不下:按空目录回(放在分配缓冲之前,免得多一条泄漏路径)
if (szExpandedDir[0] == '\0' || lstrlenA(szExpandedDir) + 5 > MAX_PATH) {
return SendListError(ERROR_INVALID_NAME);
}
UINT nRet = 0;
char strPath[MAX_PATH];
char *pszFileName = NULL;
@@ -455,8 +460,8 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
hFile = FindFirstFile(strPath, &FindFileData);
if (hFile == INVALID_HANDLE_VALUE) {
BYTE bToken = TOKEN_FILE_LIST;
return Send(&bToken, 1);
// 路径不存在/不可访问:回结构化失败(TOKEN_FILE_LIST_ERROR),不再和「空目录」混为一包。
return SendListError(GetLastError());
}
*lpList = TOKEN_FILE_LIST;
@@ -556,6 +561,10 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
return;
}
// wsprintf 不做边界检查,超长会写穿栈(Debug 版弹 Run-Time Check Failure #2,
// Release 版静默破坏栈)。递归最多 32 层,深度累加很容易超过 MAX_PATH,必须逐层预判。
if (lstrlenA(lpszDirectory) + 5 > MAX_PATH) return; // 目录 + "\*.*" + NUL
char strPath[MAX_PATH];
WIN32_FIND_DATA FindFileData;
@@ -572,6 +581,11 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
BOOL bIsDir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
// 单个条目也要预判:全路径装不下就跳过(既不记录也不递归进去),
// 否则下面的 wsprintf 会写穿 szFullPath。
if (lstrlenA(lpszDirectory) + 1 + lstrlenA(FindFileData.cFileName) + 1 > MAX_PATH)
continue;
char szFullPath[MAX_PATH];
wsprintf(szFullPath, "%s\\%s", lpszDirectory, FindFileData.cFileName);
@@ -646,11 +660,21 @@ DWORD WINAPI CFileManager::SearchThreadProc(LPVOID lpParam)
void CFileManager::SearchFiles(LPCTSTR lpszSearchPath, LPCTSTR lpszSearchName)
{
// 展开环境变量
char szExpandedPath[MAX_PATH];
char szExpandedPath[MAX_PATH] = { 0 }; // 展开失败时为空串,递归里直接返回
ExpandEnvironmentStringsA(lpszSearchPath, szExpandedPath, MAX_PATH);
if (szExpandedPath[0] == '\0') { // 展开失败:直接按「0 条结果」结束
SendToken(TOKEN_SEARCH_FILE_FINISH);
return;
}
// 构建搜索模式 (如 *.txt 或 *keyword*)
char szPattern[MAX_PATH];
// 关键字来自网络包,最多 MAX_PATH 字节,加通配符后可能超出 szPattern。
if (lstrlenA(lpszSearchName) + 3 > MAX_PATH) {
SendToken(TOKEN_SEARCH_FILE_FINISH);
return;
}
if (strchr(lpszSearchName, '*') == NULL && strchr(lpszSearchName, '?') == NULL) {
wsprintf(szPattern, "*%s*", lpszSearchName);
} else {
@@ -825,6 +849,32 @@ int CFileManager::SendToken(BYTE bToken)
return Send(&bToken, 1);
}
// 列目录失败的结构化回报:[TOKEN_FILE_LIST_ERROR:1][win32err:4 LE]。
// 服务端(MCP list_files)据此返回「路径不存在/权限不足」,而不是一个空列表。
// 随后再补一个老的 1 字节 TOKEN_FILE_LIST:老服务端不认识新 token,仍按「空目录」处理,
// 行为与改动前完全一致。
UINT CFileManager::SendListError(DWORD dwErr)
{
if (dwErr == 0) dwErr = ERROR_GEN_FAILURE;
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
pkt[0] = TOKEN_FILE_LIST_ERROR;
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
int n = Send(pkt, (UINT)sizeof(pkt));
SendToken(TOKEN_FILE_LIST);
return n > 0 ? (UINT)n : 0;
}
// 下载请求无可用文件的结构化回报:[TOKEN_DOWNLOAD_ERROR:1][win32err:4 LE]。
// 走文件管理器子连接(传输子连接此时尚未建立),服务端立即失败而不是等停滞看门狗。
void CFileManager::SendDownloadError(DWORD dwErr)
{
if (dwErr == 0) dwErr = ERROR_FILE_NOT_FOUND;
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
pkt[0] = TOKEN_DOWNLOAD_ERROR;
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
m_ClientObject->Send2Server((char*)pkt, (UINT)sizeof(pkt));
}
bool CFileManager::UploadToRemote(LPBYTE lpBuffer)
{
if (lpBuffer[lstrlen((char *)lpBuffer) - 1] == '\\') {
@@ -1119,19 +1169,23 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
if (remotePaths.empty()) {
Mprintf("[V2] 没有要传输的文件\n");
SendDownloadError(ERROR_INVALID_PARAMETER);
return;
}
// 收集所有文件(展开目录)
std::vector<std::string> allFiles;
std::vector<std::string> rootCandidates; // 用于计算公共根目录
DWORD dwFirstErr = 0; // 首个失败的 win32 码(全部不存在时回传)
for (const auto& remotePath : remotePaths) {
std::string localPath = ExpandPath(remotePath.c_str());
DWORD attrs = GetFileAttributesA(localPath.c_str());
if (attrs == INVALID_FILE_ATTRIBUTES)
if (attrs == INVALID_FILE_ATTRIBUTES) {
if (dwFirstErr == 0) dwFirstErr = GetLastError();
continue;
}
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
// 目录:递归收集
@@ -1150,7 +1204,8 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
}
if (allFiles.empty()) {
Mprintf("[V2] 没有找到可传输的文件\n");
Mprintf("[V2] 没有找到可传输的文件 (win32=%lu)\n", dwFirstErr);
SendDownloadError(dwFirstErr);
return;
}
+2
View File
@@ -55,6 +55,8 @@ private:
void CreateFolder(LPBYTE lpBuffer);
void Rename(LPBYTE lpBuffer);
int SendToken(BYTE bToken);
UINT SendListError(DWORD dwErr); // 列目录失败的结构化回报(TOKEN_FILE_LIST_ERROR + win32 码)
void SendDownloadError(DWORD dwErr); // 下载无可用文件的结构化回报(TOKEN_DOWNLOAD_ERROR + win32 码)
void CreateLocalRecvFile(LPBYTE lpBuffer);
void SetTransferMode(LPBYTE lpBuffer);
+158 -1
View File
@@ -227,7 +227,11 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
m_DataProcess = NULL;
m_ReconnectFunc = NULL;
m_masker = mask ? new HttpMask(DEFAULT_HOST) : new PkgMask();
#ifdef _DEBUG
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % (HeaderEncV6 + 1)));
#else
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % HeaderEncNum));
#endif
m_EncoderType = encoder;
m_Encoder = encoder ? new HellEncoder(enc, new XOREncoder16()) : new ProtocolEncoder();
#ifdef _WIN32
@@ -387,6 +391,9 @@ BOOL ConnectWithTimeout(SOCKET sock, SOCKADDR *addr, int timeout_sec=5)
BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
{
// 登录确认标志只描述「当前这条连接」:任何一次新建连都先清零,避免上一条连接的
// 确认结果替新连接背书(协议切换的自动回退靠它判断新入口是否真的登录成功)。
m_loginAcked.store(false, std::memory_order_release);
if (szServerIP != NULL && uPort != 0) {
SetServerAddress(szServerIP, uPort);
}
@@ -461,6 +468,134 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
#else
// 设置保活选项
SetKeepAliveOptions(m_sClientSocket);
#endif
}
// 握手超时:TLS / WebSocket 握手都是同步阻塞的(WsChannel::Handshake 逐字节 recv 等
// 101 响应),而 socket 默认没有收超时——对端接受 TCP 却迟迟不回数据时(反代上游黑洞、
// 中间设备只收不发),recv 会永久阻塞,StartClient 的重连循环整个停摆,只能重启进程。
// 这里给握手窗口设 15s 超时(与服务端两个握手线程同一个值),握手结束后立刻清零,
// 避免影响 WorkThread 之后依赖 select + 阻塞 recv 的常规收包。
bool hsTmoSet = false;
#ifdef _WIN32
{
DWORD hsTmo = 15000;
hsTmoSet = setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO,
(const char*)&hsTmo, sizeof(hsTmo)) == 0;
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&hsTmo, sizeof(hsTmo));
}
#else
{
struct timeval hsTmo;
hsTmo.tv_sec = 15;
hsTmo.tv_usec = 0;
hsTmoSet = setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO, &hsTmo, sizeof(hsTmo)) == 0;
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, &hsTmo, sizeof(hsTmo));
}
#endif
// WebSocket 传输(PROTO_WS / PROTO_WSS):出站被限制在 80/443/8080 等端口时,经反代
// 分流进来。与应用协议无关,位置和 TLS 相同(TLS 之下、应用协议之上);须在
// m_bConnected 置位前完成,确保工作线程不会在 Upgrade 尚未完成时就开始 recv。
// Linux / macOS / Android 不传 conn,协议由 SetDefaultProto 给出(见 IOCPClient.h)。
// 两边都没有时按明文直连,并留一行日志——否则「改成 WS 却毫无反应」无从排查。
const int protoType = m_conn ? (int)(unsigned char)m_conn->protoType : m_defaultProto;
if (!m_conn && m_defaultProto < 0) {
// 只记一次:重连循环每轮都会走到这里,否则日志会被刷满。
static std::atomic<bool> logged{false};
if (!logged.exchange(true))
Mprintf("[WS] 无连接配置(m_conn 为空)且未设置默认协议,本次按明文 TCP 直连\n");
}
const bool wsProto = (protoType == PROTO_WS || protoType == PROTO_WSS);
const bool wsTls = (protoType == PROTO_WSS);
m_useWs = false;
// Host 头与 SNI 用配置里的地址(域名),子连接只拿到解析后的 IP,必须回到 conn 取。
// 多地址(分号分隔)时取第一个:经反代接入的场景应在地址里只填一个域名。
std::string wsHost = m_sCurIP;
if (m_conn) {
std::string configured = m_conn->GetFirstServerIP();
if (!configured.empty())
wsHost = configured;
}
// IP 字面量不能当 SNI(RFC 6066);直接连 IP 时反代会落到默认 server 块。
const bool wsHostIsDomain = (inet_addr(wsHost.c_str()) == INADDR_NONE) && wsHost.find(':') == std::string::npos;
// WSS 但没有信任锚时的降级标记:本连接按明文 WS 走,服务端下发锚并热重载后,
// 下一次连接会自动升级为 WSS(见下方 else if 分支)。
bool wsDegraded = false;
#ifdef YAMA_TLS_CHANNEL
// 单向 TLS:证书存在(TlsEnabled())时,在应用协议首包前完成握手;握手失败即断开,
// 不回退明文(fail-closed,防降级)。证书存在但加载失败(TlsLoadError())同样拒绝
// 连接。握手须在 m_bConnected 置位前,确保工作线程不会在握手尚未完成时就开始 recv。
// m_useTls 在这里一次性锁定:Linux 客户端可能在此后收到服务端下发并热切换传输方式,
// 那条连接已建立,本连接的 Send/Recv 必须继续按握手时的传输方式走。
m_useTls = false;
if (TlsLoadError()) {
Mprintf("[TLS] 证书加载失败,拒绝连接(fail-closed)\n");
closesocket(m_sClientSocket);
m_sClientSocket = INVALID_SOCKET;
return FALSE;
}
// PROTO_WS 是显式选择的明文形态(反代的 80 端口、内网直连):即便本客户端配了信任锚
// 也不叠加 TLS,否则该形态永远不可达。WSS 与直连主控端口仍按上面的规则强制 TLS。
if (TlsEnabled() && protoType != PROTO_WS) {
// SNI:WSS 经反代时要让反代按域名分流到正确的 server 块;直连 IP/主控端口时保持
// 原样(不传名字),与既有行为一致。
const char* sni = (wsTls && wsHostIsDomain) ? wsHost.c_str() : NULL;
if (!m_tls.Handshake(m_sClientSocket, sni)) {
Mprintf("[TLS] 握手失败,断开连接(fail-closed)\n");
closesocket(m_sClientSocket);
m_sClientSocket = INVALID_SOCKET;
return FALSE;
}
m_useTls = true;
} else if (wsTls) {
// 回退(不是降级攻击面):没有信任锚时无法校验反代出示的证书,但此时客户端
// 本来也还没被「颁发」证书——先用明文 WS 把隧道打通,等服务端下发信任锚
// (COMMAND_TLS_ENABLE → TlsReload)后,下一次连接自动走 WSS。
// 注意:有锚但握手失败、或锚存在却加载失败(上面 TlsLoadError),仍然 fail-closed,
// 绝不静默降级。
wsDegraded = true;
Mprintf("[WS] 未配置信任锚,本次按明文 WebSocket 连接;服务端下发证书后重连将升级为 WSS\n");
}
#else
if (wsTls) {
Mprintf("[WS] 本平台不支持 TLS,无法使用 WSS 协议\n");
closesocket(m_sClientSocket);
m_sClientSocket = INVALID_SOCKET;
return FALSE;
}
#endif
if (wsProto) {
#ifdef YAMA_TLS_CHANNEL
m_ws.SetTls(m_useTls ? &m_tls : NULL);
#endif
std::string werr;
if (!m_ws.Handshake(m_sClientSocket, wsHost, (int)port, WS_UPGRADE_PATH, &werr)) {
Mprintf("[WS] WebSocket 握手失败(%s),断开连接\n", werr.c_str());
closesocket(m_sClientSocket);
m_sClientSocket = INVALID_SOCKET;
return FALSE;
}
m_useWs = true;
// 注意:这里不能读 m_useTls——无 TLS 的平台上(macOS/Android)它不存在;
// 本连接实际走的形态由 wsDegraded 区分:WSS 有锚走 TLS,没锚则明文回退。
Mprintf("[WS] WebSocket 已就绪: %s:%d%s%s\n", wsHost.c_str(), (int)port,
WS_UPGRADE_PATH, wsDegraded ? " (明文,等待信任锚)"
: (wsTls ? " (TLS)" : ""));
}
// 握手阶段结束(成功路径):清零握手超时,恢复普通阻塞收包。
if (hsTmoSet) {
#ifdef _WIN32
DWORD noTmo = 0;
setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&noTmo, sizeof(noTmo));
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&noTmo, sizeof(noTmo));
#else
struct timeval noTmo;
noTmo.tv_sec = 0;
noTmo.tv_usec = 0;
setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO, &noTmo, sizeof(noTmo));
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, &noTmo, sizeof(noTmo));
#endif
}
m_bConnected = TRUE;
@@ -526,6 +661,16 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
Sleep(50);
continue;
}
#ifdef YAMA_TLS_CHANNEL
// TLS 会话里可能有已解密、尚未交付的明文(select 只看底层 socket,看不到
// TLS 库内部缓冲),优先消费,避免被 select 卡住。
if (This->HasPendingData()) {
if (!This->ProcessRecvData(&m_CompressedBuffer, szBuffer, MAX_RECV_BUFFER - 1, 0)) {
break;
}
continue;
}
#endif
FD_ZERO(&fd);
FD_SET(This->m_sClientSocket, &fd);
// Linux select() 会修改 timeval,必须每次重置
@@ -632,7 +777,14 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
for (int i = 0; i < 16 && i < (int)bufLen; ++i) {
char tmp[12]; sprintf(tmp, "%02X ", (unsigned char)src[i]); buf += tmp;
}
Mprintf("[ERROR] Unknown header! bufLen=%lu, first 16 bytes: %s\n", bufLen, buf.c_str());
#ifdef YAMA_TLS_CHANNEL
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s (useTls=%d tlsReady=%d)\n",
this, bufLen, buf.c_str(), (int)m_useTls, (int)m_tls.IsReady());
#else
// macOS/Android 没有 TlsChannel(TLS 只在这两个平台之外的客户端实现)
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s\n",
this, bufLen, buf.c_str());
#endif
m_CompressedBuffer->ClearBuffer();
break;
}
@@ -861,6 +1013,11 @@ VOID IOCPClient::Disconnect()
closesocket(m_sClientSocket);
m_sClientSocket = INVALID_SOCKET;
#ifdef YAMA_TLS_CHANNEL
m_useTls = false; // 连接已断,Send/Recv 回到明文路径(下次 ConnectServer 重新锁定)
#endif
m_useWs = false; // WebSocket 帧状态同样按连接锁定,重连时重新握手
m_ws.Reset();
m_bConnected = FALSE;
}
+67 -1
View File
@@ -11,6 +11,13 @@
#pragma comment(lib,"ws2_32.lib")
#endif
// TLS 通道:Windows 走 Schannel,Linux 走 OpenSSL;macOS/Android 下该头为空,
// 且不定义 YAMA_TLS_CHANNEL,下方代码自动退回明文。
#include "TlsChannel.h"
// WebSocket 传输(经反代 443 等受限端口接入)。头文件实现,各平台编译目标无需改动。
#include "WsChannel.h"
#include "Buffer.h"
#include "zstd/zstd.h"
#include "domain_pool.h"
@@ -32,6 +39,7 @@
#endif
#include "IOCPBase.h"
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <chrono>
@@ -200,6 +208,12 @@ public:
m_nHostPort = uPort;
}
// 没有 conn 的构造路径(Linux / macOS / Android 的 main 都是 new IOCPClient(exit, false))
// 用它给出传输协议:直接取外壳注入的 CONNECT_ADDRESS.protoType。不调用则保持 -1,
// ConnectServer 按明文 TCP 直连——那正是「配置成 WS 却毫无反应」的来源,故三个平台
// 的 main 都要在进入重连循环前调一次。
void SetDefaultProto(int p) { m_defaultProto = p; }
std::string ServerIP() const
{
return m_sCurIP;
@@ -282,6 +296,14 @@ public:
// 仅在我们正在等待 auth 响应时(m_authPending=true)才消费;否则透传给 manager。
bool TryHandleAuthResponse(PBYTE buf, ULONG len);
// 登录是否已被服务端接受。服务端把本机加入在线列表后立刻下发 CMD_MASTERSETTING
// (2015RemoteDlg.cpp::SendMasterSettings(ctx, ...) 的登录路径),客户端在这里置位。
// 协议切换用来判断「新入口真的登录成功」,而不是只看 IsConnected()——那只代表
// TCP/TLS/WS 握手完成,登录可能被丢弃(选错后端、反代指到别的 WS 服务)。
// 每次 ConnectServer 开始时清零,故它只描述当前这条连接。
void SetLoginAcked(bool v) { m_loginAcked.store(v, std::memory_order_release); }
bool IsLoginAcked() const { return m_loginAcked.load(std::memory_order_acquire); }
// 主动断开当前连接,关闭 socket。提到 public 让外层(如 Linux/macOS main 的心跳
// 循环检测到服务端身份校验超时)能在重连前显式关闭旧 fd,避免泄漏。
virtual VOID Disconnect(); // 函数支持 TCP/UDP
@@ -289,14 +311,41 @@ public:
protected:
virtual int ReceiveData(char* buffer, int bufSize, int flags)
{
// WebSocket 传输:字节流在 WS 帧里,帧层自己处理 TLS(WSS)或裸 socket(WS)
if (m_useWs)
return m_ws.Recv(m_sClientSocket, buffer, bufSize - 1);
#ifdef YAMA_TLS_CHANNEL
if (m_useTls)
return m_tls.Recv(m_sClientSocket, buffer, bufSize - 1);
#endif
// TCP版本调用 recv
return recv(m_sClientSocket, buffer, bufSize - 1, 0);
int n = recv(m_sClientSocket, buffer, bufSize - 1, 0);
return n;
}
virtual bool ProcessRecvData(CBuffer* m_CompressedBuffer, char* szBuffer, int len, int flag);
virtual int SendTo(const char* buf, int len, int flags)
{
if (m_useWs)
return m_ws.Send(m_sClientSocket, buf, len);
#ifdef YAMA_TLS_CHANNEL
if (m_useTls)
return m_tls.Send(m_sClientSocket, buf, len);
#endif
return ::send(m_sClientSocket, buf, len, flags);
}
// TLS 会话里可能有已解密但尚未交付的明文(select 只能看到底层 socket 可读性,
// 看不到 TLS 库内部缓冲),接收线程在 select 前须优先消费,避免其被卡住。
// WebSocket 同理:已读进帧头、载荷还没交完的字节同样看不到。
bool HasPendingData() const
{
if (m_useWs)
return m_ws.HasPending();
#ifdef YAMA_TLS_CHANNEL
return m_useTls && m_tls.HasPending();
#else
return false;
#endif
}
BOOL OnServerSending(const char* szBuffer, ULONG ulOriginalLength, PkgMask* mask);
static DWORD WINAPI WorkThreadProc(LPVOID lParam);
VOID OnServerReceiving(CBuffer *m_CompressedBuffer, char* szBuffer, ULONG ulReceivedLength);
@@ -305,6 +354,23 @@ protected:
protected:
sockaddr_in m_ServerAddr;
SOCKET m_sClientSocket;
// WebSocket 传输(PROTO_WS / PROTO_WSS):ConnectServer 里握手成功时置位,
// Disconnect 时清除。与 m_useTls 一样按连接锁定,Send/Recv 不再现查 protoType。
WsChannel m_ws;
// 收发分处两个线程:连接线程写、接收/发送线程读。形式上必须是原子量(x86 上实践
// 无害,但换成别的架构就不能再依赖这个巧合)。
std::atomic<bool> m_useWs{false};
std::atomic<bool> m_loginAcked{false};
// m_conn 为空时的协议来源(见 SetDefaultProto)。-1 = 未设置,按明文 TCP 处理。
int m_defaultProto = -1;
#ifdef YAMA_TLS_CHANNEL
TlsChannel m_tls; // TLS 会话(证书存在时才启用,见 TlsChannel.h)
// 本连接是否走 TLS:在 ConnectServer 里握手成功时置位、Disconnect 时清除,Send/Recv
// 一律按这个快照走,不再每次现查 TlsEnabled()。Linux 客户端支持服务端下发后热切换
// 传输方式(TlsReload),若现查全局开关,切换后到重连完成之间的这一秒里会把明文塞进
// 已建立的 TLS 会话(或反过来),白白制造协议错误。
std::atomic<bool> m_useTls{false};
#endif
BOOL m_bWorkThread;
HANDLE m_hWorkThread;
BOOL m_bIsRunning;
+147
View File
@@ -0,0 +1,147 @@
// ImageResource.h: 不经加载器,直接从内存中的模块映像读取资源
//
// 加壳部署(EXE + SC_AES/sRDI)下,载荷映像以裸 shellcode 运行、未注册进加载器,
// FindResource/LoadIcon/CreateDialogParamA 这类按 hInstance 找资源的 API 全部失败
// (实测 Win11 返回 err=1812 / 59)。但映像的节(含 .rsrc)是按 PE 布局正常映射
// 的,资源目录里的偏移又都是 RVA,因此可以直接遍历 IMAGE_RESOURCE_DIRECTORY
// 取到资源数据。本文件只读调用方给出的映像,不做任何映射。
//
// 适用:正常 EXE/DLL、MemoryModule 手工映射 DLL、sRDI 包装的 shellcode 载荷。
// 注意:调用方传入的必须是已映射映像的基址(如 &__ImageBase),不是磁盘文件。
//
// 稳定性:所有偏移都按 SizeOfImage / 资源目录大小做越界检查,映像布局异常
// (被第三方加壳改坏、资源被裁剪等)时一律返回 NULL,绝不越界读取。
#ifndef YAMA_IMAGE_RESOURCE_H
#define YAMA_IMAGE_RESOURCE_H
#include <windows.h>
#ifdef __cplusplus
extern "C" const IMAGE_DOS_HEADER __ImageBase;
#endif
// RT_ICON / RT_GROUP_ICON 的数字 ID(与同名 RT_ 宏对应)
#define IMAGE_RES_TYPE_ICON 3
#define IMAGE_RES_TYPE_GROUP_ICON 14
#pragma pack(push, 1)
typedef struct GRPICONDIRENTRY {
BYTE bWidth;
BYTE bHeight;
BYTE bColorCount;
BYTE bReserved;
WORD wPlanes;
WORD wBitCount;
DWORD dwBytesInRes;
WORD nID;
} GRPICONDIRENTRY;
#pragma pack(pop)
#define IMAGE_RES_DIR_IN_BOUNDS(resOffset, resSize) \
((resOffset) <= (resSize) - sizeof(IMAGE_RESOURCE_DIRECTORY))
#define IMAGE_RES_ENTRY_ARRAY_OK(resOffset, resCount, resSize) \
((resCount) <= ((resSize) - (resOffset) - sizeof(IMAGE_RESOURCE_DIRECTORY)) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))
// 在已映射映像中查找 type/id(取第一个语言项)的资源数据,返回映像内指针
static const BYTE* FindImageResource(const void* pvImage, WORD nType, WORD nId, DWORD* pdwSize)
{
if (pdwSize) *pdwSize = 0;
if (!pvImage) return NULL;
const BYTE* pBase = (const BYTE*)pvImage;
const DWORD dwLfanew = *(const DWORD*)(pBase + 0x3C);
// 正常 PE 头远小于一页;sRDI 的 CLEARHEADER 只保留 PE 头(e_lfanew 之后),
// 所以这里不能用 MZ 判断,只能靠 e_lfanew 与 PE 签名
if (dwLfanew == 0 || dwLfanew > 0x1000) return NULL;
const PIMAGE_NT_HEADERS pNt = (const PIMAGE_NT_HEADERS)(pBase + dwLfanew);
if (pNt->Signature != IMAGE_NT_SIGNATURE) return NULL;
const DWORD dwImageSize = pNt->OptionalHeader.SizeOfImage;
const DWORD dwResRva = pNt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
const DWORD dwResSize = pNt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size;
if (dwResRva == 0 || dwResSize < sizeof(IMAGE_RESOURCE_DIRECTORY) ||
dwResRva > dwImageSize || dwResSize > dwImageSize - dwResRva) {
return NULL;
}
const BYTE* pRes = pBase + dwResRva;
// 已映射映像:资源目录与数据项偏移都是相对资源节起点的偏移 / RVA
// 目录三层:类型 -> 名称/ID -> 语言
const WORD keys[2] = { nType, nId };
DWORD dwDirOff = 0;
for (int i = 0; i < 2; i++) {
if (!IMAGE_RES_DIR_IN_BOUNDS(dwDirOff, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY* pRd = (const IMAGE_RESOURCE_DIRECTORY*)(pRes + dwDirOff);
const DWORD dwCount = (DWORD)pRd->NumberOfNamedEntries + pRd->NumberOfIdEntries;
if (!IMAGE_RES_ENTRY_ARRAY_OK(dwDirOff, dwCount, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pEntry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(pRd + 1);
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pFound = NULL;
for (DWORD j = 0; j < dwCount; j++) {
// 只按数字 ID 匹配;命名项(NameIsString)跳过
if (!(pEntry[j].Name & IMAGE_RESOURCE_NAME_IS_STRING) && pEntry[j].Id == keys[i]) {
pFound = &pEntry[j];
break;
}
}
if (!pFound || !pFound->DataIsDirectory) return NULL;
dwDirOff = pFound->OffsetToDirectory;
}
if (!IMAGE_RES_DIR_IN_BOUNDS(dwDirOff, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY* pLangDir = (const IMAGE_RESOURCE_DIRECTORY*)(pRes + dwDirOff);
const DWORD dwLangCount = (DWORD)pLangDir->NumberOfNamedEntries + pLangDir->NumberOfIdEntries;
if (dwLangCount == 0 || !IMAGE_RES_ENTRY_ARRAY_OK(dwDirOff, dwLangCount, dwResSize)) return NULL;
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pLang = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(pLangDir + 1);
if (pLang->DataIsDirectory) return NULL;
const DWORD dwDataOff = pLang->OffsetToData;
if (dwDataOff > dwResSize - sizeof(IMAGE_RESOURCE_DATA_ENTRY)) return NULL;
const IMAGE_RESOURCE_DATA_ENTRY* pData = (const IMAGE_RESOURCE_DATA_ENTRY*)(pRes + dwDataOff);
const DWORD dwRva = pData->OffsetToData;
const DWORD dwBytes = pData->Size;
if (dwRva > dwImageSize || dwBytes > dwImageSize - dwRva) return NULL;
if (pdwSize) *pdwSize = dwBytes;
return pBase + dwRva; // OffsetToData 是 RVA
}
// 按图标组(RT_GROUP_ICON)ID 建 HICON:选尺寸最接近 nWidth x nHeight 的一帧,
// 用 CreateIconFromResourceEx 创建。返回的 HICON 由调用方负责 DestroyIcon。
static HICON CreateImageIcon(const void* pvImage, WORD nGroupId, int nWidth, int nHeight)
{
DWORD dwGroupSize = 0;
const BYTE* pGroup = FindImageResource(pvImage, IMAGE_RES_TYPE_GROUP_ICON, nGroupId, &dwGroupSize);
if (!pGroup || dwGroupSize < 6 + sizeof(GRPICONDIRENTRY)) return NULL;
// GRPICONDIR: WORD idReserved, idType, idCount
const WORD nCount = *(const WORD*)(pGroup + 4);
if (*(const WORD*)(pGroup + 2) != 1 || nCount == 0) return NULL;
if (dwGroupSize < 6 + (DWORD)nCount * sizeof(GRPICONDIRENTRY)) return NULL;
const GRPICONDIRENTRY* pBest = NULL;
int nBestDiff = 0x7FFFFFFF;
for (WORD i = 0; i < nCount; i++) {
const GRPICONDIRENTRY* pEntry = (const GRPICONDIRENTRY*)(pGroup + 6 + i * sizeof(GRPICONDIRENTRY));
const int w = pEntry->bWidth ? pEntry->bWidth : 256; // 0 表示 256
const int h = pEntry->bHeight ? pEntry->bHeight : 256;
const int dx = w > nWidth ? w - nWidth : nWidth - w;
const int dy = h > nHeight ? h - nHeight : nHeight - h;
if (dx + dy < nBestDiff) {
nBestDiff = dx + dy;
pBest = pEntry;
}
}
if (!pBest) return NULL;
DWORD dwIconSize = 0;
const BYTE* pIcon = FindImageResource(pvImage, IMAGE_RES_TYPE_ICON, pBest->nID, &dwIconSize);
if (!pIcon || dwIconSize == 0) return NULL;
return (HICON)CreateIconFromResourceEx((PBYTE)pIcon, dwIconSize, TRUE, 0x00030000,
nWidth, nHeight, LR_DEFAULTCOLOR);
}
#endif // YAMA_IMAGE_RESOURCE_H
+382 -9
View File
@@ -45,6 +45,10 @@ IOCPClient* NewNetClient(CONNECT_ADDRESS* conn, State& bExit, const std::string&
return new IOCPUDPClient(bExit, exit_while_disconnect);
if (type == PROTO_HTTP || type == PROTO_HTTPS)
return new IOCPClient(bExit, exit_while_disconnect, MaskTypeHTTP, conn, publicIP);
// WebSocket:仍然是 IOCPClient(TCP 承载),只是 ConnectServer 里多做一次 Upgrade
// 握手,Send/Recv 换成 WS 帧。HTTP 伪装层不用(WS 帧本身就是 HTTP 升级后的流)。
if (type == PROTO_WS || type == PROTO_WSS)
return new IOCPClient(bExit, exit_while_disconnect, MaskTypeNone, conn, publicIP);
if (type == PROTO_KCP) {
return new IOCPKCPClient(bExit, exit_while_disconnect);
}
@@ -800,6 +804,28 @@ void ResponseDisable(IOCPClient *client, const char* type, LPBYTE data, int size
extern "C" bool IsSystemInSession0();
// 信任锚已写入/删除:热重载 TLS 状态,只在传输方式真正变化(明文 ↔ TLS)时断开重连;
// 仅换证书(仍是 TLS)不打断现有会话,新锚从下一条新连接开始生效。与 Linux 版的
// linux/main.cpp::ApplyTlsAnchorChange 同一语义。
static void ApplyTlsAnchorChange(IOCPClient* client)
{
const bool before = TlsEnabled();
std::string err;
if (!TlsReload(err)) {
Mprintf("[TLS] reload failed: %s (keeping current transport)\n", err.c_str());
return;
}
const bool after = TlsEnabled();
if (before == after) {
Mprintf("[TLS] trust anchor updated, transport unchanged (%s)\n",
after ? "TLS" : "plaintext");
return;
}
Mprintf("[TLS] transport switched to %s, reconnecting\n", after ? "TLS" : "plaintext");
if (client)
client->Disconnect(); // 断开后由重连循环用新传输方式重新登录
}
VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
bool isExit = szBuffer[0] == COMMAND_BYE || szBuffer[0] == SERVER_EXIT;
@@ -838,6 +864,132 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
m_cfg->SetStr("settings", "group_name", group);
break;
}
case COMMAND_REGEN_CLIENT_ID: {
// 撞 ID 的克隆机:服务端已判定「主机名不同却撞 client_id」,让本机重生成 ID。
// 新 ID = 旧 ID + 随机 UUID 再哈希,写回注册表后主动断开主连接,重连循环
// 会用新 ID 重新登录,脱离撞 ID 状态(脱离替补、正常显示在主机列表)。
uint64_t newID = RegenerateClientID(m_conn->clientID);
m_cfg->SetStr("settings", "client_id", std::to_string(newID));
Mprintf("[regen-client-id] 重生成 client_id: %llu -> %llu,即将重连\n",
m_conn->clientID, newID);
if (m_ClientObject)
m_ClientObject->Disconnect();
break;
}
case COMMAND_TLS_ENABLE: {
// 服务端下发信任锚证书:payload = PEM 正文(szBuffer+1 .. ulLength-1)。
// 写入注册表 settings\tls_cert 后热重载:明文 → TLS 的切换会断开本连接,重连
// 循环随即用 TLS 重新登录(此前按明文回退的 WSS 客户端就此升级为 WSS)。
if (ulLength > 1) {
std::string certPem((char*)szBuffer + 1, ulLength - 1);
m_cfg->SetStr("settings", "tls_cert", certPem);
ApplyTlsAnchorChange(m_ClientObject);
} else {
// 没有证书正文就等于「启用但没有锚」——不该悄悄忽略,留一行便于排查。
Mprintf("[TLS] COMMAND_TLS_ENABLE without a certificate payload, ignored\n");
}
break;
}
case COMMAND_TLS_DISABLE: {
// 删除注册表信任锚后热重载:TLS → 明文时断开重连(WSS 客户端会回到明文回退)。
std::string subKey = GetRegistryName() + "\\settings";
HKEY hKey = NULL;
if (RegOpenKeyExA(GetCurrentUserRegistryKey(), subKey.c_str(), 0,
KEY_SET_VALUE, &hKey) == ERROR_SUCCESS) {
RegDeleteValueA(hKey, "tls_cert");
RegCloseKey(hKey);
}
ApplyTlsAnchorChange(m_ClientObject);
break;
}
case COMMAND_SET_PROTO: {
// 协议切换(TCP / WS / WSS):把目标入口写进本机配置后断开本连接,重连循环
// (ClientDll.cpp 的 ApplyProtoSwitch)按新入口重连。入口覆盖要落盘,否则在线
// 升级换 DLL 后会被外壳注入的 protoType 按回 TCP。
//
// 载荷:[ProtoSwitchPacket][certLen 字节 PEM];host/port 都为空 = 还原到固定
// 直连入口(客户端记着安装时的 base 入口)。WSS 可附带信任锚(反代证书),先
// 落盘并重建 TLS 上下文,但这里不主动断开——断开统一放在末尾,避免丢后续包。
// 分享实例的连接入口由分享方控制,主控的协议切换对它无效——直接忽略,
// 避免白白断开一次再按注入配置连回来。
if (m_ClientApp && m_ClientApp->IsShared()) {
Mprintf("[proto-switch] ignored: shared instance follows the sharing host's entry\n");
break;
}
if (ulLength < 1 + sizeof(ProtoSwitchPacket)) {
Mprintf("[proto-switch] payload too short (%u), ignored\n", ulLength);
break;
}
ProtoSwitchPacket p = {};
memcpy(&p, szBuffer + 1, sizeof(p));
p.host[sizeof(p.host) - 1] = '\0';
p.port[sizeof(p.port) - 1] = '\0';
const int proto = p.proto;
if (proto != PROTO_TCP && proto != PROTO_WS && proto != PROTO_WSS) {
Mprintf("[proto-switch] unsupported proto %d, ignored\n", proto);
break;
}
const std::string host(p.host);
const int port = atoi(p.port);
const bool restore = (proto == PROTO_TCP && host.empty());
if (!restore && (host.empty() || port <= 0)) {
Mprintf("[proto-switch] missing proxy entry for proto %d, ignored\n", proto);
break;
}
// 随包下发的信任锚(WSS):写入后热重载,让下一次连接能校验反代证书。
const uint32_t maxCert = (uint32_t)(ulLength - 1 - sizeof(ProtoSwitchPacket));
uint32_t certLen = p.certLen < maxCert ? p.certLen : maxCert;
if (certLen > 0) {
std::string certPem((const char*)szBuffer + 1 + sizeof(ProtoSwitchPacket), certLen);
const std::string prevCert = m_cfg->GetStr("settings", "tls_cert");
m_cfg->SetStr("settings", "tls_cert", certPem);
std::string err;
if (!TlsReload(err)) {
// 放弃本次切换(不写 proto_override/entry_*,不断连):PEM 加载不了时客户端
// 会进入 TlsLoadError() 的 fail-closed 状态,切过去只会「新入口连不上,等
// 5 分钟自动回退」——而且自动回退本身也可能被误撤销。回滚证书并回报操作端。
m_cfg->SetStr("settings", "tls_cert", prevCert);
const std::string loadErr = err;
TlsReload(err); // 让 TLS 上下文回到旧锚(失败也不影响:旧锚此前是好的)
Mprintf("[proto-switch] trust anchor reload failed: %s, switch aborted\n", loadErr.c_str());
ClientMsg msg("协议切换", ("证书加载失败,已取消切换: " + loadErr).c_str());
SendData((LPBYTE)&msg, sizeof(msg));
break;
}
}
if (restore) {
m_cfg->SetStr("settings", "proto_override", "");
m_cfg->SetStr("settings", "entry_host", "");
m_cfg->SetStr("settings", "entry_port", "");
m_cfg->SetStr("settings", "entry_try_at", "0");
Mprintf("[proto-switch] restore request, reconnecting to the direct entry\n");
} else {
// 首次切换记下安装时的直连入口(「还原」用);每次切换记下当前入口(自动回退用)
if (m_cfg->GetStr("settings", "base_host").empty()) {
m_cfg->SetStr("settings", "base_host", m_conn->ServerIP());
m_cfg->SetStr("settings", "base_port", std::to_string(m_conn->ServerPort()));
m_cfg->SetStr("settings", "base_proto",
std::to_string((int)(unsigned char)m_conn->protoType));
}
m_cfg->SetStr("settings", "prev_host", m_conn->ServerIP());
m_cfg->SetStr("settings", "prev_port", std::to_string(m_conn->ServerPort()));
m_cfg->SetStr("settings", "prev_proto", std::to_string((int)(unsigned char)m_conn->protoType));
m_cfg->SetStr("settings", "proto_override", std::to_string(proto));
m_cfg->SetStr("settings", "entry_host", host);
m_cfg->SetStr("settings", "entry_port", std::to_string(port));
m_cfg->SetStr("settings", "entry_try_at", std::to_string((long long)time(0)));
Mprintf("[proto-switch] switching to proto %d via %s:%d, reconnecting\n",
proto, host.c_str(), port);
}
if (m_ClientObject)
m_ClientObject->Disconnect();
break;
}
case COMMAND_DOWN_EXEC: {
std::thread(DownExecute, std::string((char*)szBuffer + 1), this).detach();
@@ -1090,6 +1242,11 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
OnHeatbeatResponse(szBuffer, ulLength);
break;
case CMD_MASTERSETTING:
// 登录已被服务端接受:服务端把本机加入在线列表后才下发 MasterSettings
// (2015RemoteDlg.cpp::SendMasterSettings(ctx, ...) 的登录路径)。协议切换的
// 自动回退靠这个信号撤销,而不是只看连接是否建立——连接建立只说明握手完成。
if (m_ClientObject)
m_ClientObject->SetLoginAcked(true);
if (ulLength > MasterSettingsOldSize) {
memcpy(&m_settings, szBuffer + 1, ulLength > sizeof(MasterSettings) ? sizeof(MasterSettings) : MasterSettingsOldSize);
if (m_settings.Signature[0] && m_LoginSignature.empty()) {
@@ -1113,6 +1270,13 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
mgr->EnableOfflineRecord(TRUE);
}
Logger::getInstance().usingLog(m_settings.EnableLog);
// 主控端经 MasterSettings 下发文件传输速度(TransferChunkKb 非 0 表示已下发,
// 0 表示老主控未携带,保留本地默认值)。写入 [transfer] 节,供各 InitFileUpload
// 调用点经 GetTransferSpeed 读取。
if (m_settings.TransferChunkKb) {
m_cfg->SetInt("transfer", "ChunkKb", m_settings.TransferChunkKb);
m_cfg->SetInt("transfer", "DurationMs", m_settings.TransferDurationMs);
}
}
if (IsAuthKernel() &&
(m_settings.FeedbackUrl[0] || m_settings.HelpUrl[0] || m_settings.RequestAuthUrl[0] || m_settings.GetPluginUrl[0])) {
@@ -1472,16 +1636,43 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
case COMMAND_SEND_FILE_V2: {
// 主连接接收 V2 上传:确保文件传输模块已初始化(RecvFileChunkV2 依赖 g_status==1)。
// static 标志保证进程内只初始化一次,不随主连接重连反复 Init/Uninit。
static bool s_v2RecvInited = false;
if (!s_v2RecvInited) {
int chunkKb, durMs;
GetTransferSpeed(*m_cfg, chunkKb, durMs);
InitFileUpload({}, m_LoginMsg, m_LoginSignature, chunkKb, durMs, Logf);
s_v2RecvInited = true;
}
EnsureV2TransferInited();
// C2C/V2 文件接收(RecvFileChunkV2 内部会打印进度)
int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn,
// 展开文件名中的环境变量(如 %USERPROFILE%),与 V1 的 COMMAND_FILE_SIZE 保持一致。
// 快捷图标定位远程目录时,主控端下发的 targetDir 仍含未展开的 %USERPROFILE%
// (server/2015Remote/FileManagerDlg.cpp OnRemoteDesktop/Downloads/Home),
// 若不在接收端展开,RecvFileChunkV2 会按字面量建目录(如 CWD\%%USERPROFILE%%\...)。
char* recvBuf = (char*)szBuffer;
size_t recvLen = ulLength;
std::vector<uint8_t> rebuilt;
if (ulLength >= sizeof(FileChunkPacketV2) && szBuffer[0] == COMMAND_SEND_FILE_V2) {
const FileChunkPacketV2* pkt = (const FileChunkPacketV2*)szBuffer;
if (ulLength >= sizeof(FileChunkPacketV2) + pkt->nameLength + pkt->dataLength) {
// 文件名未必以 '\0' 结尾,先构造出以 '\0' 结尾的副本
std::string name((const char*)szBuffer + sizeof(FileChunkPacketV2), (size_t)pkt->nameLength);
char expanded[MAX_PATH * 2] = { 0 };
DWORD n = ExpandEnvironmentStringsA(name.c_str(), expanded, (DWORD)sizeof(expanded));
if (n > 0 && n < (DWORD)sizeof(expanded)) {
std::string newName(expanded, n - 1); // n 含末尾 '\0'
if (newName.size() != pkt->nameLength) {
// 展开后长度变化,重建包:[header][展开后的 name][data]
size_t newLen = sizeof(FileChunkPacketV2) + newName.size() + pkt->dataLength;
rebuilt.resize(newLen);
memcpy(rebuilt.data(), szBuffer, sizeof(FileChunkPacketV2));
FileChunkPacketV2* newPkt = (FileChunkPacketV2*)rebuilt.data();
newPkt->nameLength = newName.size();
memcpy(rebuilt.data() + sizeof(FileChunkPacketV2), newName.data(), newName.size());
memcpy(rebuilt.data() + sizeof(FileChunkPacketV2) + newName.size(),
(const char*)szBuffer + sizeof(FileChunkPacketV2) + pkt->nameLength,
(size_t)pkt->dataLength);
recvBuf = (char*)rebuilt.data();
recvLen = newLen;
}
}
}
}
int n = RecvFileChunkV2(recvBuf, recvLen, m_conn,
nullptr, m_hash, m_hmac, m_MyClientID);
if (n) {
Mprintf("[C2C] RecvFileChunkV2 failed: %d\n", n);
@@ -1489,6 +1680,12 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
}
case COMMAND_C2C_SEND_FILES: {
// C2C 按路径清单发送:服务端指定「源端路径 + 目标端目录」,见 OnC2CSendFiles。
OnC2CSendFiles(szBuffer, ulLength);
break;
}
case COMMAND_CLIPBOARD_V2: {
// C2C 剪贴板请求:被请求发送剪贴板文件到另一个客户端
ClipboardRequestV2* req = (ClipboardRequestV2*)szBuffer;
@@ -1764,6 +1961,182 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
}
// V2 文件传输模块是进程级的(InitFileUpload/UninitFileUpload 成对),发送与接收共用一次初始化:
// static 标志保证进程内只初始化一次,不随主连接重连反复 Init/Uninit,也不会被发送/接收两个
// 入口各自初始化一次(第二次 Init 会重置状态并泄漏前一次的上下文)。
void CKernelManager::EnsureV2TransferInited()
{
static bool s_v2Inited = false;
if (s_v2Inited) return;
int chunkKb, durMs;
GetTransferSpeed(*m_cfg, chunkKb, durMs);
int rc = InitFileUpload({}, m_LoginMsg, m_LoginSignature, chunkKb, durMs, Logf);
if (rc != 0) Mprintf("[V2] InitFileUpload 返回 %d,V2 文件传输可能不可用\n", rc);
s_v2Inited = true;
}
// 收集目录下的文件与子目录(语义同 CFileManager::CollectFilesRecursiveV2:
// 目录本身先作为一条 V2 目录项,随后是子项)。无成员依赖,主连接侧直接复用。
static void CollectFilesForC2C(const std::string& dirPath, std::vector<std::string>& files)
{
std::string dirEntry = dirPath;
while (!dirEntry.empty() && (dirEntry.back() == '\\' || dirEntry.back() == '/'))
dirEntry.pop_back();
if (!dirEntry.empty()) files.push_back(dirEntry);
WIN32_FIND_DATAA wfd;
HANDLE hFind = FindFirstFileA((dirPath + "*.*").c_str(), &wfd);
if (hFind == INVALID_HANDLE_VALUE) return;
do {
if (wfd.cFileName[0] == '.') continue;
std::string fullPath = dirPath + wfd.cFileName;
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
CollectFilesForC2C(fullPath + "\\", files);
else
files.push_back(fullPath);
} while (FindNextFileA(hFind, &wfd));
FindClose(hFind);
}
// 展开 %VAR%(与 CFileManager 的静态 ExpandPath 同语义,展开失败返回原路径)
static std::string ExpandPathForC2C(const char* path)
{
char szExpanded[MAX_PATH * 2] = { 0 };
DWORD len = ExpandEnvironmentStringsA(path, szExpanded, (DWORD)sizeof(szExpanded));
if (len > 0 && len < (DWORD)sizeof(szExpanded)) return szExpanded;
return path;
}
// C2C 按路径清单发送(服务端 → 源客户端)。
// 包格式:[C2CSendFilesPacket][targetDir\0][path1\0]...[pathN\0][\0](ANSI/936)。
// 与 COMMAND_CLIPBOARD_V2 的差别只在文件来源:这里的路径由服务端指定,不取剪贴板/资源管理器选中项。
// 数据由本端新开子连接上行,服务端按包内 dstClientID 原样中继到目标客户端的主连接。
void CKernelManager::OnC2CSendFiles(PBYTE szBuffer, ULONG ulLength)
{
if (ulLength < sizeof(C2CSendFilesPacket)) return;
const C2CSendFilesPacket* req = (const C2CSendFilesPacket*)szBuffer;
const char* p = (const char*)szBuffer + sizeof(C2CSendFilesPacket);
const char* end = (const char*)szBuffer + ulLength;
std::string targetDir = (p < end) ? std::string(p) : std::string();
p += targetDir.size() + 1;
std::vector<std::string> paths;
while (p < end && *p != '\0') {
paths.push_back(p);
p += strlen(p) + 1;
}
// 收包缓冲在 OnReceive 返回后即失效:先把要用的字段拷出来,线程里只用副本。
const uint64_t transferID = req->transferID;
const uint64_t dstClientID = req->dstClientID;
std::string hash(req->hash, strnlen(req->hash, sizeof(req->hash)));
std::string hmac(req->hmac, strnlen(req->hmac, sizeof(req->hmac)));
// 结果包(服务端 TOKEN_C2C_SEND_RESULT → MCP 等待线程)。任何早退都要回一包,
// 否则服务端只能干等超时——这与 download_file 早期的「静默超时」是同一种毛病。
auto sendResult = [&](uint32_t status, uint32_t win32err, int32_t workerRc,
uint32_t fileCount, uint64_t totalBytes) {
C2CSendResultPacket res = {};
res.cmd = TOKEN_C2C_SEND_RESULT;
res.transferID = transferID;
res.dstClientID = dstClientID;
res.status = status;
res.win32err = win32err;
res.workerRc = workerRc;
res.fileCount = fileCount;
res.totalBytes = totalBytes;
m_ClientObject->Send2Server((char*)&res, sizeof(res));
};
// FileBatchTransferWorkerV2 依赖 g_status==1(InitFileUpload 已调用),否则直接返回 -1。
// 源端可能从未打开过文件管理器、也从未接收过上传,所以这里必须显式初始化。
EnsureV2TransferInited();
if (paths.empty() || targetDir.empty()) {
Mprintf("[C2C] 路径清单发送请求非法: transferID=%llu, paths=%zu, targetDir=%s\n",
transferID, paths.size(), targetDir.c_str());
sendResult(FEV2_FILE_NOT_FOUND, ERROR_INVALID_PARAMETER, 0, 0, 0);
return;
}
// 收集文件:展开环境变量、递归展开目录(目录项本身也发给目标端,用于建空目录)
std::vector<std::string> allFiles;
DWORD dwFirstErr = 0;
for (const std::string& raw : paths) {
std::string localPath = ExpandPathForC2C(raw.c_str());
DWORD attrs = GetFileAttributesA(localPath.c_str());
if (attrs == INVALID_FILE_ATTRIBUTES) {
if (dwFirstErr == 0) dwFirstErr = GetLastError();
Mprintf("[C2C] 源路径不可访问: %s (win32=%lu)\n", localPath.c_str(), dwFirstErr);
continue;
}
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
std::string dirPath = localPath;
if (dirPath.back() != '\\') dirPath += '\\';
CollectFilesForC2C(dirPath, allFiles);
} else {
allFiles.push_back(localPath);
}
}
if (allFiles.empty()) {
sendResult(FEV2_FILE_NOT_FOUND,
dwFirstErr ? dwFirstErr : (DWORD)ERROR_FILE_NOT_FOUND, 0, 0, 0);
return;
}
// 统计(目录项不计入 fileCount/totalBytes)
uint32_t fileCount = 0;
uint64_t totalBytes = 0;
for (const std::string& f : allFiles) {
WIN32_FILE_ATTRIBUTE_DATA fad;
if (!GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad)) continue;
if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
fileCount++;
totalBytes += ((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow;
}
IOCPClient* pClient = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn);
pClient->EnableSubConnAuth(); // V2 文件传输子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
if (!pClient->ConnectServer(m_ClientObject->ServerIP().c_str(), m_ClientObject->ServerPort())) {
delete pClient;
Mprintf("[C2C] 连接服务器失败\n");
sendResult(1001, 0, -1, 0, 0);
return;
}
TransferOptionsV2 opts;
opts.transferID = transferID;
opts.srcClientID = m_MyClientID;
opts.dstClientID = dstClientID;
opts.enableResume = false; // v1 不做断点续传:失败即整包重发(目标端状态按 transferID 索引)
std::thread([allFiles, targetDir, pClient, opts, hash, hmac,
transferID, dstClientID, fileCount, totalBytes]() {
int rc = FileBatchTransferWorkerV2(allFiles, targetDir, pClient,
[](void* user, FileChunkPacketV2* chunk, unsigned char* data, int size) -> bool {
IOCPClient* client = (IOCPClient*)user;
return client->Send2Server((char*)data, size) != FALSE;
},
nullptr, hash, hmac, opts);
C2CSendResultPacket res = {};
res.cmd = TOKEN_C2C_SEND_RESULT;
res.transferID = transferID;
res.dstClientID = dstClientID;
res.status = (rc == 0) ? (uint32_t)FEV2_OK : (uint32_t)1001;
res.win32err = 0;
res.workerRc = (int32_t)rc;
res.fileCount = fileCount;
res.totalBytes = totalBytes;
pClient->Send2Server((char*)&res, sizeof(res));
delete pClient;
Mprintf("[C2C] 路径清单发送结束: transferID=%llu, %u 个文件, rc=%d\n",
transferID, fileCount, rc);
}).detach();
}
void CKernelManager::OnHeatbeatResponse(PBYTE szBuffer, ULONG ulLength)
{
if (ulLength > 8) {
+6 -11
View File
@@ -125,17 +125,7 @@ private:
bool IsWorkstationLocked()
{
HDESK hInput = OpenInputDesktop(0, FALSE, GENERIC_READ);
// 如果无法打开桌面,可能是因为桌面已经切换到 Winlogon
if (!hInput) return true;
char name[256] = {0};
DWORD needed;
bool isLocked = false;
if (GetUserObjectInformationA(hInput, UOI_NAME, name, sizeof(name), &needed)) {
isLocked = (_stricmp(name, "Winlogon") == 0);
}
CloseDesktop(hInput);
return isLocked;
return ::IsWorkstationLocked();
}
};
@@ -200,6 +190,11 @@ public:
std::string m_hash;
std::string m_hmac;
uint64_t m_MyClientID = 0;
// COMMAND_C2C_SEND_FILES:按服务端指定的路径清单把文件直接发给另一个客户端。
// 包格式 [C2CSendFilesPacket][targetDir\0][path1\0]...[pathN\0][\0],结果用 TOKEN_C2C_SEND_RESULT 回传。
void OnC2CSendFiles(PBYTE szBuffer, ULONG ulLength);
// 进程级 V2 文件传输模块初始化(幂等),发送与接收两条路径共用。
void EnsureV2TransferInited();
// 执行代码
std::map<std::string, std::vector<BYTE>> m_MemDLL;
void SetLoginMsg(const std::string& msg)
+5 -1
View File
@@ -679,7 +679,11 @@ DWORD WINAPI CKeyboardManager1::KeyLogger(LPVOID lparam)
if (!SetHook(WriteBuffer, pThis->m_Buffer)) {
return -1;
}
while (pThis->IsConnected() && PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
// 低层键盘钩子的回调在本线程的消息泵里执行,所以只要钩子还装着就必须泵消息。
// 离线记录时即使没有键盘子连接钩子也常驻;此前要求 IsConnected() 才泵,
// 等于在输入链上挂一个永不返回的钩子(每个按键被 LowLevelHooksTimeout 卡住),
// 同机的 YAMA 钩子收不到完整按键对,Win 快捷键与 Ctrl+V 转发失效。
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
#else
int num = lstrlen(KeyBuffer);
if (pThis->IsWindowsFocusChange(PreviousFocus, WindowCaption, szText, num > 0) || num > 2000) {
+56 -10
View File
@@ -289,6 +289,35 @@ uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normal
return XXH64(s.c_str(), s.length(), 0);
}
// 撞 ID 的克隆机重生成 client_id:在旧 ID 基础上掺一个一次性随机 UUID 再哈希。
// 只在服务端判定「主机名不同却撞 ID」后下发 COMMAND_REGEN_CLIENT_ID 触发,不影响
// 正常(首次)登录的 CalcalateIDv2 算法;唯一性由随机 UUID 保证,同批克隆机各自
// 随机,重算后必然不同。
uint64_t RegenerateClientID(uint64_t oldID)
{
// 16 字节随机数充当一次性 UUID(RtlGenRandom = advapi32 SystemFunction036)。
unsigned char rnd[16] = {};
if (!RtlGenRandom(rnd, (ULONG)sizeof(rnd))) {
// 极少数环境 RtlGenRandom 可能失败:退化为时间/进程/线程/性能计数混合的 LCG,
// 保证仍能产出与旧 ID 不同的新 ID(不追求密码学强度,只需撞车概率足够低)。
uint64_t mix = GetTickCount64() ^ ((uint64_t)GetCurrentProcessId() << 32)
^ (uint64_t)GetCurrentThreadId();
LARGE_INTEGER pc;
QueryPerformanceCounter(&pc);
mix ^= (uint64_t)pc.QuadPart;
for (int i = 0; i < 16; ++i) {
mix = mix * 6364136223846793005ULL + 1442695040888963407ULL;
rnd[i] = (unsigned char)(mix >> 56);
}
}
char hex[33];
for (int i = 0; i < 16; ++i)
sprintf_s(hex + i * 2, 3, "%02X", (unsigned)rnd[i]);
hex[32] = '\0';
std::string seed = std::to_string(oldID) + "|" + hex;
return XXH64(seed.c_str(), seed.size(), 0);
}
BOOL IsAuthKernel(std::string &str) {
BOOL isAuthKernel = FALSE;
std::string pid = std::to_string(GetCurrentProcessId());
@@ -378,13 +407,29 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
std::string pubIP = cfg.GetStr("settings", "public_ip", "");
auto ip_time = cfg.GetInt("settings", "ip_time");
bool timeout = ip_time <= 0 || (time(0) - ip_time > 7 * 86400);
// 升级后强制重新查询一次:旧版缓存的 location 是 GBK/CP1252,或已把 ö/ä/ß 等替换成 '?';
// 新版 GetGeoLocation 改为 UTF-8 上报(见 common/location.h),需重新拉取才能修正。
// 版本号即编译日期 __DATE__(见 common/commands.h 的 DLL_VERSION):编译期宏,内存 DLL
// 也能取到,且每次编译都会变,天然标识“升级”,无需手动递增,也不依赖 exe 版本资源。
bool cacheVerChanged = (cfg.GetStr("settings", "loc_cache_ver", "") != __DATE__);
IPConverter cvt;
if (loc.empty() || pubIP.empty() || timeout) {
pubIP = cvt.getPublicIP();
loc = cvt.GetGeoLocation(pubIP);
cfg.SetStr("settings", "location", loc);
cfg.SetStr("settings", "public_ip", pubIP);
cfg.SetInt("settings", "ip_time", time(0));
if (loc.empty() || pubIP.empty() || timeout || cacheVerChanged) {
std::string newPubIP = pubIP;
// 升级重查 location 时复用已缓存的公网 IP;仅当 IP 缺失或 7 天过期才重新探测,
// 否则离线/无外网机器每次重连都会轮询 5 个公网 IP 源、空等数秒到十几秒。
if (pubIP.empty() || timeout) {
newPubIP = cvt.getPublicIP();
}
std::string newLoc = cvt.GetGeoLocation(newPubIP);
// 仅查询成功才覆盖缓存并推进版本号;失败保留旧值,下次登录仍会重试。
if (!newLoc.empty() && !newPubIP.empty()) {
pubIP = newPubIP;
loc = newLoc;
cfg.SetStr("settings", "location", loc);
cfg.SetStr("settings", "public_ip", pubIP);
cfg.SetInt("settings", "ip_time", time(0));
cfg.SetStr("settings", "loc_cache_ver", __DATE__);
}
}
LoginInfor.AddReserved(loc.c_str());
LoginInfor.AddReserved(pubIP.c_str());
@@ -396,13 +441,13 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
sprintf(cpuInfo, "%dMHz", dwCPUMHz);
std::string clientID = cfg.GetStr("settings", "client_id");
if (clientID.empty()) {
// V2 ID 算法:MachineGuid + 归一化路径
// - 同机同程序路径永远同 ID(不依赖 IP/PCName/OS/CPU 漂移)
// - 局域网多机即便同镜像(sysprep 会让 MachineGuid 各不同)也不撞库
// V2 ID 算法:MachineGuid + 主机名 + 归一化路径
// - 主机名兜底区分同镜像克隆机:MachineGuid 相同、路径相同仍能靠主机名区分。
// - 代价:改名会让 client_id 变化,丢该主机的备注/授权/历史;主机名非硬件唯一,重名仍撞。
// MachineGuid 读取失败的极端情况退化到老算法,保兼容。
std::string machineGuid = GetMachineGuidWindows();
if (!machineGuid.empty()) {
conn.clientID = CalcalateIDv2(machineGuid, NormalizeExePathLower(buf), isAuth);
conn.clientID = CalcalateIDv2(machineGuid + "|" + szPCName, NormalizeExePathLower(buf), isAuth);
} else {
Mprintf("WARN: MachineGuid 读取失败,回退到老 ID 算法\n");
conn.clientID = CalcalateID({ pubIP, szPCName, LoginInfor.OsVerInfoEx, cpuInfo, buf });
@@ -428,6 +473,7 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
double KB = fileInfo.nFileSizeLow > 1024 ? fileInfo.nFileSizeLow / 1024.0 : 0;
sprintf_s(fileSize, "%.1f%s", MB > 0 ? MB : KB, MB > 0 ? "M" : "K");
LoginInfor.AddReserved(fileSize); // 文件大小
LoginInfor.AddReserved(TlsEnabled() ? 1 : 0); // TLS 启用标志:有信任锚(证书)即 1
return LoginInfor;
}
+1
View File
@@ -7,6 +7,7 @@
std::string GetMachineGuidWindows();
uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normalizedPath, bool isAuth = false);
uint64_t RegenerateClientID(uint64_t oldID);
BOOL IsAuthKernel(std::string& str);
LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS &conn, const std::string& expiredDate, bool isAuth);
DWORD CPUClockMHz();
+400 -131
View File
@@ -122,6 +122,23 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
case COMMAND_MACHINE_TASK:
GetRoot();
break;
// 计划任务动作:lpBuffer+1 起是 NUL 结尾的窄字符串(服务端按 MultiByte 组包)
case COMMAND_TASKSTART:
RunOrStopTask(lpBuffer + 1, TRUE);
GetRoot();
break;
case COMMAND_TASKSTOP:
RunOrStopTask(lpBuffer + 1, FALSE);
GetRoot();
break;
case COMMAND_TASKDEL:
DelTask(lpBuffer + 1);
GetRoot();
break;
case COMMAND_TASKCREAT:
CreateTask(lpBuffer + 1);
GetRoot();
break;
case COMMAND_MACHINE_HOSTS:
SendHostsList();
break;
@@ -190,8 +207,13 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
DebugPrivilege(SE_DEBUG_NAME, TRUE);
char strProcessName[MAX_PATH] = { 0 };
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, *(LPDWORD)(lpBuffer + 1));
if (hProcess == NULL) {
DebugPrivilege(SE_DEBUG_NAME, FALSE);
break;
}
GetModuleFileNameEx(hProcess, NULL, strProcessName, MAX_PATH);
if (lpBuffer[1]) {
// PID 的第 2~4 字节非零时也要删除:只看 lpBuffer[1] 会把低字节为 0 的 PID 漏掉
if (*(LPDWORD)(lpBuffer + 1) != 0) {
char Tem_path[MAX_PATH];
char path_one[MAX_PATH];
char path_two[MAX_PATH];
@@ -218,10 +240,10 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
DeleteFile(path_one); //删除目录(目录)
Sleep(200);
if (GetFileAttributes(strProcessName) == -1) //检查文件不存在 退出
return;
break;
n++;
if (n >= 10) //无法删除 一段时间后退出
return;
break;
}
}
CloseHandle(hProcess);
@@ -282,11 +304,13 @@ void CMachineManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
while (b) {
if (th32.th32OwnerProcessID == Pid) {
HANDLE oth = OpenThread(THREAD_ALL_ACCESS, FALSE, th32.th32ThreadID);
::ResumeThread(oth);
CloseHandle(oth);
break;
if (oth) {
::ResumeThread(oth);
CloseHandle(oth);
}
}
::Thread32Next(hThreadSnap, &th32);
// 冻结挂起了全部线程,解冻也必须逐个恢复;这里不能 break,否则进程只会恢复一个线程
b = ::Thread32Next(hThreadSnap, &th32);
}
::CloseHandle(hThreadSnap);
}
@@ -554,7 +578,11 @@ LPBYTE CMachineManager::getProcessList()
pe32.dwSize = sizeof(PROCESSENTRY32);
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1024);
if (lpBuffer == NULL) {
CloseHandle(hSnapshot);
DebugPrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_PROCESS;
dwOffset = 1;
@@ -572,6 +600,8 @@ LPBYTE CMachineManager::getProcessList()
if ((pe32.th32ProcessID != 0) && (pe32.th32ProcessID != 4) && (pe32.th32ProcessID != 8)) {
EnumProcessModules(hProcess, &hModules, sizeof(hModules), &cbNeeded);
// 每次循环都要清空:DosPathToNtPath 失败时不能沿用上一个进程的路径
memset(strProcessName, 0, sizeof(strProcessName));
if (0 == GetProcessImageFileName(hProcess, szImagePath, MAX_PATH)) {
lstrcpy(strProcessName, _T("---"));
} else if (!DosPathToNtPath(szImagePath, strProcessName)) {
@@ -590,8 +620,15 @@ LPBYTE CMachineManager::getProcessList()
dwLength = sizeof(DWORD) * 5 + sizeof(bool) + MAX_PATH * sizeof(char) + lstrlen(pe32.szExeFile) * sizeof(char) +
lstrlen(strProcessName) * sizeof(char) + lstrlen(strProcessUser) * sizeof(char) + 6;
// 缓冲区太小,再重新分配下
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,结束收集并返回已拿到的记录
CloseHandle(hProcess);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, &(pe32.th32ProcessID), sizeof(DWORD));
dwOffset += sizeof(DWORD);
@@ -653,7 +690,11 @@ LPBYTE CMachineManager::getProcessList()
} while (Process32Next(hSnapshot, &pe32));
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
DebugPrivilege(SE_DEBUG_NAME, FALSE);
CloseHandle(hSnapshot);
@@ -687,6 +728,13 @@ LPBYTE CMachineManager::getWindowsList()
{
LPBYTE lpBuffer = NULL;
EnumWindows((WNDENUMPROC)EnumWindowsProc, (LPARAM)&lpBuffer);
if (lpBuffer == NULL) {
// 一个可见窗口都没有时回调不会分配缓冲区:仍要回一个只带令牌的包,
// 否则下面写 lpBuffer[0] 就是空指针写,客户端会崩溃。
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1);
if (lpBuffer == NULL)
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_WINDOWS;
return lpBuffer;
}
@@ -739,13 +787,18 @@ bool CALLBACK CMachineManager::EnumWindowsProc(HWND hwnd, LPARAM lParam)
::GetWindowText(hwnd, m_ibfo.strTitle, 1024);
if (lpBuffer == NULL) {
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1);
dwOffset = 1;
lpBuffer = (LPBYTE)LocalAlloc(LPTR, dwOffset + sizeof(WINDOWSINFO));
if (lpBuffer == NULL)
return true;
} else {
dwOffset = (DWORD)LocalSize(lpBuffer);
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset + sizeof(WINDOWSINFO), LMEM_ZEROINIT | LMEM_MOVEABLE);
// 分配失败时原缓冲区仍然有效,不能把指针覆盖成 NULL
if (lpNew == NULL)
return true;
lpBuffer = lpNew;
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset + sizeof(WINDOWSINFO), LMEM_ZEROINIT | LMEM_MOVEABLE);
} catch (...) {
return true;
}
@@ -853,8 +906,15 @@ LPBYTE CMachineManager::getSoftWareList()
// 缓冲区太小,再重新分配下
dwLength = lstrlen(regDisplayName) * sizeof(char) + lstrlen(regPublisher) * sizeof(char) + lstrlen(regDisplayVersion) *
sizeof(char) + lstrlen(regInstallData) * sizeof(char) + lstrlen(regUninstallString) * sizeof(char) + 11;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,跳过这一条并结束枚举
RegCloseKey(hSubKey);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, regDisplayName, lstrlen(regDisplayName) * sizeof(char) + 2);
dwOffset += lstrlen(regDisplayName) * sizeof(char) + 2;
@@ -870,11 +930,13 @@ LPBYTE CMachineManager::getSoftWareList()
memcpy(lpBuffer + dwOffset, regUninstallString, lstrlen(regUninstallString) * sizeof(char) + 2);
dwOffset += lstrlen(regUninstallString) * sizeof(char) + 2;
RegCloseKey(hSubKey);
}
}
}
} else {
return FALSE; //打开键失败
LocalFree(lpBuffer);
return NULL; //打开键失败
}
RegCloseKey(hKey);
@@ -898,6 +960,7 @@ LPBYTE CMachineManager::getSoftWareList()
// 取ParentKeyName键值,判断是否是补丁信息, 是补丁信息键值为"OperatingSystem"
RegQueryValueEx(hSubKey, _T("ParentKeyName"), 0, &dwType, (LPBYTE)regBufferValue, &dwRegSize);
if (lstrlen(regDisplayName) == 0 || lstrcmp(regBufferValue, _T("OperatingSystem")) == 0) { //判断是否是补丁信息
RegCloseKey(hSubKey);
continue;
}
@@ -935,8 +998,15 @@ LPBYTE CMachineManager::getSoftWareList()
// 缓冲区太小,再重新分配下
dwLength = lstrlen(regDisplayName) * sizeof(char) + lstrlen(regPublisher) * sizeof(char) + lstrlen(regDisplayVersion) *
sizeof(char) + lstrlen(regInstallData) * sizeof(char) + lstrlen(regUninstallString) * sizeof(char) + 11;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,跳过这一条并结束枚举
RegCloseKey(hSubKey);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, regDisplayName, lstrlen(regDisplayName) * sizeof(char) + 2);
dwOffset += lstrlen(regDisplayName) * sizeof(char) + 2;
@@ -952,15 +1022,23 @@ LPBYTE CMachineManager::getSoftWareList()
memcpy(lpBuffer + dwOffset, regUninstallString, lstrlen(regUninstallString) * sizeof(char) + 2);
dwOffset += lstrlen(regUninstallString) * sizeof(char) + 2;
RegCloseKey(hSubKey);
}
}
}
} else
return FALSE; //打开键失败
} else {
//打开键失败
LocalFree(lpBuffer);
return NULL;
}
RegCloseKey(hKey);
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
return lpBuffer;
}
@@ -991,6 +1069,12 @@ LPBYTE CMachineManager::getIEHistoryList()
DWORD dwOffset = 1;
DWORD dwLength = 0;
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 10000);
if (lpBuffer == NULL) {
if (SUCCEEDED(hr) && puhs != NULL)
puhs->Release();
CoUninitialize();
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_HTML;
Browsinghistory m_Browsinghistory;
dwLength = sizeof(Browsinghistory);
@@ -1012,12 +1096,20 @@ LPBYTE CMachineManager::getIEHistoryList()
SYSTEMTIME st;
if (&su.ftLastVisited != NULL) {
FileTimeToSystemTime(&su.ftLastVisited, &st);
wsprintf(m_Browsinghistory.strTime, _T("%d-%d-%d %d:%d:%d"), st.wYear, st.wMonth, st.wDay, st.wHour, st.wSecond, st.wMinute);
wsprintf(m_Browsinghistory.strTime, _T("%d-%02d-%02d %02d:%02d:%02d"), st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
} else {
wsprintf(m_Browsinghistory.strTime, _T("---"));
}
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL) {
// 扩容失败时原缓冲区仍然有效,停止收集,返回已拿到的记录
CoTaskMemFree(su.pwcsUrl);
CoTaskMemFree(su.pwcsTitle);
break;
}
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, &m_Browsinghistory, sizeof(Browsinghistory));
dwOffset += sizeof(Browsinghistory);
@@ -1028,11 +1120,15 @@ LPBYTE CMachineManager::getIEHistoryList()
su.pwcsTitle = nullptr;
}
pesu->Release();
puhs->Release();
}
puhs->Release();
}
CoUninitialize();
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
return lpBuffer;
}
@@ -1053,15 +1149,22 @@ void CMachineManager::FindFavoritesUrl(char* searchfilename, PBYTE &lpFUBuffer,
char tmpPath[MAX_PATH] = { 0 };
DWORD dwFULength = 0;
lstrcat(favpath, searchfilename);
// 拼接要限长:收藏夹目录较深时 searchfilename 可能已接近 MAX_PATH
if (lstrlen(searchfilename) + 4 >= MAX_PATH)
return;
lstrcpyn(favpath, searchfilename, MAX_PATH - 4);
lstrcat(favpath, _T("\\*.*"));
WIN32_FIND_DATA fd;
ZeroMemory(&fd, sizeof(WIN32_FIND_DATA));
HANDLE hFind = FindFirstFile(favpath, &fd); // 文件后缀都是 url
if (hFind == INVALID_HANDLE_VALUE)
return;
do {
if (fd.cFileName[0] != _T('.')) {
if (lstrlen(searchfilename) + 1 + lstrlen(fd.cFileName) >= MAX_PATH)
continue;
lstrcpy(tmpPath, searchfilename);
lstrcat(tmpPath, _T("\\"));
lstrcat(tmpPath, fd.cFileName);
@@ -1074,8 +1177,13 @@ void CMachineManager::FindFavoritesUrl(char* searchfilename, PBYTE &lpFUBuffer,
dwFULength = lstrlen(buf) * sizeof(char) + lstrlen(fd.cFileName) * sizeof(char) + 4;
if (LocalSize(lpFUBuffer) < (dwFUOffset + dwFULength))
lpFUBuffer = (LPBYTE)LocalReAlloc(lpFUBuffer, (dwFUOffset + dwFULength) + 1024, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpFUBuffer) < (dwFUOffset + dwFULength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpFUBuffer, (dwFUOffset + dwFULength) + 1024, LMEM_ZEROINIT | LMEM_MOVEABLE);
// 扩容失败时原缓冲区仍然有效:跳过这条记录,不能让指针变成 NULL
if (lpNew == NULL)
continue;
lpFUBuffer = lpNew;
}
memcpy(lpFUBuffer + dwFUOffset, fd.cFileName, lstrlen(fd.cFileName) * sizeof(char) + 2);
dwFUOffset += lstrlen(fd.cFileName) * sizeof(char) + 2;
@@ -1094,21 +1202,32 @@ LPBYTE CMachineManager::getFavoritesUrlList()
char favpath[MAX_PATH] = { 0 };
// 从注册表获取收藏夹所在位置
HKEY hKEY;
HKEY hKEY = NULL;
DWORD type = REG_SZ;
LPCTSTR path = _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
DWORD cbData = 80;
::RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_READ, &hKEY);
::RegQueryValueEx(hKEY, _T("Favorites"), NULL, &type, (LPBYTE)favpath, &cbData);
::RegCloseKey(hKEY);
DWORD cbData = sizeof(favpath);
// RegOpenKeyEx 失败时 hKEY 是无效值,不能再拿它查值/关闭
if (::RegOpenKeyEx(HKEY_CURRENT_USER, path, 0, KEY_READ, &hKEY) == ERROR_SUCCESS) {
if (::RegQueryValueEx(hKEY, _T("Favorites"), NULL, &type, (LPBYTE)favpath, &cbData) != ERROR_SUCCESS)
favpath[0] = 0;
::RegCloseKey(hKEY);
}
favpath[MAX_PATH - 1] = 0;
LPBYTE lpFUBuffer = (LPBYTE)LocalAlloc(LPTR, 10000);
if (lpFUBuffer == NULL)
return NULL;
lpFUBuffer[0] = TOKEN_MACHINE_FAVORITES;
int dwFUOffset = 1;
FindFavoritesUrl(favpath, lpFUBuffer, dwFUOffset);
if (favpath[0] != 0)
FindFavoritesUrl(favpath, lpFUBuffer, dwFUOffset);
lpFUBuffer = (LPBYTE)LocalReAlloc(lpFUBuffer, dwFUOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpFUBuffer, dwFUOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpFUBuffer = lpNew;
}
return lpFUBuffer;
}
@@ -1141,15 +1260,30 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
DWORD dwSize = 1024 * 8;
sc = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (sc == NULL) {
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
//第一次调用来得到需要多大的内存区
EnumServicesStatus(sc, dwScType, SERVICE_STATE_ALL, lpServices, size, &size, &ret, NULL);
//申请需要的内存
lpServices = (LPENUM_SERVICE_STATUS)LocalAlloc(LPTR, size);
if (lpServices == NULL) {
CloseServiceHandle(sc);
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
EnumServicesStatus(sc, dwScType, SERVICE_STATE_ALL, lpServices, size, &size, &ret, NULL);
// 申请Buffer内存
lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1024 * sizeof(char));
if (lpBuffer == NULL) {
LocalFree(lpServices);
CloseServiceHandle(sc);
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return NULL;
}
lpBuffer[0] = TOKEN_MACHINE_SERVICE_LIST;
dwOffset = 1;
@@ -1166,7 +1300,7 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
// 描述
memset(lpDescription, 0, sizeof(lpDescription));
if (((LPSERVICE_DESCRIPTION)szInfo)->lpDescription != NULL)
lstrcpy(lpDescription, ((LPSERVICE_DESCRIPTION)szInfo)->lpDescription);
lstrcpyn(lpDescription, ((LPSERVICE_DESCRIPTION)szInfo)->lpDescription, sizeof(lpDescription));
// 状态
memset(strState, 0, sizeof(strState));
@@ -1200,6 +1334,7 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
ZeroMemory(szInfo, dwSize);
dwSize = 1024 * 8;
if (!QueryServiceConfig(sh, (LPQUERY_SERVICE_CONFIG)szInfo, dwSize, &dwSize)) {
CloseServiceHandle(sh);
continue;
}
// 启动类型
@@ -1234,8 +1369,15 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
//==========================================================================================
// 缓冲区太小,再重新分配下
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
// 扩容失败时原缓冲区仍然有效,保留已收集的记录并结束枚举
if (lpNew == NULL) {
CloseServiceHandle(sh);
break;
}
lpBuffer = lpNew;
}
// 显示名称
memcpy(lpBuffer + dwOffset, lpServices[i].lpDisplayName, lstrlen(lpServices[i].lpDisplayName) * sizeof(char) + sizeof(char));
@@ -1277,8 +1419,14 @@ LPBYTE CMachineManager::getServiceList(DWORD dwScType)
}
CloseServiceHandle(sc);
LocalFree(lpServices);
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
// 收缩到实际长度;失败时原缓冲区仍有效,直接按原大小返回
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return lpBuffer;
}
@@ -1303,7 +1451,16 @@ void CMachineManager::SendHostsList()
if (hFile == INVALID_HANDLE_VALUE)
return;
dwSize = GetFileSize(hFile, NULL);
// GetFileSize 失败返回 INVALID_FILE_SIZE:不加判断会按 0xFFFFFFFF 分配并读入
if (dwSize == INVALID_FILE_SIZE) {
CloseHandle(hFile);
return;
}
lpBuffer = (LPBYTE)LocalAlloc(LPTR, dwSize + 2);
if (lpBuffer == NULL) {
CloseHandle(hFile);
return;
}
if (!ReadFile(hFile, lpBuffer + 1, dwSize, &dwRead, NULL)) {
LocalFree(lpBuffer);
CloseHandle(hFile);
@@ -1320,46 +1477,63 @@ void CMachineManager::SendHostsList()
LPBYTE CMachineManager::getNetStateList()
{
LPBYTE lpBuffer = (LPBYTE)LocalAlloc(LPTR, 1024);
if (lpBuffer == NULL)
return NULL;
lpBuffer[0] = TOKEN_MACHINE_NETSTATE;
DWORD dwOffset = 1;
DWORD dwLength = 0;
WCHAR* temp;
// 定义扩展函数指针
PFNAllocateAndGetTcpExTableFromStack pAllocateAndGetTcpExTableFromStack;
PFNAllocateAndGetUdpExTableFromStack pAllocateAndGetUdpExTableFromStack;
// 获取扩展函数的入口地址
HMODULE hModule = ::LoadLibrary(_T("iphlpapi.dll"));
pAllocateAndGetTcpExTableFromStack =
pAllocateAndGetTcpExTableFromStack = hModule == NULL ? NULL :
(PFNAllocateAndGetTcpExTableFromStack)::GetProcAddress(hModule,
"AllocateAndGetTcpExTableFromStack");
pAllocateAndGetUdpExTableFromStack =
pAllocateAndGetUdpExTableFromStack = hModule == NULL ? NULL :
(PFNAllocateAndGetUdpExTableFromStack)::GetProcAddress(hModule,
"AllocateAndGetUdpExTableFromStack");
if (pAllocateAndGetTcpExTableFromStack != NULL || pAllocateAndGetUdpExTableFromStack != NULL) {
// 两个导出函数要么都有(XP/2003)、要么都没有(Vista+):用 && 避免只匹配到一个时空指针调用
if (pAllocateAndGetTcpExTableFromStack != NULL && pAllocateAndGetUdpExTableFromStack != NULL) {
// 调用扩展函数,获取TCP扩展连接表和UDP扩展监听表
PMIB_TCPEXTABLE pTcpExTable;
PMIB_UDPEXTABLE pUdpExTable;
PMIB_TCPEXTABLE pTcpExTable = NULL;
PMIB_UDPEXTABLE pUdpExTable = NULL;
// pTcpExTable和pUdpExTable所指的缓冲区自动由扩展函数在进程堆中申请
if (pAllocateAndGetTcpExTableFromStack(&pTcpExTable, TRUE, GetProcessHeap(), 2, 2) != 0) {
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
if (pAllocateAndGetUdpExTableFromStack(&pUdpExTable, TRUE, GetProcessHeap(), 2, 2) != 0) {
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
// 给系统内的所有进程拍一个快照
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE) {
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
char szLocalAddr[128];
char szRemoteAddr[128];
char szProcessName[128];
in_addr inadLocal, inadRemote;
char strState[128];
DWORD dwRemotePort = 0;
@@ -1419,24 +1593,26 @@ LPBYTE CMachineManager::getNetStateList()
// 远程IP地址
inadRemote.s_addr = pTcpExTable->table[i].dwRemoteAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pTcpExTable->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
temp = char2wchar_t(inet_ntoa(inadRemote));
wsprintf(szRemoteAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
SAFE_DELETE_AR(temp);
// 客户端是 MultiByte 工程,缓冲区是 char[]:这里必须用窄字符格式化,
// 不能先转成 WCHAR* 再交给 _T("%s")(ANSI 的 %s 只会读到首字符,地址显示成 0/1)。
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pTcpExTable->table[i].dwLocalPort)));
sprintf_s(szRemoteAddr, "%s:%u", inet_ntoa(inadRemote),
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[TCP]");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pTcpExTable->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pTcpExTable->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(strState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1461,23 +1637,25 @@ LPBYTE CMachineManager::getNetStateList()
for (DWORD i = 0; i < pUdpExTable->dwNumEntries; ++i) {
// 本地IP地址
inadLocal.s_addr = pUdpExTable->table[i].dwLocalAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[UDP]");
const char* szRemoteAddr = _T("*.*.*.*:*");
const char* szUDPState = _T(" ");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(szUDPState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1498,28 +1676,43 @@ LPBYTE CMachineManager::getNetStateList()
dwOffset += lstrlen(szUDPState) * sizeof(char) + 2;
}
::CloseHandle(hProcessSnap);
::LocalFree(pTcpExTable);
::LocalFree(pUdpExTable);
// 扩展表是扩展函数在 GetProcessHeap() 上用 HeapAlloc 申请的,应对应用 HeapFree 释放
if (pTcpExTable)
::HeapFree(GetProcessHeap(), 0, pTcpExTable);
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
::FreeLibrary(hModule);
} else {
char szLocalAddr[128];
char szRemoteAddr[128];
char szProcessName[128];
in_addr inadLocal, inadRemote;
char strState[128];
DWORD dwRemotePort = 0;
PMIB_TCPEXTABLE_VISTA pTcpTable_Vista;
_InternalGetTcpTable2 pGetTcpTable = (_InternalGetTcpTable2)GetProcAddress(hModule, "InternalGetTcpTable2");
if (pGetTcpTable == NULL)
PMIB_TCPEXTABLE_VISTA pTcpTable_Vista = NULL;
_InternalGetTcpTable2 pGetTcpTable = hModule == NULL ? NULL :
(_InternalGetTcpTable2)GetProcAddress(hModule, "InternalGetTcpTable2");
if (pGetTcpTable == NULL) {
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return 0;
}
if (pGetTcpTable(&pTcpTable_Vista, GetProcessHeap(), 1))
if (pGetTcpTable(&pTcpTable_Vista, GetProcessHeap(), 1)) {
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return 0;
}
// 给系统内的所有进程拍一个快照
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE) {
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
::FreeLibrary(hModule);
LocalFree(lpBuffer);
return NULL;
}
@@ -1577,25 +1770,25 @@ LPBYTE CMachineManager::getNetStateList()
// 远程IP地址
inadRemote.s_addr = pTcpTable_Vista->table[i].dwRemoteAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pTcpTable_Vista->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
temp = char2wchar_t(inet_ntoa(inadRemote));
wsprintf(szRemoteAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
SAFE_DELETE_AR(temp);
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pTcpTable_Vista->table[i].dwLocalPort)));
sprintf_s(szRemoteAddr, "%s:%u", inet_ntoa(inadRemote),
ntohs((unsigned short)(0x0000FFFF & dwRemotePort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[TCP]");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pTcpTable_Vista->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pTcpTable_Vista->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(strState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1619,7 +1812,7 @@ LPBYTE CMachineManager::getNetStateList()
PMIB_UDPEXTABLE pUdpExTable = NULL;
// 表明为 Vista 或者 7 操作系统
PFNInternalGetUdpTableWithOwnerPid pInternalGetUdpTableWithOwnerPid;
pInternalGetUdpTableWithOwnerPid =
pInternalGetUdpTableWithOwnerPid = hModule == NULL ? NULL :
(PFNInternalGetUdpTableWithOwnerPid)GetProcAddress(hModule, "InternalGetUdpTableWithOwnerPid");
if (pInternalGetUdpTableWithOwnerPid != NULL) {
if (pInternalGetUdpTableWithOwnerPid(&pUdpExTable, GetProcessHeap(), 1)) {
@@ -1627,8 +1820,12 @@ LPBYTE CMachineManager::getNetStateList()
HeapFree(GetProcessHeap(), 0, pUdpExTable);
}
::CloseHandle(hProcessSnap);
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
FreeLibrary(hModule);
hModule = NULL;
LocalFree(lpBuffer);
return 0;
}
@@ -1637,23 +1834,25 @@ LPBYTE CMachineManager::getNetStateList()
for (DWORD i = 0; i < pUdpExTable->dwNumEntries; ++i) {
// 本地IP地址
inadLocal.s_addr = pUdpExTable->table[i].dwLocalAddr;
temp = char2wchar_t(inet_ntoa(inadLocal));
wsprintf(szLocalAddr, _T("%s:%u"), temp,
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
SAFE_DELETE_AR(temp);
sprintf_s(szLocalAddr, "%s:%u", inet_ntoa(inadLocal),
ntohs((unsigned short)(0x0000FFFF & pUdpExTable->table[i].dwLocalPort)));
// 打印出此入口的信息
char strProcessName[100] = { 0 };
const char* strType = _T("[UDP]");
const char* szRemoteAddr = _T("*.*.*.*:*");
const char* szUDPState = _T(" ");
lstrcpy(strProcessName, ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, szProcessName));
ProcessPidToName(hProcessSnap, pUdpExTable->table[i].dwProcessId, strProcessName, sizeof(strProcessName));
dwLength = lstrlen(strProcessName) * sizeof(char) + sizeof(DWORD) + lstrlen(strType) * sizeof(char) +
lstrlen(szLocalAddr) * sizeof(char) + lstrlen(szRemoteAddr) * sizeof(char) + lstrlen(szUDPState) *
sizeof(char) + 12;
if (LocalSize(lpBuffer) < (dwOffset + dwLength))
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (LocalSize(lpBuffer) < (dwOffset + dwLength)) {
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, (dwOffset + dwLength), LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew == NULL)
break; // 扩容失败时保留原缓冲区,已收集的记录照常返回
lpBuffer = lpNew;
}
memcpy(lpBuffer + dwOffset, strProcessName, lstrlen(strProcessName) * sizeof(char) + 2);
dwOffset += lstrlen(strProcessName) * sizeof(char) + 2;
@@ -1673,26 +1872,42 @@ LPBYTE CMachineManager::getNetStateList()
memcpy(lpBuffer + dwOffset, szUDPState, lstrlen(szUDPState) * sizeof(char) + 2);
dwOffset += lstrlen(szUDPState) * sizeof(char) + 2;
}
if (pUdpExTable)
::HeapFree(GetProcessHeap(), 0, pUdpExTable);
}
// Vista 分支的资源必须在这里释放:每次刷新网络列表都会走到这里
::CloseHandle(hProcessSnap);
if (pTcpTable_Vista)
::HeapFree(GetProcessHeap(), 0, pTcpTable_Vista);
::FreeLibrary(hModule);
}
lpBuffer = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
{
LPBYTE lpNew = (LPBYTE)LocalReAlloc(lpBuffer, dwOffset, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpBuffer = lpNew;
}
return lpBuffer;
}
// 将进程ID号(PID)转化为进程名称
char* CMachineManager::ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName)
char* CMachineManager::ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName, int nSize)
{
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(processEntry);
if (ProcessName == NULL || nSize <= 0)
return ProcessName;
// 找不到的话,默认进程名为“???”
lstrcpy(ProcessName, _T("???"));
lstrcpyn(ProcessName, _T("???"), nSize);
if (!::Process32First(hProcessSnap, &processEntry))
return ProcessName;
do {
if (processEntry.th32ProcessID == ProcessId) { // 就是这个进程
lstrcpy(ProcessName, processEntry.szExeFile);
// szExeFile 最长 MAX_PATH,目标缓冲区可能只有 100 字节,必须限长拷贝
lstrcpyn(ProcessName, processEntry.szExeFile, nSize);
break;
}
} while (::Process32Next(hProcessSnap, &processEntry));
@@ -1700,16 +1915,6 @@ char* CMachineManager::ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, ch
}
wchar_t* CMachineManager::char2wchar_t(char* cstr)
{
int len = MultiByteToWideChar(CP_ACP, 0, cstr, -1, NULL, 0);
wchar_t* wstr = new wchar_t[len];
memset(wstr, 0, len * sizeof(wchar_t));
MultiByteToWideChar(CP_ACP, 0, cstr, -1, wstr, len);
return wstr;
}
BOOL CMachineManager::EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable)
{
HANDLE hToken;
@@ -1733,18 +1938,21 @@ BOOL CMachineManager::EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable)
void CMachineManager::DeleteService(LPBYTE lpBuffer, UINT nSize)
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
SERVICE_STATUS status;
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS);
DWORD _err = GetLastError();
BOOL isSuccess = QueryServiceStatus(service, &status);
if (status.dwCurrentState != SERVICE_STOPPED) {
isSuccess = ControlService(service, SERVICE_CONTROL_STOP, &status);
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (scm == NULL) {
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return;
}
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS);
if (service != NULL) {
SERVICE_STATUS status = { 0 };
if (QueryServiceStatus(service, &status) && status.dwCurrentState != SERVICE_STOPPED) {
ControlService(service, SERVICE_CONTROL_STOP, &status);
}
::DeleteService(service);
CloseServiceHandle(service);
}
isSuccess = ::DeleteService(service);
CloseServiceHandle(service);
CloseServiceHandle(scm);
// 稍稍Sleep下,防止出错
@@ -1757,25 +1965,55 @@ void CMachineManager::DeleteService(LPBYTE lpBuffer, UINT nSize)
void CMachineManager::MyControlService(LPBYTE lpBuffer, UINT nType)
{
EnablePrivilege(SE_DEBUG_NAME, TRUE);
SERVICE_STATUS status;
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); // 打开服务管理对象
SC_HANDLE scm = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); // 打开服务管理对象
if (scm == NULL) {
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return;
}
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS); // 打开www服务
SC_HANDLE service = OpenService(scm, (char*)lpBuffer, SERVICE_ALL_ACCESS); // 打开服务
if (service == NULL) {
CloseServiceHandle(scm);
SendServicesList(m_dwServiceType);
EnablePrivilege(SE_DEBUG_NAME, FALSE);
return;
}
SERVICE_STATUS status = { 0 };
BOOL isSuccess = QueryServiceStatus(service, &status);
switch (nType) {
case 0:
case 0: {
if (status.dwCurrentState == SERVICE_STOP_PENDING) {
// 服务端“重启服务”是 STOP 后 100ms 就发 START:这里等服务真正停下来,
// 否则 StartService 会以服务仍在停止中失败,表现为“重启后服务没起来”。
for (int i = 0; i < 50 && status.dwCurrentState == SERVICE_STOP_PENDING; i++) {
Sleep(100);
if (!QueryServiceStatus(service, &status))
break;
}
}
if (status.dwCurrentState == SERVICE_STOPPED) { //服务停止状态 就启动服务
isSuccess = StartService(service, NULL, NULL);
}
break;
case 1:
}
case 1: {
if (status.dwCurrentState != SERVICE_STOPPED) {
isSuccess = ControlService(service, SERVICE_CONTROL_STOP, &status);
if (status.dwCurrentState != SERVICE_STOP_PENDING)
isSuccess = ControlService(service, SERVICE_CONTROL_STOP, &status);
// 同步等待停止完成(最多 5 秒),让紧随其后的 START 能成功
if (isSuccess || status.dwCurrentState == SERVICE_STOP_PENDING) {
for (int i = 0; i < 50 && status.dwCurrentState != SERVICE_STOPPED; i++) {
Sleep(100);
if (!QueryServiceStatus(service, &status))
break;
}
}
}
break;
}
case 2:
if (status.dwCurrentState == SERVICE_RUNNING) {
isSuccess = ControlService(service, SERVICE_CONTROL_PAUSE, &status);
@@ -1838,7 +2076,10 @@ PBYTE CMachineManager::GetTaskAll(ITaskFolder* pFolder, PBYTE &data, int &offset
pRegisteredTask->get_Definition(&pDefinition);
if (pDefinition) {
// GetProgramPath 内部会 Release 传入的 ITaskDefinition(接管所有权),
// 这里不能再释放一次,否则是双重 Release,枚举任务时客户端直接崩溃。
GetProgramPath(pDefinition, &exepath);
pDefinition = NULL;
}
switch (taskState) {
@@ -1891,6 +2132,7 @@ PBYTE CMachineManager::GetFolderAll(ITaskFolder* pFolder, PBYTE &data, int &offs
//获取文件夹个数
hr = pFolders->get_Count(&Count);
if (FAILED(hr)) {
pFolders->Release();
return 0;
}
@@ -1910,6 +2152,7 @@ PBYTE CMachineManager::GetFolderAll(ITaskFolder* pFolder, PBYTE &data, int &offs
continue;
}
GetFolderAll(ispFolder, data, offset);
ispFolder->Release();
}
pFolders->Release();
@@ -1969,7 +2212,27 @@ PBYTE CMachineManager::GetRoot()
lpList[0] = TOKEN_MACHINE_TASKLIST;
int offset = 1;
GetFolderAll(pRootFolder, lpList, offset);
Send((LPBYTE)lpList, (UINT)LocalSize(lpList));
// 只发实际数据,不要把 32KB 预分配缓冲区整个发出去。
// 服务端解析靠每条记录末尾的两个 NUL 判断结束,所以非空列表要多带 2 字节结束标记;
// 没有任务时只发令牌 1 字节(长度为 1 时服务端循环直接结束)。
UINT dwSend = 1;
if (offset > 1) {
dwSend = (UINT)(offset + 2);
if ((UINT)LocalSize(lpList) < dwSend) {
PBYTE lpNew = (PBYTE)LocalReAlloc(lpList, dwSend, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (lpNew != NULL)
lpList = lpNew;
}
if ((UINT)LocalSize(lpList) >= dwSend) {
lpList[offset] = 0;
lpList[offset + 1] = 0;
} else {
// 扩不出结束标记时只回令牌,避免服务端越界读
dwSend = 1;
}
}
Send((LPBYTE)lpList, dwSend);
LocalFree(lpList);
}
pRootFolder->Release();
@@ -2033,15 +2296,18 @@ BOOL CMachineManager::CreateTask(LPBYTE lpBuffer)
//设置被结束后自动延迟10分钟运行
pSettings->put_StartWhenAvailable(VARIANT_TRUE);
//创建触发器
ITrigger* pTrigger;
ITrigger* pTrigger = NULL;
hr = pTriggers->Create(TASK_TRIGGER_LOGON, &pTrigger);
IAction* pAction;
IAction* pAction = NULL;
//设置执行
pActions->Create(TASK_ACTION_EXEC, &pAction);
pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction);
//设置程序路径等信息
pExecAction->put_Path(CharToBSTR(path));
if (pAction) {
pAction->QueryInterface(IID_IExecAction, (void**)&pExecAction);
//设置程序路径等信息
if (pExecAction)
pExecAction->put_Path(CharToBSTR(path));
}
//注册
hr = pRootFolder->RegisterTaskDefinition(CharToBSTR(taskname), pDefinition, TASK_CREATE_OR_UPDATE,
_variant_t(), _variant_t(), TASK_LOGON_INTERACTIVE_TOKEN, _variant_t(L""), &pRegisteredTask);
@@ -2162,10 +2428,13 @@ void CMachineManager::SaveData(const std::string& taskname, const std::string& p
sum = nameLEN + taskpathLEN + statusLEN + exeLEN + sizeof(DATE) * 2;
// 动态扩展缓冲区
if (LocalSize(lpList) < (offset + sum)) {
lpList = (BYTE*)LocalReAlloc(lpList, LocalSize(lpList)+4*1024, LMEM_ZEROINIT | LMEM_MOVEABLE);
if (!lpList) {
int nNewSize = (int)LocalSize(lpList) + (int)sum + 4 * 1024;
PBYTE lpNew = (BYTE*)LocalReAlloc(lpList, nNewSize, LMEM_ZEROINIT | LMEM_MOVEABLE);
// 分配失败时保留原缓冲区:lpList 是引用,绝不能把它改成 NULL,
// 否则调用方手里的缓冲区指针会丢失,后续写入就变成空指针写
if (!lpNew)
return;
}
lpList = lpNew;
}
//拷贝数据
+1 -2
View File
@@ -34,8 +34,7 @@ private:
HWND GetHwndByPid(DWORD dwProcessID);
bool Is64BitOS();
bool Is64BitPorcess(DWORD dwProcessID);
char* ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName);
wchar_t* char2wchar_t(char* cstr);
char* ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName, int nSize);
BOOL EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable);
void DeleteService(LPBYTE lpBuffer, UINT nSize);
void MyControlService(LPBYTE lpBuffer, UINT nType);
+16
View File
@@ -156,6 +156,22 @@ HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess)
return hInputDesktop;
}
bool IsWorkstationLocked()
{
HDESK hInput = OpenInputDesktop(0, FALSE, GENERIC_READ);
// 打不开输入桌面,通常就是已经切到 Winlogon(锁屏)
if (!hInput) return true;
char name[256] = { 0 };
DWORD needed = 0;
bool isLocked = false;
if (GetUserObjectInformationA(hInput, UOI_NAME, name, sizeof(name), &needed)) {
isLocked = (_stricmp(name, "Winlogon") == 0);
}
CloseDesktop(hInput);
return isLocked;
}
// 返回新桌面句柄,如果没有变化返回NULL
HDESK IsDesktopChanged(HDESK currentDesk, DWORD accessRights)
{
+4
View File
@@ -15,6 +15,10 @@
HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess = 0);
// 工作站是否已锁屏(输入桌面切到 Winlogon)。锁屏时 DXGI 桌面复制在部分环境会卡在
// 初始化里不返回,抓屏初始化需要据此提前走 GDI。
bool IsWorkstationLocked();
HDESK IsDesktopChanged(HDESK currentDesk, DWORD accessRights);
bool SwitchToDesktopIfChanged(HDESK& currentDesk, DWORD accessRights);
+16
View File
@@ -57,6 +57,22 @@ VOID CRegisterManager::Find(char bToken, char *szPath)
// 子键包(TOKEN_REG_PATH):无子键时也回传空包,保证服务端(含 MCP 无头查询)
// 能确定性收齐 PATH+KEY 两包,无需靠超时猜测是否有第二包。
char *szBuffer= Opt.FindPath();
// 键打不开(不存在 / 路径不存在 / 拒绝访问 …):回结构化错误包。此前这种情况与
// 「空键」同为 NULL,服务端只能回一个空列表,调用方无法区分。
LSTATUS st = Opt.GetLastOpenStatus();
if (st != ERROR_SUCCESS) {
BYTE pkt[1 + sizeof(LSTATUS)] = { 0 };
pkt[0] = TOKEN_REG_ERROR;
memcpy(pkt + 1, &st, sizeof(LSTATUS));
m_ClientObject->Send2Server((char*)pkt, sizeof(pkt));
// 老服务端不认识 TOKEN_REG_ERROR:补上原来的两个空包,仍按「空键」处理,行为不变。
char empty[1 + sizeof(REGMSG)] = { 0 };
empty[0] = TOKEN_REG_PATH;
m_ClientObject->Send2Server(empty, sizeof(empty));
empty[0] = TOKEN_REG_KEY;
m_ClientObject->Send2Server(empty, sizeof(empty));
return;
}
if(szBuffer!=NULL) {
m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer));
//目录下的目录
+5 -2
View File
@@ -60,6 +60,7 @@ RegisterOperation::RegisterOperation(char bToken)
}
ZeroMemory(KeyPath,MAX_PATH);
m_lastOpenStatus = ERROR_SUCCESS;
}
RegisterOperation::~RegisterOperation()
@@ -73,7 +74,8 @@ char* RegisterOperation::FindPath()
char *szBuffer=NULL;
HKEY hKey; //注册表返回句柄
/*打开注册表 User kdjfjkf\kdjfkdjf\ */
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey)==ERROR_SUCCESS) { //打开
m_lastOpenStatus = RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey);
if(m_lastOpenStatus==ERROR_SUCCESS) { //打开
DWORD dwIndex=0,NameCount,NameMaxLen;
DWORD KeySize,KeyCount,KeyMaxLen,MaxDataLen;
//这就是枚举了
@@ -127,7 +129,8 @@ char* RegisterOperation::FindKey()
char *szBuffer=NULL;
HKEY hKey; //注册表返回句柄
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey)==ERROR_SUCCESS) { //打开
m_lastOpenStatus = RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey);
if(m_lastOpenStatus==ERROR_SUCCESS) { //打开
DWORD dwIndex=0,NameSize,NameCount,NameMaxLen,Type;
DWORD KeyCount,KeyMaxLen,DataSize,MaxDataLen;
//这就是枚举了
+5
View File
@@ -19,6 +19,11 @@ public:
char KeyPath[MAX_PATH];
void SetPath(char *szPath);
char* FindKey();
// 最近一次 RegOpenKeyEx 的状态:区分「键打不开」(不存在/拒绝访问)与「键为空」
// (后者返回 NULL 但状态是 ERROR_SUCCESS)。
LSTATUS GetLastOpenStatus() const { return m_lastOpenStatus; }
private:
LSTATUS m_lastOpenStatus;
};
#endif // !defined(AFX_REGISTEROPERATION_H__BB4F3ED1_FA98_4BA4_97D6_A78E683131CC__INCLUDED_)
+35 -1
View File
@@ -14,6 +14,7 @@
#include <functional>
#include <future>
#include <memory>
#include <atomic>
#include <emmintrin.h> // SSE2
#include "common/config.h"
#include "VideoEncoderBase.h"
@@ -149,6 +150,9 @@ public:
int m_FrameID; // 帧序号
int m_GOP; // 关键帧间隔
bool m_SendKeyFrame; // 发送关键帧
// Web 端请求下一帧强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ)。只对 H.264 生效;
// 必须在成功编码出 IDR 后清除,否则 ScanNextScreen 失败/硬编 EAGAIN 时请求会丢。
std::atomic<bool> m_bForceKeyFrame{false};
std::unique_ptr<VideoEncoderBase> m_encoder; // 编码器,ensureEncoder() lazy 创建,走 EncoderFactory 探测
bool m_bEncoderPrimed = false; // encoder 是否已成功产出过一个包;
// false 时禁止 skip——避免单显示器路径
@@ -257,6 +261,11 @@ public:
m_BlockBuffers[blockY] = new BYTE[m_ulFullWidth * m_ulFullHeight * 4 * 2 / m_BlockNum + 12];
}
}
// 请求下一帧强制 IDR(可跨线程调用)。只影响 H.264 编码路径;
// 实际清除发生在成功编码出 IDR 之后。
void RequestKeyFrame() { m_bForceKeyFrame.store(true, std::memory_order_relaxed); }
virtual ~ScreenCapture()
{
if (m_BitmapInfor_Full != NULL) {
@@ -857,6 +866,24 @@ public:
return bmpInfo;
}
// 默认发送尺寸上限:等比缩放,保证长边 ≤1920、短边 ≤1080(横竖屏都成立)。
// 原实现是 min(1920,w) 与 min(1080,h) 各自独立截断,宽高比会被破坏:
// 竖屏 1440×2560 会被压成 1440×1080(高度只剩 42%)。
static void FitDefaultSendSize(LONG& w, LONG& h)
{
const LONG longEdge = (w > h) ? w : h;
const LONG shortEdge = (w > h) ? h : w;
float s = 1.0f;
if (longEdge > 1920)
s = 1920.0f / (float)longEdge;
if ((float)shortEdge * s > 1080.0f)
s = 1080.0f / (float)shortEdge;
if (s < 1.0f) {
w = (LONG)((float)w * s);
h = (LONG)((float)h * s);
}
}
// 编码器 lazy 创建。委托 EncoderFactory 完成"硬编探测 + 软编 fallback"。
void ensureEncoder(int width, int height)
{
@@ -876,7 +903,12 @@ public:
{
BYTE algo = m_bAlgorithm;
int frameID = m_FrameID + 1;
bool keyFrame = (frameID % m_GOP == 0);
// Web 端可请求强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ),只对 H.264 有意义。
// 标志在成功编码出 IDR 后才清除(见下方 H.264 keyframe 分支),
// 保证 ScanNextScreen 失败或硬编 EAGAIN 时请求不会丢失。
bool forceKeyFrame = (algo == ALGORITHM_H264) &&
m_bForceKeyFrame.load(std::memory_order_relaxed);
bool keyFrame = forceKeyFrame || (frameID % m_GOP == 0);
m_RectBuffer[0] = keyFrame ? TOKEN_KEYFRAME : TOKEN_NEXTSCREEN;
LPBYTE data = m_RectBuffer + 1;
// 写入使用了哪种算法
@@ -967,6 +999,8 @@ public:
*ulNextSendLength = 1 + offset + encoded_size;
memcpy(data + offset, encoded_data, encoded_size);
m_bEncoderPrimed = true; // 与下方 FirstBuffer 同步:自此 skip 安全
// IDR 已成功产出,满足(可能的)强制关键帧请求。
m_bForceKeyFrame.store(false, std::memory_order_relaxed);
break;
}
default:
+382 -32
View File
@@ -24,6 +24,39 @@ private:
ID3D11Texture2D* cpuTexture = nullptr;
BYTE* m_NextBuffer = nullptr;
// 各缓冲是否已成功抓到过至少一帧。
// DXGI 的语义是「只在桌面有变化时才返回新帧」,静止桌面下 AcquireNextFrame
// 必然超时(DXGI_ERROR_WAIT_TIMEOUT)。超时必须复用上一帧而不是当作失败,
// 否则 ScanNextScreen 恒返回 nullptr → 只发光标帧 → H.264 编码器永远拿不到
// 首帧 IDR → 服务端 Decode() 不执行 → m_bIsFirst 无法解除 → 永久黑屏。
bool m_bFirstValid = false;
bool m_bNextValid = false;
static constexpr int kNoNewFrame = -100; // 无新帧,非错误
// 旋转输出(竖屏)下 DXGI 给的表面是「未旋转」的横向位图,
// 与桌面逻辑尺寸互为宽高交换,需要自行旋转。这里记录表面真实尺寸与旋转角。
int m_surfW = 0;
int m_surfH = 0;
DXGI_MODE_ROTATION m_rotation = DXGI_MODE_ROTATION_IDENTITY;
// InitDXGI 探测阶段抓到的帧。DuplicateOutput 之后 DXGI 会推送一帧当前桌面,
// 静止桌面下这往往就是唯一能拿到的一帧,丢弃它会导致首屏只能等桌面变化。
// 因此探测完先留在手上(不 ReleaseFrame),由 ConsumeProbeFrame() 消费。
IDXGIResource* m_probeRes = nullptr;
// DXGI 在部分环境下完全拿不到帧(无头/虚拟显示、Session 0 桌面、驱动不推送
// duplication 通知等),连首屏都要靠 GDI 兜底。这种情况下本会话直接降级为
// GDI 抓屏,否则 ScanNextScreen 永远返回 nullptr,表现为「首屏有画面,
// 但之后切换窗口画面不再更新」。
bool m_bGDIFallback = false;
// GDI 兜底用的离屏缓冲。降级后是每帧都要走的持续路径,必须复用,
// 否则每帧 CreateDIBSection/DeleteObject 会反复分配十几 MB 造成抖动。
HDC m_hGdiMemDC = nullptr;
HBITMAP m_hGdiBmp = nullptr;
HGDIOBJ m_hGdiOldBmp = nullptr;
void* m_pGdiBits = nullptr;
public:
ScreenCapturerDXGI(BYTE algo, int gop = DEFAULT_GOP, BOOL all = FALSE, int level = LEVEL_H264_SOFT,
RECT rc = {0}, BOOL switchScreen = TRUE)
@@ -73,7 +106,8 @@ public:
// 4. 获取 DXGI 输出(屏幕)
static UINT screen = 0;
HRESULT r = dxgiAdapter->EnumOutputs(switchScreen ? screen++ : screen, &dxgiOutput);
UINT outIndex = switchScreen ? screen++ : screen;
HRESULT r = dxgiAdapter->EnumOutputs(outIndex, &dxgiOutput);
if (r == DXGI_ERROR_NOT_FOUND && all) {
screen = 0;
idx ++;
@@ -101,16 +135,67 @@ public:
// 7. 获取屏幕大小
DXGI_OUTDUPL_DESC duplDesc;
deskDupl->GetDesc(&duplDesc);
m_ulFullWidth = duplDesc.ModeDesc.Width;
m_ulFullHeight = duplDesc.ModeDesc.Height;
// 8. 创建 CPU 访问纹理
// 旋转输出(竖屏)下 ModeDesc 报告的是逻辑桌面尺寸,而实际捕获表面是
// 「未旋转」的横向位图,两者宽高互换。若按 ModeDesc 建 CPU 纹理,
// CopyResource 会静默不复制(返回 void)→ cpuTexture 全零 → 黑屏。
// 先取一帧读真实纹理描述;取不到时按旋转关系推导,避免退回错误尺寸。
m_rotation = duplDesc.Rotation;
const bool swapWH = (m_rotation == DXGI_MODE_ROTATION_ROTATE90 ||
m_rotation == DXGI_MODE_ROTATION_ROTATE270);
UINT realW = swapWH ? duplDesc.ModeDesc.Height : duplDesc.ModeDesc.Width;
UINT realH = swapWH ? duplDesc.ModeDesc.Width : duplDesc.ModeDesc.Height;
DXGI_FORMAT realFmt = DXGI_FORMAT_B8G8R8A8_UNORM;
{
IDXGIResource* probeRes = nullptr;
DXGI_OUTDUPL_FRAME_INFO probeInfo = {};
HRESULT phr = deskDupl->AcquireNextFrame(200, &probeInfo, &probeRes);
if (SUCCEEDED(phr)) {
if (probeRes) {
ID3D11Texture2D* probeTex = nullptr;
if (SUCCEEDED(probeRes->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&probeTex)) && probeTex) {
D3D11_TEXTURE2D_DESC td = {};
probeTex->GetDesc(&td);
realW = td.Width;
realH = td.Height;
realFmt = td.Format;
probeTex->Release();
}
// 不要丢弃这一帧:暂存起来,等缓冲分配完由 ConsumeProbeFrame()
// 直接填充首屏。否则静止桌面下首屏 AcquireNextFrame 必然超时。
m_probeRes = probeRes;
} else {
deskDupl->ReleaseFrame();
}
}
}
// 内存布局按 4 字节/像素计算,非 4 字节格式回退 BGRA
switch (realFmt) {
case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
case DXGI_FORMAT_R10G10B10A2_UNORM:
break;
default:
Mprintf("[DXGI] unsupported fmt=%d, fallback BGRA\n", (int)realFmt);
realFmt = DXGI_FORMAT_B8G8R8A8_UNORM;
break;
}
// 后续所有缓冲/位图信息/缩放都按「正立」的逻辑尺寸计算
m_surfW = (int)realW;
m_surfH = (int)realH;
m_ulFullWidth = swapWH ? realH : realW;
m_ulFullHeight = swapWH ? realW : realH;
// 8. 创建 CPU 访问纹理(按表面原始尺寸/格式,保证 CopyResource 成功)
D3D11_TEXTURE2D_DESC desc = {};
desc.Width = m_ulFullWidth;
desc.Height = m_ulFullHeight;
desc.Width = realW;
desc.Height = realH;
desc.MipLevels = 1;
desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
desc.Format = realFmt;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_STAGING;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
@@ -135,9 +220,8 @@ public:
((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) *
4 * m_BitmapInfor_Send->bmiHeader.biHeight;
} else {
// strategy=0 或 maxWidth=0: 默认 1080p 限制
m_BitmapInfor_Send->bmiHeader.biWidth = min(1920, m_BitmapInfor_Send->bmiHeader.biWidth);
m_BitmapInfor_Send->bmiHeader.biHeight = min(1080, m_BitmapInfor_Send->bmiHeader.biHeight);
// strategy=0 或 maxWidth=0: 默认 1080p 限制(等比,避免竖屏被压扁)
FitDefaultSendSize(m_BitmapInfor_Send->bmiHeader.biWidth, m_BitmapInfor_Send->bmiHeader.biHeight);
m_BitmapInfor_Send->bmiHeader.biSizeImage =
((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) *
4 * m_BitmapInfor_Send->bmiHeader.biHeight;
@@ -149,6 +233,12 @@ public:
m_BmpZoomBuffer = new BYTE[m_BitmapInfor_Send->bmiHeader.biSizeImage * 2 + 12];
m_BmpZoomFirst = nullptr;
// 缓冲就绪,把探测阶段暂存的那一帧直接填成首屏内容。
// 这一步让首屏不再依赖「桌面发生变化」,连接后立即可出画面。
if (m_probeRes) {
ConsumeProbeFrame();
}
// ROI
int w = m_ROI.right - m_ROI.left, h = m_ROI.bottom - m_ROI.top;
if (w > 0 && h > 0) {
@@ -158,6 +248,11 @@ public:
m_BitmapInfor_Send->bmiHeader.biHeight = h;
m_BitmapInfor_Send->bmiHeader.biSizeImage = w * h * 4;
}
Mprintf("[DXGI] out=%u mode=%ux%u surf=%ux%u fmt=%d rot=%d -> send=%dx%d\n",
outIndex, duplDesc.ModeDesc.Width, duplDesc.ModeDesc.Height,
m_surfW, m_surfH, (int)realFmt, (int)m_rotation,
(int)m_BitmapInfor_Send->bmiHeader.biWidth,
(int)m_BitmapInfor_Send->bmiHeader.biHeight);
break;
} while (true);
@@ -175,6 +270,27 @@ public:
void CleanupDXGI()
{
// GDI 兜底缓冲:先把旧位图选回 DC,再删 DC,最后删位图
if (m_hGdiMemDC) {
// SelectObject 失败会返回 HGDI_ERROR,不能拿它去恢复,否则位图仍被
// DC 选入,后面的 DeleteObject 会失败
if (m_hGdiOldBmp && m_hGdiOldBmp != HGDI_ERROR)
SelectObject(m_hGdiMemDC, m_hGdiOldBmp);
DeleteDC(m_hGdiMemDC);
m_hGdiMemDC = nullptr;
m_hGdiOldBmp = nullptr;
}
if (m_hGdiBmp) {
DeleteObject(m_hGdiBmp);
m_hGdiBmp = nullptr;
m_pGdiBits = nullptr;
}
// 探测帧若还挂着(例如 InitDXGI 中途失败),必须归还,否则 duplication 无法释放
if (m_probeRes) {
if (deskDupl) deskDupl->ReleaseFrame();
m_probeRes->Release();
m_probeRes = nullptr;
}
if (cpuTexture) cpuTexture->Release();
if (deskDupl) deskDupl->Release();
if (d3dContext) d3dContext->Release();
@@ -196,14 +312,59 @@ public:
LPBYTE GetFirstScreenData(ULONG* ulFirstScreenLength) override
{
int ret = CaptureFrame(m_FirstBuffer, ulFirstScreenLength, 1);
scaleBitmap(m_BmpZoomBuffer, m_FirstBuffer);
memcpy(m_FirstBuffer, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
if (ret)
return nullptr;
// 首屏是一次性同步操作:ScreenManager 在调用前已把 m_SendFirst 置 TRUE,
// 一旦返回 nullptr 就不会再重试。所以这里尽量拿到内容——探测阶段暂存的
// 帧通常已填充好,静止桌面下偶尔无新帧时再用短超时补抓几次。
const DWORD startTick = GetTickCount();
int ret = 0;
int attempts = 0;
if (!m_bFirstValid) { // 探测帧已填充时直接用,不再白等一次 AcquireNextFrame
ret = kNoNewFrame;
while (attempts < 3) {
++attempts;
ret = CaptureFrame(m_FirstBuffer, ulFirstScreenLength, 1, &m_bFirstValid);
if (ret != kNoNewFrame) break;
if (m_bFirstValid) { ret = 0; break; }
Sleep(20);
}
}
const DWORD elapsed = GetTickCount() - startTick;
if (elapsed > 300) {
// 只在明显偏慢时记录,正常连接不会产生这行
Mprintf("[DXGI] first screen slow: %ums attempts=%d ok=%d\n",
elapsed, attempts, ret == 0);
}
if (ret != 0) {
// DXGI 抓帧失败(无新帧 / 尺寸异常 / Map 失败等)。首屏不能放弃:一旦
// 返回 nullptr,服务端 m_bIsFirst 就再无机会解锁(ScreenManager 的
// m_SendFirst 已置 TRUE 不会重试),只能等桌面变化,表现为一直"请等待"。
if (CaptureByGDI(m_FirstBuffer, 1)) {
// duplication 连首帧都产不出来,本会话后续帧也必然是空的。
// 直接降级为 GDI 抓屏,保证画面能持续更新(否则只有首屏是活的)。
m_bGDIFallback = true;
if (deskDupl) {
deskDupl->Release();
deskDupl = nullptr;
}
Mprintf("[DXGI] no frame from duplication (ret=%d), session falls back to GDI\n", ret);
ret = 0;
} else {
*ulFirstScreenLength = 0;
return nullptr;
}
}
// reservedBytes=1,实际位图从 m_FirstBuffer+1 开始;
// 服务端也是从偏移 1 开始拷贝,写回时必须保持同样的偏移
scaleBitmap(m_BmpZoomBuffer, m_FirstBuffer + 1);
memcpy(m_FirstBuffer + 1, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
// 缓冲已被缩放图覆盖,+1 处不再是完整帧,后续无新帧时不可再复用
m_bFirstValid = false;
if (m_bAlgorithm == ALGORITHM_GRAY) {
ToGray(1 + m_RectBuffer, 1 + m_RectBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
}
// 长度必须是缩放后的发送尺寸,不能沿用 CaptureFrame 写入的全尺寸,
// 否则会把整帧原始数据(数倍于图像)一并发给服务端
*ulFirstScreenLength = m_BitmapInfor_Send->bmiHeader.biSizeImage;
m_FirstBuffer[0] = TOKEN_FIRSTSCREEN;
return m_FirstBuffer;
}
@@ -211,11 +372,16 @@ public:
LPBYTE ScanNextScreen() override
{
ULONG ulNextScreenLength = 0;
int ret = CaptureFrame(m_NextBuffer, &ulNextScreenLength, 0);
scaleBitmap(m_BmpZoomBuffer, m_NextBuffer);
memcpy(m_NextBuffer, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
int ret = CaptureFrame(m_NextBuffer, &ulNextScreenLength, 0, &m_bNextValid);
if (ret == kNoNewFrame) {
// 无新帧:m_NextBuffer 里已是上次缩放后的结果,必须原样返回,
// 不能再走一遍 scaleBitmap(源已是缩放图,重复缩放会损坏画面)
return m_bNextValid ? m_NextBuffer : nullptr;
}
if (ret)
return nullptr;
scaleBitmap(m_BmpZoomBuffer, m_NextBuffer);
memcpy(m_NextBuffer, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
return m_NextBuffer;
}
@@ -229,6 +395,12 @@ private:
// 重新初始化 Desktop Duplication
BOOL ReinitDuplication()
{
// 重建前必须把暂存帧归还,否则旧的 duplication 无法释放
if (m_probeRes) {
if (deskDupl) deskDupl->ReleaseFrame();
m_probeRes->Release();
m_probeRes = nullptr;
}
if (deskDupl) {
deskDupl->Release();
deskDupl = nullptr;
@@ -263,23 +435,178 @@ private:
return SUCCEEDED(hr) && deskDupl;
}
int CaptureFrame(LPBYTE buffer, ULONG* frameSize, int reservedBytes)
// 惰性创建 GDI 离屏 DIB(尺寸与 DXGI 表面一致,32bpp bottom-up,与发送格式相同)
bool EnsureGDIBuffer()
{
if (m_hGdiMemDC && m_hGdiBmp && m_pGdiBits) return true;
// m_BitmapInfor_Full 已是 32bpp BI_RGB、biHeight 为正(bottom-up)、
// 尺寸等于 m_ulFullWidth/Height,直接复用,不必另建一份 BITMAPINFO
if (!m_BitmapInfor_Full || m_ulFullWidth == 0 || m_ulFullHeight == 0) return false;
HDC hScreen = GetDC(NULL);
if (!hScreen) return false;
if (!m_hGdiMemDC) m_hGdiMemDC = CreateCompatibleDC(hScreen);
if (!m_hGdiBmp) {
m_hGdiBmp = CreateDIBSection(hScreen, m_BitmapInfor_Full, DIB_RGB_COLORS,
&m_pGdiBits, NULL, 0);
}
ReleaseDC(NULL, hScreen);
if (!m_hGdiMemDC || !m_hGdiBmp || !m_pGdiBits) return false;
HGDIOBJ old = SelectObject(m_hGdiMemDC, m_hGdiBmp);
if (!old || old == HGDI_ERROR) {
// 选入失败:销毁位图,否则下次会被上面的「已就绪」判断误认为可用,
// 而实际 BitBlt 写不到 m_pGdiBits,抓出来是未初始化的内存
DeleteObject(m_hGdiBmp);
m_hGdiBmp = nullptr;
m_pGdiBits = nullptr;
return false;
}
m_hGdiOldBmp = old;
return true;
}
// DXGI 的 AcquireNextFrame 只在桌面有新内容呈现时才返回。在无头/虚拟显示环境,
// 或驱动在 DuplicateOutput 后不推送初始帧时,它可能永远超时。此时首屏发不出去,
// 服务端 m_bIsFirst 永不解锁,表现为远程桌面一直停在"请等待......"。
// GDI BitBlt 不依赖桌面变化,这里用它兜底抓一帧。
bool CaptureByGDI(LPBYTE buffer, int reservedBytes)
{
if (!EnsureGDIBuffer()) return false;
HDC hScreen = GetDC(NULL);
if (!hScreen) return false;
BOOL blt = BitBlt(m_hGdiMemDC, 0, 0, (int)m_ulFullWidth, (int)m_ulFullHeight,
hScreen, m_iScreenX, m_iScreenY, SRCCOPY);
ReleaseDC(NULL, hScreen);
if (!blt) return false;
memcpy(buffer + reservedBytes, m_pGdiBits,
(size_t)m_ulFullWidth * m_ulFullHeight * 4);
return true;
}
// 把 DXGI 表面(top-down,srcW×srcH,BGRA)按 rotation 摆正后写入目标
// (bottom-up DIB,m_ulFullWidth×m_ulFullHeight)。分块处理保证缓存友好。
void BlitRotated(BYTE* dst, const BYTE* src, int srcPitch,
int srcW, int srcH, DXGI_MODE_ROTATION rot)
{
const int dstW = (int)m_ulFullWidth;
const int dstH = (int)m_ulFullHeight;
const int dstPitch = dstW * 4;
auto put = [&](int x, int y, int sx, int sy) {
memcpy(dst + (size_t)(dstH - 1 - y) * dstPitch + (size_t)x * 4,
src + (size_t)sy * srcPitch + (size_t)sx * 4, 4);
};
if (rot == DXGI_MODE_ROTATION_ROTATE90 || rot == DXGI_MODE_ROTATION_ROTATE270) {
const bool cw = (rot == DXGI_MODE_ROTATION_ROTATE90);
const int T = 32;
for (int y0 = 0; y0 < dstH; y0 += T) {
const int yEnd = (y0 + T < dstH) ? y0 + T : dstH;
for (int x0 = 0; x0 < dstW; x0 += T) {
const int xEnd = (x0 + T < dstW) ? x0 + T : dstW;
for (int y = y0; y < yEnd; y++) {
for (int x = x0; x < xEnd; x++) {
const int sx = cw ? y : (srcW - 1 - y);
const int sy = cw ? (srcH - 1 - x) : x;
put(x, y, sx, sy);
}
}
}
}
} else if (rot == DXGI_MODE_ROTATION_ROTATE180) {
for (int y = 0; y < dstH; y++)
for (int x = 0; x < dstW; x++)
put(x, y, srcW - 1 - x, srcH - 1 - y);
} else {
// IDENTITY:整行拷贝(快路径)
for (int y = 0; y < dstH; y++)
memcpy(dst + (size_t)(dstH - 1 - y) * dstPitch,
src + (size_t)y * srcPitch, (size_t)dstPitch);
}
}
// 消费 InitDXGI 探测阶段暂存的那一帧,直接填充 m_FirstBuffer(偏移 1 起)。
// 无论成败都会释放暂存资源与 DXGI 帧,避免泄漏。
bool ConsumeProbeFrame()
{
if (!m_probeRes) return false;
bool ok = false;
ID3D11Texture2D* tex = nullptr;
if (cpuTexture && m_FirstBuffer &&
SUCCEEDED(m_probeRes->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&tex)) && tex) {
// 尺寸与格式都必须与建 cpuTexture 时一致,否则 CopyResource 静默不复制
// (读出来是全零)。探测阶段 QI 失败会退回推导尺寸、格式白名单也可能把
// 非常见格式回退成 BGRA,这里再核对一次,不符就放弃消费,让
// GetFirstScreenData 走正常抓帧路径,避免把全黑画面当成首屏发出去。
D3D11_TEXTURE2D_DESC sd = {}, dd = {};
tex->GetDesc(&sd);
cpuTexture->GetDesc(&dd);
if (sd.Width == dd.Width && sd.Height == dd.Height && sd.Format == dd.Format) {
d3dContext->CopyResource(cpuTexture, tex);
D3D11_MAPPED_SUBRESOURCE mapped = {};
if (SUCCEEDED(d3dContext->Map(cpuTexture, 0, D3D11_MAP_READ, 0, &mapped))) {
BlitRotated(m_FirstBuffer + 1, (const BYTE*)mapped.pData,
(int)mapped.RowPitch, m_surfW, m_surfH, m_rotation);
d3dContext->Unmap(cpuTexture, 0);
m_bFirstValid = true;
ok = true;
}
} else {
Mprintf("[DXGI] probe %ux%u fmt=%d != cpu %ux%u fmt=%d, skip probe frame\n",
sd.Width, sd.Height, (int)sd.Format, dd.Width, dd.Height, (int)dd.Format);
}
tex->Release();
}
if (deskDupl) deskDupl->ReleaseFrame();
m_probeRes->Release();
m_probeRes = nullptr;
return ok;
}
int CaptureFrame(LPBYTE buffer, ULONG* frameSize, int reservedBytes, bool* valid)
{
// 本会话已降级为 GDI(首屏就是靠 GDI 兜底才成功的,说明 duplication 在这个
// 环境产不出帧)。继续轮询 DXGI 只会一直返回「无新帧」,画面就停住不动。
if (m_bGDIFallback) {
if (!CaptureByGDI(buffer, reservedBytes)) return -1;
*frameSize = m_ulFullWidth * m_ulFullHeight * 4;
if (valid) *valid = true;
return 0;
}
if (!deskDupl) {
if (!ReinitDuplication()) return -10;
}
// 超时保持 100ms(与修复前一致)。AcquireNextFrame 的 timeout 是「最多等
// 多久」而不是「一定等这么久」,有帧会立即返回;静止桌面下白等只会拖慢
// 抓屏线程的轮询节奏(曾用 1000ms,导致首屏和之后每一帧都阻塞 1 秒)。
const UINT timeout = 100;
// 1. 获取下一帧
IDXGIResource* desktopResource = nullptr;
DXGI_OUTDUPL_FRAME_INFO frameInfo;
HRESULT hr = deskDupl->AcquireNextFrame(100, &frameInfo, &desktopResource);
HRESULT hr = deskDupl->AcquireNextFrame(timeout, &frameInfo, &desktopResource);
// 处理全屏切换导致的访问丢失
if (hr == DXGI_ERROR_ACCESS_LOST) {
if (ReinitDuplication()) {
hr = deskDupl->AcquireNextFrame(100, &frameInfo, &desktopResource);
hr = deskDupl->AcquireNextFrame(timeout, &frameInfo, &desktopResource);
}
}
// 桌面静止时没有新帧,这是 DXGI 的正常语义,不能当成错误。
// 调用方据此复用上一帧内容,保证编码器持续有输入。
if (hr == DXGI_ERROR_WAIT_TIMEOUT) {
return kNoNewFrame;
}
if (FAILED(hr)) {
return -1;
}
@@ -289,10 +616,40 @@ private:
hr = desktopResource->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&texture);
if (FAILED(hr)) {
deskDupl->ReleaseFrame();
desktopResource->Release(); // 原来漏了,每次失败都会泄漏一个 DXGI 资源
return -2;
}
// 3. 复制到 CPU 纹理
// ID3D11DeviceContext::CopyResource 返回 void:尺寸/格式不匹配时不会报错,
// 只会静默不复制(目标保持原值 = 全零)。这里显式比对描述。
// 尺寸不一致时必须放弃这一帧:BlitRotated 按 m_surfW/H 计算源偏移,
// 表面变小会越界读取(崩溃或花屏),宁可跳过等 ReinitDuplication。
{
D3D11_TEXTURE2D_DESC sd = {};
texture->GetDesc(&sd);
if ((int)sd.Width != m_surfW || (int)sd.Height != m_surfH) {
static LONG s_sizeLog = 0;
if (s_sizeLog++ < 3) {
Mprintf("[DXGI] surface changed %dx%d -> %ux%u, drop frame\n",
m_surfW, m_surfH, sd.Width, sd.Height);
}
deskDupl->ReleaseFrame();
texture->Release();
desktopResource->Release();
return -4;
}
static LONG s_fmtLog = 0;
if (s_fmtLog < 3) {
D3D11_TEXTURE2D_DESC dd = {};
cpuTexture->GetDesc(&dd);
if (sd.Format != dd.Format) {
Mprintf("[DXGI] DESC MISMATCH fmt src=%d dst=%d\n",
(int)sd.Format, (int)dd.Format);
}
s_fmtLog++;
}
}
d3dContext->CopyResource(cpuTexture, texture);
// 4. 释放 DXGI 资源
@@ -307,22 +664,15 @@ private:
return -3;
}
// 6. 复制数据到缓冲区(垂直翻转)
BYTE* pData = (BYTE*)mapped.pData;
int rowSize = m_ulFullWidth * 4; // 每行的字节数(RGBA)
BYTE* dest = buffer + reservedBytes + (m_ulFullHeight - 1) * rowSize;
BYTE* src = pData;
for (int y = 0; y < m_ulFullHeight; y++) {
memcpy(dest, src, rowSize);
dest -= rowSize;
src += mapped.RowPitch;
}
// 6. 复制数据到缓冲区(按旋转角摆正 + 垂直翻转到 bottom-up DIB)
BlitRotated(buffer + reservedBytes, (const BYTE*)mapped.pData,
(int)mapped.RowPitch, m_surfW, m_surfH, m_rotation);
// 7. 清理
d3dContext->Unmap(cpuTexture, 0);
*frameSize = m_ulFullWidth * m_ulFullHeight * 4;
if (valid) *valid = true;
return 0;
}
};
+41 -1
View File
@@ -467,6 +467,26 @@ static BOOL RestoreConsoleSession()
return FALSE;
}
// 进程所在会话是否已断开(RDP 断开后没有显示输出)。
// 这种会话里 DXGI 桌面复制拿不到帧,部分驱动上连初始化都不返回,必须走 GDI。
// Session 0 是服务会话,没有「断开」这个概念,直接返回 FALSE。
static BOOL IsCurrentSessionDisconnected()
{
DWORD sessionId = 0;
if (!ProcessIdToSessionId(GetCurrentProcessId(), &sessionId) || sessionId == 0)
return FALSE;
WTS_CONNECTSTATE_CLASS* pState = NULL;
DWORD bytes = 0;
if (!WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSConnectState,
(LPSTR*)&pState, &bytes) || !pState) {
return FALSE;
}
const BOOL disconnected = (*pState == WTSDisconnected);
WTSFreeMemory(pState);
return disconnected;
}
void CScreenManager::InitScreenSpy()
{
int DXGI = USING_GDI;
@@ -551,7 +571,20 @@ void CScreenManager::InitScreenSpy()
}
}
SAFE_DELETE(m_ScreenSpyObject);
if ((USING_DXGI == DXGI && IsWindows8orHigher())) {
// 锁屏(输入桌面切到 Winlogon)或会话已断开时,当前会话没有可用的交互桌面:
// DXGI 桌面复制拿不到帧,部分环境(无 GPU 的 Server、断开/锁定的 RDP 会话)
// 甚至会在初始化里卡死不返回 —— 那样 InitScreenSpy 走不完,WorkThreadProc 里
// 紧随其后的 SendBitMapInfo() 永远发不出去,主控端一直等不到 TOKEN_BITMAPINFO,
// 连远程桌面窗口都不会弹。GDI 的 BitBlt 不依赖桌面变化,这些情况下照样能抓,
// 所以直接走 GDI。
const BOOL locked = IsWorkstationLocked();
const BOOL disconnected = IsCurrentSessionDisconnected();
const bool noDesktop = (USING_DXGI == DXGI && (locked || disconnected));
if (noDesktop) {
Mprintf("CScreenManager: no interactive desktop (locked=%d, disconnected=%d), use GDI instead of DXGI\n",
(int)locked, (int)disconnected);
}
if ((USING_DXGI == DXGI && IsWindows8orHigher() && !noDesktop)) {
m_isGDI = FALSE;
auto s = new ScreenCapturerDXGI(algo, DEFAULT_GOP, all, m_ScreenSettings.EncodeLevel, rect, switchScreen);
if (s->IsInitSucceed()) {
@@ -930,6 +963,13 @@ VOID CScreenManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
SwitchScreen();
break;
}
case COMMAND_SCREEN_KEYFRAME_REQ: {
// Web 屏幕墙恢复/新加入者请求:下一帧强制 IDR,立即重建参考链。
if (m_ScreenSpyObject) {
m_ScreenSpyObject->RequestKeyFrame();
}
break;
}
case CMD_FULL_SCREEN: {
int fullScreen = szBuffer[1];
iniFile cfg(CLIENT_PATH);
+2 -3
View File
@@ -66,9 +66,8 @@ CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk, int gop, BOOL
Mprintf("CScreenSpy: 自定义分辨率 %dx%d\n",
m_BitmapInfor_Send->bmiHeader.biWidth, m_BitmapInfor_Send->bmiHeader.biHeight);
} else {
// strategy=0 或 maxWidth=0: 默认 1080p 限制
m_BitmapInfor_Send->bmiHeader.biWidth = min(1920, m_BitmapInfor_Send->bmiHeader.biWidth);
m_BitmapInfor_Send->bmiHeader.biHeight = min(1080, m_BitmapInfor_Send->bmiHeader.biHeight);
// strategy=0 或 maxWidth=0: 默认 1080p 限制(等比,避免竖屏被压扁)
FitDefaultSendSize(m_BitmapInfor_Send->bmiHeader.biWidth, m_BitmapInfor_Send->bmiHeader.biHeight);
m_BitmapInfor_Send->bmiHeader.biSizeImage =
((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) *
4 * m_BitmapInfor_Send->bmiHeader.biHeight;
+5 -5
View File
@@ -34,13 +34,13 @@ END
IDD_CHAT DIALOGEX 0, 0, 235, 155
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Chat"
FONT 10, "System", 0, 0, 0x0
CAPTION "Remote Chat"
FONT 9, "MS Shell Dlg", 400, 0, 0x1
BEGIN
EDITTEXT IDC_EDIT_CHATLOG,3,3,229,107,ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY | WS_VSCROLL
EDITTEXT IDC_EDIT_NEWMSG,3,113,170,38,ES_MULTILINE | ES_AUTOVSCROLL | WS_VSCROLL
DEFPUSHBUTTON "Send",IDC_BUTTON_SEND,178,116,54,14
PUSHBUTTON "End",IDC_BUTTON_END,178,133,54,14
PUSHBUTTON "End Chat",IDC_BUTTON_END,178,133,54,14
END
@@ -103,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,4,0
FILEVERSION 1,0,4,2
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.0"
VALUE "FileVersion", "1.0.4.2"
VALUE "InternalName", "ServerDll.dll"
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
VALUE "OriginalFilename", "ServerDll.dll"
+17 -4
View File
@@ -24,11 +24,20 @@ CServicesManager::~CServicesManager()
VOID CServicesManager::SendServicesList()
{
LPBYTE szBuffer = GetServicesList();
DWORD dwErr = 0;
LPBYTE szBuffer = GetServicesList(&dwErr);
if (szBuffer == NULL) {
if (dwErr == 0) dwErr = ERROR_GEN_FAILURE;
Mprintf("Get service list failed[IP: %s][win32=%lu]\n", m_ClientObject->GetPublicIP().c_str(), dwErr);
// 结构化失败回报:MCP 端据此立即返回「权限不足/SCM 打不开」,不必等 20s 超时。
// 老服务端不认识 TOKEN_SERVICE_ERROR,走 default 分支丢弃,随后仍按原样收到 ClientMsg。
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
pkt[0] = TOKEN_SERVICE_ERROR;
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
m_ClientObject->Send2Server((char*)pkt, sizeof(pkt));
// 保留原有弹窗消息:老服务端与 MFC 服务管理器(新 token 由对话框忽略)行为不变。
char buf[128];
sprintf_s(buf, "Get service list failed[IP: %s]", m_ClientObject->GetPublicIP().c_str());
Mprintf("%s\n", buf);
ClientMsg msg("服务管理", buf);
m_ClientObject->Send2Server((char*)&msg, sizeof(msg));
return;
@@ -42,7 +51,7 @@ VOID CServicesManager::SendServicesList()
#define skCrypt(p) p
#endif
LPBYTE CServicesManager::GetServicesList()
LPBYTE CServicesManager::GetServicesList(DWORD* err)
{
LPENUM_SERVICE_STATUS ServicesStatus = NULL;
LPQUERY_SERVICE_CONFIG ServicesInfor = NULL;
@@ -52,12 +61,14 @@ LPBYTE CServicesManager::GetServicesList()
DWORD dwLength = 0;
DWORD dwOffset = 0;
if((m_hscManager=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS))==NULL) {
if (err) *err = GetLastError(); // 典型 5=拒绝访问(未提权)
return NULL;
}
ServicesStatus = (LPENUM_SERVICE_STATUS) LocalAlloc(LPTR,64*1024);
if (ServicesStatus==NULL) {
if (err) *err = ERROR_NOT_ENOUGH_MEMORY;
CloseServiceHandle(m_hscManager);
return NULL;
}
@@ -75,8 +86,10 @@ LPBYTE CServicesManager::GetServicesList()
&dwResumeHandle);
szBuffer = (LPBYTE)LocalAlloc(LPTR, MAX_PATH);
if (szBuffer == NULL)
if (szBuffer == NULL) {
if (err) *err = ERROR_NOT_ENOUGH_MEMORY;
return NULL;
}
szBuffer[0] = TOKEN_SERVERLIST;
dwOffset = 1;
for (unsigned long i = 0; i < dwServicesCount; ++i) { // Display The Services,显示所有的服务
+1 -1
View File
@@ -20,7 +20,7 @@ public:
CServicesManager(IOCPClient* ClientObject, int n, void* user = nullptr);
virtual ~CServicesManager();
VOID SendServicesList();
LPBYTE GetServicesList();
LPBYTE GetServicesList(DWORD* err = NULL);
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
void ServicesConfig(PBYTE szBuffer, ULONG ulLength);
SC_HANDLE m_hscManager;
+33
View File
@@ -0,0 +1,33 @@
// TalkDialogTemplate.h: IDD_DIALOG 的编译后 DLGTEMPLATEEX(内嵌内存模板)
//
// 用途:加壳部署(EXE + SC_AES/sRDI)的客户端里,TalkManager 的 hInstance 是外壳进程
// 映像,其资源里没有 IDD_DIALOG;而载荷以裸 shellcode 运行、未注册进加载器,
// FindResource/LoadResource/DialogBoxParamA 一律取不到对话框资源。此时用下面的内存模板
// 直接 DialogBoxIndirectParamA 建窗,与部署形态无关。
//
// 数据来源:client/Script.rc 的 IDD_DIALOG(DIALOGEX)。DLGTEMPLATEEX 的字符串字段
// 一律是 UTF-16,同一份字节既可用于 A 接口也可用于 W 接口。
//
// 重新生成(改动 Script.rc 的 IDD_DIALOG 后必须同步):
// 1. rc /fo dlg.res dlg.rc (dlg.rc 只保留与 Script.rc 相同的 IDD_DIALOG 块)
// 2. link /dll /noentry /machine:x64 /out:dlg.dll dlg.res
// 3. 从 dlg.dll 的 RT_DIALOG(5) → 101 → 任意语言 取数据块,按 16 字节一行导出。
// 当前块 104 字节:CAPTION "消息提示"、FONT 10 "System" charset 0、
// 控件 ID 1000,与 Script.rc 完全一致;已与构建出的 ghost.exe 的
// RT_DIALOG(5) → 101 逐字节比对一致。
#ifndef YAMA_TALK_DIALOG_TEMPLATE_H
#define YAMA_TALK_DIALOG_TEMPLATE_H
// DLGTEMPLATEEX 的 DWORD 字段要求模板指针 4 字节对齐。
__declspec(align(4)) static const unsigned char kTalkDialogTemplate[] = {
0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC2, 0x00, 0xC8, 0x80,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB4, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x6D,
0x6F, 0x60, 0xD0, 0x63, 0x3A, 0x79, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x00,
0x79, 0x00, 0x73, 0x00, 0x74, 0x00, 0x65, 0x00, 0x6D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, 0x05, 0x00, 0x05, 0x00, 0xAA, 0x00, 0x5F, 0x00,
0xE8, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, 0x53, 0x00, 0x74, 0x00, 0x61, 0x00, 0x74, 0x00,
0x69, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif // YAMA_TALK_DIALOG_TEMPLATE_H
+26 -3
View File
@@ -4,6 +4,7 @@
#include "stdafx.h"
#include "TalkManager.h"
#include "TalkDialogTemplate.h"
#include "Common.h"
#include "resource.h"
#include <IOSTREAM>
@@ -49,10 +50,23 @@ VOID CTalkManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
default: {
memcpy(g_Buffer, szBuffer, min(ulLength, sizeof(g_Buffer)));
// 服务端只发正文、不带结尾 NUL:按实际长度补终止符(留一格),
// 否则正好填满缓冲区时 SetDlgItemText 会越界读
size_t nCopy = min(ulLength, sizeof(g_Buffer) - 1);
memcpy(g_Buffer, szBuffer, nCopy);
g_Buffer[nCopy] = '\0';
//创建一个DLG
DialogBoxParamA(m_hInstance,MAKEINTRESOURCE(IDD_DIALOG),
NULL, DialogProc, (LPARAM)this); //SDK C MFC C++
INT_PTR nRet = DialogBoxParamA(m_hInstance, MAKEINTRESOURCEA(IDD_DIALOG),
NULL, DialogProc, (LPARAM)this); //SDK C MFC C++
if (nRet == -1) {
// 与聊天窗口同样的原因:加壳部署(EXE + SC_AES/sRDI)时 m_hInstance 是
// 外壳进程映像,取不到 IDD_DIALOG 资源,DialogBoxParamA 直接失败(Win11
// 实测 err=1812/59),右下角消息窗口不会出现。回退到内嵌的编译后模板。
DWORD dwError = GetLastError();
Mprintf("DialogBoxParamA(%lu) 失败,改用内嵌对话框模板\n", dwError);
DialogBoxIndirectParamA(m_hInstance, (LPCDLGTEMPLATEA)kTalkDialogTemplate,
NULL, DialogProc, (LPARAM)this);
}
break;
}
}
@@ -97,6 +111,15 @@ VOID CTalkManager::OnInitDialog(HWND hDlg)
{
MoveWindow(hDlg, 0, 0, 0, 0, TRUE);
// 标题栏:DialogBoxParamA 会把模板里的 UTF-16 标题按系统 ANSI 代码页转换,
// 德语等 1252 系统上"消息提示"会变成 "???"。这里在显示前用 W 接口重设标题
// (消息正文仍走 ANSI,保持原有编码语义)。中文系统显示中文,其余显示英文。
{
static const bool bChineseUI =
(PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE);
SetWindowTextW(hDlg, bChineseUI ? L"消息提示" : L"Message");
}
static HICON hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_ICON_MSG));
::SendMessage(hDlg, WM_SETICON, (WPARAM)hIcon, (LPARAM)hIcon);
BIN
View File
Binary file not shown.
+569
View File
@@ -0,0 +1,569 @@
// TlsChannel.cpp — 见 TlsChannel.h 头注释。仅 _WIN32 编译。
#ifdef _WIN32
#include "stdafx.h"
#include "TlsChannel.h"
#include "common/iniFile.h" // config(settings.ini 文件回退) + GetRegistryName/GetCurrentUserRegistryKey(注册表正文)
#include <wincrypt.h> // 证书/链引擎 API
#include <winreg.h> // RegOpenKeyExA / RegQueryValueExA
#include <io.h> // _access
#include <fstream> // std::ifstream
#include <iterator> // std::istreambuf_iterator
#include <string>
#include <mutex> // std::mutex
#pragma comment(lib, "secur32.lib")
#pragma comment(lib, "crypt32.lib")
namespace {
// 进程级 TLS 状态:首连时加载一次,服务端下发/撤销信任锚后可重建(TlsReload)。
// 所有读写都在 g_tlsMtx 下;证书校验(VerifyServerCert)在校验期间持同一把锁,因此
// 重建时可以安全地释放旧的 store/engine——不会再有线程正拿着它们用。
std::mutex g_tlsMtx;
bool g_tlsLoaded = false; // 已加载过至少一次(决定首次失败是否 fail-closed)
bool g_tlsEnabled = false; // TLS 会话可用:send/recv 走加密
bool g_tlsError = false; // 证书存在但加载失败:拒绝连接(fail-closed)
HCERTSTORE g_tlsStore = NULL;
HCERTCHAINENGINE g_tlsEngine = NULL; // 只信任 g_tlsStore 的链引擎(严格钉扎)
// 解析信任锚证书路径:优先 settings.ini 的 [settings] tls_cert,其次可执行文件同目录
// yama-ca.pem。
std::string ResolveCertPath()
{
std::string certPath;
{
config cfg;
certPath = cfg.GetStr("settings", "tls_cert", "");
}
if (certPath.empty()) {
char path[MAX_PATH];
if (!GetModuleFileNameA(NULL, path, sizeof(path)))
return std::string(); // 拿不到 exe 路径,视为未配置
char* p = path + strlen(path);
while (p > path && *p != '\\') --p;
strcpy(p + 1, "yama-ca.pem");
certPath = path;
}
return certPath;
}
// 读取注册表 REG_SZ(动态扩容)。iniFile::GetStr 用 512 字节固定缓冲,会把 PEM 正文
// (约 1.3~1.8KB)截断成空,故此处自行两段式 RegQueryValueEx 读取。
// 返回 true 表示值存在且为 REG_SZ,out 为去掉末尾 '\0' 后的内容;否则 false。
bool ReadRegistrySz(HKEY root, const std::string& subKey, const std::string& valueName, std::string& out)
{
HKEY hKey = NULL;
if (RegOpenKeyExA(root, subKey.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
return false;
DWORD type = 0, size = 0;
LONG r = RegQueryValueExA(hKey, valueName.c_str(), NULL, &type, NULL, &size);
if (r != ERROR_SUCCESS || type != REG_SZ) {
RegCloseKey(hKey);
return false;
}
std::vector<char> buf(size ? size : 1, 0);
r = RegQueryValueExA(hKey, valueName.c_str(), NULL, &type,
reinterpret_cast<LPBYTE>(buf.data()), &size);
RegCloseKey(hKey);
if (r != ERROR_SUCCESS)
return false;
if (size > 0 && buf[size - 1] == '\0')
--size; // REG_SZ 的 size 含末尾 '\0'
out.assign(buf.data(), size);
return true;
}
// 取信任锚 PEM 正文。优先注册表 Software\<exehash>\settings\tls_cert(REG_SZ 直接存
// PEM 正文,便于后续服务端下发/撤销),其次 settings.ini [settings] tls_cert 路径、
// exe 同目录 yama-ca.pem 文件(向后兼容旧的文件投递方式)。
// 返回 true 表示已配置(pem 可能为空:值/文件存在但内容为空,由 LoadTrustAnchor 判为
// fail-closed);false 表示完全未配置(走明文)。source 描述来源,仅用于日志。
bool ReadTrustAnchor(std::string& pem, std::string& source)
{
// 1) 注册表正文(首选)。值存在(即便为空)即视为「已配置」,交由 LoadTrustAnchor
// 对空/损坏内容判 fail-closed,与「空文件 → fail-closed」语义保持一致,避免空值
// 被静默当成未配置而回退明文。
std::string regSubKey = GetRegistryName() + "\\settings";
std::string regVal;
if (ReadRegistrySz(GetCurrentUserRegistryKey(), regSubKey, "tls_cert", regVal)) {
pem = regVal;
source = "registry " + regSubKey + "\\tls_cert";
return true;
}
// 2) 文件回退:settings.ini [settings] tls_cert 路径 → exe 同目录 yama-ca.pem
std::string certPath = ResolveCertPath();
if (certPath.empty() || _access(certPath.c_str(), 0) != 0)
return false; // 无证书 → 明文
std::ifstream f(certPath.c_str(), std::ios::binary);
if (!f) {
Mprintf("[TLS] cannot open %s\n", certPath.c_str());
return false;
}
pem.assign((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
source = certPath;
return true;
}
// 解码 PEM/DER 信任锚正文为 DER,并加入内存信任锚存储。
bool LoadTrustAnchor(const std::string& pem, const std::string& source, HCERTSTORE* outStore)
{
if (pem.empty()) {
Mprintf("[TLS] empty certificate %s\n", source.c_str());
return false;
}
// PEM(-----BEGIN CERTIFICATE----- base64)或 DER → DER。CRYPT_STRING_ANY 两者都认,
// 失败再退回 CRYPT_STRING_BASE64HEADER(纯 PEM)。
DWORD derLen = 0;
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
NULL, &derLen, NULL, NULL) || derLen == 0) {
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
NULL, &derLen, NULL, NULL) || derLen == 0) {
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
return false;
}
}
std::vector<BYTE> der(derLen);
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
der.data(), &derLen, NULL, NULL)) {
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
der.data(), &derLen, NULL, NULL)) {
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
return false;
}
}
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, der.data(), derLen);
if (!cert) {
Mprintf("[TLS] invalid certificate %s\n", source.c_str());
return false;
}
HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING,
0, CERT_STORE_CREATE_NEW_FLAG, NULL);
if (!store) {
CertFreeCertificateContext(cert);
Mprintf("[TLS] CertOpenStore failed\n");
return false;
}
if (!CertAddCertificateContextToStore(store, cert, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) {
CertCloseStore(store, 0);
CertFreeCertificateContext(cert);
Mprintf("[TLS] CertAddCertificateContextToStore failed\n");
return false;
}
CertFreeCertificateContext(cert);
*outStore = store;
return true;
}
enum TlsAnchor { TLS_ANCHOR_OK, TLS_ANCHOR_NONE, TLS_ANCHOR_INVALID };
// 读取当前信任锚并建好 store + 链引擎(成功时经 outStore/outEngine 交出,调用方负责
// 释放)。不触碰全局状态。source 描述锚的来源,仅用于日志。
TlsAnchor BuildTlsAnchor(HCERTSTORE* outStore, HCERTCHAINENGINE* outEngine,
std::string& source, std::string& err)
{
std::string pem;
if (!ReadTrustAnchor(pem, source)) {
err = "no trust anchor configured";
return TLS_ANCHOR_NONE;
}
HCERTSTORE store = NULL;
if (!LoadTrustAnchor(pem, source, &store)) {
err = "trust anchor (" + source + ") present but failed to load";
return TLS_ANCHOR_INVALID;
}
// 严格钉扎:链引擎只信任该 store 里的根证书,排除系统根库。否则攻击者拿一张任意
// 公共 CA 签发的证书就能通过 CertGetCertificateChain(默认引擎信任系统根库)。
CERT_CHAIN_ENGINE_CONFIG ec = {};
ec.cbSize = sizeof(ec);
ec.hExclusiveRoot = store;
HCERTCHAINENGINE engine = NULL;
if (!CertCreateCertificateChainEngine(&ec, &engine)) {
CertCloseStore(store, 0);
err = "CertCreateCertificateChainEngine failed";
return TLS_ANCHOR_INVALID;
}
*outStore = store;
*outEngine = engine;
return TLS_ANCHOR_OK;
}
// 按当前信任锚重建 TLS 状态(调用方持 g_tlsMtx)。
// 首次加载失败 → fail-closed(管理员已「颁发」证书,不能静默回退明文);运行期热重载
// 失败 → 保持现有状态不变,返回 false(一次坏下发不该打死正在工作的客户端;下次启动
// 仍会 fail-closed)。
bool ApplyTlsStateLocked(bool initial, std::string& err)
{
HCERTSTORE store = NULL;
HCERTCHAINENGINE engine = NULL;
std::string source;
const TlsAnchor anchor = BuildTlsAnchor(&store, &engine, source, err);
if (anchor == TLS_ANCHOR_INVALID) {
if (initial) {
g_tlsEnabled = false;
g_tlsError = true;
g_tlsLoaded = true;
Mprintf("[TLS] FATAL: %s; refusing connections (fail-closed)\n", err.c_str());
} else {
Mprintf("[TLS] reload failed: %s (keeping current transport)\n", err.c_str());
}
return false;
}
// 互换。旧 store/engine 可以直接释放:校验路径持同一把锁,此刻没有线程在用它们。
HCERTSTORE oldStore = g_tlsStore;
HCERTCHAINENGINE oldEngine = g_tlsEngine;
g_tlsStore = store;
g_tlsEngine = engine;
g_tlsEnabled = (anchor == TLS_ANCHOR_OK);
g_tlsError = false;
g_tlsLoaded = true;
if (oldEngine) CertFreeCertificateChainEngine(oldEngine);
if (oldStore) CertCloseStore(oldStore, 0);
if (g_tlsEnabled)
Mprintf("[TLS] enabled: trust anchor loaded (%s), all connections use TLS\n", source.c_str());
else
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
return true;
}
// 首次调用时才真正加载;之后一律用缓存的状态(热重载由 TlsReload 负责)。
inline void EnsureTlsLoadedLocked()
{
if (!g_tlsLoaded) {
std::string err;
ApplyTlsStateLocked(true, err);
}
}
} // namespace
bool TlsEnabled()
{
std::lock_guard<std::mutex> lk(g_tlsMtx);
EnsureTlsLoadedLocked();
return g_tlsEnabled;
}
bool TlsLoadError()
{
std::lock_guard<std::mutex> lk(g_tlsMtx);
EnsureTlsLoadedLocked();
return g_tlsError;
}
bool TlsReload(std::string& err)
{
std::lock_guard<std::mutex> lk(g_tlsMtx);
return ApplyTlsStateLocked(!g_tlsLoaded, err);
}
// ---- TlsChannel ----
void TlsChannel::CloseHandles()
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (m_ctxValid) { DeleteSecurityContext(&m_ctx); m_ctx = {}; m_ctxValid = false; }
if (m_credValid) { FreeCredentialsHandle(&m_cred); m_cred = {}; m_credValid = false; }
m_ready = false;
m_raw.clear();
m_pending.clear();
}
bool TlsChannel::SendAll(SOCKET sock, const void* data, int len)
{
const char* p = (const char*)data;
int sent = 0;
while (sent < len) {
int n = ::send(sock, p + sent, len - sent, 0);
if (n == SOCKET_ERROR || n == 0)
return false;
sent += n;
}
return true;
}
bool TlsChannel::VerifyServerCert()
{
PCCERT_CONTEXT remote = NULL;
SECURITY_STATUS sc = QueryContextAttributesA(&m_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &remote);
if (sc != SEC_E_OK || !remote)
return false;
// 与 TlsReload 互斥:校验期间持有 g_tlsMtx,重建时释放的旧 store/engine 不会正被使用。
// 持锁时间很短:建链全是本地操作(DISABLE_AIA 禁联网取中间证书,也不带任何
// CERT_CHAIN_REVOCATION_CHECK_* 位),不会因为网络等待而卡住 TlsReload。
std::lock_guard<std::mutex> lk(g_tlsMtx);
if (!g_tlsStore || !g_tlsEngine) {
CertFreeCertificateContext(remote);
return false;
}
CERT_CHAIN_PARA para = {};
para.cbSize = sizeof(para);
PCCERT_CHAIN_CONTEXT chain = NULL;
// g_tlsEngine 的 hExclusiveRoot 已把信任锚限制为 g_tlsStore;hAdditionalStore 再传一次
// 该 store 供链引擎查找 CA/中间证书。只接受「无任何错误位」的链(含时间有效性)。
// 不设置任何 CERT_CHAIN_REVOCATION_CHECK_* 位 = 不做吊销检查(私有 CA 无 CRL/OCSP,
// 且这些位会触发联网,反而失败);只保留 CERT_CHAIN_DISABLE_AIA 禁止联网取中间证书。
BOOL ok = CertGetCertificateChain(g_tlsEngine, remote, NULL, g_tlsStore, &para,
CERT_CHAIN_DISABLE_AIA,
NULL, &chain);
bool trusted = false;
if (ok && chain) {
trusted = (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR);
}
if (chain) CertFreeCertificateChain(chain);
CertFreeCertificateContext(remote);
return trusted;
}
bool TlsChannel::Handshake(SOCKET sock, const char* sni)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
SCHANNEL_CRED cred = {};
cred.dwVersion = SCHANNEL_CRED_VERSION;
cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_DEFAULT_CREDS;
cred.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT; // TLS 1.2(与 Go 端 MinVersion 对齐)
TimeStamp tsExpiry = {};
SECURITY_STATUS sc = AcquireCredentialsHandleA(
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider",
SECPKG_CRED_OUTBOUND, NULL, &cred, NULL, NULL, &m_cred, &tsExpiry);
if (sc != SEC_E_OK) {
Mprintf("[TLS] AcquireCredentialsHandle failed: 0x%08X\n", (unsigned)sc);
return false;
}
m_credValid = true;
DWORD flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY
| ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM | ISC_REQ_MANUAL_CRED_VALIDATION;
SecBuffer outBuf = { 0, SECBUFFER_TOKEN, NULL };
SecBufferDesc outDesc = { SECBUFFER_VERSION, 1, &outBuf };
ULONG attrs = 0;
// 首次调用产生 ClientHello。pszTargetName 非空时 Schannel 会把它作为 SNI 发送,
// 供反代按域名分流;证书校验仍是手动钉信任锚(SCH_CRED_MANUAL_CRED_VALIDATION),
// 不因传了名字而启用主机名校验。
sc = InitializeSecurityContextA(&m_cred, NULL, (SEC_CHAR*)sni, flags, 0, SECURITY_NATIVE_DREP,
NULL, 0, &m_ctx, &outDesc, &attrs, &tsExpiry);
m_ctxValid = true; // 上下文已分配,之后必须 DeleteSecurityContext
if (sc != SEC_I_CONTINUE_NEEDED && sc != SEC_E_OK) {
Mprintf("[TLS] InitializeSecurityContext(initial) failed: 0x%08X\n", (unsigned)sc);
CloseHandles();
return false;
}
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer) {
if (!SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer)) {
FreeContextBuffer(outBuf.pvBuffer);
CloseHandles();
return false;
}
FreeContextBuffer(outBuf.pvBuffer);
}
std::vector<BYTE> hs;
char raw[8192];
while (sc == SEC_I_CONTINUE_NEEDED || sc == SEC_E_INCOMPLETE_MESSAGE ||
sc == SEC_I_INCOMPLETE_CREDENTIALS)
{
int r = recv(sock, raw, sizeof(raw), 0);
if (r == SOCKET_ERROR || r == 0) {
Mprintf("[TLS] handshake recv failed/EOF\n");
CloseHandles();
return false;
}
hs.insert(hs.end(), (BYTE*)raw, (BYTE*)raw + r);
SecBuffer inBufs[2] = {
{ (ULONG)hs.size(), SECBUFFER_TOKEN, hs.data() },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc inDesc = { SECBUFFER_VERSION, 2, inBufs };
outBuf = { 0, SECBUFFER_TOKEN, NULL };
outDesc = { SECBUFFER_VERSION, 1, &outBuf };
sc = InitializeSecurityContextA(&m_cred, &m_ctx, (SEC_CHAR*)sni, flags, 0, SECURITY_NATIVE_DREP,
&inDesc, 0, NULL, &outDesc, &attrs, &tsExpiry);
// 裁剪已消费的输入,仅保留 SECBUFFER_EXTRA 指向的未消费尾部
if (inBufs[1].BufferType == SECBUFFER_EXTRA) {
int extra = inBufs[1].cbBuffer;
int consumed = (int)hs.size() - extra;
hs.erase(hs.begin(), hs.begin() + consumed);
} else {
hs.clear();
}
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer) {
if (!SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer)) {
FreeContextBuffer(outBuf.pvBuffer);
CloseHandles();
return false;
}
FreeContextBuffer(outBuf.pvBuffer);
}
}
if (sc != SEC_E_OK) {
Mprintf("[TLS] handshake failed: 0x%08X\n", (unsigned)sc);
CloseHandles();
return false;
}
// 握手成功后 hs 里可能残留「未消费的尾部」= 服务端 Finished 后紧跟的首条应用数据
// (TLS 记录)。若不下发,首包会被丢弃,导致随机丢包/协议错位。交给 Recv 解。
if (!hs.empty())
m_raw.insert(m_raw.end(), hs.begin(), hs.end());
if (!VerifyServerCert()) {
Mprintf("[TLS] server certificate not trusted against yama-ca.pem (fail-closed)\n");
CloseHandles();
return false;
}
sc = QueryContextAttributesA(&m_ctx, SECPKG_ATTR_STREAM_SIZES, &m_sizes);
if (sc != SEC_E_OK) {
Mprintf("[TLS] QueryContextAttributes(StreamSizes) failed: 0x%08X\n", (unsigned)sc);
CloseHandles();
return false;
}
m_ready = true;
Mprintf("[TLS] handshake OK (TLS 1.2, server cert trusted)\n");
return true;
}
int TlsChannel::Recv(SOCKET sock, char* out, int outLen)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (!m_ready || outLen <= 0) {
Mprintf("[TLS] Recv called but m_ready=%d (outLen=%d), returning SOCKET_ERROR\n",
(int)m_ready, outLen);
return SOCKET_ERROR;
}
if (!m_pending.empty()) {
int n = (int)m_pending.size() < outLen ? (int)m_pending.size() : outLen;
memcpy(out, m_pending.data(), n);
m_pending.erase(m_pending.begin(), m_pending.begin() + n);
return n;
}
char raw[16384];
for (;;) {
// 优先解密 m_raw 里已缓冲的字节(握手时随 Finished 收下的首条应用数据,或上轮
// 一次 recv 到多条记录后剩下的记录)。select() 只看底层 socket,看不到这些字节,
// 若先 recv 就会把它们卡住(随机延迟/死锁/协议错位)。
while (!m_raw.empty()) {
SecBuffer bufs[4] = {
{ (ULONG)m_raw.size(), SECBUFFER_DATA, m_raw.data() },
{ 0, SECBUFFER_EMPTY, NULL },
{ 0, SECBUFFER_EMPTY, NULL },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
SECURITY_STATUS sc = DecryptMessage(&m_ctx, &desc, 0, NULL);
if (sc == SEC_E_INCOMPLETE_MESSAGE)
break; // 记录不完整,去 recv 补字节
if (sc == SEC_I_CONTEXT_EXPIRED)
return 0; // close_notify
if (sc == SEC_I_RENEGOTIATE || FAILED(sc)) {
// 客户端解密失败(服务端发来的密文损坏/错位)。这里只返回 SOCKET_ERROR,
// 而 WSAGetLastError() 会残留上一次 Winsock 调用的旧值(如 6001),
// 掩盖真实原因,故把真实的 SECURITY_STATUS 记下来。
Mprintf("[TLS] client DecryptMessage failed 0x%08x (raw=%u pending=%u)\n",
(unsigned)sc, (unsigned)m_raw.size(), (unsigned)m_pending.size());
return SOCKET_ERROR;
}
// 流模式 DecryptMessage 会把输入 SECBUFFER_DATA 重组为 4 段:
// bufs[0]=STREAM_HEADER(记录头+nonce)、bufs[1]=DATA(明文)、
// bufs[2]=STREAM_TRAILER(标签)、bufs[3]=EXTRA(下一条记录)。
// 明文在 bufs[1].pvBuffer,不在 m_raw 首字节。
int decLen = bufs[1].cbBuffer;
const BYTE* plain = (const BYTE*)bufs[1].pvBuffer;
int extra = (bufs[3].BufferType == SECBUFFER_EXTRA) ? bufs[3].cbBuffer : 0;
int consumed = (int)m_raw.size() - extra;
m_pending.insert(m_pending.end(), plain, plain + decLen);
m_raw.erase(m_raw.begin(), m_raw.begin() + consumed);
if (!m_pending.empty()) {
int n = (int)m_pending.size() < outLen ? (int)m_pending.size() : outLen;
memcpy(out, m_pending.data(), n);
m_pending.erase(m_pending.begin(), m_pending.begin() + n);
return n;
}
// 无明文的记录(如 alert/CCS):继续循环解下一条
}
int r = recv(sock, raw, sizeof(raw), 0);
if (r == SOCKET_ERROR)
return SOCKET_ERROR;
if (r == 0)
return 0; // 对端关闭(此时无 pending,且 m_raw 已解完/为空)
m_raw.insert(m_raw.end(), (BYTE*)raw, (BYTE*)raw + r);
// 循环回顶部,解密刚收到的字节
}
}
int TlsChannel::Send(SOCKET sock, const char* data, int len)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (!m_ready)
return SOCKET_ERROR;
if (len <= 0)
return 0;
ULONG maxMsg = m_sizes.cbMaximumMessage > 0 ? m_sizes.cbMaximumMessage : 16384;
int total = 0;
while (total < len) {
int chunk = (len - total > (int)maxMsg) ? (int)maxMsg : (len - total);
std::vector<BYTE> rec(m_sizes.cbHeader + chunk + m_sizes.cbTrailer);
BYTE* hdr = rec.data();
BYTE* body = hdr + m_sizes.cbHeader;
BYTE* trailer = body + chunk;
memcpy(body, data + total, chunk);
SecBuffer bufs[4] = {
{ m_sizes.cbHeader, SECBUFFER_STREAM_HEADER, hdr },
{ (ULONG)chunk, SECBUFFER_DATA, body },
{ m_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, trailer },
{ 0, SECBUFFER_EMPTY, NULL },
};
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
SECURITY_STATUS sc = EncryptMessage(&m_ctx, 0, &desc, 0);
if (FAILED(sc)) {
return total > 0 ? total : SOCKET_ERROR;
}
int wireLen = bufs[0].cbBuffer + bufs[1].cbBuffer + bufs[2].cbBuffer;
if (!SendAll(sock, rec.data(), wireLen)) {
return total > 0 ? total : SOCKET_ERROR;
}
total += chunk;
}
return total;
}
#endif // _WIN32
+187
View File
@@ -0,0 +1,187 @@
// TlsChannel.h — 客户端单向 TLS 会话封装(Windows: Schannel;Linux: OpenSSL)
//
// 用途:为 YAMA 客户端(被控端)提供「按需开启」的传输层加密。当信任锚证书存在时,
// 所有出站 TCP 连接在应用协议首包前先完成 TLS 握手;握手失败一律断开
// (fail-closed,不回退明文)。
//
// 选型:
// - Windows:Schannel(原生 SSPI),零第三方依赖;secur32.lib / crypt32.lib 为系统库。
// - Linux:OpenSSL(构建链已因 libsign 链接 libcrypto,另加 libssl 即可)。
// 两者都是单向 TLS:客户端只校验服务端证书链到固定的信任锚,不提供客户端证书,
// 客户端身份仍由隧道内登录(V1 PwdHmac / V2 ECDSA)承担;均不校主机名(客户端按 IP
// 连接),不做吊销检查——与 Windows 版既有语义保持一致。
//
// 线程模型:Handshake 在连接建立线程上、m_bConnected 置位前调用;Send/Recv 分别在
// 发送线程 / 接收线程上调用。上下文生命周期(Handshake/CloseHandles 释放上下文)与
// Send/Recv 对上下文的使用由 m_ctxMtx 互斥,避免重连线程释放上下文时与使用线程产生
// use-after-free。本对象作为 IOCPClient 的值成员存在,析构时释放上下文。
//
// 平台范围:_WIN32 与 Linux(非 Android)有实现;macOS / Android 不含任何内容,客户端
// 维持明文(TLS 接入按设计文档延后)。两平台都通过 YAMA_TLS_CHANNEL 宏告知调用方
// 「本平台有 TLS 通道」。
#pragma once
#if defined(_WIN32)
#define YAMA_TLS_CHANNEL 1
#include <WinSock2.h>
#ifndef SECURITY_WIN32
#define SECURITY_WIN32 1
#endif
#include <security.h>
#include <schannel.h>
#include <mutex>
#include <string>
#include <vector>
// 进程级 TLS 开关:首次调用时加载信任锚(注册表或文件),返回是否启用。线程安全。
// Windows 版同样是「可热切换」的:TlsReload() 之后本函数立刻反映新状态(不是 call_once)。
bool TlsEnabled();
// 信任锚已配置但加载失败(损坏/格式错误)时为 true:表示管理员已「颁发」证书,
// 客户端必须拒绝连接(fail-closed),不得静默回退明文。线程安全、幂等。
bool TlsLoadError();
// 按当前信任锚位置(注册表 settings\tls_cert → settings.ini → exe 同目录 yama-ca.pem)
// 重建 TLS 上下文并更新开关,让随后建立的新连接立刻走新传输方式(已建立的连接不受
// 影响)。信任锚无效时不做任何改动、返回 false 并给出原因——一次坏下发不该把正在工作
// 的客户端打死(下次启动仍 fail-closed)。线程安全:与 TlsEnabled/TlsLoadError/握手
// 的证书校验互斥。
bool TlsReload(std::string& err);
class TlsChannel
{
public:
TlsChannel() {}
~TlsChannel() { CloseHandles(); }
// 持 Schannel 句柄,禁止拷贝/赋值(避免句柄被二次释放)。
TlsChannel(const TlsChannel&) = delete;
TlsChannel& operator=(const TlsChannel&) = delete;
// 在已连通的 socket 上完成 TLS 客户端握手并校验服务端证书链。失败返回 false,
// 调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
// sni 非空且为域名时作为 SNI 发送,让反代(nginx)按域名分流到正确的 server 块;
// 证书校验仍只钉信任锚、不校主机名,与直接连主控端口时完全一致。
bool Handshake(SOCKET sock, const char* sni = NULL);
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
int Recv(SOCKET sock, char* buf, int len);
// 加密发送 len 字节:成功返回已完整发送的明文字节数(== len);失败返回已发送的
// 前缀字节数(>0)或 SOCKET_ERROR(一个字节都没发出去时)。
int Send(SOCKET sock, const char* buf, int len);
// 是否有待交付的数据:已解密明文(m_pending)或已缓冲但尚未解密的 TLS 记录(m_raw)。
// 供接收线程在 select 前优先消费——select 只看底层 socket,看不到 Schannel 缓冲的
// m_raw(握手时随 Finished 收下的首条应用数据、或一次 recv 到多条记录后的剩余),
// 若这里不把 m_raw 也算作「有数据」,这些字节会被 select 卡住。
bool HasPending() const { return !m_pending.empty() || !m_raw.empty(); }
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
bool IsReady() const { return m_ready; }
private:
void CloseHandles();
bool SendAll(SOCKET sock, const void* data, int len);
bool VerifyServerCert();
CredHandle m_cred = {};
CtxtHandle m_ctx = {};
bool m_credValid = false; // m_cred 已分配,需 FreeCredentialsHandle
bool m_ctxValid = false; // m_ctx 已分配,需 DeleteSecurityContext
bool m_ready = false; // 握手完成,Send/Recv 可用
SecPkgContext_StreamSizes m_sizes = {};
// 保护上下文生命周期:重连线程的 Handshake/CloseHandles(释放 m_ctx)与工作线程的
// Recv(DecryptMessage)、发送线程的 Send(EncryptMessage)互斥,避免 use-after-free。
// recursive 是因为 Handshake 内部会再调 CloseHandles。
std::recursive_mutex m_ctxMtx;
std::vector<BYTE> m_raw; // 尚未解密 / 未消费完的 TLS 记录原始字节
std::vector<BYTE> m_pending; // 已解密、未交付给应用层的明文
};
#elif defined(__linux__) && !defined(__ANDROID__)
#define YAMA_TLS_CHANNEL 1
#include <string>
#include <mutex>
struct ssl_st; // OpenSSL 的 SSL 类型,避免头文件把 openssl/ssl.h 拖进所有翻译单元
// 进程级 TLS 开关:首次调用时加载信任锚文件,返回是否启用。线程安全、幂等。
// Linux 版是「可热切换」的:TlsReload() 之后本函数立刻反映新状态(不是 call_once)。
bool TlsEnabled();
// 信任锚已配置但加载失败(无法读取/格式错误/内容为空)时为 true:客户端必须拒绝连接
// (fail-closed),不得静默回退明文。线程安全、幂等。
bool TlsLoadError();
// 服务端下发信任锚(COMMAND_TLS_ENABLE):把 PEM 正文写入
// $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem,无 HOME 时退回
// 程序目录),原子替换、权限 0600。写入前先解析验证,不是合法证书就整包拒绝。
// 落盘后用 TlsReload() 立即生效(Windows 客户端在 COMMAND_TLS_ENABLE 里调用同一个
// TlsReload(),两平台行为一致)。
bool TlsTrustAnchorSave(const std::string& pem, std::string& err);
// 服务端撤销信任锚(COMMAND_TLS_DISABLE):删除上述配置文件(含程序目录同名文件)。
// 返回是否删掉了至少一个文件;之后同样用 TlsReload() 立即生效。
bool TlsTrustAnchorRemove(std::string& err);
// 按当前信任锚文件重建 TLS 上下文并更新开关,让随后建立的新连接立刻走新传输方式
// (已建立的连接不受影响:SSL 对象自持 SSL_CTX 引用)。信任锚无效时不做任何改动、
// 返回 false 并给出原因——一次坏下发不该把正在工作的客户端打死(下次启动仍 fail-closed)。
// 线程安全:与 TlsEnabled/TlsLoadError/Handshake 互斥。
bool TlsReload(std::string& err);
class TlsChannel
{
public:
TlsChannel() {}
~TlsChannel() { CloseHandles(); }
// 持 SSL*,禁止拷贝/赋值(避免上下文被二次释放)。
TlsChannel(const TlsChannel&) = delete;
TlsChannel& operator=(const TlsChannel&) = delete;
// 在已连通的 socket 上完成 TLS 1.2 客户端握手并按信任锚校验服务端证书链。失败返回
// false,调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
// sni 非空且为域名时作为 SNI 发送(反代按域名分流);证书校验仍只钉信任锚。
bool Handshake(int sock, const char* sni = NULL);
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
int Recv(int sock, char* buf, int len);
// 加密发送 len 字节:成功返回已完整发送的明文字节数(== len);失败返回已发送的
// 前缀字节数(>0)或 SOCKET_ERROR(一个字节都没发出去时)。
int Send(int sock, const char* buf, int len);
// 是否有待交付的数据(SSL 内部已缓冲)供接收线程在 select 前优先消费。OpenSSL 会在
// 一个 TLS 记录里装多条应用数据,一次 SSL_read 只交付一部分;剩余的留在 SSL 内部,
// select 看不到,必须用 SSL_has_pending() 才能避免被 2 秒超时卡住。
bool HasPending() const;
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
bool IsReady() const { return m_ready; }
private:
void CloseHandles();
ssl_st* m_ssl = nullptr;
int m_fd = -1;
bool m_ready = false; // 握手完成,Send/Recv 可用
// 保护上下文生命周期:重连线程的 Handshake/CloseHandles(释放 m_ssl)与工作线程的
// Recv(SSL_read)、发送线程的 Send(SSL_write)互斥。OpenSSL 的 SSL 对象不允许
// 并发使用,所以 Send/Recv 也持锁——与 Windows 版同样式。
// mutable 是因为 HasPending() 是 const 但需要持锁读 m_ssl。
mutable std::recursive_mutex m_ctxMtx;
};
#endif // _WIN32 / __linux__ && !__ANDROID__
+563
View File
@@ -0,0 +1,563 @@
// TlsChannelLinux.cpp — 见 TlsChannel.h 头注释。仅 Linux(非 Android)编译。
//
// 与 Windows 的 Schannel 实现语义对齐:
// - 单向 TLS 1.2(min=max=1.2,与 SP_PROT_TLS1_2_CLIENT 及两套服务端一致);
// - 信任锚严格钉扎:证书链只按信任锚文件里的证书校验,不含系统根库;
// - 不校主机名(客户端按 IP 连接,与 Windows 版一致)、不做吊销检查;
// - 信任锚「存在即已配置」:读取/解析失败一律 TlsLoadError()=true → 调用方拒绝连接。
//
// 与 Windows 实现的差异:OpenSSL 自己管理 TLS 记录缓冲,不需要 m_raw/m_pending;
// 一次性交付不出去的明文留在 SSL 内部,由 SSL_has_pending()/SSL_pending() 暴露给
// 接收线程在 select 前优先消费。
#if defined(__linux__) && !defined(__ANDROID__)
#include "TlsChannel.h"
#include "common/commands.h" // SOCKET_ERROR / closesocket 等 POSIX 兼容宏
#include "common/logger.h" // Mprintf
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/x509_vfy.h>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <mutex>
#include <string>
#include <vector>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
namespace {
const char* const kAnchorName = "yama-ca.pem";
// 进程级 TLS 状态。两平台都可由 TlsReload() 热切换(Windows 版改造前是 call_once)
// (服务端 COMMAND_TLS_ENABLE/DISABLE 落盘后立即重建),因此用互斥量而不是 once_flag。
std::mutex g_stateMtx; // 保护下面四项
bool g_inited = false; // 首次加载已完成(含 fail-closed 基态)
bool g_tlsEnabled = false; // TLS 会话可用:send/recv 走加密
bool g_tlsError = false; // 信任锚存在但加载失败:拒绝连接(fail-closed)
SSL_CTX* g_tlsCtx = nullptr; // 进程级上下文(线程安全,可被多条连接共享)
std::string g_anchorPath; // 仅用于日志
// 配置目录:与 LinuxConfig 相同规则($XDG_CONFIG_HOME/ghost 或 ~/.config/ghost)。
std::string ConfigDir()
{
const char* xdg = getenv("XDG_CONFIG_HOME");
if (xdg && xdg[0])
return std::string(xdg) + "/ghost";
const char* home = getenv("HOME");
if (!home || !home[0])
return std::string();
return std::string(home) + "/.config/ghost";
}
// 可执行文件所在目录(readlink /proc/self/exe,失败返回空)。
std::string ExeDir()
{
char buf[4096];
ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
if (n <= 0)
return std::string();
buf[n] = '\0';
char* slash = strrchr(buf, '/');
if (!slash)
return std::string();
*slash = '\0';
return std::string(buf);
}
// 信任锚候选路径(按优先级),只返回已经存在的那个:
// 1) $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem)
// 2) 可执行文件同目录 yama-ca.pem(兼容手工投递,与 Windows 的 exe 同名文件回退一致)
bool FindAnchorPath(std::string& out)
{
std::vector<std::string> cands;
std::string dir = ConfigDir();
if (!dir.empty())
cands.push_back(dir + "/" + kAnchorName);
std::string exed = ExeDir();
if (!exed.empty())
cands.push_back(exed + "/" + kAnchorName);
for (size_t i = 0; i < cands.size(); ++i) {
if (access(cands[i].c_str(), F_OK) == 0) {
out = cands[i];
return true;
}
}
return false;
}
// 递归 mkdir -p(已存在视为成功)。
bool MkdirP(const std::string& path, mode_t mode)
{
if (path.empty())
return false;
struct stat st;
if (stat(path.c_str(), &st) == 0)
return S_ISDIR(st.st_mode);
size_t slash = path.find_last_of('/');
if (slash != std::string::npos && slash > 0) {
if (!MkdirP(path.substr(0, slash), mode))
return false;
}
if (mkdir(path.c_str(), mode) != 0 && errno != EEXIST)
return false;
return true;
}
// 把 PEM(可含多张证书)或 DER 信任锚写入 store。返回加入的证书数。
int LoadAnchors(const std::string& data, X509_STORE* store)
{
int added = 0;
if (data.find("-----BEGIN") != std::string::npos) {
BIO* bio = BIO_new_mem_buf(data.data(), (int)data.size());
if (bio) {
for (;;) {
X509* cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
if (!cert)
break;
if (X509_STORE_add_cert(store, cert) == 1)
++added;
else
ERR_clear_error(); // 重复证书等:忽略该张,继续读后面的
X509_free(cert);
}
BIO_free(bio);
}
ERR_clear_error();
}
if (added == 0) {
// 退回 DER(单张)
const unsigned char* p = (const unsigned char*)data.data();
X509* cert = d2i_X509(NULL, &p, (long)data.size());
if (cert) {
if (X509_STORE_add_cert(store, cert) == 1)
++added;
else
ERR_clear_error();
X509_free(cert);
}
ERR_clear_error();
}
return added;
}
enum BuildResult
{
BUILD_PLAINTEXT, // 没有信任锚文件 → 明文模式
BUILD_READY, // *outCtx 为新建上下文,调用方接管所有权
BUILD_INVALID, // 文件存在但读不了/解析不出证书(err 说明原因)
};
// 按当前信任锚文件构建一份新的 TLS 上下文。不读写任何全局状态,便于「先构建、成功再替换」。
BuildResult BuildState(SSL_CTX** outCtx, std::string& anchorPath, std::string& err, int& certs)
{
*outCtx = nullptr;
certs = 0;
anchorPath.clear();
std::string path;
if (!FindAnchorPath(path)) {
// 无证书 → 明文(默认,与老客户端一致)
return BUILD_PLAINTEXT;
}
anchorPath = path;
// 证书已配置:管理员已「颁发」,必须走 TLS;读取/解析失败即拒绝连接(fail-closed),
// 不能静默回退明文。
std::ifstream f(path.c_str(), std::ios::binary);
if (!f) {
err = "cannot open " + path + ": " + strerror(errno);
return BUILD_INVALID;
}
std::string pem((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());
if (!ctx) {
err = "SSL_CTX_new failed";
return BUILD_INVALID;
}
// TLS 1.2 钉扎:与 Windows 客户端(SP_PROT_TLS1_2_CLIENT)及两套服务端(Schannel
// SP_PROT_TLS1_2_SERVER / Go MinVersion=TLS1.2)保持一致。
SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION);
// SSL_VERIFY_PEER + 自定义 store = 严格钉扎到信任锚(不含系统根库),链校验在握手内
// 完成,失败即握手失败。verify 回调传 NULL 使用默认行为(只验链,不校主机名)。
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
SSL_CTX_set_verify_depth(ctx, 8);
// 对端不打招呼就断开(不发 close_notify)在这里是常态:服务端关闭子连接时不发,
// 客户端自己也同样不发(见 CloseHandles 的说明)。OpenSSL 3.0 起这种 unexpected EOF
// 被归为 SSL_ERROR_SSL 协议错误,于是每结束一个终端/文件传输子连接都会记一条
// 「SSL_read failed」——线上日志看着像 TLS 坏了。打开这个选项让它按正常关闭处理
// (SSL_read 返回 0),与 Recv 的文档语义以及 Windows 版的行为一致。
#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
#endif
X509_STORE* store = X509_STORE_new();
certs = store ? LoadAnchors(pem, store) : 0;
if (!store || certs <= 0) {
if (store)
X509_STORE_free(store);
SSL_CTX_free(ctx);
certs = 0;
err = "trust anchor " + path + " present but empty/invalid";
return BUILD_INVALID;
}
SSL_CTX_set_cert_store(ctx, store); // ctx 接管 store 所有权
*outCtx = ctx;
return BUILD_READY;
}
// 替换全局状态并释放旧上下文(调用方持 g_stateMtx)。SSL 对象在 SSL_new 时已递增
// SSL_CTX 的引用计数,所以已经建立的连接不会因为这里释放旧 ctx 而失效。
void InstallStateLocked(SSL_CTX* ctx, bool enabled, bool error, const std::string& anchor)
{
SSL_CTX* old = g_tlsCtx;
g_tlsCtx = ctx;
g_tlsEnabled = enabled;
g_tlsError = error;
g_anchorPath = anchor;
if (old)
SSL_CTX_free(old);
}
// 首次加载(调用方持锁):锚存在但无效时置 fail-closed。
void EnsureInitLocked()
{
if (g_inited)
return;
g_inited = true;
SSL_CTX* ctx = nullptr;
std::string anchor, err;
int certs = 0;
switch (BuildState(&ctx, anchor, err, certs)) {
case BUILD_PLAINTEXT:
InstallStateLocked(nullptr, false, false, anchor);
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
break;
case BUILD_READY:
InstallStateLocked(ctx, true, false, anchor);
Mprintf("[TLS] enabled: trust anchor loaded (%s, %d cert(s)), all connections use TLS\n",
anchor.c_str(), certs);
break;
case BUILD_INVALID:
InstallStateLocked(nullptr, false, true, anchor);
Mprintf("[TLS] FATAL: %s; refusing connections (fail-closed)\n", err.c_str());
break;
}
}
} // namespace
bool TlsEnabled()
{
std::lock_guard<std::mutex> lk(g_stateMtx);
EnsureInitLocked();
return g_tlsEnabled;
}
bool TlsLoadError()
{
std::lock_guard<std::mutex> lk(g_stateMtx);
EnsureInitLocked();
return g_tlsError;
}
bool TlsReload(std::string& err)
{
std::lock_guard<std::mutex> lk(g_stateMtx);
EnsureInitLocked(); // 未初始化就先按启动语义建立基态,保持 fail-closed 行为
SSL_CTX* ctx = nullptr;
std::string anchor;
int certs = 0;
BuildResult r = BuildState(&ctx, anchor, err, certs);
if (r == BUILD_INVALID) {
// 保留原状态:一次坏下发不该让正在工作的客户端失联(下次启动仍会 fail-closed)。
Mprintf("[TLS] reload FAILED: %s; keeping current transport (%s)\n",
err.c_str(), g_tlsEnabled ? "TLS" : "plaintext");
return false;
}
if (r == BUILD_PLAINTEXT) {
InstallStateLocked(nullptr, false, false, anchor);
Mprintf("[TLS] reloaded: no trust anchor, transport is now plaintext\n");
return true;
}
InstallStateLocked(ctx, true, false, anchor);
Mprintf("[TLS] reloaded: trust anchor %s (%d cert(s)), transport is now TLS\n",
anchor.c_str(), certs);
return true;
}
// ---- 信任锚下发 / 撤销(服务端 COMMAND_TLS_ENABLE / COMMAND_TLS_DISABLE)----
bool TlsTrustAnchorSave(const std::string& pem, std::string& err)
{
if (pem.empty()) {
err = "empty certificate payload";
return false;
}
// 先验证再落盘:文件一旦写进去,下次启动就会被无条件信任,坏锚等于把客户端锁死
// (fail-closed 连不上,也没法再从服务端改回来)。宁可拒绝一次下发。
{
X509_STORE* probe = X509_STORE_new();
int n = probe ? LoadAnchors(pem, probe) : 0;
if (probe)
X509_STORE_free(probe);
if (n <= 0) {
err = "payload is not a valid PEM/DER certificate";
return false;
}
}
std::string dir = ConfigDir();
if (dir.empty()) {
dir = ExeDir(); // 无 HOME 的极端环境:退回程序目录
if (dir.empty()) {
err = "cannot resolve config directory";
return false;
}
}
if (!MkdirP(dir, 0700)) {
err = "cannot create directory " + dir + ": " + strerror(errno);
return false;
}
std::string path = dir + "/" + kAnchorName;
std::string tmp = path + ".tmp";
int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (fd < 0) {
err = "cannot create " + tmp + ": " + strerror(errno);
return false;
}
size_t off = 0;
while (off < pem.size()) {
ssize_t w = write(fd, pem.data() + off, pem.size() - off);
if (w <= 0) {
if (w < 0 && errno == EINTR)
continue;
err = "cannot write " + tmp + ": " + strerror(errno);
close(fd);
unlink(tmp.c_str());
return false;
}
off += (size_t)w;
}
fsync(fd);
close(fd);
// 原子替换 + 收紧权限(目录可能已由 LinuxConfig 以 0755 创建)
if (rename(tmp.c_str(), path.c_str()) != 0) {
err = "cannot replace " + path + ": " + strerror(errno);
unlink(tmp.c_str());
return false;
}
chmod(path.c_str(), 0600);
Mprintf("[TLS] trust anchor saved to %s\n", path.c_str());
return true;
}
bool TlsTrustAnchorRemove(std::string& err)
{
std::vector<std::string> paths;
std::string dir = ConfigDir();
if (!dir.empty())
paths.push_back(dir + "/" + kAnchorName);
std::string exed = ExeDir();
if (!exed.empty())
paths.push_back(exed + "/" + kAnchorName);
bool removed = false;
for (size_t i = 0; i < paths.size(); ++i) {
if (unlink(paths[i].c_str()) == 0) {
removed = true;
Mprintf("[TLS] trust anchor removed: %s\n", paths[i].c_str());
} else if (errno != ENOENT) {
err = "cannot remove " + paths[i] + ": " + strerror(errno);
return false;
}
}
if (!removed) {
err = "no trust anchor configured";
return false;
}
return true;
}
// ---- TlsChannel ----
void TlsChannel::CloseHandles()
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (m_ssl) {
SSL_free(m_ssl); // 不发送 close_notify:与 Windows 的 DeleteSecurityContext 同语义
m_ssl = nullptr;
}
m_fd = -1;
m_ready = false;
}
bool TlsChannel::Handshake(int sock, const char* sni)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
// 在状态锁内取一份上下文:SSL_new 会递增 SSL_CTX 引用计数,此后即使 TlsReload()
// 把全局上下文换掉(旧 ctx 被 SSL_CTX_free),本次握手的 SSL 仍然安全。
SSL* ssl = nullptr;
{
std::lock_guard<std::mutex> lk(g_stateMtx);
EnsureInitLocked();
if (g_tlsCtx)
ssl = SSL_new(g_tlsCtx);
}
if (!ssl) {
Mprintf("[TLS] handshake called but no TLS context is available\n");
return false;
}
if (SSL_set_fd(ssl, sock) != 1) {
Mprintf("[TLS] SSL_set_fd failed\n");
SSL_free(ssl);
return false;
}
// SNI:反代(nginx)据此按域名分流到正确的 server 块。证书校验仍是自定义 store 里的
// 信任锚(SSL_VERIFY_PEER + 不校主机名),与直连主控端口时完全一致。
if (sni && *sni)
SSL_set_tlsext_host_name(ssl, sni);
SSL_set_connect_state(ssl);
// 阻塞 socket:WANT_READ / WANT_WRITE 只在记录分片等极端情形出现,重试即可。
for (;;) {
ERR_clear_error();
int r = SSL_do_handshake(ssl);
if (r == 1)
break;
int e = SSL_get_error(ssl, r);
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
continue;
if (e == SSL_ERROR_SSL) {
unsigned long err = ERR_peek_last_error();
char ebuf[256] = {0};
if (err)
ERR_error_string_n(err, ebuf, sizeof(ebuf));
Mprintf("[TLS] handshake failed: %s\n", ebuf[0] ? ebuf : "SSL error");
} else if (e == SSL_ERROR_SYSCALL) {
Mprintf("[TLS] handshake failed: syscall error (%s)\n", strerror(errno));
} else {
Mprintf("[TLS] handshake failed: SSL_get_error=%d (peer closed?)\n", e);
}
SSL_free(ssl);
return false;
}
// 单向 TLS:链必须钉扎到信任锚,且服务端确实出示了证书。默认 verify 只验链不校主机名,
// 与 Windows 版(CertGetCertificateChain 只验链)行为一致。
long vr = SSL_get_verify_result(ssl);
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
X509* peer = SSL_get1_peer_certificate(ssl);
#else
X509* peer = SSL_get_peer_certificate(ssl);
#endif
if (!peer || vr != X509_V_OK) {
Mprintf("[TLS] server certificate not trusted against trust anchor (%s)\n",
X509_verify_cert_error_string(vr));
if (peer)
X509_free(peer);
SSL_free(ssl);
return false;
}
X509_free(peer);
m_ssl = ssl;
m_fd = sock;
m_ready = true;
Mprintf("[TLS] handshake OK (%s, server cert trusted)\n", SSL_get_version(ssl));
return true;
}
int TlsChannel::Recv(int sock, char* out, int outLen)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (!m_ready || outLen <= 0) {
Mprintf("[TLS] Recv called but m_ready=%d (outLen=%d), returning SOCKET_ERROR\n",
(int)m_ready, outLen);
return SOCKET_ERROR;
}
(void)sock; // SSL 已绑定 fd
for (;;) {
ERR_clear_error();
int n = SSL_read(m_ssl, out, outLen);
if (n > 0)
return n;
int e = SSL_get_error(m_ssl, n);
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
continue;
if (e == SSL_ERROR_ZERO_RETURN)
return 0; // close_notify:对端正常关闭
if (e == SSL_ERROR_SYSCALL && ERR_peek_last_error() == 0)
return 0; // 对端未发 close_notify 就断开(unexpected EOF),按关闭处理
Mprintf("[TLS] SSL_read failed: SSL_get_error=%d (%s)\n", e, strerror(errno));
return SOCKET_ERROR;
}
}
int TlsChannel::Send(int sock, const char* data, int len)
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (!m_ready)
return SOCKET_ERROR;
if (len <= 0)
return 0;
(void)sock; // SSL 已绑定 fd
int total = 0;
while (total < len) {
ERR_clear_error();
int n = SSL_write(m_ssl, data + total, len - total);
if (n > 0) {
total += n;
continue;
}
int e = SSL_get_error(m_ssl, n);
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
continue;
Mprintf("[TLS] SSL_write failed: SSL_get_error=%d (%s), sent=%d/%d\n",
e, strerror(errno), total, len);
return total > 0 ? total : SOCKET_ERROR;
}
return total;
}
bool TlsChannel::HasPending() const
{
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
if (!m_ready || !m_ssl)
return false;
// SSL_pending: 已解密未交付的明文;SSL_has_pending: 内部还缓冲着未处理的记录字节。
// 任一为真都说明 select 看不到但可以立刻读,必须优先消费。
return SSL_pending(m_ssl) > 0 || SSL_has_pending(m_ssl) == 1;
}
#endif // __linux__ && !__ANDROID__
+6 -1
View File
@@ -21,7 +21,7 @@ CVideoManager::CVideoManager(IOCPClient* ClientObject, int n, void* user) : CMan
m_pVideoCodec = NULL;
m_fccHandler = 1129730893;
m_CapVideo.Open(0,0); // 开启
m_bVideoOpened = m_CapVideo.Open(0,0) == S_OK; // 开启
lpBuffer = NULL;
m_hWorkThread = __CreateThread(NULL, 0, WorkThread, this, 0, NULL);
@@ -31,6 +31,11 @@ CVideoManager::CVideoManager(IOCPClient* ClientObject, int n, void* user) : CMan
DWORD CVideoManager::WorkThread(LPVOID lParam)
{
CVideoManager *This = (CVideoManager *)lParam;
if (!This->m_bVideoOpened) {
This->Destroy();
return 0x20261013;
}
static ULONGLONG dwLastScreen = GetTickCount64();
if (This->Initialize()) { //转到Initialize
+1
View File
@@ -25,6 +25,7 @@ public:
BOOL m_bIsWorking;
HANDLE m_hWorkThread;
BOOL m_bVideoOpened;
void SendBitMapInfor();
BOOL SendNextScreen();
+401
View File
@@ -0,0 +1,401 @@
// WsChannel.h — WebSocket 传输层(客户端侧,头文件实现,无需改工程文件)
//
// 用途:当出站被限制在 80/443/8080 等少数端口时,客户端经反代(如 nginx 的 443)
// 以 WebSocket 进入服务端。应用协议完全不变:本层只把字节流套进 WS 帧里,位置与
// TLS 相同(TLS 之下、应用协议之上)。
//
// 两种形态(见 common/commands.h 的 ProtoType):
// PROTO_WS 裸 WebSocket(反代把明文 upgrade 转发到主控端口)
// PROTO_WSS WebSocket over TLS(反代终止 TLS;客户端仍用既有信任锚校验证书,
// 并通过 SNI 让反代按域名分流到正确的 server 块)
//
// 线程模型:Handshake 在连接线程上、m_bConnected 置位前调用;之后 Recv 只由接收
// 线程调用、Send 只由发送线程调用。但 Recv 里要为 ping/close 回写控制帧,收、发两个
// 线程会同时写 socket,因此写方向必须用 m_sendMtx 串行化,且一帧的头与体要一次写出,
// 否则两帧会互相穿插、对端解帧错位。TLS 自身的互斥由 TlsChannel 负责。
#pragma once
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include <ctime>
#include <atomic>
#include <mutex>
#include <string>
#include <vector>
#ifdef _WIN32
#include <WinSock2.h>
#else
#include <sys/socket.h>
#include <unistd.h>
// 本头在 IOCPClient.h 里先于 common/commands.h 展开(后者是 Linux 版 SOCKET 的来源),
// 这里补一份同类型定义;重复 typedef 合法。
typedef int SOCKET;
#endif
#ifndef SOCKET_ERROR
#define SOCKET_ERROR -1
#endif
#include "TlsChannel.h"
class WsChannel
{
public:
WsChannel() {}
#ifdef YAMA_TLS_CHANNEL
// 绑定底层加密通道:WSS 指向 IOCPClient 的 TlsChannel,裸 WS 传 NULL。
// 设置后本类的所有原始收发都经由它(或直接 send/recv)。
void SetTls(TlsChannel* tls) { m_tls = tls; }
#endif
// 让 Recv/Send 立刻失效。**可由任意线程调用**(Disconnect 可能来自心跳/命令线程,
// 不只是接收线程),因此这里只碰原子量;帧解析状态留给 ResetFrames()——它只在
// Handshake 里、接收线程还没起来时清。
void Reset()
{
m_ready = false;
}
bool IsReady() const { return m_ready; }
// 在已连通的 socket 上完成 HTTP Upgrade 握手。host 用于 Host 头(WSS 的 SNI 由
// TlsChannel::Handshake 负责);path 是 Upgrade 请求的路径。失败时 err 给出原因。
bool Handshake(SOCKET sock, const std::string& host, int port, const char* path, std::string* err = NULL)
{
Reset();
ResetFrames();
char hostPort[120] = { 0 };
if (port == 80 || port == 443)
snprintf(hostPort, sizeof(hostPort), "%s", host.c_str());
else
snprintf(hostPort, sizeof(hostPort), "%s:%d", host.c_str(), port);
// Sec-WebSocket-Key 用固定值:它只用于让中间设备确认这是 WS 握手(服务端会原样
// 做 SHA1/Base64 回显),不承担任何安全职责;真正的身份由隧道内登录和 TLS 承担。
std::string req;
req.reserve(256);
req += "GET ";
req += path;
req += " HTTP/1.1\r\nHost: ";
req += hostPort;
req += "\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n";
req += "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n";
req += "Sec-WebSocket-Version: 13\r\n\r\n";
if (!SendAll(sock, req.data(), (int)req.size())) {
if (err) *err = "send upgrade request failed";
return false;
}
// 逐字节读响应头,读到空行即停(多读的字节会被当作 WS 帧,而服务端在我们发首包
// 前不会主动发数据,所以这里读到空行为止是安全的)。
std::string head;
bool complete = false;
char c = 0;
while (head.size() < 4096) {
int n = RawRecv(sock, &c, 1);
if (n <= 0) {
if (err) *err = "connection closed during upgrade";
return false;
}
head += c;
if (head.size() >= 4 && head.compare(head.size() - 4, 4, "\r\n\r\n") == 0) {
complete = true;
break;
}
}
if (!complete) {
if (err) *err = "upgrade response head too large";
return false;
}
if (head.compare(0, 12, "HTTP/1.1 101") != 0) {
if (err) {
std::string line = head.substr(0, head.find("\r\n"));
*err = "upgrade rejected: " + line;
}
return false;
}
m_ready = true;
return true;
}
// 读取应用层字节:>0 为读到的字节数;0 表示对端正常关闭;SOCKET_ERROR 表示出错。
// 与 recv 语义一致,调用方按同样方式处理。
int Recv(SOCKET sock, char* buf, int len)
{
if (!m_ready || len <= 0)
return SOCKET_ERROR;
for (;;) {
if (m_remaining > 0) {
int want = (m_remaining < (long long)len) ? (int)m_remaining : len;
int n = RawRecv(sock, buf, want);
if (n <= 0)
return n; // 0 = 对端关闭;SOCKET_ERROR = 出错(TLS 已记录原因)
if (m_masked) {
for (int i = 0; i < n; i++) {
buf[i] ^= (char)m_mask[m_maskPos];
m_maskPos = (m_maskPos + 1) & 3;
}
}
m_remaining -= n;
return n;
}
unsigned char opcode = 0;
long long frameLen = 0;
if (!ReadHeader(sock, opcode, frameLen))
return SOCKET_ERROR;
if (opcode >= 0x8) {
// 控制帧:载荷 ≤125 字节,必须在数据帧之间处理
char ctl[125];
if (frameLen > (long long)sizeof(ctl))
return SOCKET_ERROR;
if (frameLen > 0) {
if (!ReadExact(sock, ctl, (int)frameLen))
return SOCKET_ERROR;
Unmask(ctl, (int)frameLen);
}
if (opcode == 0x8) { // close:回一个 close,然后按正常关闭处理
(void)WriteFrame(sock, 0x8, ctl, (int)frameLen);
m_ready = false;
return 0;
}
if (opcode == 0x9) { // ping → pong
if (!WriteFrame(sock, 0xA, ctl, (int)frameLen))
return SOCKET_ERROR;
}
// 0xA (pong) 与其它的直接忽略
continue;
}
if (opcode != 0x0 && opcode != 0x1 && opcode != 0x2)
return SOCKET_ERROR;
if (frameLen == 0)
continue;
m_remaining = frameLen;
m_maskPos = 0;
}
}
// 发送应用层字节:全部发出返回 len;否则 SOCKET_ERROR。每包一帧(FIN + binary),
// 与主控端 wsConn 的「一次 Write 一帧」对齐,保证包边界与发出时一致。
int Send(SOCKET sock, const char* buf, int len)
{
if (!m_ready)
return SOCKET_ERROR;
if (len <= 0)
return 0;
return WriteFrame(sock, 0x2, buf, len) ? len : SOCKET_ERROR;
}
// 是否有已收到但尚未交付的应用层字节。两处来源:帧载荷只解析了一半(m_remaining),
// 或 TLS 会话内部还压着已解密明文(WSS)。接收线程在 select 之前要优先消费,
// 否则 select 看不到这些字节会被 2 秒超时卡住。
bool HasPending() const
{
if (m_remaining > 0)
return true;
#ifdef YAMA_TLS_CHANNEL
if (m_tls)
return m_tls->HasPending();
#endif
return false;
}
private:
// ---- 原始收发:有 TLS 会话时全程走 TLS,否则裸 socket ----
int RawRecv(SOCKET sock, char* buf, int len)
{
#ifdef YAMA_TLS_CHANNEL
if (m_tls)
return m_tls->Recv(sock, buf, len);
#endif
return ::recv(sock, buf, len, 0);
}
int RawSend(SOCKET sock, const char* buf, int len)
{
#ifdef YAMA_TLS_CHANNEL
if (m_tls)
return m_tls->Send(sock, buf, len);
#endif
return ::send(sock, buf, len, 0);
}
bool SendAll(SOCKET sock, const char* buf, int len)
{
int sent = 0;
while (sent < len) {
int n = RawSend(sock, buf + sent, len - sent);
if (n <= 0)
return false;
sent += n;
}
return true;
}
bool ReadExact(SOCKET sock, void* buf, int len)
{
char* p = (char*)buf;
int got = 0;
while (got < len) {
int n = RawRecv(sock, p + got, len - got);
if (n <= 0)
return false;
got += n;
}
return true;
}
// 读帧头(含扩展长度与掩码键)。服务端发来的帧不应带掩码,带了也照样解。
static const long long kMaxFramePayload = 256LL * 1024 * 1024;
bool ReadHeader(SOCKET sock, unsigned char& opcode, long long& frameLen)
{
unsigned char h[2] = { 0, 0 };
if (!ReadExact(sock, h, 2))
return false;
if (h[0] & 0x70)
return false; // 未协商扩展却置了 RSV 位
opcode = h[0] & 0x0F;
m_masked = (h[1] & 0x80) != 0;
frameLen = h[1] & 0x7F;
if (frameLen == 126) {
unsigned char ext[2];
if (!ReadExact(sock, ext, 2))
return false;
frameLen = ((long long)ext[0] << 8) | ext[1];
} else if (frameLen == 127) {
unsigned char ext[8];
if (!ReadExact(sock, ext, 8))
return false;
frameLen = 0;
for (int i = 0; i < 8; i++)
frameLen = (frameLen << 8) | ext[i];
if (frameLen < 0)
return false;
}
// 单帧载荷上限,与主控端 ServerWsSession 的 kMaxFramePayload 取同一个值(256 MB)。
// 没有上限时,一个错误/被篡改的长度字段就能把 m_remaining 定在天文数字上,此后
// 所有字节都被当成该帧的内容吞掉,连接表面上还活着却永远收不到新包——比直接断线
// 难查得多。正常业务的最大单包远小于此值,故不会挡住既有功能。
if (frameLen > kMaxFramePayload)
return false;
if (m_masked && !ReadExact(sock, m_mask, 4))
return false;
m_maskPos = 0;
return true;
}
void Unmask(char* buf, int len)
{
if (!m_masked)
return;
for (int i = 0; i < len; i++) {
buf[i] ^= (char)m_mask[m_maskPos];
m_maskPos = (m_maskPos + 1) & 3;
}
}
// 写一帧。客户端发往服务端的帧必须带掩码(RFC 6455 §5.3)。整帧(帧头 + 掩码后的
// 载荷)在 m_sendMtx 内一次写出:接收线程可能在同一时刻回 pong/close,若两帧各自
// 分「头」「体」两次发送就会交错,对端从此解帧错位。
bool WriteFrame(SOCKET sock, unsigned char opcode, const char* payload, int len)
{
unsigned char hdr[14];
int hn = 2;
hdr[0] = (unsigned char)(0x80 | opcode);
if (len < 126) {
hdr[1] = (unsigned char)(0x80 | len);
} else if (len <= 0xFFFF) {
hdr[1] = 0x80 | 126;
hdr[2] = (unsigned char)((len >> 8) & 0xFF);
hdr[3] = (unsigned char)(len & 0xFF);
hn = 4;
} else {
hdr[1] = 0x80 | 127;
unsigned long long v = (unsigned long long)len;
for (int i = 0; i < 8; i++)
hdr[2 + i] = (unsigned char)((v >> (56 - 8 * i)) & 0xFF);
hn = 10;
}
std::lock_guard<std::mutex> lock(m_sendMtx);
// 掩码在锁内、用本实例私有的 PRNG 生成:发送线程与接收线程(pong / close)都会
// 写帧,锁外取掩码会让两个线程并发推进共享状态;而全局 rand() 更不能用了——
// HttpMask 的构造函数里有 srand(time(nullptr)),会在同进程内重置全局序列。
// xorshift64 对本场景足够(RFC 6455 §5.3 只要求掩码来自概率性熵源,不承担安全职责)。
unsigned long long r = NextMask64();
unsigned char mask[4];
for (int i = 0; i < 4; i++)
mask[i] = (unsigned char)((r >> (8 * i)) & 0xFF);
memcpy(hdr + hn, mask, 4);
hn += 4;
// 复用同一个缓冲区:发送热路径上每帧不再分配一个新 vector。
m_frame.resize((size_t)hn + (size_t)len);
char* frame = m_frame.data();
memcpy(frame, hdr, hn);
char* dst = frame + hn;
for (int i = 0; i < len; i++)
dst[i] = (char)(payload[i] ^ (char)mask[i & 3]);
return SendAll(sock, frame, hn + len);
}
#ifdef YAMA_TLS_CHANNEL
TlsChannel* m_tls = NULL; // WSS 时指向 IOCPClient 的 TLS 会话
#endif
// 会话是否就绪。收、发分处两个线程,且 Disconnect 可能从接收线程侧走 Reset(),
// 故用原子量:x86 上裸 bool 实践无害,但换架构就不能再依赖这个巧合。
std::atomic<bool> m_ready{false};
// 写帧掩码用的私有 PRNG(只在 m_sendMtx 内推进)。种子取地址 + 时间,够用即可:
// 掩码只用于让帧在链路上不再是固定形态,安全性由 TLS 与隧道内登录承担。
unsigned long long NextMask64()
{
unsigned long long x = m_maskState;
if (x == 0) {
x = (unsigned long long)(uintptr_t)this;
x = x * 0x9E3779B97F4A7C15ULL ^ (unsigned long long)time(nullptr);
if (x == 0)
x = 0x2545F4914F6CDD1DULL;
}
// xorshift64*
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
m_maskState = x;
return x * 0x2545F4914F6CDD1DULL;
}
unsigned long long m_maskState = 0;
// 写方向串行化(发送线程与接收线程的 pong/close 都会写帧),以及复用的整帧缓冲。
std::mutex m_sendMtx;
std::vector<char> m_frame;
// 当前数据帧的剩余载荷长度与掩码状态(只由接收线程读写,无需加锁)。
// 只能在接收线程未运行时清(见 public Reset()):Handshake 在连接线程上、m_bConnected
// 置位之前调用,那时接收线程还没开始读 socket。
void ResetFrames()
{
m_remaining = 0;
m_masked = false;
m_maskPos = 0;
}
long long m_remaining = 0;
bool m_masked = false;
unsigned char m_mask[4] = { 0, 0, 0, 0 };
int m_maskPos = 0;
};
+13 -4
View File
@@ -2,21 +2,30 @@
#include <string.h>
#include <stdio.h>
// libyuv 与 x264 是两个独立依赖,必须分开处理:硬编路径(CFFmpegAV1Encoder /
// CFFmpegH264Encoder)也拿 libyuv 做色彩空间转换,但这两个文件自己没有
// #pragma comment(lib),一直靠这里引入。所以 libyuv 必须留在 x264 开关之外——
// 否则 DISABLE_X264_FOR_TEST=1 会把 libyuv 一起丢掉,链接时立刻报
// LNK2001: RGB24ToI420 / ARGBToNV12 / I420ToNV12。
#ifdef _WIN64
#pragma comment(lib,"libyuv/libyuv_x64.lib")
#else
#pragma comment(lib,"libyuv/libyuv.lib")
#endif
#if DISABLE_X264_FOR_TEST
CX264Encoder::CX264Encoder() { memset(&m_Param, 0, sizeof(m_Param)); m_pCodec = NULL; m_pPicIn = NULL; m_pPicOut = NULL; m_forceIDR = false; }
// 合规构建的桩实现:头文件已不含 x264 类型,这里也不能碰 m_Param / x264_param_t。
CX264Encoder::CX264Encoder() { m_forceIDR = false; }
CX264Encoder::~CX264Encoder() {}
bool CX264Encoder::open(int, int, int, int) { return false; }
bool CX264Encoder::open(x264_param_t*) { return false; }
bool CX264Encoder::open(const EncoderParams&) { return false; }
void CX264Encoder::close() {}
int CX264Encoder::encode(uint8_t*, uint8_t, uint32_t, uint32_t, uint32_t, uint8_t**, uint32_t*, int) { return -1; }
#else
#ifdef _WIN64
#pragma comment(lib,"libyuv/libyuv_x64.lib")
#pragma comment(lib,"x264/libx264_x64.lib")
#else
#pragma comment(lib,"libyuv/libyuv.lib")
#pragma comment(lib,"x264/libx264.lib")
#endif
+44 -2
View File
@@ -1,14 +1,54 @@
#pragma once
#include "VideoEncoderBase.h"
// 必须在下面的条件编译之前:DISABLE_X264_FOR_TEST 定义在这里。
// 原来它排在 x264 头文件之后,导致开关无论怎么设,x264.h 都已经被拉进来了。
#include "common/config.h"
#if DISABLE_X264_FOR_TEST
// 合规构建(DISABLE_X264_FOR_TEST=1):不包含 x264 / libyuv 头文件,不声明任何
// x264 类型,整棵源码树不含 GPL 头文件,也不链接 libx264。
//
// 类仍保留基类接口(EncoderFactory::CreateEncoder 通过 VideoEncoderBase 指针创建
// 并调用),但 open() 恒返回 false,由 CreateEncoder 自然回退到硬编路径;
// 若硬编也不可用则返回 nullptr,调用方按“无编码器”处理。
class CX264Encoder : public VideoEncoderBase
{
private:
bool m_forceIDR; // 保留成员以对齐两套实现的行为,桩里不使用
public:
// 旧签名保留:与非合规构建保持同一份对外接口
bool open(int width, int height, int fps, int crf);
// VideoEncoderBase
bool open(const EncoderParams& params) override;
void close() override;
int encode(
uint8_t * rgb,
uint8_t bpp,
uint32_t stride,
uint32_t width,
uint32_t height,
uint8_t ** lppData,
uint32_t * lpSize,
int direction = 1
) override;
void forceIDR() override { m_forceIDR = true; }
VideoCodec codec() const override { return VideoCodec::H264; }
const char* backendName() const override { return "x264"; }
CX264Encoder();
~CX264Encoder() override;
};
#else
extern "C" {
#include <libyuv\libyuv.h>
#include <x264\x264.h>
}
#include "common/config.h"
class CX264Encoder : public VideoEncoderBase
{
private:
@@ -42,3 +82,5 @@ public:
CX264Encoder();
~CX264Encoder() override;
};
#endif // DISABLE_X264_FOR_TEST
+5
View File
@@ -573,6 +573,11 @@ UINT CFileManager::SendFilesList(TCHAR* lpszDirectory)
else
lpszSlash = _T("");
TCHAR str_last[] = { _T('%'),_T('s'),_T('%'),_T('s'),_T('*'),_T('.'),_T('*'),_T('\0') };
// wsprintf 不做边界检查:目录 + "\*.*" + NUL 装不下就按空目录回,别写穿 strPath。
if ((int)(_tcslen(lpszDirectory) + _tcslen(lpszSlash)) + 4 > MAX_PATH) {
BYTE bToken = TOKEN_FILE_LIST;
return Send(&bToken, 1);
}
wsprintf(strPath, str_last, lpszDirectory, lpszSlash);
hFile = FindFirstFile(strPath, &FindFileData);
+5
View File
@@ -233,6 +233,7 @@
<ClCompile Include="CFFmpegH264Encoder.cpp" />
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="VideoManager.cpp" />
@@ -299,7 +300,11 @@
<ClInclude Include="SystemManager.h" />
<ClInclude Include="VideoEncoderBase.h" />
<ClInclude Include="TalkManager.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
+207
View File
@@ -0,0 +1,207 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="..\common\file_upload.cpp" />
<ClCompile Include="..\common\ikcp.c" />
<ClCompile Include="..\common\zstd_wrapper.c" />
<ClCompile Include="..\server\2015Remote\pwd_gen.cpp" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="Audio.cpp" />
<ClCompile Include="AudioManager.cpp" />
<ClCompile Include="Buffer.cpp" />
<ClCompile Include="CaptureVideo.cpp" />
<ClCompile Include="clang_rt_compat.c" />
<ClCompile Include="ClientDll.cpp" />
<ClCompile Include="Common.cpp" />
<ClCompile Include="FileManager.cpp" />
<ClCompile Include="file\FileManager.cpp" />
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="IOCPClient.cpp" />
<ClCompile Include="IOCPKCPClient.cpp" />
<ClCompile Include="IOCPUDPClient.cpp" />
<ClCompile Include="KernelManager.cpp" />
<ClCompile Include="KeyboardManager.cpp" />
<ClCompile Include="keylogger.cpp" />
<ClCompile Include="Loader.cpp" />
<ClCompile Include="LoginServer.cpp" />
<ClCompile Include="ClientLogManager.cpp" />
<ClCompile Include="Manager.cpp" />
<ClCompile Include="MemoryModule.c" />
<ClCompile Include="proxy\ProxyManager.cpp" />
<ClCompile Include="RegisterManager.cpp" />
<ClCompile Include="RegisterOperation.cpp" />
<ClCompile Include="reg_startup.c" />
<ClCompile Include="SafeThread.cpp" />
<ClCompile Include="ScreenManager.cpp" />
<ClCompile Include="ScreenPreview.cpp" />
<ClCompile Include="ScreenSpy.cpp" />
<ClCompile Include="ServicesManager.cpp" />
<ClCompile Include="ConnectionsManager.cpp" />
<ClCompile Include="ServiceWrapper.c" />
<ClCompile Include="session.cpp" />
<ClCompile Include="SessionMonitor.c" />
<ClCompile Include="ShellManager.cpp" />
<ClCompile Include="ConPTYManager.cpp" />
<ClCompile Include="StdAfx.cpp" />
<ClCompile Include="SystemManager.cpp" />
<ClCompile Include="CFFmpegAV1Encoder.cpp" />
<ClCompile Include="CFFmpegH264Encoder.cpp" />
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="VideoManager.cpp" />
<ClCompile Include="X264Encoder.cpp" />
<ClCompile Include="decrypt\DecryptManager.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\Get360seInfo.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\GetBrowserInfo.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\UnCode.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\sqlite3\rijndael.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\sqlite3\sqlite3.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\cJSON\cJSON.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\cJSON\cJSON_Utils.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\base64\base64.c">
<Filter>decrypt</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\file_upload.h" />
<ClInclude Include="..\common\ikcp.h" />
<ClInclude Include="..\common\mask.h" />
<ClInclude Include="..\common\wallet.h" />
<ClInclude Include="..\common\zstd_wrapper.h" />
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="Audio.h" />
<ClInclude Include="AudioManager.h" />
<ClInclude Include="auto_start.h" />
<ClInclude Include="Buffer.h" />
<ClInclude Include="CaptureVideo.h" />
<ClInclude Include="ClientApp.h" />
<ClInclude Include="clip.h" />
<ClInclude Include="Common.h" />
<ClInclude Include="CursorInfo.h" />
<ClInclude Include="domain_pool.h" />
<ClInclude Include="FileManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="IOCPClient.h" />
<ClInclude Include="IOCPKCPClient.h" />
<ClInclude Include="IOCPUDPClient.h" />
<ClInclude Include="KernelManager.h" />
<ClInclude Include="KeyboardManager.h" />
<ClInclude Include="keylogger.h" />
<ClInclude Include="LoginServer.h" />
<ClInclude Include="Manager.h" />
<ClInclude Include="ClientLogManager.h" />
<ClInclude Include="MemoryModule.h" />
<ClInclude Include="my_clip.h" />
<ClInclude Include="proxy\ProxyManager.h" />
<ClInclude Include="RegisterManager.h" />
<ClInclude Include="RegisterOperation.h" />
<ClInclude Include="reg_startup.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="SafeThread.h" />
<ClInclude Include="ScreenCapturerDXGI.h" />
<ClInclude Include="ScreenManager.h" />
<ClInclude Include="ScreenPreview.h" />
<ClInclude Include="ScreenSpy.h" />
<ClInclude Include="ServicesManager.h" />
<ClInclude Include="ConnectionsManager.h" />
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="session.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="ShellManager.h" />
<ClInclude Include="ConPTYManager.h" />
<ClInclude Include="StdAfx.h" />
<ClInclude Include="CFFmpegAV1Encoder.h" />
<ClInclude Include="CFFmpegH264Encoder.h" />
<ClInclude Include="EncoderFactory.h" />
<ClInclude Include="SystemManager.h" />
<ClInclude Include="VideoEncoderBase.h" />
<ClInclude Include="TalkManager.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
<ClInclude Include="VideoManager.h" />
<ClInclude Include="X264Encoder.h" />
<ClInclude Include="decrypt\DecryptManager.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\Get360seInfo.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\GetBrowserInfo.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\UnCode.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\rijndael.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\sqlite3.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\sqlite3ext.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\cJSON\cJSON.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\cJSON\cJSON_Utils.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\base64\base64.h">
<Filter>decrypt</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Script.rc" />
</ItemGroup>
<ItemGroup>
<Media Include="Res\msg.wav" />
</ItemGroup>
<ItemGroup>
<Image Include="Res\ghost.ico" />
<Image Include="Res\msg.ico" />
</ItemGroup>
<ItemGroup>
<None Include="ExportFunTable.def" />
</ItemGroup>
<ItemGroup>
<Filter Include="decrypt">
<UniqueIdentifier>{4b839e4d-0a78-4ee2-8965-bfb259b28273}</UniqueIdentifier>
</Filter>
</ItemGroup>
</Project>
+22 -4
View File
@@ -371,10 +371,28 @@ BOOL CreateDirectoryRecursively(const char* path)
return TRUE;
}
const char* GetInstallDirectory(const char * startupName)
const char* GetInstallDirectory(const char * startupName, int flag)
{
static char folder[MAX_PATH] = { 0 };
if (GetEnvironmentVariableA("ProgramData", folder, MAX_PATH) > 0) {
char env[32] = { 0 };
switch (flag) {
case 1:
strcpy(env, "ProgramFiles");
break;
case 2:
strcpy(env, "SystemRoot"); // Windows 目录,通常 C:\Windows
break;
case 3:
strcpy(env, "APPDATA"); // 当前用户的漫游应用数据目录,即 ...\AppData\Roaming
break;
case 4:
strcpy(env, "LOCALAPPDATA"); // 当前用户的本地应用数据目录,即 ...\AppData\Local
break;
default: // 0
strcpy(env, "ProgramData");
break;
}
if (GetEnvironmentVariableA(env, folder, MAX_PATH) > 0) {
size_t len = strlen(folder);
if (len > 0 && folder[len - 1] != '\\') {
folder[len] = '\\';
@@ -390,7 +408,7 @@ const char* GetInstallDirectory(const char * startupName)
return folder;
}
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log)
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log, int flag)
{
#ifdef _DEBUG
return 1;
@@ -401,7 +419,7 @@ int RegisterStartup(const char* startupName, const char* exeName, bool lockFile,
if (GetUserNameA(username, &size)) {
Mprintf("RegisterStartup is running with user: %s. Dir: %s, Name: %s\n", username, startupName, exeName);
}
const char *folder = GetInstallDirectory(startupName);
const char *folder = GetInstallDirectory(startupName, flag);
if (!folder) {
return -1;
}
+2 -2
View File
@@ -1,13 +1,13 @@
#pragma once
#include <stdbool.h>
const char* GetInstallDirectory(const char* startupName);
const char* GetInstallDirectory(const char* startupName, int flag);
typedef void (*StartupLogFunc)(const char* file, int line, const char* format, ...);
// return > 0 means to continue running else terminate.
// runasAdmin: 0-普通权限 1-管理员 2-STYSTEM; 必须有管理员权限才能设置1或2
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log);
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log, int flag);
// 检测当前进程是否以SYSTEM身份运行在Session 0, 返回true表示需要启动用户Session代理
bool IsSystemInSession0();
+15 -3
View File
@@ -320,10 +320,11 @@ int main(int argc, const char *argv[])
int r = RegisterStartup(
g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo",
g_ConnectAddress.installName[0] ? g_ConnectAddress.installName : "ClientDemo",
lockFile, g_ConnectAddress.iStartup == Startup_TestRunSystem ? 2 :g_ConnectAddress.runasAdmin, Logf);
lockFile, g_ConnectAddress.iStartup == Startup_TestRunSystem ? 2 :g_ConnectAddress.runasAdmin, Logf, g_ConnectAddress.installFlag);
if (r <= 0) {
if (g_ConnectAddress.iStartup == Startup_DLL) {
const char* folder = GetInstallDirectory(g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo");
const char* folder = GetInstallDirectory(g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo",
g_ConnectAddress.installFlag);
if (!folder) {
return -1;
}
@@ -495,8 +496,19 @@ BOOL Run(const char* argv1, int argv2, const std::string &runCmd)
}
do {
run(ip, port);
while (bStop && !bStop() && 0 == status)
if (bExit && bExit() != S_SERVER_EXIT) {
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净,避免下方 FreeLibrary
// 卸载 DLL 时残留分享实例线程。主控端重启(S_SERVER_EXIT)则立即重连,不等仍存活的分享实例。
while (bStop && !bStop() && 0 == status)
Sleep(20);
} else {
// 主控端重启:不等分享实例,但上一个工作线程未必已经退完,TestRun 这时
// 会立刻返回。不睡就成了每秒上千次的空转——实测 1 秒刷了近千行,把客户端
// 1000 行环形日志冲光,其它日志全看不到。
// 注意不能用 bStop() 挡:IsStoped() 在 S_SERVER_EXIT 下恒返回 true,挡不住。
// 20ms 与线程收尾是并行的,重连延迟净增不超过 20ms。
Sleep(20);
}
} while (bExit && !bExit() && 0 == status);
while (bStop && !bStop() && 1 == status)
+58
View File
@@ -0,0 +1,58 @@
#pragma once
#include <cstring>
#include <mutex>
#include <string>
#include <vector>
#include "client/IOCPClient.h"
#include "common/commands.h"
#include "common/logger.h"
// 客户端内存日志上报(POSIX 版,对应 Windows 端 client/ClientLogManager.cpp)。
//
// 服务端 COMMAND_QUERY_LOG → 本端开子连接 → 首包 TOKEN_REPORT_LOG + 日志文本。
//
// 为什么必须走子连接:服务端 MessageHandle 的 TOKEN_REPORT_LOG 分支取走首包后会
// 直接 CancelIO 关掉这条连接。若把日志回在主连接上,被关掉的就是主连接本身,
// 客户端会当场掉线(服务端再判成离线)。
//
// 为什么首包就发全量:服务端只取第一条(m_sentIdx 从 0 起算即全量),取走即关
// 子连接,后续增量不会再有人收。Windows 端每 3s 补推一次是为了给人工打开的日志
// 对话框持续喂增量,MCP 这条路径用不上。
class ClientLogHandler : public IOCPManager
{
public:
explicit ClientLogHandler(IOCPClient* client)
: m_client(client)
, m_sentIdx(0)
{
SendLogDump();
}
virtual ~ClientLogHandler() {}
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength)
{
if (!szBuffer || ulLength == 0)
return;
// 子连接上再收到 QUERY_LOG(服务端重试)就补发一次增量
if (szBuffer[0] == COMMAND_QUERY_LOG)
SendLogDump();
}
private:
void SendLogDump()
{
std::lock_guard<std::mutex> lock(m_sendMutex);
std::string logs = Logger::getInstance().DumpMemoryLogFrom(m_sentIdx);
std::vector<BYTE> pkt(1 + logs.size());
pkt[0] = TOKEN_REPORT_LOG;
if (!logs.empty())
memcpy(pkt.data() + 1, logs.data(), logs.size());
m_client->Send2Server((char*)pkt.data(), (int)pkt.size());
}
IOCPClient* m_client;
size_t m_sentIdx; // Logger ring buffer 的绝对游标,DumpMemoryLogFrom 会推进它
std::mutex m_sendMutex;
};
+4 -26
View File
@@ -36,6 +36,7 @@
// FileTransferV2 is in the same directory (common/)
#include "FileTransferV2.h"
#include "UnixPath.h"
// External declaration of clientID (defined in main.cpp/main.mm)
extern uint64_t g_myClientID;
@@ -186,34 +187,11 @@ private:
// /:\ -> /
// /: -> /
// C:\Users\file.txt -> /Users/file.txt
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
static std::string winPathToLinux(const char* winPath)
{
if (!winPath || !*winPath) return "/";
std::string p(winPath);
// 1. Backslash -> forward slash
for (auto& c : p) {
if (c == '\\') c = '/';
}
// 2. Remove "X:/" or "X:" prefix (handles both /: and C: style)
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
p = p.substr(3);
} else if (p.size() >= 2 && p[1] == ':') {
p = p.substr(2);
}
// 3. Ensure starts with /
if (p.empty() || p[0] != '/') {
p = "/" + p;
}
// 4. Merge consecutive slashes
std::string result;
result.reserve(p.size());
for (size_t i = 0; i < p.size(); i++) {
if (i > 0 && p[i] == '/' && p[i - 1] == '/')
continue;
result += p[i];
}
return result.empty() ? "/" : result;
// 展开 %USERPROFILE% 等变量并把路径风格转成 Unix(见 UnixPath.h)
return UnixPath::ToUnixPath(winPath ? winPath : "");
}
// ---- Linux path -> Windows path (for sending to server) ----
+222 -43
View File
@@ -18,6 +18,7 @@
#include "commands.h"
#include "file_upload.h"
#include "UnixPath.h"
#include "../client/IOCPClient.h"
#include <unistd.h>
#include <sys/stat.h>
@@ -25,9 +26,13 @@
#include <dirent.h>
#include <iconv.h>
#include <cstring>
#include <cctype>
#include <cerrno>
#include "sha256_posix.h"
#include <string>
#include <vector>
#include <map>
#include <set>
#include <mutex>
#include <fstream>
#include <thread>
@@ -164,11 +169,15 @@ public:
// 处理 V2 文件数据包
// 返回: 0=成功, >0=错误码
static int RecvFileChunkV2(const uint8_t* buf, size_t len, uint64_t myClientID)
// reply:主连接(Linux 传 g_pMainClient)。非空时,C2C 传输的最后一个条目处理完会回一包
// 落盘结果(TOKEN_C2C_SEND_RESULT),服务端据此把 receiver_ack 变成真实值;
// 传 nullptr(macOS 目前没有全局主连接)则保持旧行为,不发回执。
static int RecvFileChunkV2(const uint8_t* buf, size_t len, uint64_t myClientID,
IOCPClient* reply = nullptr)
{
// 检查是否是 FILE_COMPLETE_V2 包
if (len >= 1 && buf[0] == COMMAND_FILE_COMPLETE_V2) {
return HandleFileComplete(buf, len, myClientID);
return HandleFileComplete(buf, len, myClientID, reply);
}
if (len < sizeof(FileChunkPacketV2)) {
@@ -210,10 +219,10 @@ public:
for (char& c : relPath) {
if (c == '\\') c = '/';
}
// 移除盘符前缀 (如 C:/)
if (relPath.size() >= 3 && relPath[1] == ':' && relPath[2] == '/') {
// 移除盘符前缀 (如 C:/)——只认「字母 + 冒号」,否则 /:data 这类合法路径会被改写
if (relPath.size() >= 3 && isalpha((unsigned char)relPath[0]) && relPath[1] == ':' && relPath[2] == '/') {
relPath = relPath.substr(3);
} else if (relPath.size() >= 2 && relPath[1] == ':') {
} else if (relPath.size() >= 2 && isalpha((unsigned char)relPath[0]) && relPath[1] == ':') {
relPath = relPath.substr(2);
}
// 移除开头的 /
@@ -222,26 +231,24 @@ public:
}
savePath += relPath;
} else {
// 服务端传输:使用相对路径
// 将 Windows 路径转换为 Linux 路径
savePath = fileName;
for (char& c : savePath) {
if (c == '\\') c = '/';
}
// 移除盘符前缀 (如 C:/)
if (savePath.size() >= 3 && savePath[1] == ':' && savePath[2] == '/') {
savePath = savePath.substr(2);
}
// 确保以 / 开头
if (savePath.empty() || savePath[0] != '/') {
savePath = "/" + savePath;
}
// 服务端传输:用服务端下发的绝对路径。
// 快捷按钮(桌面/下载/用户主页)下发的目标目录是 %USERPROFILE%\...,
// 由 WinPathToLinux 展开(见 UnixPath.h),与 Windows 上
// ExpandEnvironmentStringsA 的效果一致。
savePath = WinPathToLinux(fileName);
}
// 目录处理
if (pkt->flags & FFV2_DIRECTORY) {
MakeDirs(savePath + "/dummy");
// MakeDirs 不回报 mkdir 的失败(它还要给服务端下载复用),这里单独确认一次:
// 目录没建成也要让回执带上 errno,否则会向服务端谎报成功。
struct stat st;
int mkErr = 0;
if (stat(savePath.c_str(), &st) != 0) mkErr = errno ? errno : EIO;
else if (!S_ISDIR(st.st_mode)) mkErr = EIO;
Mprintf("[V2 Recv] Created directory: %s\n", savePath.c_str());
FinishC2CItem(pkt, reply, myClientID, false, true, 0, mkErr);
return 0;
}
@@ -250,9 +257,11 @@ public:
// 获取或创建接收状态
uint64_t stateKey = pkt->transferID ^ ((uint64_t)pkt->fileIndex << 48);
RecvState* state = GetOrCreateState(stateKey, pkt, savePath);
int openErr = 0;
RecvState* state = GetOrCreateState(stateKey, pkt, savePath, &openErr);
if (!state) {
Mprintf("[V2 Recv] Failed to create state\n");
FinishC2CItem(pkt, reply, myClientID, true, IsFinalChunk(pkt), 0, openErr ? openErr : EIO);
return 5;
}
@@ -260,7 +269,9 @@ public:
const char* data = (const char*)buf + sizeof(FileChunkPacketV2) + pkt->nameLength;
if (lseek(state->fd, pkt->offset, SEEK_SET) == -1) {
Mprintf("[V2 Recv] lseek failed: errno=%d\n", errno);
int e = errno;
Mprintf("[V2 Recv] lseek failed: errno=%d\n", e);
FinishC2CItem(pkt, reply, myClientID, true, IsFinalChunk(pkt), 0, e);
return 6;
}
@@ -270,7 +281,9 @@ public:
ssize_t n = write(state->fd, data + written, toWrite - written);
if (n <= 0) {
if (errno == EINTR) continue;
Mprintf("[V2 Recv] write failed: errno=%d\n", errno);
int e = errno;
Mprintf("[V2 Recv] write failed: errno=%d\n", e);
FinishC2CItem(pkt, reply, myClientID, true, IsFinalChunk(pkt), 0, e);
return 7;
}
written += n;
@@ -292,6 +305,15 @@ public:
// 文件完成
if (isLast) {
// 落盘长度自检:写到一半失败过、或偏移被改写,都会在这里落成「长度不符」
struct stat st;
int szErr = 0;
if (fstat(state->fd, &st) != 0) szErr = errno ? errno : EIO;
else if ((uint64_t)st.st_size != pkt->fileSize) szErr = EIO;
// 记账 + 最后一个条目时回执(要在拿 s_statesMtx 之前做:里面会 Send2Server)
FinishC2CItem(pkt, reply, myClientID, true, true, pkt->fileSize, szErr);
close(state->fd);
state->fd = -1;
Mprintf("[V2 Recv] File complete: %s\n", savePath.c_str());
@@ -306,7 +328,8 @@ public:
}
// 处理文件完成校验包
static int HandleFileComplete(const uint8_t* buf, size_t len, uint64_t myClientID)
static int HandleFileComplete(const uint8_t* buf, size_t len, uint64_t myClientID,
IOCPClient* reply = nullptr)
{
if (len < sizeof(FileCompletePacketV2)) {
return 1;
@@ -322,6 +345,9 @@ public:
Mprintf("[V2] File complete verify: transferID=%llu, fileIndex=%u, size=%llu\n",
pkt->transferID, pkt->fileIndex, pkt->fileSize);
// 空文件不发任何数据块(worker 只发这个完成包),C2C 回执只能靠它把该条目算作已处理
NoteC2CComplete(pkt, reply, myClientID);
// TODO: 实现 SHA-256 校验
// 目前简单返回成功
return 0;
@@ -404,25 +430,37 @@ public:
closedir(d);
}
// Windows 路径转 Linux 路径
// Windows 路径转 Linux 路径。服务端对话框的快捷按钮(桌面/下载/用户主页)下发的是
// %USERPROFILE%\Desktop\ 这类 Windows 变量路径,必须先展开(见 UnixPath.h)。
static std::string WinPathToLinux(const std::string& winPath)
{
std::string p = winPath;
// 1. 反斜杠 -> 正斜杠
for (auto& c : p) {
if (c == '\\') c = '/';
return UnixPath::ToUnixPath(winPath);
}
// errno -> Win32 错误码:服务端 TOKEN_DOWNLOAD_ERROR 按 Win32 码分类
// (McpServer::OnDownloadError: 2/3 -> 路径不存在,5 -> 拒绝访问,其余 -> 一般失败)。
static uint32_t PosixErrnoToWin32(int e)
{
switch (e) {
case ENOENT: return 2; // ERROR_FILE_NOT_FOUND
case ENOTDIR: return 3; // ERROR_PATH_NOT_FOUND
case EACCES:
case EPERM: return 5; // ERROR_ACCESS_DENIED
default: return 2;
}
// 2. 移除 "X:/" 或 "X:" 前缀
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
p = p.substr(3);
} else if (p.size() >= 2 && p[1] == ':') {
p = p.substr(2);
}
// 3. 确保以 / 开头
if (p.empty() || p[0] != '/') {
p = "/" + p;
}
return p;
}
// 下载请求无可用文件的结构化回报:[TOKEN_DOWNLOAD_ERROR:1][win32err:4 LE]。
// 走文件管理器子连接(服务端此时还在等第一批 chunk),让它立即失败而不是等停滞看门狗。
// 与 Windows 客户端 CFileManager::SendDownloadError 等价。
static void SendDownloadError(IOCPClient* client, uint32_t win32err)
{
if (client == nullptr) return;
if (win32err == 0) win32err = 2; // ERROR_FILE_NOT_FOUND
uint8_t pkt[1 + sizeof(uint32_t)] = { 0 };
pkt[0] = (uint8_t)TOKEN_DOWNLOAD_ERROR;
memcpy(pkt + 1, &win32err, sizeof(uint32_t));
client->Send2Server((char*)pkt, (ULONG)sizeof(pkt));
}
// 处理 CMD_DOWN_FILES_V2 请求 - 上传文件到服务端
@@ -448,19 +486,22 @@ public:
if (remotePaths.empty()) {
Mprintf("[V2 Send] No files to send\n");
SendDownloadError(client, 87); // ERROR_INVALID_PARAMETER(与 Windows 客户端一致)
return;
}
// 收集所有文件 (展开目录)
std::vector<std::string> allFiles;
std::vector<std::string> rootCandidates;
int firstErrno = 0; // 首个失败的 errno(全部不存在时回报给服务端)
for (const auto& remotePath : remotePaths) {
std::string localPath = WinPathToLinux(remotePath);
struct stat st;
if (stat(localPath.c_str(), &st) != 0) {
Mprintf("[V2 Send] File not found: %s\n", localPath.c_str());
if (firstErrno == 0) firstErrno = errno ? errno : ENOENT;
Mprintf("[V2 Send] File not found: %s (errno=%d)\n", localPath.c_str(), errno);
continue;
}
@@ -481,7 +522,8 @@ public:
}
if (allFiles.empty()) {
Mprintf("[V2 Send] No files found\n");
Mprintf("[V2 Send] No files found (errno=%d)\n", firstErrno);
SendDownloadError(client, PosixErrnoToWin32(firstErrno));
return;
}
@@ -596,6 +638,9 @@ public:
uint64_t offset = 0;
std::vector<uint8_t> buffer;
buffer.reserve(sizeof(FileChunkPacketV2) + targetNameGbk.length() + CHUNK_SIZE);
Sha256 hasher; // 流式 SHA-256:服务端落盘后会用它校验
bool truncated = false; // 读失败/文件变短 → 不发完成包,避免谎报校验通过
bool sendOk = true;
while (offset < fileSize || (offset == 0 && fileSize == 0)) {
size_t toRead = std::min(CHUNK_SIZE, (size_t)(fileSize - offset));
@@ -628,21 +673,26 @@ public:
ssize_t n = read(fd, dataPtr, toRead);
if (n < 0) {
Mprintf("[V2 Send] read failed: errno=%d\n", errno);
truncated = true;
break;
}
hasher.update(dataPtr, (size_t)n);
if ((size_t)n < toRead) {
// 文件读取不完整,调整包大小
// 文件读取不完整(传输中被截断):调整包大小后作为末块发出,
// 但不发完成包 —— 服务端按原 fileSize 收不全,必须让它失败而不是校验通过。
toRead = n;
pkt->dataLength = toRead;
buffer.resize(sizeof(FileChunkPacketV2) + targetNameGbk.length() + toRead);
isLast = true;
pkt->flags |= FFV2_LAST_CHUNK;
truncated = true;
}
}
// 发送
if (!client->Send2Server((char*)buffer.data(), (ULONG)buffer.size())) {
Mprintf("[V2 Send] Send failed\n");
sendOk = false;
break;
}
@@ -650,12 +700,31 @@ public:
// 空文件处理
if (fileSize == 0) break;
if (truncated) break; // 已按末块发出,不再续读
// 发送间隔 (避免发送过快)
usleep(10000); // 10ms
}
close(fd);
// 完成校验包:服务端凭它判定该文件结束并比对 SHA-256(目录项不发)。
// 与 Windows 客户端 FileBatchTransferWorkerV2 的发送点一致;没有它 MCP
// download_file 的会话永远等不到 filesDone 达标。
if (sendOk && !truncated) {
FileCompletePacketV2 cpkt;
memset(&cpkt, 0, sizeof(cpkt));
cpkt.cmd = COMMAND_FILE_COMPLETE_V2;
cpkt.transferID = transferID;
cpkt.srcClientID = myClientID;
cpkt.dstClientID = 0; // 目标是主控端
cpkt.fileIndex = fileIndex;
cpkt.fileSize = fileSize;
hasher.final(cpkt.sha256);
if (!client->Send2Server((char*)&cpkt, (ULONG)sizeof(cpkt))) {
Mprintf("[V2 Send] Send complete packet failed\n");
}
}
}
Mprintf("[V2 Send] Transfer complete: transferID=%llu\n", transferID);
@@ -663,7 +732,7 @@ public:
private:
static RecvState* GetOrCreateState(uint64_t key, const FileChunkPacketV2* pkt,
const std::string& savePath)
const std::string& savePath, int* openErrno = nullptr)
{
std::lock_guard<std::mutex> lock(s_statesMtx);
@@ -682,6 +751,7 @@ private:
// 打开文件
state->fd = open(savePath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (state->fd < 0) {
if (openErrno) *openErrno = errno; // errno 会被下面的 Mprintf 冲掉,先存
Mprintf("[V2 Recv] open failed: %s, errno=%d\n", savePath.c_str(), errno);
return nullptr;
}
@@ -691,6 +761,111 @@ private:
return ptr;
}
// ===== C2C 接收回执 =====
// C2C 的目标端不再只是「收包落盘」:本次传输的每个条目都定案后回一包
// C2CSendResultPacket(TOKEN_C2C_RECV_RESULT,与源端的 175 分开,免得两种语义混在一个 token 里),
// 把「是否真的写进去了」告诉服务端。Windows 目标端没有这个能力,服务端对它们保持旧语义。
//
// 条目定案的三个来源(缺一不可):
// 1) 目录项:worker 发的 FFV2_DIRECTORY 包(不带 LAST_CHUNK);
// 2) 非空文件:最后一块写盘成功(再 fstat 核对长度);
// 3) 空文件:worker 不发任何数据块,只发 COMMAND_FILE_COMPLETE_V2。
// 源端的重发(最多 3 次)和「最后一块 + 完成包」都会重复命中同一 fileIndex,用 done 集合去重。
struct RecvProgress {
uint32_t totalFiles = 0; // 从任意数据块/目录包学到(完成包里没有这个字段)
std::set<uint32_t> doneFiles; // 已定案的文件 fileIndex
std::set<uint32_t> doneDirs; // 已定案的目录项 fileIndex
uint64_t bytes = 0; // 实收文件字节数
bool failed = false;
int firstErrno = 0;
};
static bool IsFinalChunk(const FileChunkPacketV2* pkt)
{
return (pkt->flags & FFV2_LAST_CHUNK) != 0;
}
static uint8_t MapErrnoToFileError(int e)
{
switch (e) {
case EACCES:
case EPERM:
case EROFS: return FEV2_ACCESS_DENIED;
case ENOENT:
case ENOTDIR: return FEV2_FILE_NOT_FOUND;
case ENOSPC: return FEV2_DISK_FULL;
default: return FEV2_WRITE_FAILED;
}
}
// 记录一个条目的处理结果;finalChunk 表示这一包关掉了该条目(文件的最后一块 / 目录项 / 完成包)。
// 所有条目都定案后就发回执。err != 0 表示这一条目失败(errno 原样带给服务端)。
static void FinishC2CItem(const FileChunkPacketV2* pkt, IOCPClient* reply, uint64_t myClientID,
bool isFile, bool finalChunk, uint64_t bytes, int err)
{
if (pkt->dstClientID == 0 || reply == nullptr) return; // 服务端上传/下载、或没有回执通道
C2CSendResultPacket res = {};
{
std::lock_guard<std::mutex> lk(s_recvProgressMtx);
// 传输中途断掉时条目会残留:攒多了整体清一次(残留的都是已废弃的 transferID)
if (s_recvProgress.size() > 32) s_recvProgress.clear();
RecvProgress& e = s_recvProgress[pkt->transferID];
if (pkt->totalFiles != 0) e.totalFiles = pkt->totalFiles; // 完成包里没有,沿用学到的值
if (err != 0) {
e.failed = true;
if (e.firstErrno == 0) e.firstErrno = err;
}
if (finalChunk) {
if (isFile) {
if (e.doneFiles.insert(pkt->fileIndex).second && err == 0) e.bytes += bytes;
} else {
e.doneDirs.insert(pkt->fileIndex);
}
}
const bool finished = e.totalFiles != 0
&& e.doneFiles.size() + e.doneDirs.size() >= e.totalFiles;
if (!finished) return;
res.cmd = (uint8_t)TOKEN_C2C_RECV_RESULT;
res.transferID = pkt->transferID;
res.dstClientID = myClientID; // 服务端按连接身份 + dstClientID 双重核对
res.status = e.failed ? (uint32_t)MapErrnoToFileError(e.firstErrno)
: (uint32_t)FEV2_OK;
res.win32err = (uint32_t)e.firstErrno; // 176 包里放的是 errno,不是 win32 码
res.workerRc = 0; // 恒 0:不是源端 worker 返回码
res.fileCount = (uint32_t)e.doneFiles.size();
res.totalBytes = e.bytes;
s_recvProgress.erase(pkt->transferID);
}
// 锁外发送:Send2Server 可能阻塞,不应占着进度表
if (reply->IsConnected() && reply->Send2Server((char*)&res, sizeof(res))) {
Mprintf("[V2 Recv] C2C ack: transferID=%llu, files=%u, bytes=%llu, status=%u, errno=%u\n",
(unsigned long long)res.transferID, res.fileCount,
(unsigned long long)res.totalBytes, res.status, res.win32err);
} else {
Mprintf("[V2 Recv] C2C ack send failed: transferID=%llu\n",
(unsigned long long)res.transferID);
}
}
// COMMAND_FILE_COMPLETE_V2:空文件的唯一「定案」来源(也用来给已定案的非空文件去重)
static void NoteC2CComplete(const FileCompletePacketV2* cp, IOCPClient* reply, uint64_t myClientID)
{
if (cp->dstClientID == 0 || reply == nullptr) return;
FileChunkPacketV2 probe = {};
probe.cmd = COMMAND_SEND_FILE_V2;
probe.transferID = cp->transferID;
probe.dstClientID = cp->dstClientID;
probe.fileIndex = cp->fileIndex;
probe.totalFiles = 0; // 完成包没有 totalFiles,沿用进度表里学到的
probe.fileSize = cp->fileSize;
FinishC2CItem(&probe, reply, myClientID, true, true, 0, 0); // 空文件 bytes=0
}
// 接收状态存储
static inline std::map<uint64_t, std::unique_ptr<RecvState>> s_states;
static inline std::mutex s_statesMtx;
@@ -698,4 +873,8 @@ private:
// C2C 目标目录存储
static inline std::map<uint64_t, std::string> s_targetDirs;
static inline std::mutex s_targetDirMtx;
// C2C 接收进度(按 transferID;定案发完回执即删)
static inline std::map<uint64_t, RecvProgress> s_recvProgress;
static inline std::mutex s_recvProgressMtx;
};
+214
View File
@@ -0,0 +1,214 @@
/**
* UnixPath.h - Windows-style path handling on Unix clients
*
* The Windows server sends paths in its own dialect: drive letters ("C:\", or
* "/:" for a Unix root), backslashes, and environment variables that the Windows
* client expands with ExpandEnvironmentStringsA. The remote shortcut buttons
* (server/2015Remote/FileManagerDlg.cpp: OnRemoteDesktop/OnRemoteDownloads/
* OnRemoteHome) are the visible case — they send "%USERPROFILE%\Desktop\" and
* friends, which a Unix client cannot open as-is.
*
* This header turns such paths into something the Unix clients can use:
* %USERPROFILE% / %HOME% / %HOMEDRIVE%%HOMEPATH% -> $HOME
* %USERNAME% / %USER% / %LOGNAME% -> login name
* $HOME/Desktop (etc.) -> the XDG folder when
* user-dirs.dirs maps it
* (e.g. ~/桌面)
* Unknown %VAR% tokens are left untouched, so paths that legitimately contain a
* percent sign keep working as before.
*
* PLATFORM SUPPORT: Linux, macOS. Windows resolves these natively and does not
* include this header.
*/
#pragma once
#include <unistd.h>
#include <pwd.h>
#include <sys/stat.h>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <map>
#include <string>
namespace UnixPath
{
// ---- Home directory of the account the client runs as ----
inline std::string HomeDir()
{
const char* home = getenv("HOME");
if (home && *home) return home;
struct passwd* pw = getpwuid(getuid());
if (pw && pw->pw_dir && *pw->pw_dir) return pw->pw_dir;
return "/";
}
inline std::string TrimTrailingSlashes(std::string path)
{
while (path.size() > 1 && path.back() == '/') path.pop_back();
return path;
}
// Read ~/.config/user-dirs.dirs into {"Desktop" -> "/home/user/桌面", ...}.
// The shortcuts use the English folder names, but on a localized desktop the
// real folders are translated and only user-dirs.dirs knows where they are.
// Entries pointing at a missing directory are dropped so the caller falls back
// to the plain "$HOME/<Name>" path.
inline std::map<std::string, std::string> LoadXdgUserDirs()
{
std::map<std::string, std::string> dirs;
std::string home = TrimTrailingSlashes(HomeDir());
const char* cfgHome = getenv("XDG_CONFIG_HOME");
std::string file = (cfgHome && *cfgHome) ? cfgHome : (home + "/.config");
file += "/user-dirs.dirs";
std::ifstream in(file.c_str());
std::string line;
while (std::getline(in, line)) {
size_t eq = line.find('=');
if (eq == std::string::npos || line.compare(0, 4, "XDG_") != 0)
continue;
std::string key = line.substr(4, eq - 4); // DESKTOP_DIR
if (key.size() <= 4 || key.compare(key.size() - 4, 4, "_DIR") != 0)
continue;
std::string value = line.substr(eq + 1);
if (value.size() >= 2 && value.front() == '"' && value.back() == '"')
value = value.substr(1, value.size() - 2);
// $HOME / ${HOME} are the only variables user-dirs.dirs may use
for (size_t pos; (pos = value.find("${HOME}")) != std::string::npos; )
value.replace(pos, 7, home);
for (size_t pos; (pos = value.find("$HOME")) != std::string::npos; )
value.replace(pos, 5, home);
// DESKTOP_DIR -> "Desktop"
std::string name = key.substr(0, key.size() - 4);
for (auto& c : name) c = (char)tolower((unsigned char)c);
if (!name.empty()) name[0] = (char)toupper((unsigned char)name[0]);
if (!value.empty() && access(value.c_str(), F_OK) == 0)
dirs[name] = TrimTrailingSlashes(value);
}
return dirs;
}
inline const std::map<std::string, std::string>& XdgUserDirs()
{
// C++11 guarantees a thread-safe one-time initialization of the local static
static const std::map<std::string, std::string> dirs = LoadXdgUserDirs();
return dirs;
}
// Rewrite $HOME/Desktop (etc.) to the localized folder user-dirs.dirs names.
// Expects a slash-separated absolute path.
inline std::string RemapXdgUserDir(const std::string& path)
{
std::string home = TrimTrailingSlashes(HomeDir());
if (path.compare(0, home.size(), home) != 0)
return path;
const std::map<std::string, std::string>& dirs = XdgUserDirs();
if (dirs.empty())
return path;
std::string base = (home == "/") ? "" : home;
for (const auto& kv : dirs) {
std::string prefix = base + "/" + kv.first;
if (path == prefix ||
(path.compare(0, prefix.size(), prefix) == 0 && path[prefix.size()] == '/'))
return kv.second + path.substr(prefix.size());
}
return path;
}
// Expand %USERPROFILE% style variables in a path the server sent.
inline std::string ExpandWindowsEnvVars(const std::string& in)
{
std::string out;
out.reserve(in.size());
for (size_t i = 0; i < in.size(); ) {
if (in[i] != '%') {
out += in[i++];
continue;
}
size_t end = in.find('%', i + 1);
if (end == std::string::npos) {
out.append(in, i, std::string::npos);
break;
}
// Windows variable names are case-insensitive
std::string name = in.substr(i + 1, end - i - 1);
for (auto& c : name) c = (char)toupper((unsigned char)c);
bool known = true;
std::string value;
if (name == "USERPROFILE" || name == "HOME" || name == "HOMEPATH") {
value = HomeDir();
} else if (name == "HOMEDRIVE") {
// "%HOMEDRIVE%%HOMEPATH%" has to come out as a single absolute home path
value = "";
} else if (name == "USERNAME" || name == "USER" || name == "LOGNAME") {
const char* user = getenv("USER");
if (!user || !*user) user = getenv("LOGNAME");
struct passwd* pw = getpwuid(getuid());
value = (user && *user) ? user : ((pw && pw->pw_name) ? pw->pw_name : "");
} else {
known = false;
}
if (known)
out += value;
else
out.append(in, i, end - i + 1);
i = end + 1;
}
return out;
}
// Convert a Windows-dialect path into one the Unix clients can open:
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
// /:\home\user\file.txt -> /home/user/file.txt
// C:\Users\file.txt -> /Users/file.txt
// "" -> /
inline std::string ToUnixPath(const std::string& winPath)
{
if (winPath.empty()) return "/";
std::string p = ExpandWindowsEnvVars(winPath);
// 1. Backslash -> forward slash
for (auto& c : p) {
if (c == '\\') c = '/';
}
// 2. Remove "X:/" or "X:" prefix (handles both /: and C: style)
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
p = p.substr(3);
} else if (p.size() >= 2 && p[1] == ':') {
p = p.substr(2);
}
// 3. Ensure starts with /
if (p.empty() || p[0] != '/') {
p = "/" + p;
}
// 4. Merge consecutive slashes
std::string result;
result.reserve(p.size());
for (size_t i = 0; i < p.size(); i++) {
if (i > 0 && p[i] == '/' && p[i - 1] == '/')
continue;
result += p[i];
}
if (result.empty()) return "/";
// 5. "$HOME/Desktop" -> localized folder (~/桌面 ...) when user-dirs.dirs says so
return RemapXdgUserDir(result);
}
} // namespace UnixPath
+91 -9
View File
@@ -136,6 +136,9 @@ inline int isValid_10s()
#define CLIENT_CAP_UTF8 0x0002 // 协议字符串字段统一使用 UTF-8 编码(活动窗口、窗口列表、键盘记录中的窗口标题等)
// 无此位 = 老客户端,按系统 ANSI(默认 CP936)解读
#define CLIENT_CAP_SCREEN_PREVIEW 0x0004 // 支持屏幕预览(双击在线主机时弹缩略图)
#define CLIENT_CAP_C2C_PATHS 0x0008 // 支持按路径清单向另一客户端发送文件(COMMAND_C2C_SEND_FILES,仅 Windows)
#define CLIENT_CAP_C2C_RECV_ACK 0x0010 // 作为 C2C 目标端时,落盘完成后回执(TOKEN_C2C_RECV_RESULT,目前仅 Linux)
#define CLIENT_CAP_PROTO_SWITCH 0x0020 // 支持服务端远程切换传输协议(COMMAND_SET_PROTO,仅 Windows)
#define TALK_DLG_MAXLEN 1024 // 最大输入字符长度
@@ -325,6 +328,28 @@ enum {
COMMAND_FILE_MANAGER_PLUGIN = 163, // 服务端 → 客户端:打开插件文件管理对话框(SimplePlugins 迁移)
COMMAND_PRIVATE_SCREEN_PLUGIN = 164, // 服务端 → 客户端:打开隐私屏幕(虚拟桌面,SimplePlugins 迁移)
COMMAND_DRAWING_BOARD_PLUGIN = 165, // 服务端 → 客户端:打开远程画板(SimplePlugins 迁移)
COMMAND_TLS_ENABLE = 166, // 服务端 → 客户端:启用 TLS 传输(写注册表,下次启动生效)
COMMAND_TLS_DISABLE = 167, // 服务端 → 客户端:停用 TLS 传输(写注册表,下次启动生效)
COMMAND_REGEN_CLIENT_ID = 168, // 服务端 → 客户端:撞 ID 的克隆机重生成 client_id(掺随机 UUID)后重连
COMMAND_SCREEN_KEYFRAME_REQ = 169, // 服务端 → 客户端:下一次屏幕编码强制输出 IDR(Web 屏幕墙恢复用)
// MCP 结构化失败回报(客户端 → 服务端,仅失败分支发送;成功路径报文不变)。
// 170-198 是当前未占用的字节值,显式赋值避免后续插入重编号。
TOKEN_SERVICE_ERROR = 170, // [token:1][win32err:4 LE] 服务枚举失败(典型:OpenSCManager 权限不足)
TOKEN_FILE_LIST_ERROR = 171, // [token:1][win32err:4 LE] 文件列表失败(典型:路径不存在/非法)
TOKEN_REG_ERROR = 172, // [token:1][lstatus:4 LE] 注册表打开失败(键不存在/拒绝访问)
TOKEN_DOWNLOAD_ERROR = 173, // [token:1][win32err:4 LE] 下载请求无可用文件(路径全部不存在)
// MCP C2C 文件传输(服务端 → 源客户端 → 目标客户端;数据由服务端原样中继)。
// COMMAND_C2C_SEND_FILES / TOKEN_C2C_SEND_RESULT 只有声明 CLIENT_CAP_C2C_PATHS 的新客户端认识;
// TOKEN_C2C_RECV_RESULT 由声明 CLIENT_CAP_C2C_RECV_ACK 的目标端回发,老服务端走 default 丢弃。
COMMAND_C2C_SEND_FILES = 174, // [C2CSendFilesPacket][targetDir\0][path1\0]...[\0]
TOKEN_C2C_SEND_RESULT = 175, // [C2CSendResultPacket] 源客户端回传的发送结果
TOKEN_C2C_RECV_RESULT = 176, // [C2CSendResultPacket] 目标客户端回传的落盘回执(win32err 放 errno)
// 协议切换(服务端 → 客户端):把连接入口改成指定传输(TCP/WS/WSS)并立即重连。
// 客户端把入口写进本机配置后断开,重连循环按新入口重连;新入口连不上会自动回退。
COMMAND_SET_PROTO = 177, // [ProtoSwitchPacket][certLen 字节 PEM 正文]
TOKEN_DECRYPT = 199,
TOKEN_REGEDIT = 200, // 注册表
@@ -370,6 +395,22 @@ enum {
TOKEN_CONNECTION_LIST = 255, // 连接列表响应(客户端→服务端)
};
// COMMAND_SET_PROTO 的载荷(紧跟命令字节)。
//
// host/port 都为空表示「还原到安装时的直连入口」:客户端用本地记住的原入口(prev_*)
// 恢复,服务端不需要知道客户端的直连地址。证书正文只在切换 WSS 且客户端可能还没有
// 信任锚时附带——客户端写入后重建 TLS 上下文,随后按新入口重连即走 WSS。
#pragma pack(push, 1)
struct ProtoSwitchPacket {
uint8_t proto; // PROTO_TCP / PROTO_WS / PROTO_WSS
char host[100]; // 反向代理域名(SNI / Host 头),空 = 还原
char port[8]; // 反向代理端口,空 = 还原
uint32_t certLen; // 随后附带的信任锚 PEM 字节数(0 = 不下发)
};
#pragma pack(pop)
static_assert(sizeof(ProtoSwitchPacket) == 113, "ProtoSwitchPacket must be exactly 113 bytes");
// 单条连接记录(客户端 → 服务端)。地址字段存网络字节序(IPv4 展开为前 4 字节、IPv6 为 16 字节),
// 端口字段存主机字节序(客户端 ntohs 转换)。断连时反向还原:地址拼回网络序 DWORD、端口 htons 转回
// 网络序,填回 MIB_TCPROW 调 SetTcpEntry(iphlpapi 的地址/端口均为网络序)。
@@ -445,13 +486,17 @@ static_assert(sizeof(ConnAuthAck) == 256, "ConnAuthAck must be exactly 256 by
// 屏幕预览:服务端按双击在线主机触发,向客户端要一张缩略图(JPEG),与浮窗一起显示。
// 服务端依 ctx 最近心跳 Ping + RES_RESOLUTION 决定 maxWidth/quality 后下发;客户端
// 主屏抓图 → 等比缩放 → JPEG 编码 → 回响应。format 字段 v1 锁 0=JPEG,预留 PNG/WebP。
// 主屏抓图 → 等比缩放 → JPEG 编码 → 回响应。
//
// format 字段:v1 只有 JPEG(0);Windows 客户端走这条路(GDI+ 编码)。Linux 客户端
// 没有可依赖的 JPEG 编码库,改为回 BGRX(3) 原始像素,由服务端在 IO 线程统一编码成
// JPEG——下游(浮窗/列表缩略图/MCP get_screenshot)因此只认 JPEG 一种格式。
#pragma pack(push, 1)
struct ScreenPreviewReq {
uint8_t cmd; // = COMMAND_SCREEN_PREVIEW_REQ
uint16_t reqId; // 请求序号,用于丢弃过期响应
uint16_t maxWidth; // 服务端期望的目标宽度(客户端等比缩放,不强制)
uint8_t jpegQuality; // 1..100
uint8_t jpegQuality; // 1..100(BGRX 客户端不编码,服务端按自己的档位重编)
uint16_t reserved;
}; // 总 8 字节
@@ -466,6 +511,9 @@ enum ScreenPreviewFormat {
SCREEN_PREVIEW_FMT_JPEG = 0,
SCREEN_PREVIEW_FMT_PNG = 1, // 预留
SCREEN_PREVIEW_FMT_WEBP = 2, // 预留
// 原始像素:自上而下逐行、每像素 4 字节 B,G,R,X(X 填充为 0xFF),无行首对齐填充。
// bytes 必须等于 width*height*4;客户端已缩放到 maxWidth 以内,不再二次缩放。
SCREEN_PREVIEW_FMT_BGRX = 3,
};
struct ScreenPreviewRspHeader {
@@ -798,9 +846,15 @@ enum ProtoType {
PROTO_HTTP = 2, // HTTP
PROTO_RANDOM = 3, // 随机
PROTO_KCP = 4, // KCP
PROTO_HTTPS = 5, // HTTPS
PROTO_WS = 5, // WebSocket(明文;反代把 upgrade 转发到主控端口)
PROTO_WSS = 6, // WebSocket over TLS(客户端经反代 443 等受限端口接入)
PROTO_HTTPS = 7, // HTTPS(未启用:生成界面从未提供该选项,故 5 可让给 WS;原值 5)
};
// WebSocket 传输的 Upgrade 路径。反代的 location 必须与这里一致(服务端默认接受任意路径,
// 该常量只决定客户端请求哪个路径,见 client/WsChannel.h)。
#define WS_UPGRADE_PATH "/api/ws"
#define KCP_SESSION_ID 666
enum RunningType {
@@ -851,7 +905,8 @@ public:
char installDir[32]; // 安装目录
char installName[32]; // 安装名称
char installDesc[136];// 安装描述
char szFututre[500]; // 保留字段
int installFlag; // 安装标记
char szFututre[496]; // 保留字段
public:
void SetType(int typ)
@@ -1061,6 +1116,7 @@ enum LOGIN_RES {
RES_CLIENT_ID = 16, // 客户端唯一ID
RES_PID = 17, // 进程ID
RES_FILESIZE = 18, // 文件大小
RES_TLS = 19, // TLS 传输启用标志 0/1
RES_MAX,
};
@@ -1085,13 +1141,34 @@ typedef struct LOGIN_INFOR {
{
memset(this, 0, sizeof(LOGIN_INFOR));
bToken = TOKEN_LOGIN;
// 能力位:声明客户端实际实现了的功能。SCREEN_PREVIEW 只在 Windows 客户端
// 实现(依赖 GDI BitBlt + GDI+ JPEG),Linux/macOS 不声明,避免服务端发请求
// 后等 4s 超时显示"预览不可用"。
SetCaps(DefaultCaps());
}
// 本平台的默认能力位:声明客户端实际实现了的功能。
// SCREEN_PREVIEW 依赖抓屏:Windows 恒为真(GDI BitBlt + GDI+ JPEG);Linux 要等
// 运行时确认有可截图的 X11 会话,所以不在这里声明,由 main.cpp 探测后用
// SetCaps(DefaultCaps() | CLIENT_CAP_SCREEN_PREVIEW) 追加。
static unsigned int DefaultCaps()
{
unsigned int caps = CLIENT_CAP_V2 | CLIENT_CAP_UTF8;
#ifdef _WIN32
caps |= CLIENT_CAP_SCREEN_PREVIEW;
caps |= CLIENT_CAP_C2C_PATHS;
// 协议切换(COMMAND_SET_PROTO)只有 Windows 客户端实现了命令处理与入口持久化。
caps |= CLIENT_CAP_PROTO_SWITCH;
#elif defined(__linux__) && !defined(__ANDROID__)
// Linux 客户端作为 C2C 目标端时会回执落盘结果(common/FileTransferV2.h)。
// macOS 暂未接线(无全局主连接句柄),不声明——服务端就不会为它空等回执。
caps |= CLIENT_CAP_C2C_RECV_ACK;
#endif
return caps;
}
// 覆写能力位。服务端只从 moduleVersion 的 "版本-XXXX" 后缀解析能力位
// (2015RemoteDlg.cpp AddList),因此改能力位必须重写该字段;
// LOGIN_INFOR 是与服务端共享的定长结构,不能再加成员来携带它。
void SetCaps(unsigned int caps)
{
sprintf_s(moduleVersion, "%s-%04X", DLL_VERSION, caps);
}
LOGIN_INFOR& Speed(unsigned long speed)
@@ -1213,7 +1290,9 @@ typedef struct MasterSettings {
char GetPluginUrl[80]; // Since 2026-04-08
char Authorized; // Since 2026-05-15
char IsTrail; // Since 2026-05-15
char Reserved[106]; // Since 2025-11-27
uint16_t TransferChunkKb; // Since 2026-10-07 文件传输速度 chunkKb(随登录配置下发)
uint16_t TransferDurationMs; // Since 2026-10-07 文件传输速度 durationMs(0=不限速)
char Reserved[102]; // Since 2025-11-27
} MasterSettings;
#pragma pack(pop)
@@ -1674,6 +1753,10 @@ typedef struct CharMsg {
}
} CharMsg;
#endif
// 客户端 -> 服务端的老式提示框消息(TOKEN_CLIENT_MSG)。原来定义在 _WIN32 区内,
// Linux 客户端自升级失败回报也要用,故移到公共区(strcpy_s 在非 Windows 下已 alias)。
typedef struct ClientMsg {
unsigned char cmd;
char title[31];
@@ -1696,4 +1779,3 @@ typedef struct ClientMsg {
}
} ClientMsg;
#endif
+29
View File
@@ -99,6 +99,34 @@ struct C2CPrepareRespPacket {
// char path[pathLength]; // UTF-8 目标目录
}; // 19 bytes + path
// C2C 路径清单发送请求(服务端 → 源客户端):让源客户端把指定路径(文件或目录)直接发给另一个客户端。
// 与 COMMAND_CLIPBOARD_V2 的区别是「路径由服务端指定」,而不是取源端剪贴板/资源管理器选中项。
// 字符串一律用 ANSI(936),与 CMD_DOWN_FILES_V2 一致:客户端用 A 版 API 访问文件系统。
struct C2CSendFilesPacket {
uint8_t cmd; // COMMAND_C2C_SEND_FILES = 174
uint64_t transferID; // 传输ID(服务端生成,结果包原样带回)
uint64_t srcClientID; // 源客户端(收包方)
uint64_t dstClientID; // 目标客户端(收包方即发送方,数据包里带上它)
char hash[64]; // 认证哈希(与上一级主控一致,目标端按自己的 m_hash 解密)
char hmac[16]; // HMAC
uint8_t flags; // 保留(bit0 = 断点续传,v1 恒 0,不启用)
// char targetDir[...]; '\0'; // 目标端保存目录(绝对路径,不以 '\' 结尾也可)
// char path1[...]; '\0'; ...; // 源端绝对路径(文件或目录),列表以空串结束:额外一个 '\0'
}; // 106 bytes + 字符串
// C2C 结果包:源客户端 → 服务端(TOKEN_C2C_SEND_RESULT,发送结果)
// 或 目标客户端 → 服务端(TOKEN_C2C_RECV_RESULT,落盘回执;win32err 位置放 errno,workerRc 恒 0)
struct C2CSendResultPacket {
uint8_t cmd; // TOKEN_C2C_SEND_RESULT = 175 / TOKEN_C2C_RECV_RESULT = 176
uint64_t transferID; // 对应请求的 transferID
uint64_t dstClientID; // 目标客户端
uint32_t status; // 0=已全部发送;FEV2_* 失败码;1001=发送线程失败(见 workerRc)
uint32_t win32err; // status=FEV2_FILE_NOT_FOUND/ACCESS_DENIED 时的首个 win32 码
int32_t workerRc; // FileBatchTransferWorkerV2 返回值(0=成功)
uint32_t fileCount; // 实际发出的文件数(不含目录项)
uint64_t totalBytes; // 实际发出的(回执里是实际落盘的)文件字节数
}; // 41 bytes(#pragma pack(1))
// V2 文件完成校验包
struct FileCompletePacketV2 {
uint8_t cmd; // COMMAND_FILE_COMPLETE_V2 = 91
@@ -130,6 +158,7 @@ enum FileErrorV2 : uint8_t {
FEV2_TRANSFER_CANCEL = 6, // 传输被取消
FEV2_CHECKSUM_ERROR = 7, // 校验和错误(块级CRC)
FEV2_HASH_MISMATCH = 8, // 哈希不匹配(文件级SHA-256)
FEV2_WRITE_FAILED = 9, // 接收端写盘失败(POSIX 端 errno 无法归类时用它,明细在 win32err)
};
// V2 续传查询包(发送方在传输前发送)
+4 -2
View File
@@ -328,8 +328,10 @@ private:
}
}
std::string city = Utf8ToAnsi(json[cityField].asString());
std::string country = Utf8ToAnsi(json[countryField].asString());
// 地理位置 API 返回 UTF-8;不再转 CP_ACP——那会把 ö/ä/ß 等变音符替换成 '?'。
// GetGeoLocation 现统一返回 UTF-8,消费方按需用 NormalizeLocationToUtf8 / SafeUtf8ToAnsi 转。
std::string city = json[cityField].asString();
std::string country = json[countryField].asString();
if (!city.empty() && !country.empty()) return city + ", " + country;
if (!city.empty()) return city;
+148
View File
@@ -0,0 +1,148 @@
/**
* sha256_posix.h - 最小实现 SHA-256(POSIX 侧)
*
* 为什么不用现成的:Windows 侧的 SHA-256 走 BCrypt(common/VerifyV2.h),
* Linux/macOS 没有 BCrypt,也没有 OpenSSL 依赖,而 V2 文件发送要向服务端
* 回报 FileCompletePacketV2.sha256,必须自己算。
*
* 只实现 FileTransferV2 需要的流式接口(update/final),不做别的事。
*/
#pragma once
#if defined(_WIN32) || defined(_WIN64)
#error "sha256_posix.h is POSIX-only; Windows uses BCrypt via VerifyV2.h."
#endif
#include <cstddef>
#include <cstdint>
#include <cstring>
class Sha256
{
public:
Sha256() { reset(); }
void reset()
{
static const uint32_t init[8] = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
};
memcpy(m_h, init, sizeof(m_h));
m_bufLen = 0;
m_totalLen = 0;
}
void update(const void* data, size_t len)
{
const uint8_t* p = (const uint8_t*)data;
m_totalLen += len;
if (m_bufLen > 0) {
size_t take = 64 - m_bufLen;
if (take > len) take = len;
memcpy(m_buf + m_bufLen, p, take);
m_bufLen += take;
p += take;
len -= take;
if (m_bufLen == 64) {
transform(m_buf);
m_bufLen = 0;
}
}
while (len >= 64) {
transform(p);
p += 64;
len -= 64;
}
if (len > 0) {
memcpy(m_buf, p, len);
m_bufLen = len;
}
}
// 输出 32 字节摘要;调用后对象可 reset() 复用(不自动 reset,避免隐式行为)
void final(uint8_t out[32])
{
uint64_t bitLen = m_totalLen * 8;
// 0x80 + 零填充 + 64 位长度,凑满整块
uint8_t pad[72];
memset(pad, 0, sizeof(pad));
pad[0] = 0x80;
size_t padLen = (m_bufLen < 56) ? (56 - m_bufLen) : (120 - m_bufLen);
update(pad, padLen);
uint8_t lenBytes[8];
for (int i = 0; i < 8; ++i) {
lenBytes[i] = (uint8_t)(bitLen >> (56 - 8 * i));
}
update(lenBytes, sizeof(lenBytes));
for (int i = 0; i < 8; ++i) {
out[4 * i] = (uint8_t)(m_h[i] >> 24);
out[4 * i + 1] = (uint8_t)(m_h[i] >> 16);
out[4 * i + 2] = (uint8_t)(m_h[i] >> 8);
out[4 * i + 3] = (uint8_t)(m_h[i]);
}
}
static void hash(const void* data, size_t len, uint8_t out[32])
{
Sha256 s;
s.update(data, len);
s.final(out);
}
private:
static uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }
void transform(const uint8_t block[64])
{
static const uint32_t K[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
uint32_t w[64];
for (int i = 0; i < 16; ++i) {
w[i] = ((uint32_t)block[4 * i] << 24) | ((uint32_t)block[4 * i + 1] << 16) |
((uint32_t)block[4 * i + 2] << 8) | (uint32_t)block[4 * i + 3];
}
for (int i = 16; i < 64; ++i) {
uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
uint32_t a = m_h[0], b = m_h[1], c = m_h[2], d = m_h[3];
uint32_t e = m_h[4], f = m_h[5], g = m_h[6], h = m_h[7];
for (int i = 0; i < 64; ++i) {
uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
uint32_t ch = (e & f) ^ (~e & g);
uint32_t t1 = h + S1 + ch + K[i] + w[i];
uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
uint32_t t2 = S0 + maj;
h = g; g = f; f = e; e = d + t1;
d = c; c = b; b = a; a = t1 + t2;
}
m_h[0] += a; m_h[1] += b; m_h[2] += c; m_h[3] += d;
m_h[4] += e; m_h[5] += f; m_h[6] += g; m_h[7] += h;
}
uint32_t m_h[8];
uint8_t m_buf[64];
size_t m_bufLen;
uint64_t m_totalLen;
};
+24 -19
View File
@@ -67,7 +67,7 @@ static int send_duration = 50; // 默认 50ms
| 方向 | 发送方 | `InitFileUpload` 调用点 | 生效方式 |
|---|---|---|---|
| 上传(主控端 → 被控端) | 主控端 | `server/2015Remote/2015RemoteDlg.cpp:2223`(启动一次) | 读 `THIS_CFG`,重启主控端生效 |
| 下载(被控端 → 主控端) | 被控端 | `client/FileManager.cpp:40`(CFileManager 构造,每会话一次) | 读客户端配置,下次打开文件管理会话生效 |
| 下载(被控端 → 主控端) | 被控端 | `client/FileManager.cpp:40`(CFileManager 构造,每会话一次) | 读客户端配置(`MasterSettings` 登录下发写入),下次打开文件管理会话生效 |
### 4.1 上传方向(主控端本地,无协议改动)
@@ -79,17 +79,22 @@ int durMs = THIS_CFG.GetInt("transfer", "DurationMs", 50);
InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
```
### 4.2 下载方向(需下发到被控端)
### 4.2 下载方向(随 `MasterSettings` 登录下发到被控端)
新增命令 `CMD_FILE_SPEED`,照 `CMD_QUALITY_LEVEL(78)` 的“服务端下发 → 客户端持久化 → 本地生效”套路:
下载速度**不再用独立命令下发**,而是折叠进 `MasterSettings` 结构体,随**客户端每次登录成功**第一时间下发(主连接建立即 `SendMasterSettings`),客户端持久化到 `[transfer]` 节后本地生效:
1. **`common/commands.h`**:新增 `CMD_FILE_SPEED = 252`(命令号单字节,252 < 255 安全)。
2. **命令格式**:`[cmd:1][chunkKb:uint16 LE][durationMs:uint16 LE]`,共 5 字节。
- 传原始 `chunkKb`/`durationMs` 而非档位索引,**避免客户端复制映射表**,映射表只存在于主控端对话框。
3. **主控端下发**:在 `OnOnlineFileManager()`(`server/2015Remote/2015RemoteDlg.cpp:4737`,发 `COMMAND_LIST_DRIVE` 开文件管理会话)发 `COMMAND_LIST_DRIVE` **之前**,先经主连接把当前档位 `CMD_FILE_SPEED`(5 字节)发给被控端;`OnOnlineDesktopManager()`(`2015RemoteDlg.cpp:4723`,发 `COMMAND_SCREEN_SPY`)同理也发一次,覆盖“先开远程桌面再开文件管理”的引用计数时序。两处都在 `SendFileSpeedCommand()`(`:9310`)统一读取并下发。
4. **被控端接收**:在客户端主连接分发 `client/KernelManager.cpp:814` 的 `switch`(`COMMAND_LIST_DRIVE` 所在,`case` 加在 `1280` 附近)加 `case CMD_FILE_SPEED`,把两数写入 `iniFile cfg(CLIENT_PATH)` 的 `[transfer]` 节。
5. **被控端调用点读配置**:`client/FileManager.cpp:40`(CFileManager 构造)改为读 `cfg.GetInt("transfer","ChunkKb",64)` / `DurationMs`,替换硬编码 `64, 50`。CFileManager 每会话重建(构造 Init、析构 Uninit),故下次打开文件管理即生效。
1. **`common/commands.h`**:在 `MasterSettings` 结构体 `Reserved` 之前新增两个字段(`sizeof` 仍为 1000,`Signature` 偏移不变,向下兼容老客户端):
```c
uint16_t TransferChunkKb; // 文件传输速度 chunkKb(随登录配置下发)
uint16_t TransferDurationMs; // 文件传输速度 durationMs(0=不限速)
```
2. **主控端登录即下发**:`OnInitDialog()` 读 `THIS_CFG` 的 `[transfer]`(`GetTransferSpeed`,默认 64/50),填入 `m_settings.TransferChunkKb/TransferDurationMs`。登录链路本就把 `m_settings` 经 `SendMasterSettings` 下发给每个新连接客户端,**无需任何额外命令**。
3. **主控端改速即时广播**:`OnFileTransferSpeed()` 保存后同步更新 `m_settings` 两个字段并 `SendMasterSettings(nullptr, m_settings)`,在线客户端即时收到新速度;新连接主机也自动获取。
4. **被控端接收**:客户端 `CMD_MASTERSETTING` 处理器(`client/KernelManager.cpp:1116` 附近)中,`TransferChunkKb` 非 0(老主控未携带时为 0,保留本地默认值)则把两数写入 `iniFile(CLIENT_PATH)` 的 `[transfer]` 节。
5. **被控端调用点读配置**:`client/FileManager.cpp:40`(CFileManager 构造)等 4 个 `InitFileUpload` 调用点均读 `cfg.GetInt("transfer", ...)`,替换硬编码 `64, 50`。CFileManager 每会话重建(构造 Init、析构 Uninit),故下次打开文件管理即生效。
> **为何不用独立命令**:v1.4.0 曾用独立 `CMD_FILE_SPEED(252)` 在 `OnOnlineFileManager()`/`OnOnlineDesktopManager()` 发 `COMMAND_LIST_DRIVE`/`COMMAND_SCREEN_SPY` **之前**追加下发。主控端 IOCP 对两次背靠背 `Send2Client` 会合并为两次整包 `WSASend`(`OutCompressedBuffer` 累积),导致客户端收到重复的 `[FILE_SPEED][SCREEN_SPY]` 命令流——这正是“点击远程桌面弹出两个对话框”的根因(commit 76decec)。改为随 `MasterSettings` 登录下发后,下载方向不再有任何背靠背发送。
> **向后兼容**:`CMD_FILE_SPEED = 252` 命令号与客户端 `case CMD_FILE_SPEED` 处理器仍保留,供老主控(仍按旧机制下发)与新客户端互通;新主控不再发送该命令。
> **关键**:库用进程级引用计数,速度只在**首次** `InitFileUpload` 时设定(`g_threadCount > 1` 时提前返回,不重设)。客户端共 4 个 `InitFileUpload` 调用点(`FileManager.cpp:40`、`ScreenManager.cpp:109`、`ScreenManager.cpp:873`、`KernelManager.cpp:1399`),谁先初始化谁锁定速度。故**这 4 处必须全部改为读同一配置**,否则下载速度会被先初始化的管理器(如远程桌面会话)锁成旧值。
---
@@ -97,7 +102,7 @@ InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
## 5. 配置存储
- 主控端:`THIS_CFG`(ini)`[transfer]` 节 `ChunkKb` / `DurationMs`(int)。
- 被控端:`iniFile(CLIENT_PATH)` 的 `[transfer]` 节 `ChunkKb` / `DurationMs`(int),由 `CMD_FILE_SPEED` 写入。
- 被控端:`iniFile(CLIENT_PATH)` 的 `[transfer]` 节 `ChunkKb` / `DurationMs`(int),由 `MasterSettings` 登录下发写入。
存 `ChunkKb`/`DurationMs` 两个 int 而非档位索引:自解释、直接对应 `InitFileUpload` 入参、不易错位。
@@ -111,9 +116,9 @@ InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
| `server/2015Remote/2015Remote.rc` | 「高级」菜单加一项;新增对话框资源(滑块+预估标签+按钮)。**文件为 UTF-16LE 编码,须按 Unicode 读写** |
| `server/2015Remote/CFileSpeedDlg.h` | 新建:档位表 + `OnHScroll` 实时预估 + 恢复默认(照 `CPreviewLevelsDlg.h` 内联实现) |
| `server/2015Remote/2015RemoteDlg.h` | 加 `OnFileTransferSpeed()` 声明 |
| `server/2015Remote/2015RemoteDlg.cpp` | 消息映射 `ON_COMMAND(ID_TOOL_FILE_SPEED, ...)`;`2223` 读配置(上传);`OnFileTransferSpeed()` 弹出对话框并写回 THIS_CFG;`OnOnlineFileManager()`/`OnOnlineDesktopManager()` 发 `CMD_FILE_SPEED` |
| `common/commands.h` | 加 `CMD_FILE_SPEED = 252` |
| `client/KernelManager.cpp` | `case CMD_FILE_SPEED` 写客户端配置(主连接 switch,`814`) |
| `server/2015Remote/2015RemoteDlg.cpp` | 消息映射 `ON_COMMAND(ID_TOOL_FILE_SPEED, ...)`;`2223` 读配置(上传);`OnInitDialog()` 把 `[transfer]` 速度填入 `m_settings`;`OnFileTransferSpeed()` 保存后更新 `m_settings` 并经 `SendMasterSettings(nullptr, ...)` 广播 |
| `common/commands.h` | `MasterSettings` 新增 `TransferChunkKb`/`TransferDurationMs`(`sizeof` 不变,`CMD_FILE_SPEED=252` 保留向后兼容) |
| `client/KernelManager.cpp` | `CMD_MASTERSETTING` 处理器写 `[transfer]`(`TransferChunkKb` 非 0 才写) |
| `client/FileManager.cpp`、`client/ScreenManager.cpp`、`client/KernelManager.cpp` | 4 个 `InitFileUpload` 调用点读配置替换硬编码 `64, 50`(引用计数要求全部一致) |
| `server/2015Remote/lang/en_US.ini`、`zh_TW.ini`、`de_DE.ini` | 追加「文件传输速度」相关 13 条中文原文→译文(GBK 编码,`RCDATA "lang\*.ini"` 由 rc.exe 嵌入) |
@@ -122,8 +127,8 @@ InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
## 7. 生效时机与提示文案
- 上传速度:重启主控端生效。
- 下载速度:下次打开该主机的文件管理会话生效。
- 对话框保存后弹提示:`文件传输速度已保存。上传速度重启主控端后生效;下载速度下次打开文件管理或远程桌面后生效。`
- 下载速度:已推送到在线客户端即时生效;新连接的主机自动获取。
- 对话框保存后弹提示:`文件传输速度已保存。上传速度重启主控端后生效;下载速度已推送到在线客户端,新连接的主机也会自动获取。`
---
@@ -131,16 +136,16 @@ InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
1. **`Sleep` 精度**:Windows 计时器粒度约 15.6ms,`durationMs` 过小则失真(见 §3)。
2. **实际速度 < 预估**:预估为纯 `chunk/delay` 理论值,未计入 `f()` 网络发送耗时;对话框文案用“约/大概”表述。
3. **命令号冲突**:`CMD_FILE_SPEED=252` 需确认 `commands.h` 无重号;252 < 255(单字节 `uint8_t cmd` 上限)。
3. **结构体字段布局**:`TransferChunkKb`/`TransferDurationMs` 加在 `Reserved` 之前(`sizeof(MasterSettings)` 仍为 1000,`Signature` 偏移不变),保证与 Go 侧/老客户端二进制兼容;`TransferChunkKb == 0` 作为“未下发”哨兵(老主控未填充 → 客户端保留本地默认值)。
4. **`.rc` 编码**:`2015Remote.rc` 为 UTF-16LE(带 BOM),编辑必须按 Unicode 处理,避免破坏资源脚本。
5. **跨平台**:Linux/macOS 客户端下载路径暂不改(`CMD_FILE_SPEED` 会被老/其他平台客户端静默忽略,向后兼容)。
5. **跨平台**:Linux/macOS 客户端下载路径暂不改;`MasterSettings` 新增字段位于原 `Reserved` 区(老/其他平台客户端不识别即忽略),向后兼容。
6. **多语言 key 精确匹配**:语言文件为 GBK 编码、key 不 trim(`CIniParser` 保留原始空格);译文 key 必须与源码逐字一致——源码为 UTF-8、经 `/execution-charset:.936` 编译为 GBK,`·`(U+00B7)、全角括号()等需一致,否则查不到翻译。
---
## 9. 实施顺序
1. `common/commands.h` 加命令号 → `resource.h` 加 ID → `.rc` 加菜单项与对话框资源。
1. `common/commands.h` 扩 `MasterSettings` → `resource.h` 加 ID → `.rc` 加菜单项与对话框资源。
2. 新建 `CFileSpeedDlg.h` → `2015RemoteDlg` 接线(上传方向,可先验证)。
3. 主控端下发 `CMD_FILE_SPEED` → 客户端接收持久化 → 客户端调用点读配置(下载方向)。
3. 主控端经 `MasterSettings` 下发速度 → 客户端 `CMD_MASTERSETTING` 持久化 → 客户端调用点读配置(下载方向)。
4. 编译验证(MSBuild 须传 `-p:SolutionDir`,见项目记忆)。
+254
View File
@@ -0,0 +1,254 @@
# MCP 远程交谈(P9):AI ↔ 客户端使用者双向对话
## 1. 目标与边界
让接入服务端 MCP 的大模型与坐在 Windows 客户端电脑前的人进行多轮文字交谈。
- **仅 Windows 客户端**:`LNX` / `MAC` / `APK` 直接返回 `-32005`,不发命令。
- **复用既有功能,协议零改动**:沿用「远程交谈」(`client/ChatManager.cpp` + `IDD_CHAT`),
报文与握手不变。客户端侧只有两处改动:聊天窗口改为 Unicode 对话框(见 §5.8,
解决非 936 ACP 系统上的中文乱码),以及加壳部署下对话框改用内嵌模板兜底(见 §5.7)。
- **独立开关 `McpChat`**(默认 `0`):与 `McpReadonly` 无关;关闭时四个工具不出现在
`tools/list`,直接调用返回 `-32006`。
- **直接弹出客户端窗口**:没有确认框;会话建立即代表开始交谈。
- 验证方式:在虚拟机里运行交互式 Windows 客户端,由人扮演使用者与服务端 AI 对话。
## 2. 复用协议
| 方向 | 报文 |
|---|---|
| 服务端主连接 → 客户端 | `[COMMAND_CHAT=161]`(1 字节) |
| 客户端新建子连接 | 先 `[TOKEN_CONN_AUTH=246]`(`EnableSubConnAuth`),再 `[TOKEN_CHAT_START=62]` |
| 服务端子连接 → 客户端 | `[COMMAND_NEXT_CHAT=0]`(1 字节,通知客户端弹窗) |
| 双向文本 | `[CP936/GBK 字节][0x00]`,无 token 前缀 |
| 服务端子连接 → 客户端 | `[COMMAND_CHAT_CLOSE=1]` 结束 |
时序:
```
chat_open:
FindMainContext(id) → 校验 Windows → 校验 McpChat
mainCtx->Send2Client([161])
客户端建子连接 → [246] 认证 → [62] 就绪
OnChatSubPacket 绑定 62 → 回 [0] → readyAt = now + 1000ms
chat_open 等到 started && now >= readyAt 才返回
chat_send:
subCtx->Send2Client(GBK + NUL) → WaitSendIdle(2000)
客户端使用者输入:
subCtx → [GBK + NUL] → OnChatSubPacket → inbox → 唤醒 chat_wait
chat_close:
subCtx->Send2Client([1]) → WaitSendIdle(1000) → CancelIO
```
未绑定子连接上的 `TOKEN_CONN_AUTH(246)` 不被聊天钩子消费,仍由 `MessageHandle`
的鉴权分支处理并回 `ConnAuthAck`,认证后子连接的 `clientID` 才可靠(新客户端路径)。
已绑定子连接上首字节为 `0xF6` 的 GBK 文本不会被误判为鉴权包(绑定连接上所有包都由
聊天钩子消费)。
## 3. 工具
| 工具 | 输入 | 输出 |
|---|---|---|
| `chat_open` | `id`;`timeout_ms`(默认 15000,2000–60000) | `{session_id, status:"open", message}` |
| `chat_send` | `id`, `session_id`, `message` | `{session_id, sent:true, bytes}` |
| `chat_wait` | `id`, `session_id`;`timeout_ms`(默认 30000,0–55000)、`max_messages`(默认 20,1–50) | `{session_id, messages:[{id,at,text}], timed_out, closed, dropped}` |
| `chat_close` | `id`, `session_id` | `{session_id, closed:true}`;主机在线时会话已不存在按幂等处理为成功;主机离线返回 `-32002` |
典型对话循环:
```
chat_open(id) → session_id
chat_send(id, sid, "你好,我是助手")
chat_wait(id, sid, 30000) → 对方的回复
chat_send(id, sid, "……")
chat_wait(id, sid, 30000)
chat_close(id, sid)
```
错误码沿用 MCP 约定:
| 码 | 含义 |
|---|---|
| `-32001` | `chat_open` 等不到客户端建窗(离线、老客户端、非交互桌面) |
| `-32002` | 主机离线 / 会话不存在或已关闭 / `session_id` 不匹配 |
| `-32003` | 同设备已有活跃会话;或同一会话已有 `chat_send` / `chat_wait` 在飞 |
| `-32004` | 发送失败(`Send2Client` 返回 FALSE) |
| `-32005` | 非 Windows 客户端 |
| `-32006` | `McpChat` 关闭 |
| `-32602` | 参数、UTF-8、GBK 可表示性或长度错误 |
## 4. 编码与长度
- **出站**:UTF-8 → CP936 **严格转换**(`MB_ERR_INVALID_CHARS` +
`WC_NO_BEST_FIT_CHARS` + `lpUsedDefaultChar`)。emoji、`ö` 等 GBK 不可表示字符
直接返回 `-32602`,绝不静默变成 `?`。
- **入站**:CP936 → UTF-8,按首个 NUL 截断。
- 出站上限 4000 GBK 字节(客户端输入缓冲 `char str[4096]`,硬上限 4095)。
- 入站单条上限 8 KiB;inbox 100 条 / 256 KiB,溢出丢最旧并在 `chat_wait` 的
`dropped` 中报告。
- 拒绝空消息、纯空白、`\r\n`、NUL 及所有 C0 控制字符。
客户端聊天窗口自 P9 起是 Unicode 对话框(见 §5.8):入站 GBK 字节先转 UTF-16 再
显示,出站 UTF-16 严格转 GBK 后发送,因此在德语等非 936 系统上中文不再乱码。协议
本身仍是 GBK,`ö`/`ß`/emoji 等 GBK 外字符两端都无法传输(服务端 `-32602`;客户端
在发送框下方给出提示并不发送)。
## 5. 客户端怪癖与规避(协议不变)
1. **首字节 101 ('e') 被丢弃(客户端已修)**:`client/ChatManager.cpp` 原在任何长度
判断之前执行 `if (szBuffer[0] == TOKEN_HEARTBEAT) return;`,而该通道承载自由文本,
于是「echo」「error」这类以 e 开头的消息被静默吞掉。交谈子连接上没有心跳(心跳只在
主连接、且是 `[101][Heartbeat]` 多字节包,由主连接分发消费),这行是照搬其它 manager
的死防御,已删除。服务端**仍保留**前置空格规避:老客户端还带这个缺陷,多一个看不见的
空格好过静默丢消息。验证见本章末尾。
2. **窗口创建前的文本被丢弃**:客户端收到 `[0]` 后 `WaitForDialogOpen` 只
`Sleep(150)`,随后才在线程里 `CreateDialogParamW`;`OnReceive` 仅在 `m_hWnd`
非空时显示文本。服务端把 `readyAt` 设为绑定后 1000ms,`chat_open` 等满再返回,
`chat_send` 也拒绝早于 `readyAt` 的发送。
3. **X / 结束交谈只隐藏不关闭**:客户端 `ShowWindow(SW_HIDE)`,会话仍活;下一条
服务端文本会 `SW_RESTORE` 重新弹出。因此隐藏不是关闭信号,结束时必须显式
`chat_close`。
4. **一字节控制包**:客户端把 `len==1` 的包当命令,故文本必须带尾部 NUL(至少
2 字节),空消息在工具层拒绝。
5. **手动「远程交谈」竞争**:MCP 会话在飞时用户又点菜单会产生第二个 `[62]`;
先到者绑定,后到者被吸收并 `CancelIO`。极窄竞争下用户这次看不到 MFC 窗口,
重试即可。
6. **Session 0 / SYSTEM**:`COMMAND_CHAT` 不像抓屏那样重定向到交互会话;以服务
方式运行的客户端没有交互桌面,`chat_open` 会超时。VM 验证必须在交互桌面运行。
7. **加壳部署的对话框兜底**:EXE + SC_AES/sRDI 打包时,
`g_hInstance = GetModuleHandle(NULL)` 是外壳进程映像,资源里只有清单、没有
`IDD_CHAT`;载荷以裸 shellcode 在壳进程内运行,未注册进加载器,Windows 的
`FindResource`/`LoadResource`/`CreateDialogParamW` 取不到对话框
(实测 err=1812 / 59),聊天线程建窗后立即退出。客户端因此保留
`CreateDialogParamW` 原路径,失败时回退到 `CreateDialogIndirectParamW` +
内嵌模板(`client/ChatDialogTemplate.h`,取自载荷 `RT_DIALOG 106`,240 字节),
图标回退为「直接遍历本模块映像的资源目录取 `RT_GROUP_ICON 105` →
`RT_ICON` → `CreateIconFromResourceEx`」(`client/ImageResource.h`),
仍失败才用 `LoadIcon(NULL, IDI_APPLICATION)`。**旧客户端无此兜底,加壳部署下
不会弹窗**:MDLL 由服务端自动下发新 DLL 即生效,EXE 需重新分发客户端。
8. **Unicode 对话框(非 936 系统乱码修复)**:客户端是 MBCS 编译,但对话框可以建
成 Unicode 窗口:`CreateDialogParamW` / `CreateDialogIndirectParamW` 创建的窗口
`IsWindowUnicode` 为真,而 `DLGTEMPLATEEX` 的字符串本来就按 UTF-16 存储。因此
聊天窗口全部改走 W 版 API——`GetWindowTextW` / `SetDlgItemTextW` / 日志用
UTF-16 拼接,消息循环用 `GetMessageW` / `IsDialogMessageW` / `DispatchMessageW`
(否则 WM_CHAR / WM_IME_* 会先按 ACP 转换)。入站
`MultiByteToWideChar(936, …)`,出站 `WideCharToMultiByte(936,
WC_NO_BEST_FIT_CHARS, …, &usedDefault)`;`usedDefault` 置位即 GBK 不可表示
字符,提示后不发送。`IDD_CHAT` 字体由点阵 "System" 改为 "MS Shell Dlg"
(可缩放,并经 SystemLink 字体链接到中文字体),否则 Unicode 窗口里同样没有
中文字形;前提是系统装有至少一种 CJK 字体(简体中文补充字体或 Microsoft YaHei
等),否则只能显示方框。静态文案按 `GetUserDefaultUILanguage()` 在中文/英文两套
间切换,`Script.rc` 因此直接写英文(德语系统看到的是英文而非乱码)。协议与服务端
逻辑不变。
**首字节 'e' 修复的验证(2026-10-25,Debug 实例 + 本机 Debug 客户端)**:验证时把
`McpChat.cpp` 的前置空格临时关掉(否则测不到客户端行为),`chat_open` 后
`chat_send "echo test"` 与 `"second line"` 各一条,再从服务端读客户端窗口文本
(`EnumWindows` → `WM_GETTEXT`):两条都完整出现在聊天记录里,`echo test` 无前导空格。
恢复前置空格后复测,显示为 `" echo test"`(多一个空格但不丢),两条路径都通过。
## 6. 服务端状态机
数据结构(`McpServer.h`,受 `m_ChatMutex` 保护):
```cpp
struct ChatSession {
std::string sessionId;
context* mainCtx; // 主连接(仅身份判断;主连接断开后置空)
uint64_t mainClientId;
context* subCtx; // 已绑定的子连接;关闭后置空
std::string peer; // GetPeerName()(老客户端 clientID=0 兜底)
bool started, closed;
bool sendBusy, waitBusy; // 同一会话串行发送 / 只允许一个 chat_wait
steady_clock::time_point readyAt;
time_t lastActiveAt;
std::deque<ChatMessage> inbox; // UTF-8,未投递
size_t inboxBytes;
uint64_t nextMsgId;
int dropped;
};
using ChatSessionPtr = std::shared_ptr<ChatSession>;
```
- 会话用 `shared_ptr` 持有:`chat_wait` / `chat_send` 在工作线程复制一份后,即使
map 条目被 `chat_close` 或断线删除也安全。
- `m_ChatSessions[device]`、`m_ChatContextToDevice[subCtx]`、`m_ChatAbsorbedSubCtx`
与 `m_ChatRoutes`(原子计数)供 `MessageHandle` 快速路径判断;无会话在飞时
`OnChatSubPacket` 无锁返回,避免音频/屏幕等高频子连接逐包抢锁。
- 锁序:`parent->m_cs`(`FindMainContext`)→ `m_ChatMutex`。持锁期间不发送、
不 `CancelIO`、不 `WaitSendIdle`。
- 超时/关闭后到达的 `[62]` 由 5s 墓碑(按 device 与 peer 两个维度)吸收并
`CancelIO`,避免弹出 MFC 聊天对话框。
- 空闲回收 600s(任一无 `busy` 且 `lastActiveAt` 超时的会话),每个 chat 工具
入口惰性调用。
## 7. 钩子与生命周期
`2015RemoteDlg.cpp`:
1. `MessageHandle`:MCP 终端块之后、**P8 `OnManagedSubPacket` 之前**调用
`OnChatSubPacket`。聊天文本是裸 GBK,首字节可能是 61/255,若先交给 P8 会被
误绑定。
2. `OfflineProc`:P8 清理之后、`RemoveFromHostList` **之前**调用
`OnChatContextClosed`(连接池会复用 `context*`,晚清理会误路由新连接)。
子连接断开 → 会话 `closed` 并唤醒 `chat_wait`;主连接断开 → 关闭其所有会话并
锁外 `CancelIO` 子连接。
3. 启动:`SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0)`。
审计:`AuditChatAction` 与 `AuditManageAction` 同落地方式(`WM_SHOWERRORMSG`),
标题 `_TR("MCP远程交谈")`;只记录 `session=...` 与 `bytes=N`,**绝不记录消息正文**。
`chat_wait` 不审计,避免刷屏。
## 8. 配置
| INI key | 默认 | 说明 |
|---|---|---|
| `McpChat` | `0` | 远程交谈工具族开关;改动需重启服务端 |
「扩展 → MCP设置」新增复选框「启用远程交谈(AI 与用户对话)」。
## 9. 验证矩阵
准备:`McpEnabled=1`、`McpChat=1` 后重启服务端;MCP 客户端重连使 `tools/list`
刷新;VM 中交互运行 Windows 客户端。
| # | 操作 | 期望 |
|---|---|---|
| 1 | `tools/list`(开关开 / 关) | 四个 chat 工具出现 / 消失;关闭时直调 `-32006` |
| 2 | `chat_open(id)` | VM 约 1s 内弹出「远程交谈」;返回 32 位 hex `session_id` |
| 3 | `chat_send` 中文;用户回中文;`chat_wait` | VM 显示「对方: …」;返回 UTF-8 原文 |
| 4 | 连续多轮、用户连发两条 | 下一轮批量返回,顺序正确,`dropped=0` |
| 5 | 发送 `"echo test"`(首字节 'e') | 新客户端原样显示;老客户端靠前置空格仍能显示(`" echo test"`) |
| 6 | open 后立刻 send,重复 10 次 | 第一条不丢(1000ms 建窗等待) |
| 7 | 4000 / 4001 字节、emoji | 边界内成功;超长与 emoji 返回 `-32602` |
| 8 | 无回复时 `chat_wait` | 到点 `timed_out:true`,会话仍活 |
| 9 | 用户点 X 隐藏后再 send | 窗口恢复,会话仍活 |
| 10 | `chat_close` | 窗口关闭;旧 id 发送 `-32002`;立即重新 open 成功 |
| 11 | `chat_wait` 阻塞时杀掉客户端 | 返回 `closed:true`;服务端稳定;重连后可重新 open |
| 12 | Linux / macOS / Android 主机 | `-32005`,不发命令 |
| 13 | 同设备第二次 `chat_open` | `-32003` |
| 14 | 无 MCP 会话时手动「远程交谈」 | MFC 聊天窗口照常打开(回归) |
| 15 | 服务端审计日志 | 有 open/send/close 的 session id 与字节数,无消息正文 |
| 16 | 现有 MCP 工具 + 手动主机/连接/终端对话框 | 行为不变 |
| 17 | `chat_wait timeout_ms=55000` | 在常见 60s 工具超时前返回 |
| 18 | 加壳(SC_AES/sRDI)EXE 客户端 `chat_open` | 仍弹出「远程交谈」且标题栏图标正常(内嵌模板 + 自模块映像取图标);客户端日志有 `CreateDialogParamW(1812) 失败,改用内嵌对话框模板` |
| 19 | 非 936 系统(如德语 Windows)`chat_open` + 中文 `chat_send` | 标题、按钮为英文(系统 UI 非中文),中文消息正常显示而非乱码;中文系统为中文按钮 |
| 20 | 德语系统客户端发送 `Grüße` / emoji | 客户端不发送并在日志区提示 GBK 不支持;服务端若直接 `chat_send` 同类字符返回 `-32602` |
| 21 | 未安装任何 CJK 字体的系统 | 中文显示为方框(字体缺失,非编码问题);安装中文补充字体后恢复 |
## 10. 已知限制
- **无投递回执**:`sent:true` 只表示已写入子连接并 `WaitSendIdle` 成功,不保证
使用者已看见。
- **HTTP 工作线程**:`chat_wait` 最长 55s 会占用一个 httplib 工作线程;不要在
同一 MCP 连接上并行大量长等待。
- **连接池复用窄竞争**:发送时捕获的 `subCtx` 在极端情况下可能已断开并被池复用;
与现有终端/屏幕实现同一取舍,靠 `closed` 检查与 `WaitSendIdle` 缩短窗口。
- **极慢 VM**:若首条消息仍丢,可把 `kChatOpenSettleMs` 调到 1500–2000ms,代价是
`chat_open` 变慢。
- **仍是 GBK 通道**:Unicode 对话框解决了「显示」,但线路上仍是 CP936,德语变音
字母(`ö`/`ä`/`ß`)、emoji 等无法传输。要根治需引入会话级编码协商(如
`TOKEN_CHAT_START` 后追加能力位,双方改用 UTF-8),属未来工作;服务端与客户端
必须同时升级,且旧客户端不能误解新报文。
- **字体依赖**:中文显示依赖系统已安装的 CJK 字体(字体链接到 "MS Shell Dlg"
的后备字体);仅此一点无法由程序保证,缺少字体时显示为方框。
+565 -4
View File
@@ -147,7 +147,8 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
"online":{"type":"boolean"},
"group":{"type":"string"},
"screen":{"type":"string"},
"clientType":{"type":"string"}
"clientType":{"type":"string"},
"tls":{"type":"boolean"}
}
}
}
@@ -164,7 +165,7 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"list_online_hosts","arguments":{}}}
```
响应(结构化输出:`structuredContent` 承载主机数组,`content` 附带可读摘要):
响应(结构化输出:`structuredContent` 承载主机数组,`content` 是可读摘要 + 同一份结构的紧凑 JSON):
```json
{"jsonrpc":"2.0","id":3,"result":{
"structuredContent":{
@@ -174,10 +175,14 @@ MCP 是 JSON-RPC 2.0。MVP 只需实现以下方法:
"activeWindow":"WeChat","online":true,"group":"default","screen":"1:1920x1080","clientType":"EXE"}
]
},
"content":[{"type":"text","text":"共 1 台主机在线。"}],
"content":[
{"type":"text","text":"共 1 台主机在线。"},
{"type":"text","text":"{\"hosts\":[{\"id\":\"123\",\"name\":\"DESKTOP-ABC\",...}]}"}
],
"isError":false
}}
```
第二个文本块来自 §14:规范要求返回 `structuredContent` 时也把序列化 JSON 放进 TextContent,否则只读 `content` 的客户端拿不到 `id`。
#### 3.3.4 可选实现
@@ -231,6 +236,7 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
- 基础标识:`id` / `name` / `remark` / `ip` / `os` / `location` / `group` / `version` / `clientType` / `screen`
- 实时信息:`rtt`(延迟)、`activeWindow`(当前活动窗口,即被控端正在做什么)
- 连接凭据:`tls`(布尔,对应在线主机列表的 TLS 列;`true` 表示该客户端本轮以 TLS 模式登录,是**登录时的凭据**而非实时探测;老客户端/空值一律 `false`)
输出结构 `{"hosts": [...]}`,每台主机一个对象,字段与 §3.3.2 的 `outputSchema` 一致。
@@ -256,6 +262,14 @@ Json::Value BuildHostJson(context* ctx, _ClientList* clientMap);
| `McpPort` | `6544` | MCP 监听端口;仅当 `McpEnabled=1` 时生效;未配置用默认 `6544` |
| `McpBind` | `127.0.0.1` | 监听地址;默认仅本机;可设 `0.0.0.0`(所有网卡)或内网 IP(如 `192.168.0.92`)以支持远程 |
| `McpToken` | 空(UI 默认随机值) | 静态 token;对话框内「token 必填、默认随机值」——首次打开若为空则预填随机并随保存持久化。运行时优先级:env `YAMA_MCP_TOKEN` → `McpToken` → 皆空则随机生成(见 §3.5) |
| `McpKeylog` | `0` | 键盘记录工具 `get_keylog` 的独立开关(见 §9.3);与 `McpReadonly` 无关,改动需重启生效 |
| `McpToolTimeoutMs` | `20000` | 工具等待客户端响应的默认超时(ms),clamp 到 `[1000, 600000]`;各工具自己的 `timeout_ms` 参数优先。**ini-only**(无设置界面控件),改动需重启生效 |
| `McpHttps` | `0` | `1` = 对外端口说 HTTPS(native TLS,见 §13),httplib 退到 `127.0.0.1:McpInternalPort`;`0` = 保持明文。经「MCP设置」对话框的「启用 HTTPS」复选框设置,改动需重启生效 |
| `McpCertPath` | 空(回退 `[tls] CertPath`) | MCP 专用证书(PEM)。面向公网客户端时应为公共 CA 证书(如 Let's Encrypt 的 `fullchain.pem`),不要复用设备端口的自签证书。对话框「证书路径」行可填/浏览;为空时按回退规则预填 `[tls]` 的值 |
| `McpKeyPath` | 空(回退 `[tls] KeyPath`) | 与 `McpCertPath` 配对的私钥,须为 PKCS#8(`-----BEGIN PRIVATE KEY-----`)。对话框「私钥路径」行可填/浏览 |
| `McpInternalPort` | 空(取 `McpPort+1`) | `McpHttps=1` 时 httplib 实际监听的回环端口,仅绑定 `127.0.0.1`。**ini-only**(对话框不暴露,自动取 `McpPort+1`) |
> 对话框里「证书路径/私钥路径」两行仅在勾选「启用 HTTPS」后可编辑;保存时校验两者非空且文件存在(加载失败会导致 MCP 监听 fail-closed,故提前挡住),格式仍以服务端实际加载为准。
> 与旧版「`McpPort=0` 即禁用」不同:启用与否改由独立的 `McpEnabled` 开关控制,`McpPort` 回归纯端口语义,二者解耦。
@@ -339,6 +353,11 @@ MCP 默认不启用,通过主对话框「扩展 → MCP设置」菜单项打
| 端口 | `McpPort` | `6544` | 数字编辑框,仅当启用时有效 |
| 绑定地址 | `McpBind` | `127.0.0.1` | 默认仅本机;可改 `0.0.0.0` / 内网 IP |
| Token | `McpToken` | 随机值 | 必填;为空时预填随机 token |
| 「启用 HTTPS」复选框 | `McpHttps` | 未勾选(`0`) | 勾选后本端口同时接受 TLS(§13);未勾选时下面两行置灰 |
| 证书路径 | `McpCertPath` | 空(回退 `[tls] CertPath`) | PEM;带「浏览」按钮。为空时按回退规则预填 `[tls]` 的值 |
| 私钥路径 | `McpKeyPath` | 空(回退 `[tls] KeyPath`) | PKCS#8;带「浏览」按钮 |
保存时若勾选了 HTTPS,证书/私钥必须非空且文件存在,否则弹提示并留在对话框(身份加载失败会让 MCP 监听 fail-closed,故提前挡住);HTTPS 改动与其它项一样重启生效。
#### 3.8.3 初始化与保存
@@ -426,6 +445,7 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
- 写操作工具的安全边界评审(操作对象、权限、审计)
- 认证升级:复用 `WebServiceAuth` 的签名 token / 过期机制
- 分组过滤:`list_online_hosts` 加 `group` 参数
- P9 远程交谈(已实现):`chat_open` / `chat_send` / `chat_wait` / `chat_close`,独立开关 `McpChat`(默认 `0`,与只读开关无关);协议不变,客户端聊天窗口改为 Unicode 对话框以支持非中文系统(见 `docs/Mcp_Chat_Design.md`)
---
@@ -440,4 +460,545 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
- ✅ **生效方式**:MCP 启用/端口/绑定/token 的改动均需重启服务端生效,对话框保存后弹窗提醒「重启程序生效」。
- ✅ **取数方案**:C(抽公共函数 `BuildHostJson`,MCP 与 WebService 平级复用)。
- ✅ **返回字段**:全量,含实时信息(`rtt` / `activeWindow`),支持 AI 监督场景。
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要。
- ✅ **序列化**:`structuredContent` + `outputSchema`,`content` 附带可读摘要(2026-10-26 起再追加一份紧凑 JSON,见 §14)。
---
## 9. 增补(2026-10-25:N1–N5)
本轮在既有工具族(P2–P9)之上补齐「能找到主机、能一次查多台、输出不撑爆上下文、认证可追溯」四件事,全部为服务端改动,客户端零改动。
### 9.1 N1 离线主机可见
- 新增工具 `list_all_hosts`(`online` / `offline` 两个布尔过滤,默认都为 `true`),数据源是 `m_ClientMap`(主机列表历史记录,`GetAll()` 快照 + `m_cs` 保护),在线条目复用 `BuildHostJson`,离线条目由 `BuildOfflineHostJson` 生成,字段:`id` / `name` / `remark` / `ip` / `os` / `location` / `online` / `group` / `last_seen` / `install_time` / `authStatus`。
- `search_hosts` 的 `online` 参数:`true` = 仅在线,`false` = 仅离线(修复此前 `online=false` 永远返回空列表的问题),缺省 = 仅在线(与改动前一致,不改变既有调用方看到的结果)。两类都要请用 `list_all_hosts`。
- `authStatus` 是 `ClientValue::Authorized` 的三态枚举(`unauthorized` / `authorized_by_super` / `authorized_by_admin` / `forbidden`),不是布尔值。
- `get_host_detail` 对「在 `m_ClientMap` 里但当前离线」的 id 不再返回 `-32002`,改为返回该主机的最后记录(`online=false`),使 `list_all_hosts` 的结果可直接消费。
### 9.2 N2 批量只读调用
- 只读工具支持 `ids: []`(最多 50 个),与 `id` 二选一(inputSchema 用 `anyOf` 表达)。命中批量的工具:`get_host_detail` / `list_processes` / `list_windows` / `list_services` / `list_files` / `list_registry` / `get_client_log` / `get_activity_history` / `list_network_connections` / 全部 `host_list_*` / `host_get_hosts_file`。
- 写操作工具传 `ids` 直接 `-32602` 拒绝(不逐个执行,避免误操作扩散)。
- 返回:`{tool, total, succeeded, failed, results:[{id, ok, data|error, text}]}`;`content` 里是「共 N 台,成功 X 台,失败 Y 台」+ 最多 ~1200 字节的失败明细。
- `limit` / `offset` 对每台主机各自生效;批量是串行执行,单台超时会占用整批等待时间。
- **outputSchema 必须声明批量形状**:只声明单机形状会让客户端把批量结果判为不合规
(`-32602: data must have required property 'host'`)。现在由 `ApplyBatchOutputSchema`
统一补成 `anyOf:[单机, 批量]`,见 §18.1。
### 9.3 N3 `get_keylog`
- 复用客户端既有键盘记录链路:主连接下发 `COMMAND_KEYBOARD(169)` → 客户端建子连接 → 子连接回 `TOKEN_KEYBOARD_START(293)` 作为就绪包绑定 → 之后每约 1 秒推一包 `TOKEN_KEYBOARD_DATA(294)`。
- 服务端把击键流**累积**(不是一问一答),窗口 `duration_ms`(默认 4000,1000–15000)或字节上限 `max_bytes`(默认 64 KiB,1024–256 KiB)先到者结束;结束时 `EndManagedSession(..., cancelIo=true)` 关闭子连接 —— 与 MFC 关对话框同一路径,客户端据此停止记录。
- 复用 P8 的挂起会话表(新增 `PendingKind::Keylog`,仍受「单设备单飞行」约束),就绪包绑定、迟到包墓碑、子连接断开唤醒全部沿用 P8 逻辑;绑定后服务端回 `COMMAND_NEXT`,让客户端 `WaitForDialogOpen` 立即返回(本工具不开 UI)。
- 返回 `{id, duration_ms, bytes, lines, lineCount, truncated}`,文本按客户端代码页转 UTF-8(`GetClientEncoding`)。**注意**:客户端连上后会先把缓冲区里已有的历史记录推过来,所以结果既含历史也含窗口期内的新击键。
- 独立开关 `McpKeylog`(默认 `0`,不要求只读关)。工具只在开关打开时出现在 `tools/list`,关闭时直接调用返回 `-32006`。
- 隐私:击键内容只进本次响应;审计只记 `CALL_OK tool=get_keylog ms=… bytes=…`,不落任何正文。
### 9.4 N4 认证加固
- 静态 token 校验失败:返回 401,并按来源 IP 计数;60 秒窗口内失败 10 次即封禁该 IP 900 秒,封禁期内返回 429 + `Retry-After`。失败表上限 1024,满时先清理过期项。
- 环回来源(`127.0.0.1` / `::1`)**只记账不封禁**:内置 frpc 把 MCP 端口映射出去时是「本机连本机」,且这条转发没开 Proxy Protocol(httplib 不解析),服务端看到的源地址恒为环回。若按 IP 封禁,一次外部扫描就能把隧道后面所有客户端(包括自己)锁死 15 分钟。审计里这类封禁触发记为 `AUTH_BLOCK ... scope=proxy-source-exempt`。
- 审计文件 `<exe>\logs\mcp_audit.log`(追加写,5 MB 轮转为 `.1`),每行:时间戳(毫秒)、事件、来源 IP、详情。
- `AUTH_FAIL`:UA(截断/清洗)、body 大小、是否因此被封禁。
- `AUTH_BLOCK`:封禁生效。
- `CALL_OK` / `CALL_FAIL`:`tool=`、耗时 `ms=`、响应字节数 `bytes=`。
- `CALL_DENIED`:被策略拒绝的调用(`-32006`)另记一条,含 `tool=` 与固定原因文本,见 §10.8。
- 审计**不记录** token、密码、哈希、剪贴板内容或工具返回正文。
### 9.5 N5 列表输出治理
- 列表类工具统一 `limit` / `offset`:默认 `limit=100`,硬上限 `1000`,`offset` 默认 0;非正数按默认值处理。
- `structuredContent` 统一附 `total` / `totalAll` / `offset` / `limit` / `hasMore`,与 `McpMachine.cpp` 既有约定一致(`host_list_*` / `list_network_connections` 本来就是这样)。
- `content` 摘要统一为「共 N <单位>,本次返回第 a-b 条(还有更多,可用 offset 继续取)。」;`hasMore=false` 时不再出现「继续取」的误导提示;`offset` 越界时明确写「offset 超出范围,本次返回 0 条」。
- 实现集中在 `McpInternal.h/.cpp`:`PageWindow` / `ResolvePageWindow` / `ApplyPageWindow` / `WritePageFields` / `AppendPagingProps` / `PageSummary`。
- `list_files` 仍受服务端 `ParseFileList` 的 500 条硬限制(`total=500` 且原目录确有更多条目时表示截断,不是服务端分页)。客户端侧不截断、按需扩缓冲一次性回全量;本轮未加 `truncated` 标记(要加得改服务端 `ParseFileList` 的调用约定),仍靠「`total=500` 且 `hasMore`」判断。
---
## 10. 增补(2026-10-25:A 批加固 / B 批非破坏性能力)
A 批只改服务端传输、元数据与校验,不动任何既有工具语义;B 批新增三个工具(两个写主机库、一个远程搜索)。**客户端零改动。**
### 10.1 A1/A2 传输层加固(`CMcpServer::Start`)
httplib 默认值对 MCP 场景不合适,改为显式配置:
| 项 | 默认 | 现在 | 原因 |
|---|---|---|---|
| 请求体上限 | 不限(`SIZE_MAX`) | 2 MB(超出 413 `RequestEntityTooLarge`) | 只收 JSON 参数,文件内容走子连接分块,绝不进 HTTP body |
| 读超时 | 5s | 15s | 经 frp 隧道上传参数时,单次 recv 不该 5s 就断 |
| 写超时 | 5s | 60s | `get_screenshot` 大图 base64、慢链路下 5s 会写断响应 |
| 线程池 | `max(8, 核数-1)` | 固定 32 | `chat_wait`(最长 55s)与批量只读会长期占线程 |
读超时是 **socket 空闲读超时**,不是「处理时长上限」:`search_file` 阻塞 20s、`chat_wait` 阻塞 55s 都正常返回(已实测)。
### 10.2 A3 工具注解(`McpInternal::ApplyToolAnnotations`)
- `tools/list` 每个工具都带 `annotations`:`readOnlyHint` / `destructiveHint` / `idempotentHint` / `openWorldHint`,由 `McpInternal.cpp` 的 `kToolHints` 表按名登记,末尾统一补一次。
- 未登记的工具按规范默认值处理(`destructiveHint=true`),即**新增工具必须显式登记**,漏登记只会更保守,不会误标成只读。
- 只读工具的 `destructiveHint` 一律 `false`(按规范对只读工具无意义,避免客户端误报「破坏性」)。
- `openWorldHint=false` 只给「只读服务端本机状态」的工具(`list_online_hosts` / `search_hosts` / `list_all_hosts` / `get_host_detail` / `get_activity_history` / `get_audit_log` / `get_server_status`),其余都会触达外部主机。
### 10.3 A4 `get_host_detail` 字段补全
在线主机现在返回:`id` / `name` / `online` / `ip` / `publicIp` / `location` / `group` / `os` / `version` / `exeVersion` / `clientType` / `clientPath` / `systemBits` / `programBits` / `cpuCores` / `memoryGB` / `monitors` / `screen` / `user` / `isAdmin` / `pid` / `installTime` / `activeWindow` / `rtt` / `tls`;离线主机返回 `authStatus` / `last_seen` / `install_time` 等最后记录。
注意 `memoryGB` 是 **double**:客户端 `GetMemorySizeGB()` 上报的就是浮点字符串(如 `"27.800000000000001"` 的原始形态),不能按整数解析。服务端按 1 位小数规范化,并给 jsoncpp 写入器设 15 位有效数字,避免输出 17 位噪声。
### 10.4 B1 主机库写入:`host_set_remark` / `host_set_watch_level`
- 写的是服务端本机的 `_ClientList`(`MAP_NOTE` / `MAP_LEVEL`),**只影响主控端自己的展示**:不下发命令、不改远端状态。
- 门控:`McpReadonly=0` 即可(不要求 `McpManage`);在线/离线(历史记录)主机都能写,id 在主机库中存在即可。
- `host_set_remark`:`remark` 必填(空串 = 清除),**严格 GBK 转换**(emoji、`ö` 等不可表示字符报 `-32602`),长度上限 63 GBK 字节(主机库列 `char Note[64]`)。
- `host_set_watch_level`:`level` 0–3。重复写同一值幂等。
- 写后 `SaveToFile(GetDbPath())` 落库,并用 `LVM_REDRAWITEMS` 让在线列表那一行立刻刷新(MCP 线程不直接碰 `CListCtrl`)。
- 审计只记「set/cleared + 字节数」与 `level=`,**不记录备注正文**。
### 10.5 B2 远程文件搜索:`search_file`
**链路**(旧文件管理器,不是 SimplePlugins 版):
```
主连接 COMMAND_LIST_DRIVE → 客户端建子连接 → 子连接回 TOKEN_DRIVE_LIST
→ 服务端 OnDriveList 下发 COMMAND_SEARCH_FILE [根目录 \0][模式 \0](ANSI/GBK 两个 C 串)
→ N × TOKEN_SEARCH_FILE_LIST(分片)→ TOKEN_SEARCH_FILE_FINISH
```
协议来自 `client/FileManager.cpp`(`COMMAND_LIST_DRIVE` → `LoopFileManager` → `CFileManager`)。客户端工程是 MultiByte,所有字段都是 GBK,服务端用 `Utf8ToCpExact` 严格转换,不可表示即 `-32602`。
要点:
- **模式**:不含 `*` / `?` 时客户端当成 `*pattern*`(不区分大小写的子串),含通配符时走 `WildcardMatch`。
- **递归**:客户端只有递归搜索(深度 32,最多 10000 条,跳过隐藏/系统目录与重解析点)。`recursive=false` 由**服务端按「父目录 == 根目录」过滤**实现。
- **路径归一化**:客户端用 `wsprintf("%s\\*.*")` 枚举,根目录带尾部反斜杠会拼成 `C:\\*.*` 导致 `FindFirstFile` 失败、搜索秒回 0 条。服务端统一切成正斜杠→反斜杠并去尾斜杠(`C:\` → `C:`,客户端再拼回 `C:\*.*`)。
- **超时**:`timeout_ms` 默认 20000(1000–120000)。到点先下发 `COMMAND_FILES_SEARCH_STOP`,再等 5s 收尾;收不到 `FINISH` 也返回已收到的部分结果,`finished=false`。
- **收集上限**:5000 条 / 4 MB 原始包,超出即让客户端停搜并置 `truncated=true`(保护服务端内存,整盘搜索能命中几十万条)。
- **子连接身份校验**:`TOKEN_SEARCH_FILE_LIST` / `TOKEN_SEARCH_FILE_FINISH` 都按 `context*` 比对当前 pending 的子链接,旧搜索(已放弃)的尾包一律不受理,避免迟到的 FINISH 终止新搜索。
- **已知风险(客户端既有缺陷,仓库内已修)**:`client/FileManager.cpp` 的 `SearchFilesRecursive` 曾用无界 `wsprintf` 往 `char[MAX_PATH]` 里拼路径(`strPath`、`szFullPath`),全程没有长度检查。目录一深(累计路径超过 260)就栈溢出:Debug 客户端弹 `Run-Time Check Failure #2 - Stack around the variable 'strPath' was corrupted` 并挂住搜索线程,Release 客户端静默破坏栈。MFC 文件管理器的「搜索」走同一函数,**与 MCP 无关**。源码已于 2026-10-25 修掉(commit 8f718d9,入口/逐条目长度预判);**已部署的老客户端仍带这个缺陷**,所以 `tools/mcp_smoke.ps1` 的搜索用例仍是 opt-in(`-SearchPath`)。
- **无头路由**:MFC 对话框存在时搜索结果走 `OnReceiveComplete`;只有无头子连接(MCP 调用)才会进 `MessageHandle`,所以这两条 case 只影响 MCP。`TOKEN_SEARCH_FILE_LIST` 分支**绝不 CancelIO**(后面还有 FINISH 与剩余分片)。
- 输出:`{files:[{path,name,dir,size,modified}], finished, truncated, total, totalAll, offset, limit, hasMore}`。
### 10.6 A5 冒烟测试脚本
`tools/mcp_smoke.ps1`:只调只读工具(列表/详情/搜索 + 传输层负例),断言分页字段、注解、401/413、批量汇总。
```powershell
$env:YAMA_MCP_TOKEN = '<token>'
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 # 默认 6544(Release)
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 -Base http://127.0.0.1:6545/mcp
```
token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机时加 `-SkipHost`。退出码 0/1,可接 CI。
### 10.7 明确不做的两项
- `get_clipboard`:剪贴板常含口令/令牌/私钥,属"读即泄密",且客户端没有"只读不覆盖"的现成链路;已有 `remote_clipboard` 覆盖写。需要时用 `get_screenshot` + 人工确认。
- `close_window`:`operate_window` 的 `close` 动作已覆盖(同一 `COMMAND_WINDOW_CONTROL` 链路),不重复造工具。
### 10.8 D 批:拒绝也入审计
动机:所有策略拒绝(只读模式、`Mcp*` 开关关闭、主机不支持某能力)都返回 `-32006`,而审计里只有 `CALL_FAIL`——和「参数错」「主机离线」「超时」混在一起,事后分不清「没人调过」和「被策略拦下」。
- 实现放在 `tools/call` 的统一出口(`CMcpServer` 的 HTTP 处理器),不在 24 个 `-32006` 分支里逐个埋点:成功解析响应体后多取 `error.code` / `error.message`,`code == -32006` 就追加一条
```
<时间> CALL_DENIED ip=<来源> tool=<工具名> reason=<固定英文原因>
```
同一调用仍会留下原有的 `CALL_FAIL` 行,所以 `CALL_FAIL` 的统计口径不变。
- `reason` 全部是各分支写死的英文句子(如 `File transfer is disabled: requires McpFileTransfer=1`),不含调用参数或用户输入,落盘安全;审计依旧不记录 token、参数或返回正文。
- 其他错误码(`-32602` 参数、`-32002` 主机离线、`-32001` 超时等)不额外记事件,靠 `CALL_FAIL` 行即可。
- 验证(Debug 实例):把 `McpFileTransfer` 临时置 0 重启后调 `download_file`,审计立刻出现
`CALL_FAIL ... tool=download_file ms=1 bytes=114` 紧跟 `CALL_DENIED ... reason=File transfer is disabled: requires McpFileTransfer=1`;恢复 `McpFileTransfer=1` 重启后同一调用恢复 `CALL_OK` 且无 `CALL_DENIED`。冒烟脚本 20/20 通过(未指定 `-SearchPath` 时跳过 2 个搜索用例)。
---
## 11. 增补(C 批:读侧增强,不改客户端)
### 11.1 C1 `get_audit_log` 分页与过滤
改动前每次调用都返回镜像里的全部条目(环形缓冲上限 1000 条),调用方没法只看关心的部分,日志一多就会把工具返回值撑大。
- 新增入参:`type`(类型列子串,不区分大小写,如 `MCP` 能匹配 `MCP命令执行`)、`keyword`(正文子串,不区分大小写)、`limit` / `offset`(沿用统一分页,默认 100、上限 1000)。
- 过滤在分页之前生效:`total` 是命中条数、`totalAll` 是镜像里的全部条数;`hasMore` 针对命中的条目。摘要会补一句「过滤前共 N 条」,方便判断是不是过滤写错了。
- 读取仍在 `m_cs` 临界区内完成(UI 线程会并发写入),过滤循环里先做 GBK→UTF-8 转换再比对,避免拿两种编码互相比。
- outputSchema 补 `total/totalAll/offset/limit/hasMore`(与其它列表工具一致)。
- 注意 `get_audit_log` 读的是**主界面消息镜像**,不是 `logs\mcp_audit.log`;两者的条目内容和保留策略都不同(前者是 1000 条环形缓冲,后者是 5 MB 文件滚动)。
- 验证(Debug 实例):`limit=2` 两页分别返回第 1-2 / 3-4 条且 `hasMore=true`,`offset=999` 返回「offset 超出范围」;`type=mcp` 命中 `MCP命令执行`(大小写不敏感)、`type=提示` 命中「使用提示 / 提示信息」、`keyword=监听` 命中「监听端口: 6543成功」;冒烟脚本 23/23 通过(新增分页字段、条数上限、过滤未命中 3 项断言)。
### 11.2 C2 新工具 `get_server_status`
排查「改动到底生效没有」「为什么某个工具被拒」时,原先只能靠 `list_online_hosts` 加 `get_audit_log` 侧面推断;现在有一个服务端自身的状态快照。纯内存、只读、不建子连接。
返回(`structuredContent.status`):
| 字段 | 含义 |
|---|---|
| `app_name` / `version` | 品牌名与 `BRAND_VERSION`(当前 1.4.1) |
| `exe_build_time` | exe 文件的最后写入时间=链接时间(比 `__DATE__`/`__TIME__` 可靠,后者是编译单个 .cpp 的时间) |
| `uptime_sec` | 进程已运行秒数(`GetProcessTimes` 的创建时间起算,不是开机时间,也不受 MCP 启停影响) |
| `bind` / `port` | MCP 实际监听的地址与端口(`Start` 时记录,非从配置回读) |
| `switches` | `readonly` / `terminal` / `remote_control` / `file_transfer` / `manage` / `machine` / `machine_dangerous` / `keylog` / `chat` |
| `hosts` | `online` / `offline` 台数(与 `list_all_hosts` 同源) |
| `sessions` | `pending`(一次性/管理/键盘记录挂起) / `terminal` / `remote_control` / `file_transfer` / `chat` 在飞会话数 |
| `blocked_auth_ips` | 当前处于鉴权封禁期的来源 IP 数 |
- **不返回** token、`McpCmdWhitelist` 内容或任何配置原文;`switches` 只报布尔值。
- `sessions` 各项各取各自的锁、取完即放,是「大致同一时刻」的估算值,不能当一致性快照用。
- 工具注解登记为只读 + 非破坏性 + 幂等 + 不触达外部主机;`tools/list` 总数变为 53。
- 验证(Debug 实例):返回 `Yama v1.4.1,已运行 17 秒,监听 127.0.0.1:6545;在线主机 1 台、离线 3160 台`;`terminal_open` 期间 `sessions.terminal=1`、`terminal_close` 后回到 0;冒烟脚本 26/26 通过(新增 3 项:正常返回、版本/端口/开关齐全、不含 token)。
### 11.3 C3 主机列表过滤:`list_online_hosts` / `list_all_hosts`
这两个工具原先只有分页,想找「某个分组」「某个平台」的主机只能翻页或改用 `search_hosts`(后者不支持 `client_type`,且对在线/离线的取舍规则不同)。
- 新增三个可选入参(两个工具共用同一套实现):`group` / `os` / `client_type`,均为子串匹配、ASCII 不区分大小写、AND 组合,口径与 `search_hosts` 一致。
- 过滤在分页之前生效:`total` 为命中台数、`totalAll` 为过滤前总数(`list_online_hosts` 是全部在线数,`list_all_hosts` 是主机库总数);摘要改用「共 N 台主机匹配」并补一句过滤前规模,写错条件时一眼能看出来。
- `list_all_hosts` 摘要里的在线/离线拆分也按命中条目统计。
- **离线主机没有 `clientType`**(历史记录里不存这个字段),所以带 `client_type` 条件时离线主机不会命中——按平台筛历史主机用 `os`。
- 验证(Debug 实例):`client_type=exe` 命中 1 台(`EXE`/`os=Windows 11`),`client_type=lnx` 命中 0 台但 `totalAll` 仍为 1;`list_all_hosts` 带 `group=default` 命中 3161 台并正确拆分在线 1 / 离线 3160,`os=zzz` 命中 0 台;冒烟脚本 28/28 通过(新增过滤未命中、totalAll 不变 2 项断言)。
### 11.4 C4 `search_file` 结果侧过滤
`search_file` 的搜索条件(根目录 + 通配模式)由客户端执行,改不动;但把匹配项拿回服务端后可以再筛一遍,省掉 AI 端逐条比对。
- 新增四个可选入参,**都在服务端对已收集的匹配项做过滤**,不减少客户端侧搜索耗时:
- `min_size` / `max_size`:字节数,整数,闭区间;负数或非数字返回 `-32602`;两者都给出且 `min_size > max_size` 返回 `-32602`。
- `modified_after`:接受 `YYYY-MM-DD`(当天 00:00:00 之后)或 `YYYY-MM-DD HH:MM:SS`;格式不符返回 `-32602`。客户端返回的 `modified` 是定宽 `"YYYY-MM-DD HH:MM:SS"`,可直接字典序比较,所以两种写法都合法(`"2026-01-01" <= "2026-01-01 08:00:00"`)。
- `name_only`:布尔,命中项只保留 `path` / `name` 两个字段,适合只要文件清单时省 token。
- 过滤在分页之前:`total` 为命中条数、`totalAll` 为过滤前条数;摘要补一句「过滤前共 N 条(大小/修改时间/精简字段过滤在服务端进行,不减少客户端搜索耗时)」。
- 过滤只看服务端已收到的条目,所以仍受 `max_results` / `timeout_ms` 截断:客户端没搜完时,过滤结果也是部分的(`truncated` / `finished` 字段照旧反映这一点)。
- 验证(Debug 实例,根目录 `C:\Windows\Fonts`、`*.ttf`):基线 255 条;`min_size=1000000` → 39 条且 `totalAll=255`;`name_only=true` 每条只有 `path`/`name`;`modified_after=2026-01-01` → 165 条、`2026-06-03 00:00:00` → 130 条、`2027-01-01` → 0 条;`min_size=-5`、`min_size=10 & max_size=5`、`modified_after=2026/01/01`、`modified_after=2026-01-01 12:00` 均返回预期的 `-32602`。冒烟脚本 33/33 通过(新增 3 项:`min_size` 过滤后 `totalAll` 不变、`name_only` 精简字段、非法 `modified_after` 返回 `-32602`;后三项需带 `-SearchPath` 才执行)。
## 12. 错误码速查(E 批:冒烟与文档)
工具的失败分三类,AI 端应按 `code` 决定下一步,而不是读 `message` 文本。`message` 是给人看的英文说明,随实现变化,不作为契约。
| code | 含义 | 典型触发 | 建议动作 |
|---|---|---|---|
| `-32700` | Parse error | 请求体不是合法 JSON | 修正客户端序列化 |
| `-32600` | Invalid Request | 缺 `jsonrpc` / `method` / 非法 `tools/call` 结构 | 修正请求 |
| `-32601` | Method not found | `method` 不是 `initialize` / `tools/list` / `tools/call` 等 | 修正请求 |
| `-32602` | Invalid params | 未知工具名、缺必填参数、参数类型/取值非法、批量 `ids` 超过 50 个、`search_file` 过滤参数非法、文本无法转 GBK | 改参数重试,重试同样的请求不会成功 |
| `-32001` | Timeout | 等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到) | 可加大 `timeout_ms` 重试;持续出现看主机是否卡住 |
| `-32002` | Host offline / not found | 主机 id 不存在、主连接已断、会话 id 不存在或已关闭 | 先 `list_online_hosts` 刷新再选主机 |
| `-32003` | Busy | 该主机已有同类请求在飞(终端/截屏/文件/聊天会话),或同设备重复 `chat_open`。`message` 末尾带 `(tool=..., elapsed=Ns)` 点名占用者 | 用 `mcp_list_sessions` 看全部会话;等前一个结束、先 `*_close`,或 `mcp_cancel_session` 释放 |
| `-32004` | Send failed | 命令写入主连接失败(连接刚断) | 重试一次;仍失败按 `-32002` 处理 |
| `-32005` | Not supported on this host | 能力限制,改参数也修不好:需要 Windows 的工具用在 LNX/MAC/APK 主机上;`remote_open` 遇到多显示器(阶段一);主机无屏幕预览/控制能力位 | 换主机或换工具;不要改参数重试 |
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
| `-32007` | Not in command whitelist | `exec_command` 的命令不在 `McpCmdWhitelist` 里,或词边界不匹配(`dir` 过、`dirx` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 |
| `-32012` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含 `&`/`\|`/换行;路径/参数含非法字符。**`-32008` 是同一语义的历史别名**(早期实现用它,已发布的客户端/文档可能仍在匹配),新代码一律用 `-32012` | 按 `message` 修正参数后重试 |
| `-32009` | Target not found | 远端路径/注册表键不存在(win32 `2`/`3`,由新客户端主动回报);`kill_network_connection` 的四元组在当前连接表里查不到(`dry_run` 传假四元组最常见) | 先用 `list_files`/`list_registry`(或 `host_list_network_state`)确认目标存在 |
| `-32010` | Access denied | 目标存在但权限不足(win32 `5`):非提权客户端的服务枚举(`OpenSCManager`)、受保护目录(如 `System Volume Information`)、受保护注册表键(如 `HKLM\SAM`) | **不要重试**:需客户端提权(管理员运行)或换目标 |
| `-32011` | Destination write failed | 文件传输的**目标端**已收到数据但写盘失败:`copy_files_c2c` / `upload_file` 的目标主机回了回执且 `status != 0`(`message` 带 status、首个 errno、实收文件数) | **不要原样重试**:按文案判断(errno 13/1→权限、2→路径不存在、28→磁盘满),先修目标端目录/权限 |
| `-32800` | Request cancelled | 客户端取消了这次调用:`notifications/cancelled`、`mcp_cancel_session` 或 SSE 流断开(检测到断开会置同一个取消位)。工具在 ≤1s 内退出等待并走既有的超时清理路径,主机占用已释放 | 不是主机故障,可直接重试;终止类命令可能已经执行,重试前先读一次现状 |
- **命令超时会销毁持久会话**(`terminal_exec`):等服务端收集到哨兵超时返回 `-32001`,会话随即被销毁并留 600 秒「墓碑」;对同一 `session_id` 再发命令返回 `-32002`,文案明确写 `Terminal session was destroyed after this command timed out (waited N ms); call terminal_open again`,与「id 写错」(`Terminal session not found: <id>`)区分开。
- **新客户端把失败改成结构化回报**(`TOKEN_SERVICE_ERROR=170` / `TOKEN_FILE_LIST_ERROR=171` / `TOKEN_REG_ERROR=172` / `TOKEN_DOWNLOAD_ERROR=173`,布局 `[token:1][win32 码:4 LE]`):`list_services`(未提权)、`list_files`/`list_registry`(路径/键不存在或拒绝访问)、`download_file`(远端路径全部不存在)都在客户端侧就失败并立即回报,服务端转译成 `-32009`/`-32010`,**亚秒级返回**,不再靠超时猜。老客户端不发这些包,成功路径报文一律不变,因此老客户端/老服务端的行为与改造前完全一致(老服务端把未知 token 走 `default` 丢弃)。
- **工具放弃后的「迟到首包」一律吸收,不会弹 MFC 窗口**:文件/服务/注册表/进程/日志/终端这几族的子连接都是「建成即发首包」。工具超时清理挂起后,客户端可能才把首包发上来,此时没有挂起会话,`MessageHandle` 只能把它当成人手点击,于是弹出文件管理器/服务管理器/注册表/进程管理器/日志/终端窗口(构造超时场景时实测出现过文件管理器窗口)。现在各等待函数在**放弃分支**登记「设备 → 该工具的首包 token」(`CMcpServer::MarkLateFirstPacketForTool`),包到达时 `TakeToolFirstPacket` 一次性吸收并关子连接:`list_files`/`download_file`/`upload_file`/`search_file` → `TOKEN_DRIVE_LIST`;`list_services`/`control_service` → `TOKEN_SERVERLIST`;`list_registry` → `TOKEN_REGEDIT`;`list_processes`/`kill_process` → `TOKEN_PSLIST`;`list_windows`/`operate_window` → `TOKEN_WSLIST`;`get_client_log` → `TOKEN_REPORT_LOG`;`get_activity_history` → `TOKEN_REPORT_ACTIVITY`(主连接,只丢包不关连接);`exec_command`/`terminal_open` → `TOKEN_SHELL_START` + `TOKEN_TERMINAL_START`。成功路径不登记,命中即消费,标记 5 分钟后过期。**已知代价**:同一主机在工具超时后 5 分钟内手动点开对应窗口,可能被这枚标记吞掉一次(再点即可)——比误弹窗口更可接受。
- **MCP 工具在飞时不弹客户端的老式提示框**:新客户端在失败分支同时发结构化 token 和老的 `ClientMsg`(只为兼容老服务端),后者会 `PostMessageA(WM_SHOWERRORMSG)` 在服务端 UI 上弹框。`TOKEN_CLIENT_MSG` 分支现在发现该设备有挂起请求/文件传输时就只记日志不弹框。实测 `list_services`(未提权)时客户端子连接已被服务端关掉,`ClientMsg` 根本发不出来,这条属兜底。
- **`download_file` 有停滞看门狗兜底**:60 秒没收到任何数据即失败,返回 `-32001` 且文案带 `File transfer stalled: no data received for 60s ...`。新客户端的 `TOKEN_DOWNLOAD_ERROR` 让这条路基本不再触发,看门狗只用来兜住「客户端卡住/老客户端」。
- `-32006` 会额外在审计日志里记一条 `CALL_DENIED`(§10.8),其余错误只体现在 `CALL_FAIL` 行。
- 批量调用(带 `ids[]`)**整体不报错**:每个 id 的结果单独带 `error`,顶层用 `succeeded` / `failed` / `skipped` 汇总;只有整批请求本身非法(超过 50 个 id、写操作传 `ids`)才返回顶层 `-32602`。
- 冒烟脚本 `tools/mcp_smoke.ps1` 覆盖了上表的可复现项:`-32601`(未知 method)、`-32602`(未知工具/缺参数/51 个 id)、`-32002`(不存在的主机)、`-32006`(任一开关关闭时自动挑一个关着的功能验证,并断言审计里出现 `CALL_DENIED`;全部开启时跳过)、`-32009`(新客户端的 `list_files`/`list_registry`/`download_file` 不存在路径负例)。其余码由各批次的功能验证覆盖(`-32001`/`-32003` 等需要构造竞态或超时,不进冒烟)。
- 本次验证(Debug 实例):冒烟 **40/40 通过**(原 37 项 + 3 条 `-32009` 负例);`-32010` 由 `list_services`(未提权客户端,win32=5)、`list_files "C:\System Volume Information"`、`list_registry "HKLM\SAM\SAM\Domains\Account"` 三条实测覆盖。
### 12.1 命令哨兵与输出清洗(测试报告 P1/P3/P4 的修复)
`exec_command` 与 `terminal_exec` 都靠哨兵判断「命令已执行完、退出码是多少」。哨兵有三种形态:
| 客户端 | 下发内容 | 退出码 |
|---|---|---|
| POSIX PTY(Linux,`RES_CLIENT_TYPE=LNX`) | 第一行 `PS1=`;第二行 `<cmd>`;第三行 `echo __MCP_DONE_<nonce>__$?` | 命令的真实退出码 |
| ConPTY(`is_pty=true`,新版 Windows 客户端) | 第一行 `@echo off & <cmd>`;第二行单独 `echo __MCP_DONE_<nonce>__%errorlevel%` | 命令的真实退出码 |
| 老 ShellManager 管道(`is_pty=false`) | 单行 `<cmd> 2>&1 && echo __MCP_DONE_<nonce>__0 || echo __MCP_DONE_<nonce>__1` | 仅 0 / 非 0 |
POSIX 形态与 Windows 的差别:
- **不能用 `@echo off & <cmd>` / `%errorlevel%`**:Linux 的 `bash -i` 把它们当字面量,哨兵永远不会出现,必然超时。
- **先发一行 `PS1=`**:交互式 bash 每读一行都打印提示符(`user@host:cwd$`),提示符会混进 stdout(Windows ConPTY 不会)。清空 `PS1` 后提示符消失。这一行的回显排在下发的命令行回显之前,会被「从缓冲区开头删到命令行回显结束」那一步一并切掉,不进入返回文本。
- **`$?` 是上一行的退出码**:`PS1=` 与命令各占一行,哨兵只取命令那一行的状态,未被 `PS1=` 干扰。
**为什么 PTY 要分两行下发**:`rem hello`、`cmd /c exit 0`、`if`、`for` 这类「吞行」命令会把同一行里的 `&& echo 哨兵` 一起吞掉(`rem`/`cmd /c` 把行内剩余文本当作自己的参数),哨兵永不出现,于是必然超时并销毁会话。哨兵独立成行后由 shell 自己执行,不再受命令行影响。老客户端只能维持单行形态:`client/ShellManager.cpp` 按「写入字节数」跳过回显,多写一行会吃掉上一行的输出。
**为什么用 `%errorlevel%`**:ConPTY 会把输入整行回显进输出流(80 列会折行)。回显文本里是字面 `%errorlevel%` 而不是数字,而 `FindSentinel` 只认「标记 + 数字」,折行回显再也不可能被误判成哨兵(评审 P3:`ver` 曾因回显里的 `__1` 被判成 `exit_code=1`),同时还能拿到真实退出码(如 `nosuchcmd` 的 9009)。
**输出清洗顺序**:剥 ANSI(OSC 序列以 `ESC\` 结尾时两字节一起吞,否则会残留 `\`)→ CRLF 归一 → 从缓冲区开头删到「我们下发的命令行回显」结束(顺带清掉 shell 启动画面与提示符)→ 删哨兵行回显 → **按 nonce 擦掉残留的哨兵文本** → 去首尾空行。最后一步是必需的:ConPTY 送回来的是**屏幕渲染流**(带光标移动/擦除序列),剥掉序列后同一行可能重复出现,哨兵会留下副本(实测不擦时 `rem hello` 只剩哨兵、`cmd /c echo abc` 成了 `abc__MCP_DONE_x__0`)。nonce 每条命令随机生成,命令的真实输出不可能包含它,所以按 nonce 擦除不会误伤业务输出。
**已知边界**:屏幕渲染流里「光标下移空行」会被剥成紧邻行(例如 `ping` 的统计块会贴在最后一条回复后面),不影响语义。
## 13. 增补(2026-10-26:MCP HTTPS / native TLS)
### 13.1 目标与取舍
公网 MCP 客户端(Claude Desktop、WorkBuddy 等)多数只接受 `https://` 端点,而 MCP 一直是明文 `httplib`。三条路里选了第三条:
| 方案 | 结论 |
|---|---|
| 在 vps 上用 nginx 反代加 TLS | 不行:vps 的 80/443/6544 都由 frps 持有,nginx 只在 8080,且反代会让 token 以明文经过 vps |
| 引入 OpenSSL / cpp-httplib 的 `CPPHTTPLIB_OPENSSL_SUPPORT` | 新增第三方依赖与证书/私钥加载路径,仓库已有 Schannel 实现 |
| **复用仓库既有的 Schannel 入站实现,在 MCP 端口上终结 TLS** | ✅ 零新依赖,`ServerTlsSession`/`ServerTlsIdentity` 已在设备端口跑通 |
### 13.2 结构:同端口嗅探 + 明文直通
```
客户端 ──TLS──▶ [McpTlsProxy] :McpPort ──明文──▶ httplib 127.0.0.1:McpInternalPort
客户端 ──明文─▶ │ 0x16 0x03 ? (只绑回环,不对外)
```
- `McpTlsProxy`(`McpTlsProxy.h/.cpp`)在 `McpBind:McpPort` 上监听,首包用 `MSG_PEEK` 判 TLS(首字节 `0x16` 且次字节 `0x03`,与设备端口 §5.2 同一套路):TLS 走 `ServerTlsSession::HandshakeWithCred` + `Decrypt`/`Encrypt`,否则按字节原样转发。
- 因此**同一端口两种用法并存**:本机既有的 `http://127.0.0.1:6544/mcp` 不用改,远端可以用 `https://host:6544/mcp`。
- `McpHttps=0` 时完全不启动前端,行为与改造前一致(httplib 直接监听 `McpBind:McpPort`)。
### 13.3 身份:第二份证书,独立 CNG 键名
`ServerTlsLoadIdentityFromPem(cert, key, L"YamaMcpTlsKey", id)` 构造进程内第二份入站身份,与设备端口的 `ServerTlsIdentity`(`YamaServerTlsKey`、通常自签 `CN=localhost`)并存:证书/私钥各读各的,持久化私钥用不同键名,互不覆盖。`HandshakeWithCred` 是新增的重载,设备端口仍用 `Handshake`(同一份逻辑,只是取凭据的方式不同)。
**fail-closed**:证书/私钥读不出来、CNG 导入失败、端口被占任一项失败,`McpServer::Start` 会把 httplib 一起停掉并返回 false——绝不允许「以为在跑 HTTPS、其实没在监听」。
### 13.4 实测(Debug 实例,自签证书)
| 场景 | 结果 |
|---|---|
| `https://127.0.0.1:6545/mcp`(`--cacert server.crt`)无 token | `401`,证书校验通过 |
| 同一端口 `http://127.0.0.1:6545/mcp` 无 token | `401`(明文直通未受影响) |
| TLS + token:`initialize` / `tools/list` / `tools/call get_server_status` | 正常,53 个工具 |
| 同一条 TLS 连接上连发两个请求(keep-alive) | 两次都 `200`,复用连接 |
| 错误 token | `401`(回环来源的鉴权封禁豁免仍生效) |
| 内部端口 `6546` | 只监听 `127.0.0.1` |
| `McpCertPath` 指向不存在的文件后重启 | MCP 整体不启动,无任何监听(fail-closed) |
| 公共 CA 的 ECDSA 证书(Let's Encrypt P-256 fullchain + PKCS#8 私钥) | 身份加载成功,TLS 无 token `401`、带 token `initialize`/`tools/list` 正常(53 工具) |
| 本地 CA 三级链(叶 + 中间,中间证书不在系统库) | 服务端下发 2 张证书,`openssl s_client -CAfile root.crt` 得 `Verify return code: 0` |
| 设备端口 `6543` TLS(回归) | 握手正常 |
| `McpHttps` 删除后重启(回归) | 明文明监听,无内部端口 |
### 13.5 Schannel 的一个坑(已修在共用层)
`ServerTlsSession` 原先把「首次收到的字节」直接喂给 `AcceptSecurityContext`。如果这批字节只是**半条 ClientHello**,Schannel 会先建出一个坏上下文,补齐后再送返回 `SEC_E_UNKNOWN_CREDENTIALS (0x80090301)`,握手必失败。设备端口因为累积了整包才分类、且客户端 ClientHello 通常一次到齐,一直没暴露;MCP 前端按 8 字节嗅探后接手,稳定触发。
现在 `HandshakeWithCred` 在首次 ASC 之前先凑齐**一整条 TLS 记录**(5 字节头 + 负载,上限 18432 字节,首字节非 `0x16` 或缺字节超时则 fail-closed),调用方给多少字节都行。这也顺带修好了设备端口在「ClientHello 被 TCP 分片」时的同类隐患。
### 13.6 部署公网证书
1. 把公共 CA 签发的证书链与私钥(PKCS#8)放到本机,例如 `Bin\certs\mcp-fullchain.pem` / `Bin\certs\mcp-key.pem`。证书支持 RSA 与 ECDSA(P-256/P-384/P-521),可以写成「叶证书 + 中间证书」的 fullchain(见 13.8)。
2. 「扩展 → MCP设置」勾选「启用 HTTPS」,在两行里填/浏览证书与私钥(也可直接改 ini:`McpHttps=1`、`McpCertPath=<证书>`、`McpKeyPath=<私钥>`),保存后重启 YAMA。注意「端口」填的是对外端口,httplib 自动退到 `127.0.0.1:McpPort+1`。
3. frp 的 `YAMA-MCP-*` 映射指向本机 `McpPort` 不变——TLS 在 YAMA 内终结,vps 只转发密文。
4. 证书续期后需重新拷贝 + 重启 YAMA(当前不做热加载)。
客户端配置形如:
```json
{
"mcpServers": {
"yama": {
"type": "http",
"url": "https://web.just-do-it.icu:6544/mcp",
"headers": { "Authorization": "Bearer <McpToken>" }
}
}
}
```
### 13.7 已知限制
- **按 IP 的鉴权封禁对远端不生效**:`IsAuthBlocked` 按来源 IP 计数,而经 frp 或本前端转发的请求来源都是 `127.0.0.1`,命中既有的「代理来源豁免」。因此远端的暴力尝试不受「10 次失败 / 60 秒 → 封 15 分钟」约束,真正的防线是 token 熵(32 hex ≈ 128 bit)与审计日志里的 `AUTH_FAIL` 记录。经 frp 暴露时改造前就已如此;但若改造前是把 `McpPort` 直接绑在公网地址(不经 frp),远端 IP 原本会被封禁,开启本前端后一律变成环回、不再封禁——按部署方式评估这一差异。要补需在本前端把真实来源 IP 以受信头注入 httplib 请求,属于后续工作。
- 证书不热加载:换/续证书需重启 YAMA。
- 只支持 HTTP/1.1(与 httplib 一致),不做 ALPN h2。
### 13.8 证书类型与证书链(2026-10-26 补齐)
早期实现只认 RSA:私钥一律按 `BCRYPT_RSAFULLPRIVATE_BLOB` 导出后再写入持久化键,遇到 ECDSA 证书(Let's Encrypt 自 2024 年起默认签发 P-256)会在导出处拿 `NTE_BAD_TYPE (0x8009000a)` 并报错退出。现在按**证书公钥类型**分两路落盘(`ServerTlsSession.cpp` 的 `BuildIdentity`):
| 证书公钥 | 落盘方式 |
|---|---|
| RSA | 导入 PKCS#8 为临时键 → 导出 `BCRYPT_RSAFULLPRIVATE_BLOB` → `NCryptCreatePersistedKey` + `NCryptSetProperty` + `NCryptFinalizeKey` |
| ECDSA(P-256/P-384/P-521) | 导入 PKCS#8 时在参数表里给出键名(`NCRYPTBUFFER_PKCS_KEY_NAME`),MS Software KSP 直接持久化 |
ECDSA 这条是 MS Software KSP 唯一可行的一条,其余几条均已实测不通:`NCryptCreatePersistedKey` 后写 EC 私钥 BLOB,`SetProperty` 返回 0 但 `Finalize` 给 `NTE_INVALID_PARAMETER (0x80090027)`;导入后再 `NCryptSetProperty(NCRYPT_NAME_PROPERTY)` 给 `NTE_NOT_SUPPORTED (0x80090029)`(不带键名即匿名临时键,Schannel 用不上);把临时键句柄经 `CERT_KEY_CONTEXT_PROP_ID` 挂到证书上,Schannel 报 `SEC_E_NO_CREDENTIALS (0x8009030e)`。`NCRYPTBUFFER_PKCS_KEY_NAME` 的值必须**含结尾 NUL**,少了同样报 0x80090027。曲线只支持具名 P-256/P-384/P-521,显式参数形式的曲线会带明确报错退出。
**证书链**:Schannel 的握手在进程外完成,建链时只查系统证书库——fullchain 里的中间证书塞进叶证书自带的内存库或 `paCred` 数组都不会被下发(实测只发叶证书,缺中间证书的客户端建链失败)。因此加载身份时把 fullchain 第 2 张起的证书补进「当前用户\中间证书颁发机构」库(`Cert:\CurrentUser\CA`,已在库中则跳过;.NET 的 `SslStreamCertificateContext` 也是这么做的),Schannel 建好链后随握手下发。证书文件因此可以、也建议写成「叶证书 + 中间证书」的 fullchain(Let's Encrypt 的 `fullchain.pem` 即如此)。副作用:进程所在账户的 CA 库里会多出这些中间证书(公开信息,留在库里无害)。
## 14. 增补(2026-10-26:结果外露 —— `content` 同时携带结构化 JSON)
### 14.1 问题
改造前,列表/查询类工具的 `content` 只有一句可读摘要(“共 1 台主机匹配。”),真正的载荷(`hosts[]`、`processes[]`、`files[]`、`session_id`……)只在 `structuredContent` 里。MCP 规范(Tools → Structured Content)明确建议:**返回 `structuredContent` 的工具应同时把序列化后的 JSON 放进一个 `TextContent` 块**,正是为了这种只把 `content` 交给模型的客户端。实测 WorkBuddy 就属这类:它把 `search_hosts` 的结果格式化成“共 1 台主机匹配”交给模型,`id` 完全不可见,于是后续 `get_host_detail` / `exec_command` / 终端 / 远程控制全部无从下手(用户侧表现为模型去猜 1–3100 的 id,而主机 id 是 64 位雪花值,如 `986530101822679521`,猜测不可能命中)。
### 14.2 实现
- `McpInternal::BuildResult` 统一收口:结果里 `structuredContent` 为非空对象/数组时,追加一个 `{type:"text", text:"<紧凑JSON>"}` 块到 `content` 末尾。所有工具(含 `McpMachine.cpp` / `McpChat.cpp` 的 `BuildStructuredResult` 漏斗)自动生效,新增工具无需额外处理;空 `{}`(`remote_mouse` 这类动作结果)不追加。
- 正文已经承载同一份载荷的工具用 `SetStructuredTextPayload(result, payload)` 只外露差异部分,避免同一内容在上下文里出现两三次:
| 工具 | 外露的文本块 |
|---|---|
| `exec_command` / `terminal_exec` | `{"exit_code":N}`(stdout 已在正文里) |
| `get_keylog` | `id` / `duration_ms` / `bytes` / `lineCount` / `truncated`(行内容已在正文里,最多 16 KB) |
| `get_activity_history` | `{"records":[…]}`(`activityHistory` 与 `records` 是同一份数据的两种形态) |
| `host_get_hosts_file` | `lines` + 元数据(不再重复 `content` 原文) |
- 控制键以 `$structuredTextPayload` 成员的形式挂在 result 上,`BuildResult` 消费后立即 `removeMember`,不会出现在响应里。
- 列表类工具本就有 `limit/offset` 分页,补出来的 JSON 与 `structuredContent` 同量级,不会失控。
### 14.3 验证
Debug 实例(`Bin\Yama_x64d.exe`,临时端口)实测:`list_all_hosts` 的 `content[1]` 含完整主机 JSON(`id` / `ip` / `last_seen` …),`get_server_status` 的 `content[1]` 是 `{"status":{…}}`,`search_hosts` 空结果时是 `{"hasMore":false,"hosts":[],…}`;`content[0]` 的既有摘要文案一字未改。
### 14.4 影响面
- 响应体积:列表类工具约翻倍(分页上限内),执行类工具只多一个退出码字段。
- 既有断言不受影响:摘要仍在 `content[0]`,内部批量工具(`ids` 批量调用)仍只读 `content[0].text` 并另取 `structuredContent`。
## 15. 增补(2026-10-26:`copy_files_c2c` 客户端间直传)
第 54 个工具:把文件从一台客户端**直接**发到另一台,服务端只做包中继,不落盘。复用 V2 文件传输的 C2C 通道(`FileChunkPacketV2.dstClientID != 0`),新增协议号 `COMMAND_C2C_SEND_FILES=174`(服务端给源端下路径清单)、`TOKEN_C2C_SEND_RESULT=175`(源端回传发送结果),以及能力位 `CLIENT_CAP_C2C_PATHS=0x0008`(老客户端因此被提前拒绝并提示升级)。
- 工具契约:`src_id` / `dst_id` / `paths[]` / `dst_dir` / 可选 `timeout_ms`;返回 `transfer_id` / `file_count` / `total_bytes` / `receiver_ack`。
- 开关:`McpFileTransfer=1 && McpReadonly=0`(会写远程),注解登记为破坏性 + 非只读,`McpInternal` 的 gating 表同步。
- 源端必须是 Windows 客户端(`-32005`);目标端可以是 Windows / Linux / macOS(2026-10-27 起)。POSIX 目标给绝对 POSIX `dst_dir`(`/tmp/recv`),服务端在建会话前校验形态,非法 `-32602`。
- `receiver_ack`:Linux 目标端落盘后会回一包 `TOKEN_C2C_RECV_RESULT=176`(能力位 `CLIENT_CAP_C2C_RECV_ACK=0x0010`),`true` 表示目标端确认写入、`total_bytes` 是实收值;写入失败统一 `-32011`(带 status/errno)。Windows/macOS 目标端不回执,仍为 `false`,需 `list_files` 复核。
- 实施中一个坑:服务端既有的 C2C 中继分支会在源端子连接上挂进度对话框,而 `NotifyProc` 对挂了 `hDlg` 的连接会把后续包交给对话框——源端最后那包结果就被当 V1 文件块吃掉,工具只能超时。现按「该 host 是否有 MCP 的 C2C 会话」跳过对话框,MFC 手动 C2C 不变。
- 协议细节、落盘路径语义(`dst_dir` + 相对公共父目录,Windows 与 POSIX 两种目标端)、回执与错误码映射(含 `-32011`)、限制与实测见 [Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md) §14。
## 16. 增补(2026-10-27:`download_file` / `upload_file` 支持 Linux/macOS 主机)
此前两个工具把 LNX/MAC 目标端直接拒掉(`-32005`)。现在放开,改动集中在服务端的路径门禁与 POSIX 接收端:
- **`upload_file` 不需要客户端新指令**:Linux/macOS 的文件接收走 `common/FileTransferV2.h`,`dstClientID != 0` 的包按 C2C 语义落盘,目录由包里的 name 派生。服务端按 `RES_CLIENT_TYPE` 校验 `remote_dir`:POSIX 目标必须是绝对 `/…`、不含 `\`、不含 `..` 段(`-32602`);Windows 目标行为不变。
- **`download_file`**:POSIX 文件管理器(`common/FileManager.h`)补齐两块——每个文件末尾发 `FileCompletePacketV2`(流式 SHA-256,新增 `common/sha256_posix.h`;读失败/截断不发,不谎报校验通过),以及下载失败时回 `TOKEN_DOWNLOAD_ERROR`(errno→win32,服务端转成 `-32009`/`-32010`,不用等停滞看门狗)。
- **`upload_file` 的 `receiver_ack`**:Linux 目标端会回 `TOKEN_C2C_RECV_RESULT=176`,服务端在发送完成后等 ≤5 s,`true` 表示已确认写入;回执报错 `-32011`;声明会回执却不回(且传输含字节)`-32001`。Windows/macOS 目标端仍恒为 `false`。
- **空文件**:worker 对 0 字节文件只发完成包(无路径字段),POSIX 接收端无从建文件。服务端只对 POSIX 目标补一个长度 0 的末块,接收端据此建空文件;Windows 目标的空文件仍不落地(V2 协议既有边界,未改)。
- 顺带修掉一个下载完成判定的边界:条目顺序由客户端决定,目录可能排在文件之后(如空子目录),`OnFileChunkV2` 改为按 `filesDone + directoryCount >= totalFiles` 判完成,不再出现「文件全部收完还干等超时」。
- 协议细节、POSIX 路径规则、错误码新语义与实测(含 3 MB 二进制、中文名、空文件、空目录的 SHA-256 往返)见 [Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md) §15。
## 17. 增补(2026-10-27:档 1 工具支持 Linux 客户端)
Linux 客户端(`LNX`)早已实现下面这些工具的**线上协议**,只是服务端按客户端类型一律拒绝。本次只放开服务端的判定,**不改 Linux 客户端、不加能力位**:
| 工具 | 线上协议(已存在) | 服务端改动 |
|---|---|---|
| `kill_process` | 主连接 `COMMAND_SYSTEM` → 子连接 `TOKEN_PSLIST` → `COMMAND_KILLPROCESS` + PID 数组 → 刷新列表(`linux/SystemManager.h`,`kill(SIGKILL)`,忽略 `pid<=1`) | 只拒绝 `MAC`/`APK` |
| `exec_command` | `COMMAND_SHELL` → `TOKEN_TERMINAL_START` → PTY(`common/PTYHandler.h`,`bash -i`) | 只拒绝 `MAC`;POSIX 白名单 / 元字符集 / 哨兵(§12.1) |
| `terminal_open` / `terminal_exec` / `terminal_close` | 同上,`CMD_TERMINAL_RESIZE` + `COMMAND_NEXT` 启动读线程 | 只拒绝 `MAC`;`posix` 透传到哨兵与编码(UTF-8) |
| `remote_open` / `remote_close` / `remote_mouse` / `remote_keyboard` / `remote_clipboard` | `COMMAND_SCREEN_SPY` → `TOKEN_BITMAPINFO` → `COMMAND_SCREEN_CONTROL` + `MSG64_LNX`(`linux/ScreenHandler.h`,XTest 注入);剪贴板 `COMMAND_SCREEN_SET_CLIPBOARD` | 只拒绝 `MAC`;输入事件改为**一条一包**(见下) |
要点:
- **POSIX 默认白名单是独立的一份**(`kDefaultCmdWhitelistPosix`):同名的 POSIX 命令语义与 Windows 不同(`find` 能 `-exec`、`hostname` 能改名、`sort -o` 能写文件),因此只收「参数也基本只读」的命令。`env` **刻意不收**——`env <程序>` 等于执行任意命令,会让白名单形同虚设。管理员显式配置 `McpCmdWhitelist` 时两种平台共用配置(配置者自负其责)。
- **元字符集按平台分开**:Linux 拒绝 `& | < > ;` 与反引号、`$(` `${` `!`(`!` 在交互式 bash 里触发历史展开);`^` 在 POSIX 里不是元字符,因此 `grep -v ^# /etc/hosts` 这类只读命令在 Linux 上可用,Windows 上仍按原规则拒绝。
- **输入事件一条一包**:协议允许 `[COMMAND_SCREEN_CONTROL][MSG64*N]` 批量,Windows 客户端(`CScreenManager::ProcessCommand`)也支持批量;但 `linux/ScreenHandler.h` 只处理包内第一条,批量会让 `key_press` 只按下不抬起(X11 自动重复)、`click` 只按下、`type` 只打首字符。服务端因此按消息拆包(`SendScreenCtrlEvents`),对 Windows 完全等价(它本来就一条一条处理),新老 Linux 客户端也都不用升级。
- **`remote_keyboard` 的 `type` 仍是 ASCII-only**:Linux 侧 `VKtoKeySym` 把 VK 映射为 keysym 后走 XTest,IME 组合输入做不到;非 ASCII 走 `remote_clipboard` + `Ctrl+V`(Linux 客户端把服务端下发的 GBK 转回 UTF-8 再调 `xclip`/`xsel`,需要 X11 桌面)。
- **限制**:纯 Wayland 会话无法抓屏/注入(要 X11 或 XWayland);多显示器仍按 §7.2 拒绝(Linux 客户端心跳里 `RES_RESOLUTION` 依赖 `xrandr`,没有 `xrandr` 的系统上报 `0:0*0`,按「无法判定」放行);`remote_*` 需要安装 `libX11` + `libXtst`,剪贴板需要 `xclip`/`xsel`。
- **验收**(Debug 实例 + WSL Ubuntu 24.04 客户端,WSLg `DISPLAY=:0`):`exec_command` 真实退出码(`ls` 不存在路径 → 2)、`-32007`/`-32008` 负例、`grep -v ^#` 放行、输出无提示符噪声;持久终端 `cd`/环境变量保持、`false` → 1、`;` 串联取末条、`close` 幂等;`kill_process` 杀死自己起的 `sleep` 且 `remaining` 为空、`pid 1` 被跳过;`remote_open` 返回 3840x1140、`remote_mouse` 归一化 (0.5,0.5) 落在 (1920,570)、`xev` 观测到按键/按钮成对、剪贴板中文往返 UTF-8 一致。Windows 客户端同批工具回归无变化。
## 18. 增补(2026-10-29:修掉实测报告的三个 P0)
`docs/Mcp_Test_Report_2026-10-29.md` 的 P0-1/P0-2/P0-3 有三个共同点:**inputSchema 与
outputSchema 不是同一份契约**,或者**输出体积没有上限**。三者都只改服务端(P0-3 的
Linux 半边另需客户端补一段)。
### 18.1 批量只读的 outputSchema(P0-1)
`tools/call` 带 `ids[]` 时走 `BuildBatchCall`,返回的是
`{tool, total, succeeded, failed, skipped, results[]}`;而每个工具声明的 `outputSchema`
只有单机形状。客户端按声明校验 `structuredContent`,于是**任何** `ids` 调用都以
`-32602: data must have required property 'host'` 失败——inputSchema 明写「支持 ids」,
outputSchema 却把它判死,十余个只读工具的批量能力整条不可用。
修法:`McpInternal::ApplyBatchOutputSchema(tools)` 在 `tools/list` 的最后一步(与
`ApplyToolAnnotations` 并列)给 `IsBatchReadOnlyTool` 命中的工具把 `outputSchema`
改写成 `{type:object, anyOf:[单机形状, 批量形状]}`。放最后一步是为了让三个注册点
(本文件内联 / `McpMachine` / `McpChat`)一视同仁,新增工具只要进批量清单就自动生效。
`IsBatchReadOnlyTool` 也随之从 `McpServer.cpp` 移到 `McpInternal.cpp`——清单现在同时被
`tools/call`(入口判定)和 `tools/list`(补 schema)使用,两处必须共用一份。
批量形状里的 `results[].data` 只能声明成 `object`:它就是该工具单机的
`structuredContent`,字段随工具而定。
### 18.2 `list_registry` 的根键分支(P0-2)
`path` 为空时 `BuildRegistryRoots` 只回 `keys`,而 outputSchema 把 `values` 也列进了
`required`——于是文档写的**第一种用法**(省略 path 列根键)必然 `-32602`,AI 必须先猜一个
真实键路径才能进注册表。现在 `required` 只保留 `keys`,`values` 在根键分支不返回,并在
schema 里写明这一点;同时根键分支补上 `path: ""`,让两个分支返回同一组字段(`path` /
`keys`),调用方不必按分支判断。
### 18.3 `get_client_log` 的体积与平台(P0-3)
两个症状、两个原因:
| 平台 | 症状 | 原因 |
|---|---|---|
| Windows | 返回 90,473 字符,超出客户端工具结果上限 | 快照是客户端 ring buffer 全量(最多 1000 行),工具没有 limit |
| Linux/macOS | `-32001` 稳定超时 | 客户端**根本没有处理** `COMMAND_QUERY_LOG`(只有 Windows 的 `ClientLogManager` 有),服务端永远等不到 `TOKEN_REPORT_LOG` |
服务端:`get_client_log` 新增 `limit`(默认 200,上限 2000)与 `filter`(子串,ASCII
不区分大小写),**从末尾往前取**——排障看的是最后发生了什么,不是开机第一行。返回补
`lines_total` / `lines_matched` / `lines_returned` / `truncated`。除行数外还有 64 KB
字节预算:单行可能是超长的堆栈或报文转储,只按行数截断仍会撑爆结果;末尾一行自己就超
预算时回它的尾部并置 `truncated=true`。超时文案也改成可诊断的(点明「客户端版本可能
不支持日志上报」并给出两条替代路径),而不是一句 `Timeout waiting for client log`。
客户端:新增 `common/ClientLogHandler.h`(POSIX 版,与 Windows 的 `CClientLogManager`
对应),`linux/main.cpp` 与 `macos/main.mm` 在 `COMMAND_QUERY_LOG` 分支开子连接、首包发
`TOKEN_REPORT_LOG` + `Logger::DumpMemoryLogFrom(0)`。**必须走子连接**:服务端
`MessageHandle` 的 `TOKEN_REPORT_LOG` 分支取走首包后会 `CancelIO` 关掉这条连接,回在
主连接上就是把主连接关掉(客户端当场掉线)。
### 18.4 验证与未覆盖
- 服务端 21:17:21 构建 + 两端客户端重编后实测:`ids` 批量(`get_host_detail` /
`host_list_processes` / `get_client_log`)全部 `succeeded=全数`;`list_registry` 省略
`path` 返回 5 个根键;`get_client_log` 在 Windows 上 `1000→200` 行(`truncated=true`)、
在 Linux 上正常返回 8 行,且客户端日志里 `Enter/Leave ClientLogThread` 成对、无泄漏。
明细见测试报告 §7。
- `get_activity_history` 仍是全量返回(实测 501 条),与 P0-3 同一类问题,但不在本次
三个 P0 内,留待下一轮。
- 连接器会缓存 `tools/list`,`limit`/`filter` 在重连前对模型不可见(默认参数已覆盖
P0-3 的场景),与既有的 `overwrite` 缓存问题同源。
## 19. 增补(2026-10-29:`get_activity_history` 分页,P2-1)
### 19.1 问题
`get_activity_history` 是全仓库唯一没有分页的列表类工具。客户端 `ACTIVITY_HISTORY_MAX`
= 500,`Dump()` 还会把进行中的当前窗口作为第 1 条,所以一次返回上限约 501 条——实测
正是 501 条。每行含窗口标题(可能很长),501 行直接把上下文冲爆;而报告里那份数据还
混着大量个人浏览、求职、签证页面,属于「不该被整包塞进模型上下文」的典型。
### 19.2 顺序:为什么可以直接用 `limit`/`offset`
`ActivityHistory::Loop()` 用 `m_records.push_front(...)` 维护,`Dump()` 又把当前进行中
的窗口拼在最前面——**返回顺序天然是「新在前」**。于是 `offset=0` 就是最近 `limit` 条,
不必像「新在后」的日志那样先取一次 `total` 再倒算 `offset=total-limit`。这条顺序不是
本次新增的约定,是客户端本来就这样,写进描述是为了让模型敢直接用 `offset=0`。
### 19.3 实现
- `inputSchema` 从 `BuildGetHostDetailInputSchema()` 换成 `BuildPagedHostListInputSchema()`
(`{ id | ids }` + `limit`/`offset`,与 `list_processes` / `list_windows` 同一套);
- `outputSchema` 追加 `AppendPageOutputProps()` 与 `truncated`;
- 实现里把原来的 `records` 改名 `all`(全量拆行结果),再 `ResolvePageWindow` +
`ApplyPageWindow` 切出 `records`,`WritePageFields` 写回 `total`/`totalAll`/`offset`/
`limit`/`hasMore`;
- **`activityHistory` 必须按窗口重建**:它原来是 `Dump()` 的整包原文,如果原样返回,
501 行的正文照样进上下文,等于没分页。现在它是窗口内 `records` 的按行拼接,语义仍是
「同一份数据的纯文本形态」;
- 再加 64 KB 字节预算(与 `get_client_log` 同口径),从窗口**末尾**裁——保留最新的那些。
裁断时 `truncated=true`;`hasMore` 按 `offset + returned < total` 算,而不是一律置 true
(末尾单条自己超预算时不该再报还有下一页)。调用方用 `offset + returned` 继续取;
- 至少保留 1 条:单条超预算时若不保底,`returned=0` 会让调用方在同一个 `offset` 上原地
打转。窗口标题达到 64 KB 几乎不可能,这是纯兜底。
### 19.4 批量
`get_activity_history` 在 `IsBatchReadOnlyTool` 名单里,`BuildBatchCall` 会把 `ids` 摘掉、
其余参数原样透传给单机调用,所以 `ids` + `limit` 等于「每台各取最近 N 条」,不需要额外
处理。P0-1 的 `anyOf:[单机, 批量]` 包装也自动覆盖新增字段。
### 19.5 未做
- 没有 `filter`(按窗口标题子串)。报告没提,且客户端标题是 UTF-8、过滤要按字节子串做,
与 `get_client_log` 的 `filter` 不同源,等有实际需求再加。
- 没有 `since`(按时间起点取)。记录里的时间是 `[YYYY-MM-DD HH:MM:SS]` 文本前缀,做时间
过滤得先解析每行;当前 `limit/offset` 已够用。
+309 -4
View File
@@ -1,6 +1,6 @@
# YAMA MCP 文件传输功能设计(download_file / upload_file)
# YAMA MCP 文件传输功能设计(download_file / upload_file / copy_files_c2c)
> **状态**:设计定稿(经专家审查修订,结论见 §13)。`download_file`(P1)已实施并验收;`upload_file`(P2)已实施(详见 §7,评审修订见 §13.1)。`download_file` 采用 **V2 文件传输协议**(`CMD_DOWN_FILES_V2` + 流式子连接 + SHA-256 校验),`upload_file` 复用服务端既有 `FileBatchTransferWorkerV2`(主连接同步驱动)。两者共享同一套「文件会话」注册表。
> **状态**:设计定稿(经专家审查修订,结论见 §13)。`download_file`(P1)已实施并验收;`upload_file`(P2)已实施(详见 §7,评审修订见 §13.1)。`copy_files_c2c`(P3,客户端间直传、服务端只中继)已实施(见 §14)。`download_file` 采用 **V2 文件传输协议**(`CMD_DOWN_FILES_V2` + 流式子连接 + SHA-256 校验),`upload_file` 复用服务端既有 `FileBatchTransferWorkerV2`(主连接同步驱动),`copy_files_c2c` 复用 V2 的 C2C 中继(`dstClientID != 0`)。三者共享同一套「文件会话」注册表。
> **读者**:MCP 后续功能研发/评审人员。
> **关联文档**:[Mcp_Phase2_Design.md](./Mcp_Phase2_Design.md)(双模式无头驱动机制)、[FILE_TRANSFER_V2.md](./FILE_TRANSFER_V2.md)(V2 协议清单)、[Mcp_Design.md](./Mcp_Design.md)(Phase 1 协议/架构/配置)。
@@ -175,7 +175,7 @@ MCP工具线程 服务端 MessageHandle
- 发 `CMD_DOWN_FILES_V2` 前把 `local_dir` 规范化为绝对路径并 `CreateDirectory`;`targetDir` 用 ANSI(MBCS 构建本机路径)。
- 每收到一个 chunk,校验其 `filename` 规范化后**前缀必须在 `local_dir` 内**(防 `..` 穿越,呼应 `FILE_TRANSFER_V2.md §8.3` 已识别的风险);逃逸则置 `error` 并 `CancelIO`。
- 编码:`remote_path` 走 UTF-8→ANSI(936)(Windows 客户端,复用 `McpServer.cpp` 既有 `ToAnsi`,与 `list_files` 一致)。
- 编码:`remote_path` 走 UTF-8→ANSI(936)(复用 `McpServer.cpp` 既有 `ToAnsi`,与 `list_files` 一致)。POSIX 目标端的路径规则见 §15。
### 6.5 超时与并发
@@ -248,7 +248,7 @@ MCP工具线程 主连接 (ctx→Send2Client)
- V2 无接收方→发送方 ACK:客户端 `HandleFileCompleteV2` 校验失败只打日志(`RecvFileChunkV2` 返回 8,`KernelManager.cpp:1381` 不回传主控)。
- **P2 的 `output.files[].sha256` 恒为空串**:`FileBatchTransferWorkerV2` 内部会为每个文件自算 SHA-256 并写入 `COMMAND_FILE_COMPLETE_V2` 包发给客户端,但该值**不回传调用方**;服务端侧又无导出的 SHA-256 工具函数可自行复算。故 P2 输出不填 sha256(延后 P3:worker 回传哈希,或服务端引入 SHA-256 工具)。传输完整性仍依赖客户端本地 `HandleFileCompleteV2` 校验(与 GUI upload / C2C 同权,属 V2 协议既有边界,非 MCP 引入)。
- 若未来需要「接收方验真回执」,需新增反向 ACK 包(协议扩展,进 P3)。
- 若未来需要「接收方验真回执」,需新增反向 ACK 包(协议扩展,进 P3)——**Linux 目标端的 `receiver_ack` 已实现**,复用 §14 的 176 回执(见 §15),Windows 目标端仍为 `false`。
### 7.6 overwrite 语义
@@ -309,6 +309,8 @@ int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hm
| (P2)`server/2015Remote/McpServer.h` | `FileTransferSession.tool` 增 `"upload_file"`;新增 `BeginFileUpload(id)`(单设备单传输互斥标记) |
| (P2)`server/2015Remote/McpServer.cpp` | `upload_file` schema/实现:无头回调 `UploadSendChunkHeadless` + `CollectLocalFiles` 收集 + overwrite 预检(复用 `list_files` 链路)+ 驱动 `FileBatchTransferWorkerV2`(复用主连接,无子连接路由) |
| (P2)`client/KernelManager.cpp` | `COMMAND_SEND_FILE_V2` 分支加懒初始化 `InitFileUpload`(`g_status` 由 0 置 1,见 §7.8) |
| (2026-10-27)`common/FileTransferV2.h` | POSIX 接收端:发送 `FileCompletePacketV2`(含流式 SHA-256)、下载失败回 `TOKEN_DOWNLOAD_ERROR`(errno→Win32 映射);见 §15 |
| (2026-10-27)`common/sha256_posix.h` | 新增:POSIX 侧最小流式 SHA-256(Windows 侧仍走 BCrypt,见 `common/VerifyV2.h`) |
**客户端**:`UploadToRemoteV2` / `RecvFileChunkV2` / `FileBatchTransferWorkerV2` 均已存在、未改动;仅 `COMMAND_SEND_FILE_V2` 分支新增懒初始化(见 §7.8)。
@@ -394,3 +396,306 @@ int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hm
| U7 | 实施验证发现:客户端主连接 `g_status==0`,`RecvFileChunkV2` 逐 chunk `return -1`(上传落盘 0 字节/截断) | 客户端 `COMMAND_SEND_FILE_V2` 分支加懒初始化(§7.8):`static` 一次 + 永久引用计数、析构不 `Uninit`;与 `FileManager.cpp:40` 参数一致,独立评审确认无稳定性风险 |
**判定**:7 项均已写入 §7 对应小节,无阻塞项,**定稿**。
### 13.2 实施后修复记录(2026-10-25)
| # | 问题 | 修复 |
|---|---|---|
| R1 | **纯目录树下载必超时**:完成判定 `filesDone >= totalFiles - directoryCount` 只在 `OnFileCompleteV2` 里跑,而客户端对目录项不发 `COMMAND_FILE_COMPLETE_V2`。空目录/只有子目录的树期望文件数为 0,永远等不到 COMPLETE → 只能干等 `timeout_ms`(默认 600s)后报 `1002` | `OnFileChunkV2` 的目录分支里,`directoryCount >= totalFiles`(即全部条目都是目录)时直接置 `done` + notify。实测空目录 0.2s 返回、3 文件目录树回归正常 |
| R2 | **断线无清理 → 悬空子连接指针**:`FileTransferSession.fmSubCtx / streamSubCtx` 是裸 `context*`,`OfflineProc` 只清了终端/远程控制/聊天,没有文件传输的钩子(§6.5 声称的「断线擦会话」实现缺失)。客户端传输中掉线后 connection 被连接池回收,工具线程超时路径仍对其 `CancelIO()` → 悬空指针/误取消他人连接 | 新增 `m_FileXferContextToDevice` 反查表(受 `m_FileXferMutex` 保护,`ClearFileTransfer` 同步擦除),`OfflineProc` 增 `OnFileTransferContextClosed`:清指针并移除反查项;**流式子连接**断开即判失败(`error=1003`,立即唤醒工具线程),文件管理器子连接断开只清指针(数据走流式子连接,不判失败)。实测传输中杀掉客户端:1s 返回 `Connection lost`(原来要等满 `timeout_ms`),服务端存活;重启客户端后连续两次下载、一次上传均正常 |
---
## 14. 增补(2026-10-26):C2C 直传 `copy_files_c2c`
### 14.1 动机
运维里经常要在**两台客户端之间**拷文件。此前的变通流程是「`download_file` 拉到主控本机 → `upload_file` 再推上去」,数据在服务端磁盘上落一遍、两倍耗时。文件传输 V2 本身已经支持 C2C:`FileChunkPacketV2.dstClientID != 0` 时,服务端把包**原样中继**给目标客户端,目标端在自己的主连接上 `RecvFileChunkV2` 落盘,服务端不解析、不落盘。
但客户端现有的 C2C 入口只有一个 `COMMAND_CLIPBOARD_V2`(Ctrl+V),文件来源固定是本端剪贴板/资源管理器选中项,服务端无法指定路径。因此新增一条「服务端给源端一份显式路径清单」的命令。
### 14.2 协议(`common/commands.h` / `common/file_upload.h`)
```cpp
CLIENT_CAP_C2C_PATHS 0x0008 // LOGIN_INFOR 能力位,仅 Windows 客户端置位(源端)
CLIENT_CAP_C2C_RECV_ACK 0x0010 // 作为目标端会回执落盘结果,目前仅 Linux 客户端置位(macOS 不置位)
COMMAND_C2C_SEND_FILES = 174, // 服务端 → 源客户端主连接
TOKEN_C2C_SEND_RESULT = 175, // 源客户端 → 服务端(源端自开的传输子连接上)
TOKEN_C2C_RECV_RESULT = 176, // 目标客户端 → 服务端(目标端主连接上)
```
| 包 | 布局 | 说明 |
|---|---|---|
| `C2CSendFilesPacket` | `cmd(1) transferID(8) srcClientID(8) dstClientID(8) hash(64) hmac(16) flags(1)` = 106 B | 后接 `dst_dir\0`,再是 `path1\0 … pathN\0`,以额外一个 `\0` 结束(ANSI/936) |
| `C2CSendResultPacket` | `cmd(1) transferID(8) dstClientID(8) status(4) win32err(4) workerRc(4) fileCount(4) totalBytes(8)` = 41 B(`#pragma pack(1)`) | 175:`status` 0=全部发出、`FEV2_FILE_NOT_FOUND`/`FEV2_ACCESS_DENIED`(带首个 win32 码)、1001=发送线程失败(看 `workerRc`)。176:`status` 0=全部落盘成功,否则为映射后的 `FEV2_*`;`win32err` 位置放**首个 errno**;`workerRc` 恒 0 |
老客户端不认识 174(服务端按 `CLIENT_CAP_C2C_PATHS` 提前拒绝,`-32005` 提示升级);老服务端不认识 175/176,走 `default` 丢弃,无兼容风险。回执用**独立的 176**而不是复用 175:同一台主机可能同时是 A 传输的目标端和 B 传输的源端,复用会让服务端把回执误当成源端结果去 latch `done`。
### 14.3 客户端(`client/KernelManager.cpp`)
1. `OnC2CSendFiles`:解析 `dst_dir` 与路径清单 → `ExpandEnvironmentStringsA` 展开 `%VAR%` → 目录按 `CollectFilesRecursiveV2` 同语义**递归展开,且目录项本身也入列**(目标端据此建空目录)→ 统计 `fileCount/totalBytes`。
2. `EnsureV2TransferInited()`:`FileBatchTransferWorkerV2` 依赖进程级的 `InitFileUpload`(`g_status==1`),否则直接返回 -1。源端可能从未打开文件管理器、也没接收过上传,所以发送前显式初始化;与接收分支共用同一份 `static` 一次性初始化(`InitFileUpload`/`UninitFileUpload` 成对,重复 Init 会重置状态)。
3. 新开一个 `EnableSubConnAuth()` 的子连接 → `FileBatchTransferWorkerV2(files, targetDir=dst_dir, …, opts{dstClientID=dst, enableResume=false})`,回调即 `Send2Server`。子连接经 `TOKEN_CONN_AUTH` 校验后,服务端把它钉成源主连接的 clientID。
4. 发送结束后**在同一条子连接上**回 `C2CSendResultPacket`,然后关闭子连接。任何早退分支(路径非法/全部不可访问/连不上服务端)都先回一包结果——否则工具侧只能干等超时。
### 14.4 服务端
- **会话**:`BeginC2CTransfer(src, dst, transferID)` 把会话键在**源**设备上(`tool="copy_files_c2c"`、`dstClientID`),与 `m_Pending`、目标端文件会话双向互斥;`WaitC2CDone` 只等源端那包结果,**没有停滞看门狗**(源端全程只在最后回一包,大文件中途静默是正常的),只有总超时。
- **中继**:完全复用 `COMMAND_SEND_FILE_V2` / `COMMAND_FILE_COMPLETE_V2` 的 `dstClientID != 0` 分支,零改动。
- **必须抑制源端的进度对话框**(实施中踩到的坑):该分支原本会在源端子连接上挂一个 `CDlgFileSend` 显示进度。而 `NotifyProc` 对**挂了 `hDlg` 的连接**会把后续包交给对话框的 `OnReceiveComplete`——源端最后那包 175 就被当成 V1 文件块解析(服务端 trace 里是 `RecvFileChunk failed: 3`),MCP 侧只会超时。现在用 `IsC2CTransferPending(src, dst)` 判定:MCP 发起的 C2C 不建对话框,包照常落到 `MessageHandle`;MFC 手动 C2C(Ctrl+V / 文件管理器)行为完全不变。
- **落盘位置**:目标端收到的目录是 `dst_dir`,文件名取各路径**相对公共父目录**的部分(库内 `GetCommonRoot` 语义)。例如发 `D:\data\a.txt` 与 `D:\data\sub\`,目标是 `C:\backup`,则得到 `C:\backup\a.txt`、`C:\backup\sub\b.bin`;`dst_dir` 不存在时由接收端自动创建。
- **Windows 目标**:`dst_dir` 必须是绝对 Windows 路径(`C:\backup`),服务端补尾部 `\` 后交给源端拼接。
- **Linux/macOS 目标**:`dst_dir` 必须是绝对 POSIX 路径(`/home/user/incoming`、`/tmp/recv`),不得含 `\`。源端仍然只是把 `dst_dir` 与相对路径**纯字符串拼接**(`targetDir + relPath`,库内不经过任何 Windows 路径 API),因此得到 `"/tmp/recv\sub\b.bin"`;POSIX 接收端 `GetTargetDir()` 为空时会把 `\` 归一化成 `/`、去盘符、补前导 `/` 再 `MakeDirs`,正好落到 `/tmp/recv/sub/b.bin`。这条路径不需要改 Windows 客户端。
- 目标端类型来自 `RES_CLIENT_TYPE`(`LNX`/`MAC` 视为 POSIX),服务端在**建会话前**校验形态,不合法直接 `-32602`。
- **目标端回执**:目标端声明 `CLIENT_CAP_C2C_RECV_ACK`(当前只有 Linux)时,服务端在源端结果之后再 `WaitC2CReceiver`(≤5 s,250 ms 切片)等一包 176;没有该能力位的目标端(Windows、macOS、老客户端)直接跳过,不增加任何延迟。回执状态记在 `FileTransferSession` 的 `recv*` 字段,与源端的 `done/status` 互不覆盖。
### 14.5 工具契约
入参:`src_id`、`dst_id`(必填,且不得相同)、`paths`(必填,文件或目录,1..N,源端 Windows 绝对路径)、`dst_dir`(必填,绝对路径;Windows 目标用 `C:\x`,Linux/macOS 目标用 `/x`)、`timeout_ms`(默认 600000,上限 3600000)、`overwrite`(默认 `false`,见 §14.9)。
出参(`structuredContent`):`transfer_id`、`src_id`、`dst_id`、`dst_dir`、`file_count`、`total_bytes`、`receiver_ack`、`skipped`、`skip_check_failed`。
`receiver_ack` 三种取值:
- `true` 且 `status==0`:目标端已确认全部条目落盘(`file_count`/`total_bytes` 是**目标端实收**值,与源端统计一致)。
- `false`:目标端不支持回执(Windows/macOS/老客户端),或目标端中途断线——源端只保证「包已全部发出」,请用 `list_files` 复核。
- 目标端回执报错时工具**不返回** `structuredContent`,而是下面的 `-32011` 错误。
| 码 | 触发 |
|---|---|
| `-32602` | 缺参 / id 非法 / 源目标相同 / `paths`、`dst_dir` 含 `..` 段或内嵌 NUL / 编码无法转 936 / POSIX 目标的 `dst_dir` 不是绝对 `/…` 或含 `\` |
| `-32002` | 源或目标主机不在线 |
| `-32003` | 源或目标已有在飞传输(单设备单传输) |
| `-32004` | 命令下发失败 |
| `-32005` | 源端是老客户端(无 `CLIENT_CAP_C2C_PATHS`)、或源端是 Linux/macOS(目标端可以是 Linux/macOS) |
| `-32006` | `McpFileTransfer=0` 或 `McpReadonly=1`(改远程);任一端不支持 V2 |
| `-32009` / `-32010` | 源端路径不存在(win32 2/3)/ 拒绝访问(win32 5) |
| `-32011` | **目标端写入失败**:收到 176 回执且 `status != 0`;文案带 status、首个 errno(13/1→权限、2→路径不存在、28→磁盘满)与实收文件数 |
| `-32001` | 等源端结果超时(传输可能仍在进行);或**支持回执的目标端在源端完成后 5 s 内没有回执**(对 `total_bytes>0` 的传输才判失败;全空文件传输没有数据块、目标端无从学到 `totalFiles`,按无回执处理) |
### 14.6 限制
- **回执只覆盖 Linux 目标端**:Windows 目标端(V2 接收实现里没有回执通道)与 macOS(`macos/main.mm` 的客户端对象是函数内局部变量,没有全局主连接句柄)仍是 `receiver_ack:false`,只能确认「包已全部发出」,要确认落盘请用 `list_files` 核对目标端。
- **不做断点续传**(`enableResume=false`):C2C 的续传查询/应答会多两跳,v1 从简;失败即整包重发。
- **源端必须是 Windows 客户端**(`CLIENT_CAP_C2C_PATHS` 只有 Windows 置位);目标端可以是 Windows / Linux / macOS。
- **POSIX 目标的路径限制**:`dst_dir` 与文件名的 UTF-8 → ANSI 转换固定用 CP936(协议字段没有编码标志位),GBK 无法表示的字符(如 `ö`、`ß`)会变成 `?`;POSIX 目标的 `dst_dir` 必须是绝对 `/…` 且不含 `\`;Linux 侧文件名按收到的字节原样落盘(大多是 GBK 字节),在 UTF-8 环境里 `ls` 会显示为乱码但内容与 SHA-256 正确。要根治需要为 V2 名字字段引入 UTF-8 标志位,本次不做。
- **空文件不会被创建**(协议现状,与目标端类型无关):worker 对 0 字节文件不发数据块,只发 `FileCompletePacketV2`,接收端没有对应分支去 `open(O_CREAT)`。空**目录**会创建。
- 一次只允许一对主机间的单个传输(源、目标各自都要求空闲),避免与 `download_file`/`upload_file` 抢同一主机的连接。
### 14.7 验证(Debug 实例 + 两个 Debug 客户端副本,同一台机器不同目录 → 不同 client_id)
数据确实走「源客户端子连接 → 服务端中继 → 目标客户端主连接」:
| 用例 | 结果 |
|---|---|
| 发 2 个文件(其一中文名)+ 1 个目录(含 3 MB 二进制与空子目录) | 3 个文件 SHA-256 全对,空目录被创建,`file_count=3`、耗时 3.2s |
| `dst_dir` 不存在(`…\recv\fresh\nested`) | 自动创建,文件到位 |
| `src_id == dst_id` / 源路径不存在 / 目标离线 / `dst_dir` 含 `..` | `-32602` / `-32009`(win32=3) / `-32002` / `-32602` |
| `tools/mcp_smoke.ps1`(含主机类工具,41 项) | 全通过;新增 `copy_files_c2c` 同主机 `-32602`、目标离线 `-32002` 两项 |
### 14.8 增补(2026-10-27):Linux 作为目标端 + 落盘回执
改动面:服务端门禁按目标端类型校验 `dst_dir`(§14.4);Linux 接收端 `common/FileTransferV2.h` 统计每个
`transferID` 的定案条目,全部定案后从主连接回一包 `TOKEN_C2C_RECV_RESULT`(176);服务端新增
`OnC2CRecvResult` / `WaitC2CReceiver`,在源端结果之后等回执并把它变成 `receiver_ack` 或 `-32011`。
接收端记账要点(都在 `FileTransferV2.h` 的 `RecvProgress` 里):
- 条目定案有三个来源:**目录项包**(`FFV2_DIRECTORY`,无 LAST_CHUNK)、**最后一块数据**、**空文件的完成包**;
源端重发(最多 3 次)与「最后一块 + 完成包」都会重复命中同一 `fileIndex`,用 `doneFiles`/`doneDirs` 去重。
- `totalFiles` 只能从数据块/目录包学到(`FileCompletePacketV2` 没有该字段);目录项也计入 `totalFiles`,
所以判据是 `doneFiles + doneDirs >= totalFiles`。
- `errno` 只在失败瞬间有效,open 失败处紧接着就有 `Mprintf`,因此在失败点立刻取值再传递;
`fstat` 复核最终大小,大小不符记 `EIO`。
- 回执在锁外发送;`reply->IsConnected()` 失败只记日志,不影响已落盘的文件。
验证(Debug 实例 6543/6546,WSL Ubuntu 24.04 里新编译的 `linux/ghost` 以 yuan(1000) 运行):
| 用例 | 结果 |
|---|---|
| Windows → Linux,`dst_dir=/tmp/yama_c2c/recv`,2 个文件(其一中文名)+ 目录(含 3 MB 二进制与空子目录) | 3 个文件 SHA-256 全对、`sub/empty` 空目录已建,`receiver_ack:true`、`file_count=3`、`total_bytes=3147539`(与源端一致),耗时 3.2 s |
| `dst_dir=/tmp/yama_c2c/fresh/nested`(不存在) | 自动创建,`receiver_ack:true` |
| POSIX 目标给 `dst_dir=C:\tmp\x` | `-32602` "use an absolute POSIX path such as /home/user/incoming" |
| POSIX 目标给不可写位置 `/proc/yama_c2c` | `-32011` "no such file or directory (status=3, errno=2, files=1)" |
| 只发一个 0 字节文件 | 成功返回、`receiver_ack:false`(无数据块 → 接收端学不到 `totalFiles` → 不回执),**不误报** `-32001` |
| 只发一个空目录 | 目录包携带 `totalFiles` → 回执到达,`receiver_ack:true`、`file_count=0`,目录已创建 |
| Windows → Windows 回归(原 c2c_test 用例) | 全部与改动前一致,`receiver_ack:false`,耗时 3.2 s(未增加等待) |
| `upload_file`/`download_file`(`dstClientID=0`) | 不进回执分支(`FinishC2CItem` 首行即 `dstClientID==0` 返回),行为不变 |
---
## 15. 增补(2026-10-27):`download_file` / `upload_file` 支持 Linux/macOS 主机
§6/§7 的原始实现只允许 Windows 目标端(LNX/MAC 直接 `-32005`)。本次打通:
- **`upload_file`(主控 → 目标端)**:不需要客户端新指令。POSIX 接收端本来就实现了 `COMMAND_SEND_FILE_V2`
(`common/FileTransferV2.h`),`dstClientID != 0` 的包按 C2C 语义处理,目标目录由包里的 name 派生
(§14.4 的 POSIX 规则)。服务端只放开门禁 + 按目标端类型校验 `remote_dir` 形态。
- **`download_file`(目标端 → 主控)**:走客户端文件管理器子连接的 `CMD_DOWN_FILES_V2`,Linux/macOS 的
文件管理器在 `common/FileManager.h` 里(与 Windows `client/FileManager.cpp` 同构)。缺的两块在 POSIX 接收侧补齐:
### 15.1 接收端改动(`common/FileTransferV2.h`,Linux 与 macOS 共用)
1. **发送 `FileCompletePacketV2`**(`SendFilesV2` 每个文件末尾):`cmd(1) transferID(8) srcClientID(8)
dstClientID(8) fileIndex(4) fileSize(8) sha256(32)`,SHA-256 边读边算(新增 `common/sha256_posix.h`,
自包含流式实现;Windows 侧继续用 BCrypt)。服务端 `OnFileCompleteV2` 凭它计 `filesDone` 并校验摘要——
没有它 MCP 的下载会话永远等不到完成判定。
- 读失败 / 文件在传输中被截断(短读):仍把末块发出去,但**不发**完成包(不谎报校验通过),服务端按
`fileSize` 收不全而失败。
- 发送失败(`Send2Server` 返回 false)同样不发完成包。
2. **下载失败回 `TOKEN_DOWNLOAD_ERROR`**:`[cmd:1][win32err:4 LE]`,与 Windows `CFileManager::SendDownloadError`
一致。触发点:`remote_paths` 为空(win32 87)、所有路径 stat 失败 / 展开后无文件(首个 errno 映射
`ENOENT/ENOTDIR→2/3`、`EACCES/EPERM→5`,其余→2)。服务端据此立即失败,不用等停滞看门狗。
### 15.2 服务端改动(`server/2015Remote/McpServer.cpp`)
- `BuildDownloadFile` / `BuildUploadFile`:`RES_CLIENT_TYPE` 为 `LNX`/`MAC` 时按 POSIX 校验路径:
**必须以 `/` 开头、不得含 `\`(会被客户端 `WinPathToLinux` 归一化成 `/`,语义会漂)、不得含 `..` 段**,
否则 `-32602` 并给出示例;`upload_file` 的 `remote_dir` 单独给 `/` 是合法的(写到根目录,通常因权限回 `-32011`)。
Windows 目标端行为与之前逐字节一致。
- `BeginFileUpload(device_id, transfer_id)` 现在登记 `dstClientID`/`transferID`,`OnC2CRecvResult` 同时匹配
`copy_files_c2c` 与 `upload_file` 的会话(键分别是源端与目标端,都用 `dstClientID + transferID` 定位)。
`upload_file` 因此也能拿到真实回执:Linux 目标端声明 `CLIENT_CAP_C2C_RECV_ACK`,发送完成后等 ≤5 s,
`receiver_ack` 参与输出。
- **空文件(仅 POSIX 目标)**:`FileBatchTransferWorkerV2` 对 0 字节文件不发数据块,只发完成包,而完成包
没有路径字段,POSIX 接收端无从建文件(会「回执成功但文件不存在」)。服务端在驱动 worker 前,为每个
0 字节文件补一个长度 0 的 `FFV2_LAST_CHUNK` 块(名字拼法与 worker 一致:`targetDir + relPath`),
接收端据此 `open(O_CREAT)`;随后 worker 的完成包只用于去重。**Windows 目标端不注入**——保持原有行为
(Windows 目标端的空文件仍不会被创建,属 V2 协议既有边界,见 §14.6)。
- 下载完成判定(F4 的补强):条目顺序由客户端决定,目录可能排在**最后**(如空子目录),所以
`OnFileChunkV2` 的目录分支现在按 `filesDone + directoryCount >= totalFiles` 判完成。此前只比目录数,
目录排在文件之后时整次下载会干等到超时(实测 4 个文件全部 COMPLETE 后仍卡 60 s)。
### 15.3 工具契约变化
| 工具 | 变化 |
|---|---|
| `download_file` | 支持 LNX/MAC 目标端(`remote_path` 用绝对 POSIX 路径);新增错误来源 `-32009`/`-32010`(来自客户端 `TOKEN_DOWNLOAD_ERROR`) |
| `upload_file` | 支持 LNX/MAC 目标端(`remote_dir` 用绝对 POSIX 路径);输出新增 `receiver_ack`(boolean);新增 `-32011`(目标端回执报写入失败)与 `-32001`(声明会回执却不回,且传输含字节) |
`upload_file` 的错误补充(其余码与 §7.7 一致):
| 码 | 触发 |
|---|---|
| `-32011` | 目标端回了 176 且 `status != 0`;文案带 status、首个 errno、实收文件数(13/1→权限、2→路径不存在、28→磁盘满) |
| `-32001` | 传输完成但支持回执的目标端在 5 s 内没有回执(目标端可能中途掉线);全 0 字节的传输不判失败(接收端学不到 `totalFiles`,无从回执) |
`receiver_ack` 语义与 §14.5 一致:`true` 只可能来自 Linux 目标端;Windows 目标与 macOS 目标恒为 `false`
(macOS 编译侧 `macos/main.mm` 没有全局主连接句柄,本次未接线),要确证落盘请用 `list_files` 复核。
### 15.4 验证(Debug 实例 6543/6546,WSL Ubuntu 24.04 的 `linux/ghost` 以 yuan(1000) 运行)
源目录含:`a.txt`(12 B)、`empty.txt`(0 B)、`sub/b.bin`(3 MB)、`emptydir/`、`中文名.txt`(14 B)。
| 用例 | 结果 |
|---|---|
| `upload_file` → `/tmp/yama_mcp/final` | 4 文件 + 空目录到位,SHA-256 全对(`ddda4069…`/`e3b0c442…`/`834dcf1d…`/`b2a71864…`),`receiver_ack:true`,`total_bytes=3145754` |
| 同上 `overwrite=false` 重传 | 全部跳过(`skipped=4`),不发包 |
| `download_file` 整目录 | 4 文件 + 空目录,SHA-256 全对,`total_bytes=3145754` |
| 单文件 / 单文件中文名 / 只含空子目录的目录 | 均成功(后者 0.2 s 级返回,不再等超时) |
| `download_file` 不存在的路径 | `-32009`(errno 2 → win32 2) |
| `remote_path` 给 `C:\tmp\x` 或含 `..` | `-32602` |
| `upload_file` 到 `/` 或 `/root/yama_x`(非 root) | `-32011`(errno 13/2) |
| Windows 目标端 `upload_file` / `download_file` / `copy_files_c2c` 回归 | 与改动前一致(Windows 目标的空文件仍不落地,`receiver_ack` 仍为 `false`) |
注:WSL 重启后 Linux 客户端的 machine-id 会变,`id` 随之改变,测试脚本以运行时 `list_online_hosts` 为准。
### 14.9 增补(2026-10-29):`overwrite` 与 `skipped`
#### 14.9.1 问题(实测)
同一份文件连续 C2C 两次,目标端 mtime 从 `1793276750` 变为 `1793276909`(重写),大小不变、
条目数不变 —— 即**每次都全量重发**。更麻烦的是两次返回值完全相同:
```
第一次: file_count=1, total_bytes=11595168, receiver_ack=true
第二次: file_count=1, total_bytes=11595168, receiver_ack=true
```
调用方无法分辨「这次真的传了」还是「跳过了」。`upload_file` / `download_file` 有 `overwrite` +
`skipped`,只有 C2C 缺这一对。
#### 14.9.2 做法(纯服务端,协议零改动)
目标端收包是**无条件覆盖写**(`RecvFileChunkV2` 不判断是否存在),所以跳过只能在服务端做:
发起传输前先列一次目标目录,把重名的顶层项从 `paths` 里剔掉。协议、客户端一律不动。
- `overwrite=false`(默认)时,调用 `ListRemoteTopLevelNames`(`upload_file` 已在用的同一个
helper,`McpServer.cpp`)列 `dst_dir` 一层;
- 逐个 `paths` 取 basename,与目标端已有名字比对:**Windows 目标不区分大小写,POSIX 目标区分**
(为此给 helper 加了 `foldCase` 参数,默认 `true` 保持 `upload_file` 行为不变);
- 命中的路径剔除并计入 `skipped`;全被剔除则直接返回成功,**不发起传输、不建 transferID**;
- 目标目录不存在时 helper 返回空集(`ERROR_FILE_NOT_FOUND`/`ERROR_PATH_NOT_FOUND` 视为空),
正好等价于「无同名项」,不会挡住「传到新目录」;
- **预检失败不报错**:预检本身失败时退回「全量发送」,并置 `skip_check_failed=true`。
不能让一次检查失败把本该成功的传输挡掉——这是与 `upload_file` 不同的取舍
(`upload_file` 在预检失败时直接 `-32001` 失败)。
注意这个 fallback 的**实际可达范围很窄**:目标主机被在飞传输或别的工具占用时,预检确实
失败,但紧接着的 `BeginC2CTransfer` 也查同一套 `m_Pending` / `m_FileXferSessions` 互斥,
会直接返回 `-32003`,根本走不到「全量发送」那一步(见 §14.9.5)。真正能置位的只有
「列举超时或异常,而设备此刻空闲」。
`dst_dir` 传给 helper 时用**不带尾分隔符**的形态(`dstDirListAnsi`):客户端拼 `"%s\*.*"`,
带尾分隔符会拼成 `C://*.*` 让 `FindFirstFile` 失败,与 `search_file` 踩过的是同一个坑。
#### 14.9.3 契约
| 字段 | 语义 |
|---|---|
| `overwrite`(入参,bool,默认 false) | `false`:目标目录已有同名顶层项则跳过;`true`:维持旧行为,无条件重发 |
| `skipped`(出参,int) | 本次因已存在而跳过的顶层项数;`overwrite=true` 时恒为 0 |
| `skip_check_failed`(出参,bool) | `true` 表示没能预检目标目录(主机忙/超时/拒绝访问),本次按全量发送,`skipped` 不可信 |
#### 14.9.4 验证
服务端重建并重启后(`exe_build_time=2026-10-29 14:34:33`,PID 12160)实测:
| 用例 | 结果 |
|---|---|
| 1. 同一文件连传两次,第二次 `overwrite=false` | **通过**:`file_count=0`、`skipped=1`、`transfer_id=""`、`skip_check_failed=false`,目标端 mtime 不变 |
| 2. `overwrite=true` 重传 | **通过**:`file_count=1`、`skipped=0`,目标端 mtime `1793276909` → `1793281657`(推进 4748 s),条目数不变 |
| 3. 传到不存在的新目录 | **通过**:目录自动创建,单文件落成 `<dst_dir>/<basename>`(如 `/home/shaun/c2c_probe3/settings.ini`) |
| 4. 目标主机被别的工具占住(在飞) | **不可按原描述构造**:返回 `-32003` 而不是「全量发送 + `skip_check_failed=true`」,详见 §14.9.5 |
| 5. Windows 目标 + 大小写不同的同名文件 | **通过**:目标 `C:\Temp\c2c_case5` 预置 `SETTINGS.INI`(23 B),传 `settings.ini` → `skipped=1`、`file_count=0`、`transfer_id=""`,目录内仍只有 `SETTINGS.INI` |
| 6. Linux 目标 + `SETTINGS.INI` vs `settings.ini` | **通过**:目标 `/home/shaun/c2c_case6` 预置 `SETTINGS.INI`(23 B),传 `settings.ini` → `skipped=0`、`file_count=1`,两个文件并存(23 B 与 1528 B) |
用例 1、2、3 的目标端是 Ubuntu 24.04(`ubuntu-24` / `Ubuntu24`),源端是 Windows 11(`IOU-Station`);
用例 5 的目标端是 Windows 11(`MS084`)。
#### 14.9.5 用例 4 的期望不成立(实测)
原用例假设「目标主机被别的工具占住 → 预检失败 → 仍能传完,`skip_check_failed=true`」。实测两条
路径都走不到那个结果:
- **占住目标**(后台 `download_file` 一份 17 MB 日志,随即发起 C2C):返回
`-32003 Device busy: source or destination host already has a transfer in flight`。
原因是 `BeginC2CTransfer`(`McpServer.cpp`)除了查自己的 `m_FileXferSessions`,还查
`src_id`/`dst_id` 的 `m_Pending`——与预检 `BeginPending` 的互斥条件是同一套。预检失败后
落到它这里仍然被拒,`skip_check_failed` 因此不可观测。
- **让列举失败但写入成功**(`chmod 333`,可写不可读):预检**没有**失败。Linux 客户端把
`EACCES` 当成「目录里没有条目」上报(不是 `TOKEN_FILE_LIST_ERROR`),服务端于是
`skip_check_failed=false`、`skipped=0`,随后照常覆盖写,文件确实写进了 1528 字节。
即这一路是 **fail-open**:列不出来的目录,`overwrite=false` 不会保护其中已有的同名文件。
因此 `skip_check_failed` 现在只作为「列举超时/异常且设备空闲」的兜底存在,难以稳定构造,
字段保留。若要真正验证它,需要让 `WaitPending` 超时(例如临时挂起客户端进程),代价是可能
把主机判成离线,本轮没有做。
#### 14.9.6 一次误报的复盘(重要,避免重犯)
本轮曾判定「单文件 C2C 落盘会多出 `C:/…` 目录树,只有目录/多文件正常」,并据此在
`common/FileTransferV2.h` 里加了一段接收端路径加固。**该结论是错的,加固已还原。**
根因是自制的 JSON-RPC 直连测试脚本:为了绕过连接器缓存的 `tools/list`(它还没有
`overwrite` 字段),脚本用命令行参数传 JSON,而**命令行传递层会把 `\\` 折成 `\/`**,
于是 Python 解析出来的路径已经是 `C://ProgramData//HTS//…`(双正斜杠)。源端拿到一条
没有任何反斜杠的路径后,`GetRelativePath` 的 basename 兜底用 `find_last_of('\\')` 找分隔符,
找不到就把整条绝对路径当相对路径返回 —— 于是落盘成 `<dst_dir>/C:/ProgramData/…`。
也就是说:**缺陷在测试工具里,不在产品里。** 同一个文件、同一个 `dst_dir`,用连接器
(标准 JSON 转义)调用时源端发出的名字是干净的 `/home/shaun/c2c_probe3/settings.ini`。
教训:
- 传含反斜杠的路径给自测脚本时,**必须走文件或 stdin,不要走命令行参数**;
- 判定「产品有 bug」之前,先用**真实 MCP 客户端**复现一次,别只信自建 harness;
- 中继侧/接收侧的日志只能证明「收到的字节是什么」,不能证明「上游是谁写坏的」。
+273
View File
@@ -0,0 +1,273 @@
# MCP P8 设计:在线主机 TLS 字段 / 连接管理 / 主机管理
> 延续 `Mcp_Design.md` → `Mcp_Phase2_Design.md`(P2)→ P3~P6 → `Mcp_Manage_Design.md`(P7)。
> P7 复用的是「系统/窗口/服务」对话框使用的 `COMMAND_SYSTEM`、`COMMAND_WSLIST`、
> `COMMAND_SERVICECONFIG` 链路;本轮要覆盖的「连接管理」与「主机管理」走的是**另一套**
> 命令(`COMMAND_CONNECTION` / `COMMAND_MACHINE_MANAGE`),必须在同一子连接上收发多步,
> 因此新增一层会话抽象,并为工具族增加独立开关。
>
> 安全门结论(已确认):新增独立 `host_*` 工具族;写入范围限定「只读 + 可恢复操作」;
> 开关分两层——`McpMachine`(工具族总开关)与 `McpMachineDangerous`(高风险子集),
> 均默认关闭,并与 `McpReadonly` 叠加。现有 27 个工具(含 P7)一律不改行为。
## 1. 范围
| 交付 | 内容 |
|---|---|
| TLS 字段 | `list_online_hosts` / `search_hosts` / `get_host_detail` 增加 `tls` |
| 连接管理 | `list_network_connections`、`kill_network_connection` |
| 主机管理读 | 10 个标签页各一个:`host_list_processes` … `host_get_hosts_file` |
| 主机管理写 | `host_control_process` / `host_control_window` / `host_control_service` / `host_control_task` |
| 配置 | 设置对话框两个复选框 + 启动接线(`McpMachine` / `McpMachineDangerous`) |
不做的(明确排除):kill 进程、关闭窗口、删除服务/任务、卸载软件、写 hosts、
创建任务、强制删除文件、代码注入。
## 2. TLS 字段
- `HostJson.cpp` 的 `BuildHostJson()` 末尾追加
`device["tls"] = (ctx->GetClientData(ONLINELIST_TLS) == "Y");`。
数据源是登录时写入的 `ONLINELIST_TLS`(`2015RemoteDlg.cpp` 收到 `RES_TLS=="1"` 时置 `"Y"`)。
- 语义:**登录凭据**,不是实时探测。老客户端不上报该值 → `false`。
- `BuildHostJson` 同时被 WebService 的设备列表复用,Web 端也会多出该字段(向后兼容)。
- `get_host_detail` 复用 `BuildHostItemSchema()`,自动带上。
## 3. 会话架构
两条新链路都需要「主连接发一条命令 → 客户端新建子连接 → 子连接回就绪包 →
在同一子连接上多次收发」,现有 `m_Pending` 只能等主连接上的单包。做法是给
`PendingRequest` 增加 `kind`,**复用同一张表** `m_Pending`(从而天然保证「单设备单飞行」),
而不是另开一套状态。
```cpp
enum class PendingKind { Generic, FollowUp, Machine, ConnMgr };
```
| 成员 | 用途 |
|---|---|
| `m_SubCtxToDevice` | 已绑定的子连接 → device;绑定的子连接上所有包都由 MCP 消费 |
| `m_AbsorbedSubCtx` | `CancelIO` 后仍可能到达的包:静默丢弃 |
| `m_OrphanByDevice` / `m_OrphanByPeer` | 5 秒墓碑,防止迟到的就绪包弹出 MFC 对话框 |
### 3.1 时序(工具线程)
```
BeginMachineSession(dev, tool, mainCtx) // 登记单飞行;忙 → -32003
→ 主连接 Send2Client(COMMAND_MACHINE_MANAGE)
→ 客户端开 CMachineManager 子连接,回 TOKEN_SYSINFOLIST(61)
→ OnManagedSubPacket 绑定子连接、保存首包、notify_all
WaitManagedPacket(dev, 61, …, 5000) // 就绪
每次读:
ArmManagedResponse(dev, 期望 token)
→ 子连接 Send2Client([tab 0..9]) / WaitSendIdle
→ WaitManagedPacket(dev, 期望 token, …, 12000)
EndManagedSession(dev, cancelIo=true) // 关闭子连接,不留长连接
```
整体 60 秒会话截止;每一步取 `min(step, deadline - now)`。所有超时返回 `-32001`。
### 3.2 子连接路由(`OnManagedSubPacket`)
在 `3.1` 的模型下,UI 线程收到的每个包先经过钩子
(`MessageHandle` 中终端拦截块之后、`switch (cmd)` 之前):
1. 已绑定 → 只保留 `expectedToken` 匹配的包;`TOKEN_MACHINE_MSG(42)` 存为
`clientError`(CP936→UTF-8);其余丢弃。已绑定的子连接上的一切包都归 MCP。
2. `m_AbsorbedSubCtx` 命中 → 丢弃。
3. 未绑定且 token 不是 `61` / `255` → 交回主 switch(MFC 行为不变)。
4. 未绑定且是 `61` / `255`:
- 该 context 就是主连接(`FindMainContext(parent, cid)`)→ 交回主 switch;
- 否则在同 device 的未绑定会话中按 `clientID` 精确绑定;
- 老客户端子连接 `clientID` 可能为 0 → 按 `peer` 兜底,**仅当同 peer 唯一**时才绑定;
- 都不命中:墓碑未过期 → 吸收 + `CancelIO` + 消费;否则交回主 switch
(用户手动打开对话框)。
### 3.3 必须同步调整的现有语义
- `IsPending()` 排除 `Machine` / `ConnMgr`:否则会话在飞时用户点「进程管理」,
`case TOKEN_PSLIST` 会把界面包抢走。
- `TakeMainResponse()` 顶部对 managed kind 直接返回。
- `OfflineProc` 在 `OnManageSubClosed` 之后、`RemoveFromHostList` **之前**调用
`OnManagedContextClosed`(否则连接池复用同一 context 指针后,新连接的包会被误吞)。
- 锁序:`parent->m_cs` → `m_PendingMutex`;持锁期间禁止 `Send2Client` / `CancelIO` /
`WaitSendIdle`。
### 3.4 健壮性
- UI 线程只做「有界拷贝 + 保存 + 唤醒」:单包上限 8 MiB,超限置 `clientError` 并 `CancelIO`。
- 解析全部在 MCP 工作线程上做;字符串一律用 `BoundedStrlen` / 显式偏移,
未对齐的多字节整数用 `memcpy`,禁止指针强转。
- 客户端部分列表用 `Send(buf, LocalSize(buf))` 发送,长度可能带出少量尾随 0 填充:
记录解析循环遇到「剩余全 0」即结束,定长记录列表忽略不足一条记录的尾部。
## 4. 连接管理
### 4.1 协议
- 主连接:`COMMAND_CONNECTION(253)`;客户端建 `CConnectionsManager` 子连接。
- 子连接回 `[255][u16 LE count][ConnectionInfo × count]`。
- `ConnectionInfo`(`common/commands.h`,`#pragma pack(1)`,110 字节,已 `static_assert`):
`proto(1)` / `af(1)` / `pid(4)` / `localAddr[16]` / `localPort(2,主机序)` /
`remoteAddr[16]` / `remotePort(2,主机序)` / `state(4)` / `procName[64](UTF-8)`。
地址为网络序;IPv4 取前 4 字节,`af == AF_INET(2)`,IPv6 为 `AF_INET6(23)`。
- 强制断开:子连接发 `[254][原始 110 字节记录]`;客户端 `SetTcpEntry(DELETE_TCB)`
后自动重发一次 255。
### 4.2 工具
| 工具 | 门控 | 说明 |
|---|---|---|
| `list_network_connections` | `McpMachine` | 过滤 `protocol/family/pid/process/local_port/remote_port/remote_address/state` + 分页;输出 `killable = (proto==1 && af==AF_INET)` |
| `kill_network_connection` | `McpMachine && McpManage && !McpReadonly` | 必填四元组;可选 `pid` 消歧、`dry_run` |
`kill_network_connection` 的流程刻意避免「重新拼地址」:
1. 取最新列表,**按原始 110 字节记录精确匹配**四元组(可选同时校验 PID);
2. 匹配 0 条 → `-32009`(调用方应刷新);匹配多条 → `-32602`(要求给 `pid`);
3. 目标不是 IPv4 TCP → `-32005`,不发包;
4. `dry_run` → 直接返回目标;
5. `Arm(255)` → 发 `[254][原记录]` → 等刷新列表 → 复核该四元组是否消失。
客户端 `SetTcpEntry` 的返回值被忽略且需要管理员权限,所以「断开后仍在」返回
`structuredContent.ok=false, reason="still_present"`,**绝不谎报成功**。
每次调用写审计:`tcp a:p->b:q pid=N result=…`。
## 5. 主机管理
### 5.1 协议
- 主连接:`COMMAND_MACHINE_MANAGE(162)` → 客户端 `CMachineManager` 子连接回
`TOKEN_SYSINFOLIST(61)`。
- 之后在同一子连接上发 **1 字节 tab**(0–9),响应 token 31–42。
- 动作 10–30;多数动作客户端会自动回一份刷新后的列表(服务 = 40,任务 = 41),
进程冻结/解冻(16/17)与窗口操作(11)**不回包**。
`MachineManager` 枚举(`common/commands.h`):请求 0 PROCESS / 1 WINDOWS / 2 NETSTATE /
3 SOFTWARE / 4 HTML / 5 FAVORITES / 6 WIN32SERVICE / 7 DRIVERSERVICE / 8 TASK / 9 HOSTS;
响应 31 PROCESS / 32 WINDOWS / 33 NETSTATE / 34 SOFTWARE / 35 HTML / 36 FAVORITES /
37 WIN32SERVICE / 38 DRIVERSERVICE / 39 HOSTS / 40 SERVICE_LIST / 41 TASKLIST / 42 MACHINE_MSG。
### 5.2 读工具
| 工具 | tab | 响应 | 主要过滤 |
|---|---|---|---|
| `host_list_processes` | 0 | 31 | `pid` / `name` / `arch` |
| `host_list_windows` | 1 | 32 | `pid` / `title` |
| `host_list_network_state` | 2 | 33 | `pid` / `process` / `protocol` / `local_port` / `remote_port` / `state` |
| `host_list_software` | 3 | 34 | `name` / `publisher` |
| `host_list_browser_history` | 4 | 35 | `title` / `url` |
| `host_list_favorites` | 5 | 36 | `name` / `url` |
| `host_list_win32_services` | 6 | 40 | `name` / `status` / `start_type` |
| `host_list_driver_services` | 7 | 40 | 同上 |
| `host_list_scheduled_tasks` | 8 | 41 | `name` / `folder` / `status` |
| `host_get_hosts_file` | 9 | 39 | `include_content` / `max_bytes` |
公共分页 `offset`(默认 0)/ `limit`(默认 100,上限 1000);输出
`total`(过滤后)/ `totalAll` / `offset` / `limit` / `hasMore`。
### 5.3 记录格式(与 `CMachineDlg::Show*` 逐字段对齐)
| 列表 | 格式 |
|---|---|
| 进程 31 | `DWORD pid`、`bool is64`、`title[260]`、`exe`+pad、`path`+pad、`DWORD priClass`、`DWORD threads`、`user`+pad、`DWORD workingSetKb`、`DWORD fileSizeKb`;CP936 |
| 窗口 32 | `WINDOWSINFO` 定长 1044 字节;**只含可见窗口**;空列表 = 1 字节 |
| 网络状态 33 | 进程名、`DWORD pid`、`[TCP]/[UDP]`、`ip:port`、远端、状态,各串 +2;UDP 远端 `*.*.*.*:*`、状态为空;按最后一个 `:` 拆地址 |
| 软件 34 | 5 个串各 +2:显示名、发布者、版本、安装日期、卸载命令 |
| 浏览记录 35 | 定长 2148:`time[100]` + `title[1024]` + `url[1024]` |
| 收藏夹 36 | 2 个串各 +2 |
| 服务 40 | 8 个串各 +1 NUL:显示名、描述、状态、启动类型、登录身份、交互式、**服务名**、可执行路径 |
| 计划任务 41 | `name/path/exe` 为 UTF-8、`status` 为 GBK,各 +1 NUL;两个 `DATE`;两个 0 字节结束;`folder` 由 `path` 去掉末尾 `"\<name>"` 派生 |
| hosts 39 | `[39][文件原文][0]`;有 BOM → UTF-8,否则合法 UTF-8 → UTF-8,否则 CP936 |
### 5.4 写工具
统一模式:**先取列表校验目标存在 → 发动作 → 再取列表复核**。目标不在最新快照里
返回 `-32009`,绝不盲发。
| 工具 | action | 额外门控 | 动作包 | 复核 |
|---|---|---|---|---|
| `host_control_process` | `freeze` / `thaw` | `McpMachineDangerous` | `[16/17][DWORD pid]`(无回包) | 重新取 tab 0:PID 仍在 |
| `host_control_window` | `restore/hide/maximize/minimize` | — | `[11][DWORD hwnd][DWORD SW_*]` + 零填充到 20 字节(客户端只读前 9 字节) | 重新取 tab 1:hide 后 hwnd 应消失,其余应仍在 |
| `host_control_service` | `start`/`pause`/`continue` | — | `[22/24/25][服务名 CP936][NUL]` | 客户端自动回 40 |
| `host_control_service` | `stop`/`restart` | `McpMachineDangerous` | stop = `[23]`;restart = stop → 等 40 → start | 等 40(12 s),状态在期望集合内 |
| `host_control_task` | `run` / `stop` | — | `[29/28][folder CP936][NUL][name CP936][NUL]` | 客户端自动回 41:任务仍在 + 当前状态 |
补充规则:
- 服务动作前先取一次服务列表(prime),既校验目标,也把客户端 `m_dwServiceType`
钉到正确类型(Win32 / 驱动)。
- 已是目标状态时不下发动作,返回 `ok=true, changed=false, reason=already_*`。
- 冻结/解冻、窗口动作、任务动作**没有回执**:`verified` 只表示「已用动作后的快照复核」,
不表示「动作一定生效」。冻结不改变进程存在性,因此只能确认目标仍在。
- 写工具输入串(服务名、任务 folder/name)必须能转成 CP936,否则 `-32602`,不发包。
- 审计格式:`host <id> <tool>: action=… target=… result=…`。
## 6. 门控矩阵
| 配置 | 可见工具 | 直接调用被隐藏的工具 |
|---|---|---|
| `McpMachine=0`(默认) | 0 个 | `-32006` |
| `McpMachine=1, McpReadonly=1` | 11 个读工具(`list_network_connections` + 10 个 `host_list_*` / `host_get_hosts_file`) | 5 个写工具 → `-32006` |
| `McpMachine=1, McpReadonly=0, McpManage=1` | 16 个(含 5 个写) | — |
| `McpMachine=1, McpReadonly=0, McpManage=0` | 15 个(无 `kill_network_connection`) | `kill_network_connection` → `-32006` |
| `McpMachineDangerous=0` | 工具仍可见 | `host_control_process`、`host_control_service{stop,restart}` → `-32006` |
设置对话框勾选「危险主机操作」但未勾「主机管理」时,保存会清除危险开关并提示。
## 7. 错误码
沿用 P1–P7 的约定,新增 `-32009`:
| 码 | 含义 |
|---|---|
| `-32602` | 参数非法(含:目标多条匹配、字符无法用 CP936 表示) |
| `-32000` | 解析失败 / 客户端返回错误文本(`TOKEN_MACHINE_MSG`) |
| `-32001` | 超时(就绪 5 s / 列表 12 s / 会话 60 s) |
| `-32002` | 主机离线 |
| `-32003` | 设备忙(已有 MCP 会话在飞:单设备单飞行) |
| `-32004` | 发送失败 |
| `-32005` | 不支持(非 Windows 客户端;UDP/IPv6 断连) |
| `-32006` | 开关未开启 |
| `-32009` | **目标在最新快照中不存在**(调用方应刷新后重试) |
## 8. 已知限制
1. **token 数值碰撞**:机器响应 31–42 与 `COMMAND_KEYBOARD/AUDIO/SYSTEM/SHELL/…` 同值。
靠「先按子连接身份路由」解决——未绑定的子连接不会按 token 猜测。
2. **UI 争抢就绪包**:用户恰好在 MCP 请求期间点开同一对话框时,首包可能被 MCP 绑定,
界面对话框这次不弹(与 P7 的取舍一致),重试即可。
3. **5 s 墓碑**:MCP 异常结束后 5 s 内手动打开同一台主机的对话框可能被吞,重试即可。
4. **老客户端子连接 `clientID=0`**:靠 peer 兜底,仅在同 peer 唯一会话时绑定。
5. **权限**:`SetTcpEntry`、冻结/解冻、服务控制需要客户端管理员;失败按「未生效」如实返回。
6. **编码**:机器协议以 CP936 为主;任务 `name/path/exe` 为 UTF-8、`status` 为 GBK;
写回输入统一转 CP936。GBK 不可表示的字符明确报 `-32602`。
7. **`host_list_network_state` 只有 IPv4**:数据来自客户端自身的 `GetTcpTable` 视图,
与「连接管理」(`ConnectionInfo`,含 IPv6)不是同一份数据。
8. **`McpMachineDangerous` 只覆盖本轮高风险动作**;后续加入 kill/删除/卸载/注入时,
必须按 `McpMachine && McpMachineDangerous && !McpReadonly` 三层校验。
9. **`host_control_window {action:"hide"}` 是单向的**:客户端只枚举可见窗口,隐藏后该 hwnd
从快照中消失,再发 `restore` 会在发包前被 `-32009` 拦下(MFC 对话框同样无法再操作它)。
实测确认:`hide` 复核为 `state:"hidden"`,随后 `restore` 返回 `-32009`。
10. **`host_control_service {action:"pause"}` 依赖服务自身支持 PAUSE**:实测虚拟机上的
`Spooler` 下发 PAUSE 后状态仍为 `Running`,工具如实返回 `ok:false, reason:"unexpected_state"`
(不谎报成功)。`start/stop/continue/restart` 在同一台机器上均通过。
11. **开关只在进程启动时读取**(Release 版配置来自注册表 `HKCU\Software\YAMA\settings`,
不是 `Bin\settings.ini`);在「MCP设置」里改动 `McpMachine` / `McpMachineDangerous` /
`McpReadonly` 等必须重启服务端才生效。未重启时 `tools/list` 里看不到新工具,
直接调用返回 `-32006`。
## 9. 验证要点
- TLS:`RES_TLS=1` 的主机三个工具都返回 `tls:true`;老客户端 `false`。
- 路由:MCP 关闭时手动打开「主机管理」「连接管理」照常工作;
`host_list_favorites`(token 36,与键盘等命令同值)在飞时手动打开「进程管理」,
两边都不串包。
- 迟到包:强制就绪超时后,61/255 到达应被吸收且不弹对话框。
- 单飞行:同主机并发两个 host/connection 工具,第二个 `-32003`;两台主机并发都成功。
- 连接管理:与对话框逐条对比;断开后复核消失;UDP/IPv6 → `-32005`;过期四元组 → `-32009`。
- 10 个读工具:与 MFC 标签页对比行数、首末行、中文编码;空 tab 返回 `total:0`。
- 4 个写工具:freeze→thaw、窗口四动作、服务五动作、任务 run/stop;过期目标发包前 `-32009`。
- 回归:现有 27 个工具、终端、远程控制、文件传输、10 个 MFC 标签页行为不变。
- 资源:连续调用 20 次 host 工具,服务端无残留子连接。
+700
View File
@@ -0,0 +1,700 @@
# MCP 能力扩展与优化方案(P10 起)
> 版本:v2(已按代码核对修订) 状态:评审通过,按 §6 顺序施工
> 前置文档:`Mcp_Design.md`(协议/架构/配置/错误码)、`Mcp_Phase2_Design.md`(双模式无头驱动)、
> `Mcp_Manage_Design.md`(P7 写工具范式)、`Mcp_Machine_Design.md`(P8 会话抽象)、
> `Mcp_Terminal_Design.md`、`Mcp_RemoteControl_Design.md`、`Mcp_FileTransfer_Design.md`、`Mcp_Chat_Design.md`、
> `Mcp_Test_Report_2026-10-25.md`(实测结论与已修问题)
>
> 本文回答两个问题:**还能做哪些工具**、**现有工具还能怎么优化**。所有结论都落到具体文件与行号,
> 并区分「客户端零改动」「需客户端改动」「客户端尚未实现」三种可行性。
>
> **v2 修订要点**(逐条核对代码后更正,详见各节开头的「初稿的错误」):
> §5.2 的 `mode=offline` 前提不成立(历史数据本来就会回传);§2.3 低估了服务端接线工作量;
> §5.6 的「一码四义」不成立;§5.1 的 `serverGates` 与 `get_server_status` 重复;§3.2 应给出明确优先级。
---
## 0. 结论摘要
1. **工具面已经覆盖「看 + 管 + 连」三层**(本方案写作时 54 个工具、8 个功能族;P10-A/B/C 与 P11 之后为
**60 个工具、9 个功能族**,见 §1.1)。写作时的三处结构性缺口都已关闭:
**文件系统只有读没有写**(P10-B 补了 `delete_path` / `move_path` / `create_folder`)、
**远程控制缺「防人工干扰」与「能力自述」**(P10-C 补 `remote_block_input`,P10-A 补
`get_host_detail.capabilities`)、**同一能力存在两套重叠工具**(P10-A 用描述互指解决,未合并工具)。
2. **最高性价比的一批新工具是文件系统写操作**(`delete_path` / `move_path` / `create_folder`):
客户端四个命令 + 三个完成 token **全部已实现**(`client/file/FileManager.cpp:97-121`;
`TOKEN_DELETE_FINISH` 被删文件与删目录复用)。MCP 侧复用 P7 的 `followUp` 范式即可,
**客户端零改动**,一次性补齐「AI 能整理远程磁盘」这个最常用场景。
注意这不等于「照抄 P7」:文件管理器子连接的就绪包是 `TOKEN_DRIVE_LIST` 不是
`TOKEN_SYSTEM_READY`,且三个完成 token 在服务端顶层分发里**还没有 case**——真正的接线
工作量在这里,详见 §2.3。
3. **最大的非工具类短板是「能力自述」**:`get_host_detail` 不告诉模型这台主机支持什么,
模型只能靠 `-32005` 试错(`list_registry`、`get_screenshot`、`remote_*`、`upload_file` 各有平台/能力位门槛)。
补一个 `capabilities` 对象是**纯服务端改动、几十行代码**,但直接减少一整类无效调用。
服务端开关态不必另开字段——`get_server_status` 的 `switches` 已经完整暴露(`McpServer.cpp:3142`),
`capabilities` 只描述「这台主机本身能做什么」,两者分工明确。
4. **协议层有四个空白**:`initialize.instructions`、`notifications/progress`、`notifications/cancelled`、
`logging`。其中前两个直接影响「长任务(下载/上传/搜索/chat_wait)时模型以为卡死」的体验。
**现状**(2026-10-28):前三项已落地——`instructions`(P10-A)、progress/cancelled(P11,附录 D.4);
`logging` 仍未做(服务端不声明 `capabilities.logging`,也不发 `notifications/message`)。
5. **不建议现在做**的:注册表写、Windows 事件日志、进程模块/启动项、剪贴板读——都需要客户端改,
且安全边界要单独评审;代理隧道(`COMMAND_PROXY`)价值最高但工程量大,建议单独立项。
> **一处需要纠正的常见误解**:进程「挂起 / 恢复」**已经实现**,不需要新工具——
> 它是 `host_control_process` 的 `action=freeze|thaw`(`McpMachine.cpp:2107`),
> 且已带「动作后重拉进程列表复核」的验证逻辑。本轮不再重复造这个工具。
---
## 1. 现状盘点
### 1.1 工具族(60 个)
登记表在 `server/2015Remote/McpInternal.cpp:375` 的 `kToolHints[]`(60 项,与下表的工具逐条对应)。
下表是 P11 之后的口径;写作时是 54 个、8 个族,P10-B 加 3 个(文件系统写)、P10-C 加 1 个
(`remote_block_input`)、P11 加 2 个(`mcp_list_sessions` / `mcp_cancel_session`)。
| 族 | 数 | 工具 | 门控条件 |
|---|---|---|---|
| 服务端本机只读 | 9 | `list_online_hosts` `search_hosts` `list_all_hosts` `get_host_detail` `get_activity_history` `get_audit_log` `get_server_status` `mcp_list_sessions` `mcp_cancel_session` | 全部始终在列表里、只读模式下照常可用;`mcp_list_sessions` / `mcp_cancel_session` 还**不受任何开关或只读限制**(卡住请求的唯一出路,见附录 D.5) |
| 主机只读 | 21 | `list_processes` `list_windows` `list_files` `list_services` `get_client_log` `get_keylog` `get_screenshot` `list_registry` `download_file` `search_file` `list_network_connections` + `host_list_*`(10 个标签页) | 除下列四类外始终在列表里:`get_keylog` 需 `McpKeylog=1`(其 `clear` / `set_offline` 还需 `McpReadonly=0`)、`download_file` 需 `McpFileTransfer=1`、`list_network_connections` 与 `host_list_*` 需 `McpMachine=1` |
| 终端 | 4 | `terminal_open` `terminal_exec` `terminal_close` `exec_command` | `terminal_*`:`McpTerminal=1` **且** `McpReadonly=0`;`exec_command` 只要求 `McpReadonly=0` |
| 远程控制 | 6 | `remote_open` `remote_close` `remote_mouse` `remote_keyboard` `remote_clipboard` `remote_block_input` | `McpRemoteControl=1` **且** `McpReadonly=0` |
| 文件传输 | 2 | `upload_file` `copy_files_c2c` | `McpFileTransfer=1` **且** `McpReadonly=0`(`download_file` 只要求此开关) |
| 文件系统写 | 3 | `delete_path` `move_path` `create_folder` | `McpFileWrite=1` **且** `McpReadonly=0` |
| 设备管理 | 4 | `kill_process` `operate_window` `control_service` `power_action` | `McpManage=1` **且** `McpReadonly=0` |
| 主机/连接管理 | 7 | `kill_network_connection` `host_control_process` `host_control_window` `host_control_service` `host_control_task` `host_set_remark` `host_set_watch_level` | 前 5 个:`McpMachine=1` + `McpMachineDangerous=1` + `McpReadonly=0`;`host_set_remark` / `host_set_watch_level` 始终在列表里,调用要求 `McpReadonly=0` |
| 远程交谈 | 4 | `chat_open` `chat_send` `chat_wait` `chat_close` | `McpChat=1`(与 `McpReadonly` 无关) |
合计 9+21+4+6+2+3+4+7+4 = 60。默认配置(`McpReadonly=1`、其余开关 0)下 `tools/list` **19 个**
= 服务端本机只读 9 + 主机只读 8(去掉 `get_keylog` / `download_file` / `list_network_connections` /
`host_list_*`)+ 主机/连接管理 2(`host_set_remark` / `host_set_watch_level`);其余各族依赖开关,全部不可见。
开关全开且关闭只读时为 **60 个**。
**已有的工程范式**(新工具直接复用,不必重新设计):
- **一次性子连接 + 首包即数据**:`list_processes` / `list_windows` / `list_services` / `list_registry` / `get_client_log`。
- **接管子连接 → 发写命令 → 收确认**(`PendingRequest::followUp` / `followUpSent`):`kill_process` / `operate_window` / `control_service`(`Mcp_Manage_Design.md §3`)。
- **多步会话抽象**(`PendingKind::Machine` / `ConnMgr`):`host_list_*` / `host_control_*`(`Mcp_Machine_Design.md §3`)。
- **流式会话**(`TermSession` / `ScreenCtrlSession` / `FileTransferSession` / `ChatSession`):终端、远程控制、文件传输、聊天。
- **迟到首包吸收**(`MarkLateFirstPacketForTool` / `TakeToolFirstPacket`):防超时后误弹 MFC 窗口。
### 1.2 协议层能力
| 能力 | 现状 | 证据 |
|---|---|---|
| `initialize` / `ping` / `tools/list` / `tools/call` | ✅ | `McpServer.cpp:7633` 起 |
| `initialize.instructions` | ❌ 未实现 | 全文 0 处 `instructions` |
| `tools/list` 的 `annotations` | ✅ 四类 hint 齐备 | `McpInternal.cpp:437` `ApplyToolAnnotations` |
| `outputSchema` | ✅ 48 处 | — |
| `resources` / `prompts` | ❌ 未实现 | 0 处 |
| `notifications/progress` | ❌ 未实现 | 0 处 `progressToken` |
| `notifications/cancelled` | ❌ 未实现 | 0 处 `cancelled` |
| `Mcp-Session-Id` | ❌ 无状态 | 0 处 |
| 分页 | 用 `limit`/`offset`,非 MCP `cursor` | 全部列表工具一致 |
| 传输 | Streamable HTTP `POST /mcp`;可选内置 TLS 终结(`McpTlsProxy`) | `Mcp_Design.md §13` |
| 认证 | 静态 Bearer token + 失败计数封禁 | `Mcp_Design.md §3.5` |
| 错误码 | `-32700` … `-32011` 共 14 个 | `Mcp_Design.md §12` |
### 1.3 客户端能力 → MCP 覆盖矩阵
对 `common/commands.h` 中 Windows 客户端**已实现**的命令逐个核对(`client/KernelManager.cpp`、`client/MachineManager.cpp`、`client/file/FileManager.cpp`、`client/ScreenManager.cpp`、`client/KeyboardManager.cpp`):
| 客户端能力 | 命令 | MCP 现状 | 可行性 |
|---|---|---|---|
| 列目录 / 列盘 | `COMMAND_LIST_FILES` / `COMMAND_LIST_DRIVE` | ✅ `list_files` | — |
| 搜索文件 | `COMMAND_SEARCH_FILE` | ✅ `search_file` | — |
| 下载 / 上传 | `CMD_DOWN_FILES_V2` / `COMMAND_SEND_FILE_V2` | ✅ `download_file` / `upload_file` | — |
| 客户端间直传 | `COMMAND_C2C_SEND_FILES` | ✅ `copy_files_c2c` | — |
| **删除文件** | `COMMAND_DELETE_FILE` → `TOKEN_DELETE_FINISH` | ❌ **缺** | **零客户端改动** |
| **删除目录(递归)** | `COMMAND_DELETE_DIRECTORY` → `TOKEN_DELETE_FINISH` | ❌ **缺** | **零客户端改动** |
| **新建目录** | `COMMAND_CREATE_FOLDER` → `TOKEN_CREATEFOLDER_FINISH` | ❌ **缺** | **零客户端改动** |
| **重命名 / 同卷移动** | `COMMAND_RENAME_FILE` → `TOKEN_RENAME_FINISH` | ❌ **缺** | **零客户端改动** |
| 进程列表 / 结束 | `COMMAND_PSLIST` / `COMMAND_KILLPROCESS` | ✅ `list_processes` / `kill_process` | — |
| 进程挂起 / 恢复 | `COMMAND_PROCESS_FREEZING` / `COMMAND_PROCESS_THAW` | ✅ `host_control_process(action=freeze\|thaw)` | — |
| 窗口列表 / 控制 | `COMMAND_WSLIST` / `CMD_WINDOW_CLOSE` / `CMD_WINDOW_TEST` | ✅ `list_windows` / `operate_window` | — |
| 服务列表 / 控制 | `TOKEN_SERVERLIST` / `COMMAND_SERVICECONFIG` | ✅ `list_services` / `control_service` | — |
| 计划任务 / 软件 / 驱动 / 浏览器记录 / 收藏 / hosts 读 | `COMMAND_MACHINE_*` | ✅ `host_list_*`(10 个) | — |
| **写 hosts 文件** | `COMMAND_HOSTS_SET` | ❌ **缺** | 零客户端改动,但**整文件覆盖**,高风险 |
| **卸载软件** | `COMMAND_APPUNINSTALL`(`WinExec`,无回包) | ❌ **缺** | 零客户端改动,风险高 |
| 连接列表 / 断开连接 | `COMMAND_CONNECTION` / `COMMAND_KILL_CONNECTION` | ✅ `list_network_connections` / `kill_network_connection` | — |
| 屏幕截图 | `COMMAND_SCREEN_PREVIEW_REQ` | ✅ `get_screenshot` | — |
| 鼠标 / 键盘 / 剪贴板写 | `COMMAND_SCREEN_CONTROL` + `MSG64` | ✅ `remote_*` | — |
| **锁定对端键鼠** | `COMMAND_SCREEN_BLOCK_INPUT`(2 字节) | ❌ **缺** | **零客户端改动**(无回包) |
| 黑屏 / Ctrl+Alt+Del | `COMMAND_SCREEN_BLANK` / `COMMAND_SCREEN_CTRL_ALT_DEL` | ❌ | **客户端未实现**,需客户端改动 |
| 窗口级 / 区域捕获 | `COMMAND_SCREEN_WINDOW` / `COMMAND_SCREEN_ROI` | ❌ | 流式接口,需评估(见 §4.2) |
| 注册表读 | `COMMAND_REGEDIT` + `COMMAND_REG_FIND` | ✅ `list_registry`(子键 + 值) | — |
| **注册表写** | 无命令 | ❌ | **需客户端改动** |
| 键盘记录(实时) | `COMMAND_KEYBOARD` | ✅ `get_keylog` | — |
| **键盘记录(离线常驻)** | `COMMAND_KEYBOARD_OFFLINE` / `COMMAND_KEYBOARD_CLEAR` | ❌ **缺** | **零客户端改动**(见 §5.2) |
| 客户端日志 | `COMMAND_QUERY_LOG` | ✅ `get_client_log` | — |
| 电源操作 | `TOKEN_MACHINE_MANAGE` | ✅ `power_action` | — |
| 远程交谈 | `COMMAND_CHAT` | ✅ `chat_*` | — |
| **客户端升级** | `COMMAND_UPDATE` | ❌ | 零客户端改动,需独立评审(见 §4.4) |
| **上传执行 / 下载执行** | `COMMAND_UPLOAD_EXEC` / `COMMAND_DOWN_EXEC` | ❌ | 零客户端改动,需独立评审(见 §4.4) |
| **代理映射** | `COMMAND_PROXY` | ❌ | 需独立设计(见 §4.3) |
| 摄像头 / 语音 | `COMMAND_WEBCAM` / `COMMAND_AUDIO` | ❌ | 需流式解码,建议后置 |
| 清除事件日志 / 隐藏开网页 / 卸载后门 | `COMMAND_CLEAN_EVENT` / `COMMAND_OPEN_URL_*` / `COMMAND_REMOVE` | ❌ | **当前 Windows 客户端未实现**,为死命令 |
**结论**:客户端已实现、但 MCP 还没接的能力共 **14 项**,其中 **9 项属「零客户端改动、可常规批次接入」**:
- 文件写 4 项(删除文件 / 删除目录 / 建目录 / 改名移动)
- 键鼠锁定 1 项(`remote_block_input`)
- 离线键盘记录 2 项(开关 / 清空)
- 主机侧 2 项(写 hosts、卸载软件)—— 零改动但风险高,建议后置或不做
另有 5 项(代理、升级、上传执行、摄像头、窗口级捕获)虽也零客户端改动,但工程量或风险远超常规批次,需单独立项(§4)。
---
## 2. 新工具(P10-A):文件系统写操作
### 2.1 为什么是最高优先级
MCP 现在能读、能传、能搜,**唯独不能删、不能改名、不能建目录**。任何「整理远程磁盘」「清理临时文件」「归档日志」「部署目录准备」类任务都会卡在最后一步,只能退回 `exec_command`(`del` / `move` / `mkdir`)——而 `exec_command` 受命令白名单约束(`McpCmdWhitelist`),`del` 默认不在白名单里,且无法处理中文路径与超长路径的编码问题。
用原生文件通道做,还能绕开 shell 白名单、拿到确定的 ack、复用已有的 `TOKEN_*_FINISH` 协议。
### 2.2 工具定义
| 工具 | 入参 | 客户端命令 | 完成 ack |
|---|---|---|---|
| `delete_path` | `id`、`path`、`recursive`(默认 `false`) | `recursive=true` → `COMMAND_DELETE_DIRECTORY`;否则 `COMMAND_DELETE_FILE` | `TOKEN_DELETE_FINISH` |
| `move_path` | `id`、`from`、`to` | `COMMAND_RENAME_FILE` + `[from\0][to\0]` | `TOKEN_RENAME_FINISH` |
| `create_folder` | `id`、`path` | `COMMAND_CREATE_FOLDER` + `[path\0]` | `TOKEN_CREATEFOLDER_FINISH` |
输出统一为 `{id, path, ok:true, verified?:bool}`,并附一句可读摘要。
### 2.3 复用链路(与 P7 同构,但**不是**照抄 P7)
```
主连接 COMMAND_LIST_DRIVE → 客户端建文件管理器子连接 → 子连接回 TOKEN_DRIVE_LIST
→(followUp)下发 COMMAND_DELETE_FILE / _DIRECTORY / _CREATE_FOLDER / _RENAME_FILE
→ 等 TOKEN_*_FINISH → 关闭子连接
```
- 服务端已有现成的三段式入口:`list_files`(`McpServer.cpp:2419`)、`search_file`(`McpServer.cpp:8050`)、`download_file`(`McpServer.cpp:6430`)都走 `COMMAND_LIST_DRIVE` 开子连接。
- `PendingRequest` 的 `followUp` / `followUpSent` / `subCtx` 字段(`McpServer.h:584-587`)足够承载「先等就绪首包、再发写命令、再等确认」的两阶段语义,**数据结构不用改**。
- 路径编码:客户端工程是 MultiByte,路径必须 `Utf8ToCpExact` 严格转 GBK(同 `search_file` 的做法),不可表示即 `-32602`。
**但接入点必须新写三处,这是本节的主要工作量:**
1. **就绪包分流走 `OnDriveList`,不是 `OnSystemReady`。**
`OnSystemReady`(`McpServer.cpp:8070`)里有工具名硬门(只认 `kill_process` / `operate_window`),且文件管理器子连接的就绪包是 `TOKEN_DRIVE_LIST`,根本不会进那个分支。
`OnDriveList`(`McpServer.cpp:7832`)当前对空 `path` 一律判定为「只列盘」并把 `TOKEN_DRIVE_LIST` 当数据取走(`:7846-7851`),所以必须在它最前面按 `tool` 分流:文件写工具 → 下发 `followUp`、保持子连接、返回 `false`。
2. **三个完成 token 需要在服务端顶层分发新增 case。**
`TOKEN_DELETE_FINISH` / `TOKEN_RENAME_FINISH` / `TOKEN_CREATEFOLDER_FINISH` 目前只在 `server/2015Remote/FileManagerDlg.cpp:983-995` 的 hDlg 路径里处理。MCP 的子连接 `hDlg == NULL`(`NotifyProc` 只有 hDlg 存在才交给对话框),三个包会落到 `2015RemoteDlg.cpp:7249` 的 `default:`——只打一行 "unknown command"、**并不关闭子连接**。必须新增 case:`TakeMainResponse` + `CancelIO`。
3. **`MarkLateFirstPacketForTool` 要登记新工具。**
否则工具超时后迟到的 `TOKEN_DRIVE_LIST` 会当成人工操作,**弹出 MFC 文件管理器窗口**。把新工具名加入 `TOKEN_DRIVE_LIST` 那条分支(`McpServer.cpp:7760`)即可。
### 2.4 已知限制(必须写进工具描述)
| 限制 | 原因 | 缓解 |
|---|---|---|
| **ack 只代表「已执行」,不代表「成功」** | 客户端忽略 `DeleteFile` / `MoveFile` / `MakeSureDirectoryPathExists` 的返回值,无条件 `SendToken(..._FINISH)` | 文档明确要求「调用后用 `list_files` 复核」;可选增强见 §5.7 |
| **`move_path` 仅同卷** | 客户端用 `::MoveFile`(`client/file/FileManager.cpp:990`),非 `MoveFileEx` | 描述里写「跨盘请改用 `download_file` + `upload_file`」 |
| **删除无回收站、目录递归** | `COMMAND_DELETE_DIRECTORY` → `DeleteDirectory` 递归删除 | 工具描述加显著警告;`recursive` 必须显式传 `true` |
| **删除单个只读文件会静默失败** | `COMMAND_DELETE_FILE` 直接 `DeleteFile`(`:101`),不像 `DeleteDirectory` 那样先 `SetFileAttributes(...NORMAL)`(`:659`) | 描述里提示「只读文件请先改属性」 |
| **`create_folder` 会自动建中间层** | `MakeSureDirectoryPathExists`,语义是「确保路径存在」而非「只建最后一级」 | 写进描述:传入已含文件名的路径会建出同名目录 |
| **深目录递归删除可能压垮客户端** | `DeleteDirectory` 用无界 `wsprintf` 拼 `MAX_PATH` 栈缓冲(`:643/653/657`);`SearchFiles` 已在 8f718d9 加长度预判,删除/`FixedUploadList` 尚未 | 服务端拒绝超过 MAX_PATH 的 `recursive` 目标;彻底修复归 P12 |
| 路径不存在时**不会**快速失败 | 客户端不回报 win32 码 | 需要客户端补 `TOKEN_FILE_OP_ERROR`(见 §5.7 与 §6 的 P12 批次) |
### 2.5 安全门
新增单一开关 **`McpFileWrite`**(默认 `0`),要求 `McpReadonly=0` 同时成立:
- 不复用 `McpFileTransfer`:上传是「覆盖」,删除是「毁灭」,风险等级不同,必须能分别关。
- 三个工具全部登记 `readOnlyHint=false, destructiveHint=true`(`delete_path`)/ `false`(`move_path`、`create_folder`)。
- 审计:沿用 `AuditManageAction`,记录 `path=` 与 `recursive=`,**不记录文件内容**。
- 建议追加服务端侧保护:拒绝 `path` 落在系统关键目录(`C:\Windows`、`C:\Windows\System32`、`C:\Program Files`)下的 `delete_path`,除非另开 `McpFileWriteDangerous`。这一条可在实现时按需取舍,但**至少要把 `C:\Windows` 与盘根目录挡住**(`delete_path` 传 `C:\` + `recursive=true` 是灾难级误操作)。
---
## 3. 新工具(P10-C):远程控制补全 + 工具族去重
### 3.1 `remote_block_input`(P10-C,零客户端改动)
| 项 | 内容 |
|---|---|
| 入参 | `id`、`session_id`、`block`(`true` / `false`) |
| 命令 | 屏幕子连接上 `[COMMAND_SCREEN_BLOCK_INPUT][0\|1]`(2 字节,`client/ScreenManager.cpp:1198`) |
| 门控 | 随 `remote_open`(`McpRemoteControl=1` + `McpReadonly=0`),不单独设开关 |
**价值**:AI 做 GUI 自动化时,真人碰一下鼠标就会把流程打断;锁定对端键鼠是标准做法。
**必须做的两件事**(否则会把人锁在电脑外):
1. `remote_close` 与 idle 回收时**强制补发 `block=false`**;
2. 会话内 `block=true` 超过 `max_block_ms`(建议默认 300s)自动解锁并在结果里标注 `auto_unblocked=true`。
`BlockInput` 在进程退出时会自动解除,所以真正的死锁风险只出现在「客户端进程活着但会话丢了」——上面两条正好覆盖。
### 3.2 工具族重叠:`list_*` vs `host_list_*`(P10-A,纯文档/描述改动)
**这是当前最容易被忽略、但对模型影响最大的问题**。同一件事有两套工具,走两条完全不同的链路,门控也不同:
| 能力 | 设备管理族(P2/P7) | 主机管理族(P8) | 差异 |
|---|---|---|---|
| 进程列表 | `list_processes`(`COMMAND_SYSTEM`→`CSystemManager`) | `host_list_processes`(`COMMAND_MACHINE_PROCESS`→`MachineManager`) | 后者字段更全(优先级、线程数、用户、工作集、文件大小),**且已有 `name`/`pid` 服务端过滤**(`McpMachine.cpp:2733-2741`) |
| 窗口列表 | `list_windows`(`COMMAND_WSLIST`) | `host_list_windows`(`COMMAND_MACHINE_WINDOWS`) | 同上,后者也带过滤 |
| 服务列表 | `list_services`(`COMMAND_SERVICES`→`ServicesManager`) | `host_list_win32_services`(`COMMAND_MACHINE_WIN32SERVICE`) | 后者含描述、登录身份 |
| 窗口控制 | `operate_window`(含 `close`) | `host_control_window`(**无** `close`) | 门控不同 |
门控差异是关键:`host_list_*` 需要 `McpMachine=1`,而 `list_*` 只需 `McpReadonly`。所以:
- `McpMachine=0` 时 `host_list_*` **不出现在 `tools/list`**,模型只能用 `list_*`;
- `McpMachine=1` 时两套都在,模型**没有任何依据**判断该用哪个。
**结论比初稿更强:`host_list_*` 是首选而非平级备选**——字段更全、且过滤能力本来就已存在(`list_*`
要等 §5.3 补完过滤才追平)。`list_*` 的定位是「`McpMachine=0` 时的降级路径」。
**做法**(不需要合并工具,只改描述,风险极低):
1. 在两套工具的 `description` 里互相指路,且措辞要给出明确优先级:
- `list_processes` → 「`McpMachine=0` 时的降级路径,字段较少;若 `host_list_processes` 在 `tools/list` 里,一律优先用它」;
- `host_list_processes` → 「首选;与 `list_processes` 同源但字段更全并支持服务端过滤,仅在不可用时退回」。
2. 在 `initialize.instructions`(§5.8)里写一条选型规则,一次性讲清四组关系。
**不建议合并**:两族走不同子连接、不同能力位、不同门控,合并会破坏既有安全模型(`McpMachine` 开关的意义就是「单独关掉一套」)。
---
## 4. 大能力(需独立立项,不建议并入本轮)
### 4.1 分级原则
下面这些能力「能做」但**不适合和文件写工具混在一个批次**:要么工程量大(代理、摄像头),要么安全边界必须单独评审(升级、执行、卸载)。按建议顺序列出。
| 能力 | 客户端改动 | 工程量 | 风险 | 建议 |
|---|---|---|---|---|
| 注册表写(set/delete value) | **需要**(无现成命令) | 中 | 高(可持久化篡改) | P12,独立开关 + 白名单键路径 |
| Windows 事件日志读取 | **需要** | 中 | 低(只读) | P12,优先于注册表写 |
| 进程模块 / 启动项 / 网络共享 | **需要** | 中 | 低(只读) | P12,补「主机取证」维度 |
| 剪贴板只读 | **需要**(客户端只有写) | 小 | 中(读即泄密) | 维持 `Mcp_Design.md §10.7` 的「不做」结论 |
| 窗口级一次性截图 | 需评估 | 中 | 低 | 见 §4.2 |
| 代理隧道 `proxy_*` | 否(`COMMAND_PROXY` 已有) | **大** | 高 | 见 §4.3 |
| 客户端升级 `upgrade_client` | 否(`COMMAND_UPDATE` 已有) | 中 | 高 | 见 §4.4 |
| 上传执行 `upload_exec` | 否(已有) | 小 | **极高** | 默认不做,或仅 `McpMachineDangerous` 下 |
| 摄像头快照 / 语音采集 | 否(已有流) | 大 | 中 | 后置 |
| 写 hosts 文件 | 否(已有) | 小 | 高 | 见 §4.5 |
### 4.2 窗口级截图
`COMMAND_SCREEN_WINDOW`(`client/ScreenManager.cpp:894`)接的是**屏幕流**(按窗口标题捕获,空串恢复全屏),不是一次性 JPEG。要做 `get_screenshot(window_title=...)` 需要服务端在屏幕子连接上收若干帧再截一张,本质上是「起一个临时屏幕会话」——比现有 `get_screenshot`(主连接一次 RPC)重得多。
**建议**:先做「AI 侧的替代方案」——`remote_open` 已能拿全屏,`list_windows` 能给窗口句柄与标题,模型可以据此用 `remote_mouse` 点击。等 `remote_*` 在真实任务里被证明「全屏截图不够用」再投入。
### 4.3 代理隧道(价值最高的「新维度」)
`COMMAND_PROXY`(`client/KernelManager.cpp:1039` + `client/proxy/ProxyManager.cpp`)能把客户端当 SOCKS/端口转发跳板。MCP 化的形态是:
```
proxy_open(id, target_host, target_port, local_port) → 服务端本地监听
→ AI 用普通 HTTP/DB 客户端访问 127.0.0.1:local_port
→ 流量经客户端转发到内网 target
proxy_close(session_id)
```
**这会让 AI 从「操作主机」升级为「进入主机所在内网」**——价值远高于再加几个只读工具。
但代价是:服务端要起本地监听(防火墙/端口冲突/生命周期管理)、要做并发与超时、审计粒度要细到「连接目标」,而且这是一个**新的攻击面**(本机任意进程都能用这个监听)。建议单独立项,先出安全设计再动手。
### 4.4 客户端升级 / 上传执行
- `upgrade_client`:`COMMAND_UPDATE` 链路完整,但升级失败会让主机**永久失联**,且没有回滚。至少要「先校验包完整性 + 保留旧版本 + 升级后 N 分钟无心跳则告警」。
- `upload_exec` / `download_exec`:等价于任意代码执行,**绕过 `exec_command` 的全部白名单约束**。这与现有安全模型(`McpCmdWhitelist` 逐条加白)根本冲突。**建议维持不做**;确有需要时只允许 `McpMachineDangerous` 下、且必须显式传 `confirm=true`。
### 4.5 写 hosts 文件
`COMMAND_HOSTS_SET`(`client/MachineManager.cpp:318`)用 `CREATE_ALWAYS` **整文件覆盖**,且无回包、失败静默。MCP 化必须是「读-改-写」语义:
- 入参只接受 `entries[]` 追加/删除,服务端先 `host_get_hosts_file` 读全文,服务端合并,再整文件下发;
- 必须备份原文件(服务端存一份到 `%TEMP%`);
- 门控 `McpMachineDangerous` + `McpReadonly=0`。
**建议**:本轮不做。误覆盖 hosts 会导致目标机 DNS 全断,恢复成本高。
---
## 5. 现有工具优化
按「影响面 ÷ 成本」排序。P0 = 建议本轮做,P1 = 下一轮,P2 = 择机。
> 另有一项「两套工具族重叠」的优化放在 §3.2(因为要顺带说明它为什么不合并),同样是 P0。
### 5.1 【P0,已完成 `bb55f52`】`get_host_detail` 增加 `capabilities`
**问题**:模型拿到 `clientType=WIN` 就以为所有工具都能用,于是反复撞 `-32005`:
| 工具 | 隐藏门槛 | 报错位置 |
|---|---|---|
| `get_screenshot` | `CLIENT_CAP_SCREEN_PREVIEW` 能力位 | `McpServer.cpp:2328` |
| `remote_*` | 同上 + 单显示器(多屏现在报 `-32005`,不是 `-32008`) | `McpServer.cpp:3715` 附近 |
| `list_registry` | 非 LNX/MAC | `McpServer.cpp:2569` |
| `upload_file` | 客户端 `SupportsFileV2()` | `McpServer.cpp:4972` |
| `get_keylog` | `McpKeylog=1` | 门控 |
| `host_list_*` | `McpMachine=1` | 门控 |
**做法**:在 `AppendHostTechnicalDetail`(`McpServer.cpp:2018`)末尾追加。只写**主机自身**的能力,
服务端开关不重复——`get_server_status` 的 `switches` 已经完整暴露(`McpServer.cpp:3142`),
`monitors` 也已经有了(`:2048-2053`):
```cpp
Json::Value caps(Json::objectValue);
caps["platform"] = clientType; // WIN / LNX / MAC / APK
caps["screenPreview"] = ctx->SupportsScreenPreview();
caps["remoteControl"] = ctx->SupportsScreenPreview() && monitors == 1;
caps["fileTransferV2"] = ctx->SupportsFileV2();
caps["c2cPaths"] = ctx->SupportsC2CPaths();
caps["registry"] = (clientType != "LNX" && clientType != "MAC" && clientType != "APK");
host["capabilities"] = caps;
```
**收益**:模型在规划阶段就能排除不可用工具,把「试错 → 报错 → 换工具」的三轮往返压缩成一次。
**成本**:约 30 行,零客户端改动,`outputSchema` 加一个对象。
### 5.2 【P0,已完成 `bb55f52`】`get_keylog`:补离线开关与真实状态(**已重写,初稿前提有误**)
> **初稿的错误**:原文断言「现在只能采 1–15 秒窗口,对『昨天谁敲了什么』完全无用,需要新增 `mode=offline`」。
> 这是错的。`CKeyboardManager1` 构造时就 `new CircularBuffer(m_strRecordFile)`,而 `CircularBuffer`
> 的构造函数直接 `LoadDataFromFile()`(`client/KeyboardManager.h:31-38`);`SendData` 每次(重)连上后
> 从 `pos=0` 把整个缓冲区推给服务端(`client/KeyboardManager.cpp:504-516`),缓冲区 10 MB
> (`KeyboardManager.h:15`)。**只要目标机 `kbrecord=Yes`,现有的 `get_keylog` 已经把落盘历史
> (含无人在线的时段)一并返回了**——工具描述自己就写着「先把缓冲区里已有的记录(含历史)推给服务端」
> (`McpServer.cpp:1559`)。所以 `mode=offline` 不用做,做了也是重复实现。
**真正缺的两件事**:
1. **开关**:`COMMAND_KEYBOARD_OFFLINE`(2 字节)与 `COMMAND_KEYBOARD_CLEAR`(1 字节)
已实现于 `client/KeyboardManager.cpp:125` / `:131`,就在 `get_keylog` 已经建立的那条
键盘子连接上,MCP 侧从未下发过。
2. **状态自述**:客户端在就绪包 `TOKEN_KEYBOARD_START` 的 `byte[1]` 里已经带了「离线记录是否开启」
(`client/KeyboardManager.cpp:164`),服务端 `get_keylog` 拿到了这个包却没解析。
模型因此不知道「我看到的这些历史是不是全量」。
**做法**:
| 参数 | 语义 |
|---|---|
| `offlineRecord`(**输出**) | 客户端当前是否开着离线常驻记录,取自 `TOKEN_KEYBOARD_START` 的 `byte[1]`;`false` 时历史只覆盖本进程启动后的在线时段 |
| `set_offline`(输入,`true`/`false`) | 下发 `COMMAND_KEYBOARD_OFFLINE` 改变常驻状态。写操作:需 `McpReadonly=0` |
| `clear`(输入,`true`) | 下发 `COMMAND_KEYBOARD_CLEAR` 清空客户端缓冲区与落盘文件。破坏性:需 `McpReadonly=0`,且应排在采集之前 |
两个写动作都必须**先于采集窗口下发**,且失败要如实返回(`Send2Client` 的返回值要检查)。
### 5.3 【P0,已完成 `bb55f52`】`list_processes` / `list_windows` 增加服务端过滤
**问题**:`BuildPagedHostListInputSchema` 只有 `{id, limit, offset}`(`McpServer.cpp:776`,调用点在 `:1477` 等)。一台正常 Windows 有 200–400 个进程、几十个窗口,模型要翻 3–4 页才能找到目标;每页都是完整字段,上下文开销很大。
**做法**:加可选 `name`(进程名/窗口标题子串,ASCII 不区分大小写)与 `pid`,在服务端分页**之前**过滤,`total` 为命中数、`totalAll` 为总数。口径照抄 `BuildSearchHosts`(`McpServer.cpp:1878-1887`):
```cpp
ApplyPageWindow(matched, page, pageItems);
if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
```
**收益**:`list_processes(name="chrome")` 从 3 页变 1 条;两套工具族的能力也对齐了(`host_list_*` 本来就有这两个参数)。
### 5.4 【P1,已完成 `1c832ff`】`power_action` 增加结果验证
**问题**:`power_action` 是「发完即走、无响应」(`McpServer.cpp:5812` 附近注释),返回 `ok:true` 只代表**命令写进了 socket**。模型会误以为「已重启」,紧接着调 `list_processes` 却拿到旧进程列表。
**做法**:加 `wait`(默认 `false`)与 `wait_ms`(默认 60000):
- `wait=true`:轮询主连接是否断开 → 再轮询是否重新上线,返回 `{sent:true, went_offline:true, came_back:true, elapsed_ms}`;
- 超时不算失败,返回 `came_back:false` 让模型自己决定。
### 5.5 【P1,已完成 `1c832ff`】破坏性工具统一 `dry_run`
`kill_network_connection` 有 `dry_run`(实测报告「观察项」明确肯定了这个设计),但 `kill_process`、`operate_window(close)`、`host_control_*` 都没有。建议统一:`dry_run=true` 时只做「目标存在性校验 + 返回将被影响的对象」,不执行。
对 AI 尤其重要:模型可以在执行前把「我要杀这 3 个进程」摆给用户看。
### 5.6 【P2,已完成 `1c832ff`(`-32012`,`-32008` 留作别名)】错误码:`-32008` 其实只有两种语义
> **初稿的错误**:原文说 `-32008` 一码四义(含「老客户端格式」「多显示器不支持」)。核对后全文件只有两处
> `-32008`:`exec_command` 的 shell 元字符(`McpServer.cpp:2901`)与 `terminal_exec` 的 `&`/`|`/换行
> (`McpServer.cpp:3465`)——**两者都是「改参数可修」**。多显示器早就改成 `-32005` 了,代码注释明说
> 「这是能力限制、改参数也修不好」(`McpServer.cpp:3715`)。能力类错误已经统一走 `-32005`。
因此拆分只剩一个干净的诉求:把「参数非法」从 `-32008` 换成 MCP 语义更准确的 `-32012`。
| 新码 | 语义 | 模型动作 |
|---|---|---|
| `-32012` | Validation rejected(参数非法,改参数可修) | 修参数重试 |
`-32008` 保留为历史别名(不破坏既有客户端与已发布的文档)。这是一次纯常量替换,收益是让模型
不必读英文 message 就能区分「改参数」与「换主机」,但**优先级低于 P0 各项**。
### 5.7 【P1,部分完成 `27b5431`:`verified` 三态已落地,`verify_hint` 字段未加】写工具的 ack 语义显式化
现状:`delete_path` / `move_path` / `create_folder` / `kill_process` / `operate_window` / `control_service` 的 ack 都是**客户端无条件回包**,不代表操作成功。
两条路,建议都做:
1. **文档层**:`outputSchema` 里加 `verified: bool`(可为 `null`)与 `verify_hint: string`("call list_files on the parent directory to confirm");
2. **实现层**(低成本高收益):`delete_path` / `move_path` 在收到 ack 后,**在同一个子连接上**再补一次 `COMMAND_LIST_FILES` 校验父目录,把 `verified` 填成真实结果。注意不是"多开一次子连接":子连接还开着,客户端收到 finish 后就在等下一条命令,所以代价只是同一连接上的一次往返(约 50–150ms)。实现要点是重新登记一个 `list_files` 挂起(`BeginPending(devId, "list_files", path)`,`McpServer.cpp:7795` 已有该重载),再直接 `Send2Client`;`TOKEN_FILE_LIST` 的现有 case 会在投递结果后 `CancelIO` 收尾,正好完成清场。校验本身失败(超时/连接断)时 `verified` 返回 `null`,**不要谎报 false**。
彻底的做法是客户端补 `TOKEN_FILE_OP_ERROR`(带 win32 码),归入 §4.1 的 P12 批次。
### 5.8 【P1,已完成 `bb55f52`】`initialize` 返回 `instructions`
**问题**:模型对这套服务端的「隐性知识」全靠工具描述拼凑:主机 id 是 64 位雪花值(不能猜)、要先 `list_online_hosts` 再操作、`-32003` 是单设备单飞行、`-32006` 不要重试、远程控制要先 `remote_open` 拿 `session_id`。`Mcp_Design.md` 把这些写在文档里,但**模型看不到文档**。
**做法**:`initialize` 响应里加 `instructions`(纯文本,建议 600–900 字),内容:
1. 主机 id 的获取方式与形态(禁止猜测);
2. 工具族与开关关系(哪些工具可能不在 `tools/list` 里,为什么);
3. 错误码 → 动作的对照(只列 6 个高频码);
4. 典型任务编排(文件整理、进程排查、GUI 自动化各一段);
5. 「同一主机同时只能有一个远程请求」的约束。
**收益**:这是**单点投入、全局收益**的改动——所有客户端的每一次会话都受益,且零风险。优先级应当排在所有新工具之前。
### 5.9 【P2,已完成 `1c832ff`】`notifications/progress` 与 `notifications/cancelled`
**问题**:
- `download_file` 默认超时 600s、`upload_file` / `copy_files_c2c` 同类、`search_file` 最长 120s、`chat_wait` 最长 55s。这段时间里客户端**收不到任何信号**,模型和用户都以为卡死。
- 客户端取消请求(用户按 Esc / 关闭会话)时,服务端**不会中止**正在进行的传输,主机会被锁到超时为止(实测报告 P2 的 600 秒锁定就是这类后果)。
**做法**:
- 长任务在 `tools/call` 的 `_meta.progressToken` 存在时,按 1–2 秒节流推送 `notifications/progress`(`progress` = 已传字节 / 总字节);
- 维护「进行中的请求 → 会话」映射,收到 `notifications/cancelled` 时走既有的清理路径(清 pending、关子连接、删半成品文件)。
这两项都在 `McpServer.cpp` 的 HTTP 处理器层,**不动任何工具实现**。
### 5.10 【P2,已完成 `1c832ff`】会话可观测与自救
`-32003 Device busy` 现在是死路:模型不知道是谁占着这台主机、也不知道等多久。建议加两个纯服务端工具:
| 工具 | 作用 |
|---|---|
| `mcp_list_sessions` | 列出所有在飞会话,每项 `{host_id, kind, tool, session_id, request_id, busy, elapsed_ms, idle_ms}` |
| `mcp_cancel_session` | 按 `request_id`(精确)或 `id`/`session_id`(条件)取消,返回 `{cancelled, released, waited_ms, matched}`;与 `notifications/cancelled` 走同一个取消位 |
实装口径以附录 D.5 为准。写作时设想的字段是 `{host_id, tool, session_id, started_at, idle_ms, kind}`,
落地时去掉了 `started_at`,补了 `request_id`(供 `mcp_cancel_session` 精确回传)、`busy`、`elapsed_ms`。
`-32003` 的 message 里带上「当前占用者与已持续时间」,模型就能自己决定「等」还是「取消」。
### 5.11 【P2】`tools/list` 体积
**60** 个工具(P11 之后的口径,见 §1.1)、每个都带完整中文描述 + 双 schema。按 54 个工具时(P10-A)实测,
**工具描述与属性说明文本合计约 23 KB**(54 条 `description` + 158 条 schema 属性说明),叠加 JSON
结构与 schema 骨架后,`tools/list` 响应在 **45–60 KB** 量级;多出的 6 个工具只会让它更大。
对 200K 上下文的模型不算致命,但对小上下文客户端(8K–32K)会挤占绝大部分预算,且**每轮对话都要重传**(多数客户端不缓存)。
三个可选做法(不建议同时上):
1. **精简描述**(推荐):把「实现细节、限制、已知问题」从 `description` 移到 `instructions` 或工具文档,`description` 只保留「做什么 + 关键约束」一两句。可省 30–40%。
2. **工具族合并**:`host_list_processes` … `host_get_hosts_file` 这 10 个合并为 `host_list(tab, id, limit, offset)`。省 9 个工具、约 20% 体积,代价是 `annotations` 与 `outputSchema` 变粗(10 个 tab 的条目结构不同),**discoverability 也会下降**——模型看到 `tab` 枚举才知道有哪些能力。**不建议**。
3. **可配置 profile**:`McpToolProfile=full|compact`,compact 只出 `name + 一句话 + 必填参数`。适合小模型客户端,但要维护两套描述。
### 5.12 【P2】`control_service` 的逐项 `Sleep(500)`
`client/ServicesManager.cpp:213` 的 `ServicesConfig` 对每一项 `Sleep(500)` 后再回列表。批量控制 10 个服务 = 至少 5 秒。服务端可以在 `action` 里支持 `items[]` 批量下发(一次子连接、一个 payload),把 N 次往返压成 1 次。**前提是确认客户端能解析多条目 payload**——按现有实现它只处理单条,需要客户端改动,因此列为 P2。
### 5.13 【P0,已修】`kToolHints` 表头注释过期
原注释写「53 个工具的语义登记表」,与数组实际长度不符。P10-A(`bb55f52`)先改成 54,
P10-C(`3d388f8`)加工具时索性去掉数字——避免每加一个工具就要改一次注释;
核对方式见 §1.1,60 个工具与 60 项注解逐条对应。
### 5.14 其他小项
| 项 | 位置 | 说明 |
|---|---|---|
| ~~`list_windows` 无 `pid` 过滤~~ | — | **已完成**(P10-A,`bb55f52`):`list_processes` / `list_windows` 都加了 `name` + `pid` |
| `search_file` 无深度/大小上限参数 | `McpServer.cpp:8050` | 客户端固定深度 32 / 10000 条,服务端可加 `max_depth` 但需客户端支持;暂不做(P12) |
| ~~`search_file` 的描述仍写着「会栈溢出」~~ | — | **已完成**(P10-A,`bb55f52`):描述改为「超过 260 字节的路径会被静默跳过(既不记录也不继续向下递归)」,`tools/mcp_smoke.ps1` 的两处注释改为「MAX_PATH 的条目会被客户端静默跳过(8f718d9 起不再栈溢出)」 |
| `get_screenshot` 无区域裁剪 | `McpServer.cpp:2085` | 有 `max_width`;ROI 需客户端改动,收益有限,不做 |
| 审计不含调用参数 | `Mcp_Design.md §10.8` | 有意设计(防泄漏),维持 |
| `chat_wait` 会取走 inbox | `McpInternal.cpp:431` | 已正确标注非幂等,无需改 |
---
## 6. 批次与验收建议
| 批次 | 状态 | 内容 | 客户端改动 | 规模 | 验收方式 |
|---|---|---|---|---|---|
| **P10-A** | 已完成 `bb55f52` | `instructions`、`capabilities`、`list_*` 过滤、`get_keylog` 离线开关与状态、工具族互指、`kToolHints` 注释(去数字这一步实际随 P10-C 落地,见 §5.13)、`search_file` 过期描述 | 无 | 服务端 ~450 行 | 冒烟断言 `instructions` 非空;`capabilities` 与平台一致;`list_processes(name=...)` 命中数 < 全量且 `totalAll` 正确;`get_keylog.offlineRecord` 与实际 `kbrecord` 一致 |
| **P10-B** | 已完成 `27b5431` | `delete_path` / `move_path` / `create_folder` + `McpFileWrite` 开关 + 系统目录保护 + §2.3 的三处接线 + `verified` 复核 | 无 | ~700 行 | 冒烟新增:建目录→传文件→改名→删除→删目录→越界拒绝;中文路径 + 超长路径各一条;超时后确认**不弹**文件管理器窗口 |
| **P10-C** | 已完成 `3d388f8` | `remote_block_input`(含强制解锁与超时自动解锁) | 无 | ~200 行 | 会话内 block→截图对比→unblock;`remote_close` 后确认已解锁 |
| **P11** | 已完成 `1c832ff`,见附录 D | `power_action` 验证、`dry_run` 统一、`-32012`、progress/cancelled、`mcp_list_sessions` | 无 | ~700 行 | 长任务 progress 回调计数 > 0;取消后主机 1s 内释放(`get_server_status` 可查) |
| **P12** | **待做** | 注册表写、事件日志、进程模块/启动项、`TOKEN_FILE_OP_ERROR`、`DeleteDirectory` 的路径长度防御、`control_service` 批量 payload、`search_file.max_depth` | **需要** | 客户端 + 服务端 | 单独设计文档 |
| **独立立项** | 未立项 | 代理隧道、客户端升级、摄像头/语音 | 视方案 | 大 | 单独安全评审 |
**建议顺序**:P10-A → P10-B → P10-C → P11,**每批独立提交**(已于 2026-10-28 按序完成;
未推送前按批次合并了零碎提交,故每批各一个提交,见上表)。
理由:P10-A 全是**几十行代码换全局体验**的改动(能力自述 + 使用说明 + 描述互指),先落地能立刻降低后续所有工具的试错率,且几乎不引入回归风险;P10-B 是最大的功能缺口,但涉及删除语义,需要更充分的测试与开关灰度;P10-C 小而独立,可随时插入。
---
## 7. 明确不做(本轮)
| 项 | 理由 |
|---|---|
| 剪贴板只读 | 常含口令/令牌/私钥,「读即泄密」,且客户端无只读链路(维持 `Mcp_Design.md §10.7`) |
| 上传执行 / 下载执行 | 等价任意代码执行,与 `McpCmdWhitelist` 逐条加白的安全模型冲突 |
| 写 hosts 文件 | `CREATE_ALWAYS` 整文件覆盖 + 无回包,误操作导致目标机 DNS 全断 |
| 卸载软件 | `WinExec` 卸载串,无回包、可能弹 UAC 阻塞,无法确认结果 |
| 清除事件日志 / 隐藏开网页 / 卸载后门 | 当前 Windows 客户端**未实现**这些命令(死命令) |
| `Ctrl+Alt+Del` / 黑屏 | 客户端未实现,需客户端改动 |
| 10 个 `host_list_*` 合并为 1 个 | 体积收益 20%,discoverability 损失更大(见 §5.11) |
---
## 附录 A:本轮核对过的客户端命令清单
Windows 客户端**已实现**、可作为新工具基础、MCP 尚未使用:
```
COMMAND_DELETE_FILE → TOKEN_DELETE_FINISH client/file/FileManager.cpp:97
COMMAND_DELETE_DIRECTORY → TOKEN_DELETE_FINISH client/file/FileManager.cpp:106
COMMAND_CREATE_FOLDER → TOKEN_CREATEFOLDER_FINISH client/file/FileManager.cpp:116
COMMAND_RENAME_FILE → TOKEN_RENAME_FINISH client/file/FileManager.cpp:119
COMMAND_HOSTS_SET → (无回包, 整文件覆盖) client/MachineManager.cpp:318
COMMAND_APPUNINSTALL → (无回包, WinExec) client/MachineManager.cpp:160
COMMAND_SCREEN_BLOCK_INPUT → (无回包, 2 字节) client/ScreenManager.cpp:1198
COMMAND_KEYBOARD_OFFLINE → (无回包, 2 字节) client/KeyboardManager.cpp:125
COMMAND_KEYBOARD_CLEAR → (无回包, 1 字节) client/KeyboardManager.cpp:131
COMMAND_UPDATE → 升级链路 client/KernelManager.cpp:1466
COMMAND_UPLOAD_EXEC → 执行上传文件 client/KernelManager.cpp:880
COMMAND_PROXY → 端口转发 client/KernelManager.cpp:1039
COMMAND_SCREEN_WINDOW / _ROI → 流式窗口/区域捕获 client/ScreenManager.cpp:894 / :886
COMMAND_WEBCAM / COMMAND_AUDIO→ 流式音视频 client/KernelManager.cpp:1399 / :1414
```
> 已排除 `COMMAND_PROCESS_FREEZING` / `COMMAND_PROCESS_THAW`——它们**已被 `host_control_process` 使用**
> (`McpMachine.cpp:2107`),不属于缺口。
**定义了但 Windows 客户端未实现**(不可用):`COMMAND_CLEAN_EVENT`、`COMMAND_OPEN_URL_HIDE`、`COMMAND_OPEN_URL_SHOW`、`COMMAND_REMOVE`、`COMMAND_SCREEN_CTRL_ALT_DEL`、`COMMAND_SCREEN_BLANK`。
---
## 附录 B:本轮核对过的关键代码位置
| 主题 | 位置 |
|---|---|
| 工具注解登记表(60 项) | `server/2015Remote/McpInternal.cpp:375` |
| `tools/list` 构造 | `server/2015Remote/McpServer.cpp:1408` |
| `initialize` 结果构造 / HTTP 方法分派 | `McpServer.cpp:46` `BuildInitializeResult` / `:7622` 起 |
| 主机技术字段补全 | `server/2015Remote/McpServer.cpp:2018` `AppendHostTechnicalDetail` |
| 文件链路(列目录/搜索/下载) | `McpServer.cpp:2419` / `:8050` / `:6430` |
| 机器管理写工具范式 | `McpMachine.cpp:2531` `AddTool` / `:2127` `host_control_process` |
| `power_action`(发完即走) | `McpServer.cpp:5812` |
| `get_keylog`(固定窗口) | `McpServer.cpp:1558` / `:5985` |
| 配置键全集 | `2015RemoteDlg.cpp:2416` 起 + `McpSettingsDlg.cpp:227` / `:383` |
| 错误码表 | `docs/Mcp_Design.md §12` |
| 已修问题与实测 | `docs/Mcp_Test_Report_2026-10-25.md §0` |
---
## 附录 C:服务端接线点(P10-B 施工前必读)
MCP 子连接的分包路由有三层,新增一个「用子连接完成一次写操作」的工具时,**必须三处都改**,
少改任何一处都会出现「命令发不出去」「子连接泄漏」或「弹 MFC 窗口」:
| 层 | 位置 | 作用 | 不改的后果 |
|---|---|---|---|
| 1. 就绪包分流 | `McpServer::OnDriveList`(`McpServer.cpp:7832`) | 子连接建好后的第一个包(`TOKEN_DRIVE_LIST`)到达;按 `tool` 决定下发什么 | 沿用「空 path = 只列盘」判定 → 写命令永远发不出去,工具超时 |
| 2. 完成包投递 | `CMy2015RemoteDlg::MessageHandle`(`2015RemoteDlg.cpp:6003` 的 switch) | 三个 `TOKEN_*_FINISH` 目前无 case | 落到 `default:` 只打日志、不关子连接 → 子连接泄漏 + 工具等到超时 |
| 3. 迟到吸收 | `CMcpServer::MarkLateFirstPacketForTool`(`McpServer.cpp:7760`) | 工具放弃后吸收迟到的就绪包 | 目标机上**弹出 MCP 自己触发的文件管理器窗口** |
另一处相关:`NotifyProc`(`2015RemoteDlg.cpp:5581`)在 `ContextObject->hDlg` 非空时把包转给对话框,
MCP 路径的 `hDlg` 恒为 `NULL`,所以第 2 层一定会命中——这一点已核对,不是假设。
配置开关的接线也是三处:读取(`2015RemoteDlg.cpp:2416` 块)、对话框回填(`McpSettingsDlg.cpp:227`)、
落盘(`McpSettingsDlg.cpp:383`)。对话框是**纯代码构建**的(`McpSettingsDlg.cpp:128-186`),
插入一个 checkbox 需要重排其下所有控件的 y 坐标与窗口高度。
---
## 附录 D:P11 施工记录(2026-10-28)
零客户端改动,全部落在服务端(`McpServer.cpp` / `McpServer.h` / `McpMachine.cpp` /
`McpChat.cpp` / `McpInternal.{h,cpp}`)。
### D.1 `power_action` 的结果验证(§5.4)
- 新入参 `wait`(bool,默认 false)与 `wait_ms`(1000–600000,默认 60000),`wait_ms` 是
「等离线」与「等回线」**各自**的时限;`wait=false` 时也会校验 `wait_ms` 的取值范围。
- 输出从 `{ok}` 扩展为 `{ok, sent, went_offline, came_back, elapsed_ms}`:
`sent` 恒为 true(命令写进 socket),`went_offline` / `came_back` 由主连接的出现/消失判定
(`FindMainContext`,200ms 轮询),`elapsed_ms` 为整次调用的耗时。
- **超时不是错误**:`wait=true` 但没等到离线/回线时仍返回 `ok:true` 并在正文里写清「仍在
线」或「已离线但未回线」,让模型据此决定是否再等,而不是把「没等到」当成失败重试。
- `logout` 之后主机不会自动回线(需要人工登录),正文单独提示。
### D.2 破坏性工具统一 `dry_run`(§5.5)
| 工具 | `dry_run=true` 时的行为 |
|---|---|
| `kill_process` | 只取一次进程列表,回 `{ok, dry_run, targets:[{pid,name,path}], missing:[pid...]}`,**不下发终止命令**;一个都匹配不到返回 `-32009` |
| `operate_window` | 只取一次窗口列表,回 `{ok, dry_run, action, window}`;窗口不存在返回 `-32009` |
| `host_control_process` / `_window` / `_service` / `_task` | 只做目标存在性校验,回 `{ok, dry_run, action, target, state, detail}`(detail 是被影响对象的原始字段) |
实现要点:dry run 的挂起项以 `"<tool>/dryrun"` 登记,`OnSystemReady` 只认 `kill_process` /
`operate_window` 两个**精确**工具名,因此不会误发后续写命令;迟到首包仍按既有逻辑吸收。
### D.3 `-32012` 与 `-32008` 别名(§5.6)
- 两个真实站点(`exec_command` 的 shell 元字符、`terminal_exec` 的 `&`/`|`/换行)改为
`McpInternal::kErrValidation = -32012`;`kErrValidationOld = -32008` 保留为历史别名,不再新增使用。
- `initialize.instructions` 的错误码表与 `docs/Mcp_Design.md §12` 同步;`-32800` 一并登记。
### D.4 `notifications/progress` 与 `notifications/cancelled`(§5.9)
**传输**:本服务端原本每个 POST 只回一个 JSON。带 `params._meta.progressToken` 的 `tools/call`
改走 MCP Streamable HTTP 允许的 `text/event-stream`(同一个 POST):
1. 工具在独立线程执行,`McpCallContext` 经 FLS(Fiber Local Storage)暴露给工具实现
——**不能用 `thread_local`**:本工程有 shellcode/MemoryModule 手工映射出来的线程,没有
PE 的 TLS 初始化,加一个静态 `thread_local` 就会让服务端启动约 1s 后跳飞(实测);
2. 进度通知与最终响应都从这个 SSE 流写出(`McpProgressChannel`,背压队列上限 64 条,
满了丢最旧——进度是「最新值有意义」的信号);
3. 不带 token 的请求完全不变(一次性 JSON)。
**进度上报点**(`McpCallProgress`,内部 1s 节流):
| 工具 | 进度含义 |
|---|---|
| `download_file` | `filesDone / (totalFiles - directoryCount)`;总量未知时退回已收字节数 |
| `upload_file` | 已发数据字节 / 待发数据字节总数(在 worker 的分块回调里累加) |
| `copy_files_c2c` | 源端只在最后回一包结果,因此不报中间进度;取消/超时按既有路径收尾 |
| `search_file` | 命中数在客户端,服务端只在收尾时报一次结果(见下) |
| `chat_wait` | 等待期无中间量,取消即时生效 |
**取消**:三条入口共用一个取消位(`McpCallContext::cancelled`)
- `notifications/cancelled`(`params.requestId` 按 JSON-RPC id 精确匹配,字符串与数字不混用);
- `mcp_cancel_session`(按 request_id / host id / session_id);
- SSE 流写失败(客户端已断开)。
所有长等待都改成「≤500ms 一片 + 每片检查取消位」(`WaitWithCancel`),取消后直接落到各函数
**既有的超时/放弃分支**:`MarkLateFirstPacketForTool` 照登、子连接照关、挂起项照删。因此取消
不需要第二套清理逻辑,也满足「取消后主机 1s 内释放」。取消导致的失败结果由分发层统一改写成
`-32800`(已经拿到成功结果则照实返回)。
### D.5 `mcp_list_sessions` / `mcp_cancel_session`(§5.10)
- `mcp_list_sessions`:一次快照列出在飞 `tools/call`(含 JSON-RPC `request_id`)、挂起中的一次性
请求、终端、远程控制、文件传输、远程交谈;字段 `host_id/kind/tool/session_id/request_id/busy/
elapsed_ms/idle_ms`,可选 `kind` 过滤。纯本地,**不受功能开关与只读模式限制**。
- `mcp_cancel_session`:按 `request_id`(精确)或 `id`/`session_id`(条件)取消,返回
`{cancelled, released, waited_ms, matched}`;最多等 2s 让工具线程走完清理,`released` 说明
主机是否真的松开。
- `-32003` 的文案统一追加占用者:`Device busy: another request is pending for this host
(tool=download_file, elapsed=12s)`。`DescribeBusy` 会排除发起本次错误的那个调用自身。
### D.6 已知边界
- SSE 请求会占住 httplib 的一个 worker 线程直到工具结束(线程池 32);单机管理场景足够,
不作为多租户端点使用。
- `search_file` 被取消时返回**已收到的部分结果**(`finished=false`),不是 `-32800`:搜索是只读
累积操作,部分结果对调用方更有用;它同样在 ≤1s 内释放主机。
- `mcp_cancel_session` 找不到匹配项时返回 `cancelled:0`(不是错误)——请求可能已经结束,
或 `request_id` 的 JSON 类型与调用时不一致。
+2 -2
View File
@@ -275,7 +275,7 @@ Web 是长连接,子链接可长驻;MCP 是**一次性 request/response**。
- 复用 MFC 预览的 RTT/FRP 自适应参数挑选 `ChooseScreenPreviewParams` + `SendScreenPreviewRequest`,不重复实现 `GetTargetQualityLevel`。
- **可选 `max_width` 参数**:缺省/0 沿用缩略图档位(最大 1024,4K 源屏高档 1280);`max_width`>0 覆盖宽度并钳制到客户端上限 `[64,1920]`(客户端 `CaptureAndEncodePreview` 硬钳制),供 AI 视觉/OCR 场景请求接近原分辨率(1080p 源屏传 1920 即原分辨率,4K 源屏最多 1920)。`jpegQuality` 仍沿用档位自适应值。
- **请求关联**:`ScreenPreviewReq.reqId` 提供关联;MCP 用独立 16 位 reqId 发生器(`NextPreviewReqId`,跳过 0)+ `SetPendingReqId` 登记期望值,`TakePreviewResponse` 只接受「挂起命中 + reqId 一致」的响应,过期/他途(MFC 预览并发)响应原样回落到 MFC 路径。
- 客户端能力位 `CLIENT_CAP_SCREEN_PREVIEW`(0x0004,仅 Windows 客户端声明):非 Windows 主机返回 `-32005`「不支持」。
- 客户端能力位 `CLIENT_CAP_SCREEN_PREVIEW`(0x0004):Windows 客户端恒声明;Linux 客户端在登录时探测到可用 X11 桌面才声明(无 `DISPLAY` 的服务器不声明)。未声明的主机返回 `-32005`「不支持」。
- 返回结构:`content[0] = {type:"image", data: base64(JPEG), mimeType:"image/jpeg"}` + `structuredContent.image = {mimeType,width,height,bytes}`(元数据,不含 base64,避免二次膨胀)。
**`list_files`(文件链路,一次性子链接,模式 A′)**:
@@ -303,7 +303,7 @@ Web 是长连接,子链接可长驻;MCP 是**一次性 request/response**。
**验收 / 实机验证点(待构建后执行)**:
- MFC 双击文件管理弹框仍正常(回归点);MFC 双击预览缩略图仍正常(回归点)。
- MCP `get_screenshot` 返回 JPEG(base64 + 元数据),Windows 主机正常;非 Windows 主机(或未声明 `CLIENT_CAP_SCREEN_PREVIEW`)返回 `-32005`。
- MCP `get_screenshot` 返回 JPEG(base64 + 元数据),Windows 主机正常;带 X11 桌面的 Linux 主机同样正常(客户端回 BGRA,服务端转 JPEG);未声明 `CLIENT_CAP_SCREEN_PREVIEW` 的主机返回 `-32005`。
- MCP `list_files`(无 `path`)返回 `drives[]`;`list_files(path="C:\\")` 返回 `files[]`(含目录/文件/大小/mtime),中文文件名无乱码;条目 >500 时截断为 500。
- 错误路径:缺 `id`/非数字 `id` → `-32602`;未知/离线主机 → `-32002`;同 host 并发 → `-32003`;发送失败 → `-32004`;超时 → `-32001`。
+15 -5
View File
@@ -1,7 +1,7 @@
# MCP 远程控制(Remote Control)设计文档
> 版本:v1(设计基线) 状态:待开发 关联:`docs/Mcp_Design.md`、`docs/Mcp_Terminal_Design.md`
> 定位:本文件是「AI 远程控制一台 Windows 客户端(像人一样点鼠标、敲键盘、看画面完成任务)」功能的**唯一参照设计**,后续开发一律以本文为准,改需求先改本文。
> 定位:本文件是「AI 远程控制一台 Windows 或 Linux 客户端(像人一样点鼠标、敲键盘、看画面完成任务)」功能的**唯一参照设计**,后续开发一律以本文为准,改需求先改本文。Linux 支持范围与限制见 §6.5、§12.1。
---
@@ -172,6 +172,7 @@ AI 无法「看懂」视频流。把 25fps 的远程画面直接丢给视觉模
- **包格式**:`[cmd:1][MSG64:48]`,可批量重复(`commands.h` `COMMAND_SCREEN_CONTROL=20`,`MSG64` 1581–1623)。
- **MSG64 布局**:`{uint64 hwnd, message, wParam, lParam, time; POINT pt;}` = 48 字节(`_WIN64` 下 `MYMSG` 即 `MSG`;客户端亦接受 28 字节 `MSG32`,由 `ulLength % 28/48` 判定)。
- **一条一包(重要)**:协议允许一包多消息,Windows 客户端也支持(`ProcessCommand` 按 `ulLength % 48 / % 28` 算出条数后逐条处理);但 Linux 客户端(`linux/ScreenHandler.h` `OnReceive`)**只处理包内第一条**。服务端因此统一按「一条 MSG64 一个 `COMMAND_SCREEN_CONTROL` 包」下发(`SendScreenCtrlEvents`):批量下发会让 Linux 上的 `key_press` 只按下不抬起(X11 自动重复)、`click` 只按下、`type` 只打出首字符。对 Windows 客户端完全等价。
- **客户端解码**:`ScreenManager.cpp:1175` → `ProcessCommand(1727)` → `SendInput`:
- 鼠标:坐标取 `LOWORD/HIWORD(lParam)`,`WM_MOUSEMOVE`→`MOUSEEVENTF_MOVE`,`WM_LBUTTONDOWN/UP`→`LEFTDOWN/LEFTUP`,`WM_LBUTTONDBLCLK`→额外 `LEFTDOWN`,`WM_MBUTTONDOWN/UP`,`WM_MOUSEWHEEL`→`MOUSEEVENTF_WHEEL`(`mouseData=GET_WHEEL_DELTA_WPARAM`)。
- 键盘:`wVk=(WORD)wParam`,`wScan=(lParam>>16)&0xFF`,`KEYEVENTF_EXTENDEDKEY` 由 `(lParam>>24)&1`。
@@ -205,6 +206,16 @@ AI 无法「看懂」视频流。把 25fps 的远程画面直接丢给视觉模
- 随后 `remote_keyboard` 注入 `Ctrl+V` 粘贴、`Enter` 发送。
- **编码注意(已核实)**:`UpdateClientClipboard` 用 `SetClipboardData(CF_TEXT,...)`——ANSI/GBK 格式(`CF_TEXT`,非 `CF_UNICODETEXT`)。MVP 下中文可经 `ToAnsi(utf8, 936)` 转 GBK 后直发(与终端命令同模式);但 emoji/非 GBK 字符会丢、部分新式聊天软件粘贴偏好 Unicode。更稳做法是复用 `COMMAND_C2C_TEXT`(90) 的 UTF-8→Unicode→`CF_UNICODETEXT` 逻辑(`KernelManager.cpp:1573-1587`,且已内置「设完剪贴板后自动模拟 Ctrl+V」),或新增一个 UTF-8 设剪贴板变体。见 §17 实验案例。
### 6.5 Linux 客户端(`RES_CLIENT_TYPE=LNX`)
服务端路径与 Windows 完全一致(`COMMAND_SCREEN_SPY` → `TOKEN_BITMAPINFO` → `COMMAND_SCREEN_CONTROL`),差异都在客户端(`linux/ScreenHandler.h`,本轮**未改客户端**):
- **注入**:走 XTest(`XTestFakeMotionEvent` / `XTestFakeButtonEvent` / `XTestFakeKeyEvent`),需要 `libXtst` 与可用的 X 连接(X11 或 XWayland)。
- **按键映射**:`VKtoKeySym` 把 Windows VK 映射为 X11 keysym 后 `XKeysymToKeycode`。支持 A–Z、0–9、小键盘、F1–F12、方向键/编辑键、修饰键(`VK_SHIFT→Shift_L`、`VK_CONTROL→Control_L`、`VK_MENU→Alt_L`、`VK_LWIN→Super_L`)与 OEM 标点;**F13–F24 与 `VK_APPS` 无映射**(消息被忽略,不报错)。
- **滚轮**:客户端收到 `WM_MOUSEWHEEL` 后按 120 的倍数换算成 Button4/Button5 的按放对,单条消息即可(服务端 `scroll` 只发一条)。
- **剪贴板**:服务端按 GBK 下发(与 Windows 相同),Linux 客户端 `ClipboardHandler::SetTextRaw` 检测编码并用 iconv 转 UTF-8 后写 `xclip -selection clipboard`;需要 `xclip` 或 `xsel`。非 GBK 字符(emoji)在服务端就已变成 `?`,Linux 侧无法挽回。
- **分辨率**:`TOKEN_BITMAPINFO` 的尺寸取自 root window,与服务端归一化坐标一致;多显示器判定依赖客户端心跳的 `RES_RESOLUTION`(`xrandr` 才能拿到显示器数),无 `xrandr` 时上报 `0:0*0`,服务端按「无法判定」放行。
---
## 7. 坐标约定与映射
@@ -295,10 +306,8 @@ remote_open ──► 建立子连接 ──► [remote_mouse/remote_keyboard ×
| -32002 | 设备/会话不存在 | `id` 无在线主机、`session_id` 不存在或不匹配 |
| -32003 | 设备/会话忙 | 已有控制会话、人类远程桌面占用、`get_screenshot` 在飞 |
| -32004 | 发送失败 | 注入命令发送失败 |
| -32005 | 能力不支持 | 客户端无 `CLIENT_CAP_SCREEN_PREVIEW`(Observe)/ 不支持屏幕控制(Act) |
| -32005 | 能力不支持 | 客户端无 `CLIENT_CAP_SCREEN_PREVIEW`(Observe)/ 不支持屏幕控制(Act)/ **多显示器主机(阶段一)** |
| -32006 | 被开关禁用 | `McpRemoteControl=0` 或 `McpReadonly=1` |
| -32008 | 非法/被拒参数 | 多显示器未支持时的 `remote_open` 降级拒绝(阶段一) |
---
## 11. 配置项
@@ -317,8 +326,9 @@ remote_open ──► 建立子连接 ──► [remote_mouse/remote_keyboard ×
### 12.1 阶段一(本期)
- **单显示器**:Observe 抓主屏,坐标空间与虚拟桌面重合;多显示器 `remote_open` 显式报错(`-32008`)。
- **单显示器**:Observe 抓主屏,坐标空间与虚拟桌面重合;多显示器 `remote_open` 显式报错(`-32005`,能力限制而非参数错误)。
- 注入基于**绝对坐标** `SendInput`,要求客户端处于可注入的桌面会话(已登录、非锁屏/非 UAC 安全桌面);锁屏/UAC 提示场景注入无效(客户端 `SendInput` 限制),设计文档记录为已知限制。
- **Linux 专属限制**(§6.5):纯 Wayland 会话不支持(需 X11/XWayland);需 `libX11`+`libXtst`,剪贴板需 `xclip`/`xsel`;F13–F24、`VK_APPS` 无 keysym 映射;非 ASCII 文本仍只能走剪贴板。
- **代聊实验使能项**:窗口抓屏(`COMMAND_SCREEN_WINDOW`)、UTF-8 剪贴板、窗口聚焦随阶段一落地(§17)。
### 12.2 阶段二(后续)
+6 -6
View File
@@ -153,8 +153,8 @@ FindMainContext → -32002 主机不存在/离线
clientType==LNX/MAC → -32005 仅 Windows
command 为空 → -32602
mcp.IsReadonly() → -32006 只读模式默认开,需 McpReadonly=0
含 &|<>^ 五元字符 → -32008 防注入绕过白名单
含控制字符(\r\n 等 <0x20) → -32008 防换行拆分绕过白名单
含 &|<>^ 五元字符 → -32012 防注入绕过白名单(-32008 为历史别名)
含控制字符(\r\n 等 <0x20) → -32012 防换行拆分绕过白名单
白名单前缀校验 → -32007 不在白名单
```
@@ -237,7 +237,7 @@ SweepIdleTerminals(300)
ResolveTerminalSessionHost
session_id 为空 → -32602
command 为空 → -32602
command 含 & 或 | → -32008(正确性门,见 §4.6)
command 含 & 或 | → -32012(正确性门,见 §4.6)
nonce = 随机 8 hex
BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty)
→ false 则 -32002(不存在/不匹配/未就绪/忙碌/已关)
@@ -273,7 +273,7 @@ CloseTermSession(devId, sessionId)
### 4.6 正确性门 `&|`(非安全门)
`terminal_exec` **拒绝含 `&` 或 `|` 的命令**(`find_first_of("&|")`,含 `&&`/`||`/`|`),报 `-32008`。原因:哨兵包装 `cmd 2>&1 && echo ... || echo ...` 假定命令是「扁平」的,命令内含 `&`/`|` 会与包装的控制操作符合流、导致退出码失真/输出归属不清。
`terminal_exec` **拒绝含 `&` 或 `|` 的命令**(`find_first_of("&|")`,含 `&&`/`||`/`|`),报 `-32012`(历史别名 `-32008`)。原因:哨兵包装 `cmd 2>&1 && echo ... || echo ...` 假定命令是「扁平」的,命令内含 `&`/`|` 会与包装的控制操作符合流、导致退出码失真/输出归属不清。
- 这是**正确性限制,不是白名单**——持久终端本就不设白名单。
- 同样拒绝 `<0x20` 的控制字符(`\r`/`\n`):换行会把命令拆成多行、只有末行被哨兵包装,导致退出码与输出归属失真。
@@ -415,7 +415,7 @@ McpServer().SetTerminalEnabled(THIS_CFG.GetInt("settings", "McpTerminal", 0) !=
| `-32005` | 非 Windows | LNX/MAC 客户端 |
| `-32006` | 已禁用/只读 | `IsReadonly()` 或 `!IsTerminalEnabled()` |
| `-32007` | 白名单拒绝 | `IsCommandAllowed` false |
| `-32008` | 含禁用字符 | `exec_command` 的 `&|<>^`;`terminal_exec` 的 `&|` |
| `-32012` | 含禁用字符 | `exec_command` 的 `&|<>^`;`terminal_exec` 的 `&|`(早期版本用 `-32008`,同一语义) |
| `-32602` | 参数非法 | `ParseHostIdArg` 失败、缺 required 参数 |
| `-32700` | JSON 解析错误 | 请求体非合法 JSON-RPC |
@@ -446,7 +446,7 @@ McpServer().SetTerminalEnabled(THIS_CFG.GetInt("settings", "McpTerminal", 0) !=
### 10.5 stdout 里出现命令本身 / 哨兵
- 命令本身回显 = ConPTY 输入回显,已由 `StripEchoedCommand` 服务端剔除(§2.4)。若仍出现,检查是否该行因编码(非 PTY 老管道的 GBK)与 `echoedLine` 字节不一致而 `find` 不到——老管道本应无回显。
- 哨兵 `__MCP_DONE_...` 出现 = 哨兵截断/清洗异常,通常意味着命令含 `&|` 破坏了控制操作符链(持久终端会提前 `-32008` 拒绝,一次性会 `-32008` 拒绝五元字符)。
- 哨兵 `__MCP_DONE_...` 出现 = 哨兵截断/清洗异常,通常意味着命令含 `&|` 破坏了控制操作符链(持久终端会提前 `-32012` 拒绝,一次性会 `-32012` 拒绝五元字符)。
### 10.6 中文/乱码
+166
View File
@@ -0,0 +1,166 @@
# YAMA MCP 服务测试报告
- 日期:2026-10-25(两轮:本机回环 + 虚拟机复测)
- 环境:
- 第1轮:Debug 服务端 `Yama_x64d.exe` + 本机被控端 `ghost.exe`(Windows 11,双显示器)
- 第2轮:同一 Debug 服务端 + VirtualBox 虚拟机被控端(`DESKTOP-A55C0OI`,Windows 10 19045,单显示器 1718x920,clientType=MDLL)+ 重启后的本机被控端
- 配置:`Bin\settings.ini`(McpEnabled=1,McpPort=6545,McpBind=127.0.0.1,McpReadonly=0,全部 `Mcp*` 开关开启)
- 方法:Python 直连 `http://127.0.0.1:6545/mcp`(JSON-RPC 2.0),辅以 `tools/mcp_smoke.ps1`、审计日志、`get_client_log`、代码审读交叉验证
- 敏感操作约束:删除类操作仅针对本次自建的临时文件/目录(本机 `%TEMP%\yama_mcp_test`、VM 同名目录),测试后已全部清理
---
## 0. 复核与处置(同日二次复核)
复核方式:逐条回到源码确认现象与根因,再在 Debug 实例(`Bin\Yama_x64d.exe` + 本机 `ghost.exe`,Windows 11 双屏 ConPTY 客户端)上端到端复现与验证修复。复核用的客户端配置临时改为直连本机(`x64\Debug\settings.ini`:`master=127.0.0.1`、`ghost=6543`、`UseFrp=0`,原文件备份为 `settings.ini.bak_mcptest`);修复后在 Debug 实例上 `tools/mcp_smoke.ps1 -SearchPath C:\Windows\Fonts` **37/37 通过**。
| 编号 | 复核结论 | 处置 | 验证证据(修复后实测) |
|---|---|---|---|
| P1 | 属实 | **已修**。ConPTY 下哨兵改为独立一行(`@echo off & <cmd>` + 单独 `echo __MCP_DONE_<nonce>__%errorlevel%`);会话因超时被销毁后留 600s 墓碑,报错文案区分「被销毁」与「id 写错」。老客户端(非 PTY)保持单行 `&&` 形态,行为不变。 | `rem hello` → exit 0(原 100% 超时);`cmd /c exit 0` → exit 0;`cmd /c echo abc` → `abc`。超时路径:`ping -n 40` 配 `timeout_ms=3000` → `-32001`,随后同一 session → `-32002 "Terminal session was destroyed after this command timed out (waited 3000 ms); call terminal_open again"`;假 id → `-32002 "Terminal session not found: <id> (call terminal_open first)"`;销毁后 `terminal_open` 立即成功 |
| P2 | 属实(结论成立),但「10 个纯本地 DB 读取」的**表述有误**——被挡的是经主连接向目标机取数据的远程机器管理工具(`host_list_processes/windows/network_state/scheduled_tasks/services/…`、`host_get_hosts_file` 等,都走 `BeginPending`),属 single-flight 设计;纯服务端本地工具(`get_server_status`、`get_audit_log`、`host_set_remark` 等)不受影响 | **已修**(选了「快速失败」):文件传输加 60s 停滞看门狗,`timeout_ms` 内只要持续有数据就不受影响;默认超时保持 600s(避免误杀大文件)。互斥豁免未做——远程工具之间互斥本身就是有意的。 | 不存在路径 `C:/no_such_dir_zzz_mcp` → **60096ms** 失败,`-32001 "File transfer stalled: no data received for 60s (the remote path is probably missing or inaccessible; verify it with list_files first)"`(原为 `ms=600004`);挂起期间 `get_server_status` 2120ms OK、`get_audit_log` 20ms OK,远程 `list_files` 仍 `-32003`;失败后主机立刻释放,冒烟脚本随即 37/37 通过。**2026-10-25 二次修**:新客户端在建立传输子链接前就回 `TOKEN_DOWNLOAD_ERROR`(173),`download_file` 不存在路径现在 **0.07s → `-32009`**(`Remote path does not exist: ... (win32=3)`),60s 停滞看门狗降级为兜底 |
| P3 | 属实 | **已修**。`%errorlevel%` 在回显文本里是字面模板而非数字,`FindSentinel` 改为「从后往前找第一个『标记+数字』」,不再依赖行首。 | `ver` → exit 0(原 1);`nosuchcmd_zzz` → 9009;`cmd /c exit 0` → 0;`set NOVAR` → 1 |
| P4 | 属实 | **已修**。清洗改为三段:删到「命令行回显」结束(顺带清掉 shell 启动画面/提示符)→ 删哨兵行回显 → 按 nonce 擦掉渲染残留的哨兵文本;另修 `StripAnsi` 对 `OSC…ESC\` 的收尾(会残留 `\`)。设计见 `docs/Mcp_Design.md` §12.1。 | 上述命令的 stdout 全部无 `@echo off`、无 `__MCP_DONE_*`、无提示符/空行;`type` 报错文本无残留反斜杠 |
| P5 | 属实 | **已修**(`McpInternal.cpp` 注解表 `get_activity_history` → `openWorld=true`,附代码注释说明它经 `COMMAND_QUERY_ACTIVITY` 触达远程主机) | 代码审查 + 与 §10.2 口径一致 |
| P6 | 属实(`OpenSCManager` 权限不足,客户端失败分支回普通消息包) | **已修**:新增 `TOKEN_SERVICE_ERROR`(170),客户端 `SendServicesList` 失败时回 `[170][win32:4]`(并保留原 `ClientMsg`,老服务端行为不变);服务端转译成 `-32010`,文案点明需要管理员权限 | 非提权客户端 `list_services` → **268ms `-32010`**(`Failed to enumerate services: access denied (win32=5). service enumeration requires the client to run elevated (administrator)`;原为 20s `-32001`) |
| P7 | 属实 | **已修**(文档):`docs/Mcp_Design.md` §12 补齐 `-32007`/`-32008`/`-32009` 并注明 `-32008` 的四类语义 | 文档核对 |
| P8 | 属实 | **已修**:新增 `TOKEN_FILE_LIST_ERROR`(171) / `TOKEN_REG_ERROR`(172),客户端失败分支回 `[token][win32/lstatus:4]`;服务端按 `2/3 → -32009`、`5 → -32010` 转译,空目录/空键仍返回成功空列表 | `list_files C:\no_such_dir_xyz` → **0.22s `-32009`**、`list_files C:\System Volume Information` → **0.06s `-32010 (win32=5)`**;`list_registry HKLM\Software\NoSuchKeyXYZ` → **0.10s `-32009`**、`HKLM\SAM\SAM\Domains\Account` → **0.08s `-32010`**;空目录/正常目录/正常键返回不变 |
**结论**:报告的问题清单与根因分析全部成立(仅 P2 有一处表述需要更正);P1/P3/P4(同一处哨兵机制)与 P5/P7、P2 的「长时间锁定」已在服务端修复并端到端验证,P6/P8 已在放开「客户端可小改」后按结构化失败回报修复(见上表,均为亚秒级返回)。
---
53 个工具全部可达,冒烟脚本 32/32 通过。功能面整体质量良好;VM 复测轮验证了第1轮受条件所限未能覆盖的远程控制族(11/11)、跨机文件往返、真实 kill 目标校验,并把第1轮两大疑难问题(exec_command 超时、list_services 超时)推进到根因定性。
最终问题清单:**2 个高优先级**(哨兵机制对吞行命令必然超时并销毁会话;download_file 失败路径长时间锁定主机)、**3 个中优先级**(exit_code 不可靠、stdout 内部实现泄漏、get_activity_history 注解错误)、**3 个低优先级**(list_services 权限失败无解释、错误码缺漏/-32008 复用、路径类工具静默空结果)。每条问题的逐条复核结论、处置与修复后实测证据见 §0。
## 2. 问题清单
### P1(高):哨兵机制——「吞行」命令 100% 超时,且销毁持久会话
哨兵方案:发送 `@echo off & <cmd> 2>&1 && echo __MCP_DONE_<nonce>__0 || echo __MCP_DONE_<nonce>__1`,服务端扫描输出定位哨兵取退出码(`McpServer.cpp:2721/3027` 发送、`FindSentinel :6195` 匹配)。
缺陷:**任何会消费行内剩余文本的命令都会把哨兵一起「吞掉」**,导致哨兵永远不出现:
| 命令 | 结果 | 机制 |
|---|---|---|
| `rem hello` | 超时 | `rem` 把整行剩余部分当注释,`&& echo 哨兵` 不执行 |
| `cmd /c exit 0` | 超时(2/2 会话复现) | `cmd /c` 把 `&& echo 哨兵` 一并传给子进程,子进程 `exit` 即退 |
| `if`/`for` 同理 | 预期同 | 同类吞行语句 |
后果链:20s 等待 → `-32001 Timeout waiting for command output`;**持久终端路径上 `WaitTermCommand` 超时直接销毁会话**(`McpServer.cpp:6400` 附近),后续所有 `terminal_exec` 报 `-32002 "Terminal session not found, not ready, or busy"`——报错文案无法区分「会话已被超时销毁」与「id 写错」。
- 正常对照:`whoami` 35/35 成功(62-217ms)、`set NOVAR`(失败有哨兵)正确返回 exit=1、`cmd /c echo abc`/`cmd /c ver`(子进程有输出)成功。
- 建议:
1. 哨兵改为独立行下发(先发命令行,再单独发 `echo __MCP_DONE_...__0 || echo ...` 第二行,或用 `(%cmd%) & (echo sentinel)` 子shell包裹);
2. 会话被超时销毁后,`terminal_exec` 对该 session_id 返回专门的错误文案(如 "session destroyed after timeout; re-open");
3. 文档标注 `exec_command`/`terminal_exec` 不支持 `rem`、`cmd /c` 等吞行命令。
**复核(2026-10-25)**:属实。已按建议 1、2 修复并验证(PTY 下哨兵独立成行;超时销毁会话留墓碑 + 专用文案),文档见 `docs/Mcp_Design.md` §12.1。老客户端(非 PTY)仍为单行形态,故「吞行命令」限制只适用于老客户端。
### P2(高):`download_file` 对不存在路径无快速失败,默认 600 秒锁定整台主机
- 不存在的远程路径会等满默认 `timeout_ms=600000`(实测审计日志 `ms=600004`),期间该主机**所有**远程机器管理工具 `-32003`(single-flight 跨工具互斥),含 `host_list_processes/windows/network_state/scheduled_tasks/services`、`host_get_hosts_file` 等**经主连接向目标机取数据**的工具。一次误路径 = 10 分钟整机不可管理。(初版报告把这批工具写成「10 个纯本地 DB 读取」,属表述错误:它们都要触达目标主机,被互斥挡住是设计;纯服务端本地工具如 `get_server_status` / `get_audit_log` / `host_set_remark` 不受影响,二次复核已实测确认。)
- **timeout_ms 参数本身工作正常**(显式 8000 → 实测 8031ms 终止),问题是默认值过长 + 缺路径检测。
- 建议任选:客户端枚举路径时快速失败(最优);或下调默认超时(如 60s);或本地读取类工具豁免 BeginPending 互斥。
### P3(中):`exit_code` 不可靠(哨兵匹配到回显模板)
- `ver`(成功命令)返回 `exit_code=1`。根因:ConPTY 80 列回显折行使**回显的命令模板**中 `|| echo __MCP_DONE_<nonce>__1` 片段落到行首,`FindSentinel`(`McpServer.cpp:6195`)要求哨兵前是 `\n`/`\r`,于是 rfind 命中的是回显片段而非真实执行的哨兵。
- 影响:依赖 exit_code 的自动化会把成功当失败。与 P1 同根(哨兵与回显混在同一输出流)。
- 建议:随 P1 一起修(独立行哨兵可同时解决);短期可在 FindSentinel 中排除与已发送命令行重叠的匹配位置。
**复核(2026-10-25)**:属实。已随 P1 修复:`%errorlevel%` 回显是字面模板、`FindSentinel` 改为从后往前找「标记+数字」,实测 `ver`→0、`nosuchcmd_zzz`→9009。
### P4(中):`stdout` 泄漏内部实现(回显命令行 + 哨兵文本)
- `terminal_exec`/`exec_command` 返回的 stdout 中可见 `@echo off & ...` 命令回显、`__MCP_DONE_<nonce>__0/1` 哨兵字样(多例复现,如 `cmd /c echo abc` 的 stdout 含 `__0 || echo __MCP_DONE_2c0fbce0__1\nabc`)。
- 原因:ConPTY 回显折行后 `StripEchoedCommand` 的整行匹配失效;哨兵截断点之后的清洗也不覆盖片段。
- 影响:输出不可直接展示给最终用户;nonce 泄漏无安全风险(一次性),但属于实现细节泄漏。
- 建议:清洗逻辑改为「剔除从行首到哨兵行之前的全部回显块」,而非精确整行匹配。
**复核(2026-10-25)**:属实。已修:删到命令行回显结束 → 删哨兵行回显 → 按 nonce 擦掉渲染残留的哨兵文本;另修 `StripAnsi` 对 `OSC…ESC\` 收尾会残留 `\` 的问题。设计见 `docs/Mcp_Design.md` §12.1。
### P5(中):`get_activity_history` 注解登记错误
- `McpInternal.cpp:333` 登记 `openWorldHint=false`,但该工具经 `ctx->Send2Client(COMMAND_QUERY_ACTIVITY)` 触达远程主机(`McpServer.cpp:2249`),与代码注释及 `docs/Mcp_Design.md` §10.2 口径矛盾。一行修复。
**复核(2026-10-25)**:属实,已改 `openWorld=true` 并加注释说明理由。
### P6(低):`list_services` 在非提权被控端上 20s 超时且无解释
- 第1轮本机被控端(非提权):3/3 超时。客户端日志定位根因:`ServicesManager.cpp:31 Get service list failed`——`OpenSCManager(SC_MANAGER_ALL_ACCESS)` 权限不足,失败分支回传普通消息包而非 `TOKEN_SERVERLIST`,服务端等满 20s。
- 第2轮 VM 被控端(权限足够):**成功**(服务列表正常返回)——反证根因即权限。
- 建议:客户端失败分支回传带失败标记的 `TOKEN_SERVERLIST`,服务端转译为 `-32005`/明确错误文本;文档标注需要管理员权限。
**复核(2026-10-25)**:属实(`OpenSCManager` 权限不足 → 客户端失败分支回普通消息包,服务端只能等到超时)。修它要改客户端,按「暂不动客户端」原则搁置。
### P7(低):错误码表缺 -32007/-32008/-32009,且 -32008 复用多种语义
- `docs/Mcp_Design.md` §12 只登记到 -32006。-32008 同时用于:元字符、`&|`/控制字符、老客户端格式、多显示器不支持(4 处)。后者语义近 `-32005 Not supported`。
**复核(2026-10-25)**:属实。`docs/Mcp_Design.md` §12 已补齐 `-32007`/`-32008`/`-32009`,`-32008` 行内注明其四类语义(修正参数 vs 能力限制的处理方式不同)。
### P8(低):路径类工具对不存在路径静默返回空
- `list_registry`(注册表,两轮均复现)与 `list_files`(文件列表)对不存在的路径均返回空列表 + `isError:false`,无法区分「为空」与「不存在」。建议返回错误或加 `exists:false`。
**复核(2026-10-25)**:属实,但服务端拿到的响应与「空目录/空键」完全一致,无法在服务端区分;需客户端回报错误码 → 按「暂不动客户端」原则搁置。
### 观察项(不计入问题)
- `host_list_network_state` 的 state 为本地化文本("连接"),按 `ESTABLISHED` 过滤会失配;`kill_network_connection` 内部已归一化(stateName=ESTABLISHED, killable:true),dry_run 对真实四元组校验通过。
- `remote_open` 双显示器拒绝(-32008)文案清晰、即时;VM 单屏下全链路正常。
- 第1轮 exec_command 11/12 超时在两台被控端重启后均未复现(VM 5/5、重启后本机 5/5+30/30 连发通过);当时环境长时间运行+大量会话开关,疑与资源/状态积累有关,未能复现定位。鉴于 P1/P3 已证哨兵机制脆弱,建议优先落实哨兵改造后观察。
## 3. 通过项(摘要)
| 领域 | 结果 |
|---|---|
| 传输层 | 401/413/404、-32700/-32600/-32601、ping、status 不泄露 token —— 全过 |
| 冒烟脚本 | 32/32 PASS |
| 主机列表/分页/过滤 | 分页 clamp、越界、group/os/client_type、totalAll 保留 —— 全过 |
| 批量工具 | ids>51 拒、写工具拒批量 —— 全过 |
| exec 安全门 | 白名单+词边界(`dir` 过/`dirx` 拒/`echo` 拒)、`&`/CRLF -32008、空命令 -32602 —— 全过 |
| 文件传输 V2 | 上传 11 项(中文文件名、1MB SHA-256、620 文件递归、overwrite 跳过)、下载 SHA-256、**跨机往返(本机↔VM)SHA 一致** —— 全过 |
| search_file | min_size/name_only/子串/非法时间 -32602 —— 全过 |
| 服务端本机工具 | audit 分页+过滤、status 一致性、`host_set_remark` GBK 边界(63B 过/66B 拒/emoji 拒)—— 全过 |
| 只读主机工具(双端) | get_screenshot(JPEG magic 双端过)、get_keylog、list_registry 子键、list_windows、get_activity_history —— 全过 |
| **remote 控制族(VM,第2轮新增)** | open→mouse(move/click/scroll)→keyboard(type/key_press)→clipboard→close→幂等→死会话拒绝 —— **11/11** |
| chat(双端) | 本机 6/6 + VM 4/4(open/send/wait timed_out/close)—— 全过 |
| 终端持久会话 | open/exec/close 生命周期、echo/whoami/cmd /c echo 等有输出命令 —— 全过(异常见 P1/P3/P4) |
| 写工具 | watch_level 1↔0 往返、非法值拒绝 —— 过 |
| kill_network_connection | dry_run 假四元组 -32009、**真实四元组校验通过**(VM 实测)—— 过 |
## 4. 修复优先级建议
1. **哨兵改造**(P1/P3/P4 同根一次修):独立行哨兵 + 回显块整体剔除 + 超时销毁会话的专用错误文案;
2. P2:download 快速失败或默认超时下调 + 本地读取豁免互斥;
3. P5:一行注解修复;
4. P6:客户端服务枚举失败结构化回传;
5. P7/P8 随批次顺手处理。
**复核后状态**:1 → 已修(§0 P1/P3/P4);2 → 已修「停滞 60s 快速失败」,默认超时未下调、互斥豁免未做(远程工具互斥是有意设计,本地工具本就不受限);3 → 已修;4 → 已修(`TOKEN_SERVICE_ERROR` → `-32010`);5 → P7 已修(文档),P8 已修(`TOKEN_FILE_LIST_ERROR`/`TOKEN_REG_ERROR` → `-32009`/`-32010`)。
## 附录 A:错误码实测一览
| 码 | 场景 | 实测 |
|---|---|---|
| -32001 | 等待超时 | 吞行命令、非提权 list_services、download 600s/8s 均复现(复核后:吞行命令不再超时;download 停滞 60s 即失败并说明原因) |
| -32002 | 离线/不存在 | 不存在 id 复现;会话销毁后 terminal_exec 文案混用(见 P1)→ 复核后已拆成「被超时销毁」与「id 写错」两种文案 |
| -32003 | 单设备互斥 | 挂起期间跨工具复现(含远程机器管理工具;**纯服务端本地工具不受影响**,复核已实测) |
| -32005 | 不支持 | 代码审查确认(无 LNX/MAC 主机可测) |
| -32006 | 策略拒绝 | 冒烟历史覆盖(McpKeylog=0 → CALL_DENIED) |
| -32007 | 白名单拒绝 | `echo`/`set` 复现 |
| -32008 | 元字符/&\|/老格式/多显示器 | 双屏 `remote_open`、`dir & whoami` 复现 |
| -32009 | kill 目标不存在 | dry_run 复现;真实四元组通过 |
| -32602 | 参数错误 | 备注 66B、level=99、非法时间等复现 |
## 附录 B:审计日志行为
- `CALL_OK`/`CALL_FAIL` 含 `tool= ms= bytes=`;600s 挂起精确记录 `ms=600004`;`get_audit_log` 过滤与实际一致。
## 附录 C:测试残留与清理
- 全部测试数据(本机 `%TEMP%\yama_mcp_test\src|vm_target|dl_vm` 与 VM 同名目录)测试后已删除/验证删除。
- `settings.ini` 未做修改(本轮未动开关),第1轮已恢复备份。
- VM 会话中因超时被销毁的终端已随服务端状态清理;我启动的本机 ghost.exe 已关闭,Debug 服务端保持用户启动状态。
+389
View File
@@ -0,0 +1,389 @@
# YAMA MCP 工具集实测报告
- **测试日期**:2026-10-29
- **服务端**:Yama v1.4.1,构建时间 `2026-10-29 18:26:56`,监听 `0.0.0.0:6544`,10 项开关全开(readonly=false)
- **规模**:在线 34 台、离线 3165 台,`tools/list` 共 **60 个工具**
- **测试目的**:考察 AI 使用这套 MCP 工具是否顺畅,以及能否对设备完成有效监管与处置
- **修复状态**:三个 P0 已于同日修复并实测通过,见 §7(实现说明在 `docs/Mcp_Design.md` §18);P2-1(`get_activity_history` 无分页)已于同日修复,见 §8(实现说明在 `docs/Mcp_Design.md` §19)
## 1. 测试范围与约定
按约定划分操作边界:
| 用途 | 主机 | 说明 |
|---|---|---|
| 写操作 | `DESKTOP-A55C0OI`(`3441387693643366974`,Win10 VM,MDLL)<br>`Ubuntu24`(`15731161054501180314`,Ubuntu 24.04,Stuttgart,带 UI,LNX) | 仅这两台 |
| 读操作 | 以本机 `A6`(`11261158607827860566`)为主,另抽样其他主机 | 不做写操作 |
**实际覆盖 55 / 60 个工具。** 未覆盖及原因:
- `control_service`:无 `dry_run`,执行即重启/停止 YAMA 自身服务,会切断 AI 自己的 MCP 通道,**无法安全自测**
- `operate_window`、`kill_network_connection`:仅 Windows;唯一可写的 Windows VM 在重启测试窗口内未回线,这两个工具来不及执行(该 VM 未配自动登录,人工登录后才回线,见 P1-9)
- `list_windows`:降级路径,已由首选 `host_list_windows` 覆盖
- 其余全部实测
## 2. 结论摘要
**整体可用,但"监管/处置"链路上有 3 个硬伤会直接卡住 AI,另有 1 个动作可能把设备弄丢。**
- **读得准**:所有只读工具在 A6 上返回结构正确、过滤与分页语义一致(`total` / `totalAll` / `hasMore` 三者自洽),截屏返回的是 AI 真能看的图像,不是 base64 字符串。
- **写得住**:文件上传/下载/C2C 全部正确,下载带 SHA-256 且与本地逐字节吻合,目录结构保留,`overwrite` / `skipped` / `skip_check_failed` 行为与设计一致。
- **控得了**:窗口/服务/进程/计划任务的 `dry_run` + 执行后复核闭环质量很高;远程鼠标键盘在 Windows 与 Linux 上都验证成功;远程交谈可视确认。
- **审计扎实**:每个 MCP 动作都落审计日志,含主机 id、工具名、关键参数,连鼠标归一化坐标与像素坐标都在。
- **但有 3 个硬伤**:批量读取主机详情**必定失败**、客户端日志**拿不到**、**新参数对已连接客户端不可见**。
- **重启是唯一会"弄丢设备"的动作**:目标 VM 未配自动登录,重启后停在登录界面,客户端(HKCU 启动项)要等人工输密码才起。`power_action` 既不预检自动登录状态,默认也只等 60 秒,`came_back=false` 既可能是"再等等"也可能是"必须喊人"——AI 无法分辨。
严重度分布:**P0 × 3**、**P1 × 9**、**P2 × 15**。
## 3. 发现清单
### 3.1 P0:阻断性缺陷
#### P0-1 `get_host_detail` 的批量模式必定失败 `已修复,见 §7`
```json
{"ids": ["17221709513794608622", "11261158607827860566"]}
→ -32602 Structured content does not match the tool's output schema:
data must have required property 'host'
```
input schema 明确声明支持 `ids`(最多 50 个)、"结果按台汇总在 `results` 里",但 **output schema 只认单台的 `host`**。实现返回 `results` 就必然校验失败。单台 `id` 形式正常。
影响:**所有只读工具的 `ids` 批量能力全部不可用**(`list_processes`、`list_files`、`list_registry`、`host_list_*` 等十余个工具共用同一套输出 schema)。AI 只能逐台串行调用,34 台机群的横向盘点要 34 次往返。
#### P0-2 `list_registry` 的根键分支必定失败 `已修复,见 §7`
```json
{"id": "...", "path": ""} # 省略 path,按文档应返回 5 个根键
→ -32602 ... data must have required property 'values'
```
带 `path` 时正常(返回 `keys` + `values`);省略 `path` 时只返回 `keys`,而 output schema 要求 `values` 必填。**文档描述的第一种用法("省略或空 path 返回 5 个根键")是死路**,AI 必须先猜一个真实路径才能进注册表。
#### P0-3 `get_client_log` 两种平台都不可用 `已修复,见 §7`
| 平台 | 实测结果 |
|---|---|
| Windows(A6,pid 8668) | 返回 **90,473 字符**(单行 JSON 塞 1000 行日志),直接超出客户端工具结果上限 |
| Linux(Ubuntu24) | `-32001 Timeout waiting for client log`,连续两次稳定复现 |
工具没有任何 `limit` / `offset` / `tail` / `since` 参数,只能全量取。Windows 上"取到了但塞不下",Linux 上"根本取不到"。
影响:**故障排查最需要的一手证据(客户端日志)AI 拿不到。** 本次测试中我只能改用 `download_file` 把日志文件从主机上拉回本地再读——多绕两跳,且要求 AI 自己想到这条路。
### 3.2 P1:破坏工作流
#### P1-1 服务端已发布的新参数,对已连接客户端不可见
直连 `tools/list` 确认服务端**已声明** `copy_files_c2c.overwrite`:
```
upload_file: ['id', 'local_path', 'overwrite', 'remote_dir', 'timeout_ms']
copy_files_c2c: ['dst_dir', 'dst_id', 'overwrite', 'paths', 'src_id', 'timeout_ms']
```
但连接器缓存的 schema 仍是旧版,带 `overwrite` 调用被本地拦下:
```
Parameter validation failed: root: must NOT have additional properties
```
**报错完全不提示"服务端已支持、是你的客户端缓存过期"。** AI 只会以为参数名写错了,反复尝试无效写法。
功能本身经直连验证是**正确**的:
| 调用 | 结果 |
|---|---|
| `overwrite=true` | `file_count=1, skipped=0, transfer_id=7364150632606842580` |
| 默认(不带 overwrite) | `file_count=0, skipped=1, transfer_id="", skip_check_failed=false` |
#### P1-2 本地化枚举值与英文文档冲突,且无枚举可查
```json
{"status": "Ready"} → total: 0 (schema 文档建议 "如 Ready / Disabled")
{"status": "已准备"} → total: 222
```
实际值是本地化中文。同类问题存在于 `host_list_win32_services.start_type`(`"Auto Start"` 带空格)与降级版 `list_services.start_type`(`"Auto-Start"` 带连字符)——**两套拼法**。
影响:AI 按文档写过滤条件会静默得到空结果,误判为"没有匹配项"。schema 里也没有 `enum` 可枚举合法值。
#### P1-3 Linux 主机完全没有文件变更能力
`create_folder` / `move_path` / `delete_path` 三个工具均为 Windows-only:
```
create_folder on Ubuntu24 → -32005 create_folder is only supported on Windows hosts
```
Linux 上唯一的替代是 `terminal_exec` 跑 `mkdir` / `mv` / `rm`。而这正是最危险的一类操作,恰恰**没有 `dry_run`、没有执行后复核、没有受保护路径拦截**——与 Windows 侧形成鲜明反差(Windows 的 `delete_path` 会拒绝 `C:\ProgramData` 等系统目录)。
#### P1-4 C2C 只支持 Windows 作源
```
Ubuntu24 → DESKTOP-A55C0OI → -32005 copy_files_c2c requires a Windows source host
DESKTOP-A55C0OI → Ubuntu24 → 正常,receiver_ack=true
```
混合机群里,**从 Linux 取文件到另一台主机**只能 `download_file` → `upload_file` 两跳,且文件要经过主控落盘。这与 C2C"不经主控"的设计初衷相悖,但工具描述里没有提示这一限制。
#### P1-5 `terminal_exec` 禁管道,`exec_command` 受白名单,两者都不是通用 shell
```
ls -1 /home/yuan/upload | wc -l
→ -32012 Command contains & or | or a newline (breaks output capture)
```
`exec_command` 则被白名单挡住常用工具:
```
powershell -NoProfile -Command Get-Date → -32007 Command not allowed by whitelist
```
代价是实打实的:想看"某个目录有几个文件",AI 只能把整个 `ls` 输出拉回上下文自己数;想看进程占用只能先 `host_list_processes` 再本地算。**上下文消耗与往返次数都翻倍**,且两个工具的限制互不覆盖,AI 需要记住"哪件事该用哪个"。
#### P1-6 删除保护是"建议"而非"强制"
`delete_path` 的拦截很到位:
```
delete_path C:\ProgramData → -32602 refusing to modify a protected system location
```
但提示语自己给出了绕过方式:
> use exec_command if you really need to touch them
而 `terminal_exec` 本身不受白名单约束,`rm -rf` 畅通无阻。**保护只在"守规矩的路径"上生效**,对有意或无意的越界没有约束力。
#### P1-7 持久终端会话静默过期,AI 无法预判
Linux 终端会话(`fb4903…`)在空闲约 35 分钟后消失,期间没有任何通知:
```
terminal_exec → -32002 Terminal session not found: fb4903... (call terminal_open first)
```
`mcp_list_sessions` 里也**看不到它曾经存在**,因此 AI 无法在调用前判断会话是否还活着。重新 `terminal_open` 后立刻查询,会话正常出现在列表里(`idle_ms: 3000`)——说明登记机制本身没问题,纯粹是**过期无提示、TTL 未文档化**。
(`-32002` 的文案本身写得很好,明确让人重新 `terminal_open`。)
#### P1-8 `mcp_cancel_session` 按主机取消会连带销毁持久终端
```
{"id": "15731161054501180314"} → cancelled: 2, released: false
matched 中包含 {"kind": "terminal", "session_id": "21afe3..."}
→ 后续 terminal_exec: -32002 Terminal session was destroyed because the request was cancelled
```
取消在飞请求本身**效果很好**——阻塞 40 秒的调用在 4 秒内以 `-32800` 终止。但 schema 描述的是"取消该主机上所有在飞请求",没提会连带销毁持久会话。副作用超出文档承诺范围。
#### P1-9 重启后能否自行回线,取决于目标机的自动登录配置——而工具不会告诉你
实测在 `DESKTOP-A55C0OI`(2 GB 内存的 Win10 VM)上执行,按审计日志对齐时间轴:
| 时刻 | 事件 |
|---|---|
| 18:45:47 | 下发 `{"action":"reboot","wait":true,"wait_ms":120000}` |
| 18:47:47 | 返回 `went_offline=true`、**`came_back=false`** |
| 18:52:15 | 主机重新上线(`myself` 组,即被控的那条记录) |
| 18:52:23 | 同一台机的**第二个**客户端也上线(`default` 组,见 P2-10) |
**根因已由环境方确认:该 VM 没有配置自动登录,重启后停在登录界面,必须人工输入密码。** 客户端的自启动在 `HKEY_CURRENT_USER\...\Run`(`test.exe`、`ClientDemo.exe`),HKCU 启动项只在**交互式登录之后**才执行,所以"重启 → 客户端回线"这一步完全取决于有没有人把密码输进去。本次那 4 分 28 秒不是机器自己恢复的,是登录之后才起的。
这带来三个问题:
1. **等待窗口本身也不够**:工具默认 `wait_ms=60000`,我设了 120 秒仍不够。即使配了自动登录,60 秒对真实 Windows 开机也偏短,`came_back=false` 会成为重启的常态返回值;
2. **`power_action` 没有任何自动登录预检**:AI 在按下重启前无法知道"这台会不会回来",只能盲下;
3. **`came_back=false` 之后没有下一步**,文案还把重启归到"关机后需人工开机"那一类,既不准确也没给出可执行动作。
> **两处自我更正**(都发生在本次测试中):
> 1. 初稿判断"重启把设备弄丢了、需人工介入",据此列为 P0——**已撤回**,设备确实回线了;
> 2. 第二稿改判"设备 4 分半后自行回线、只是等待窗口太短"——**也不准确**,回线是人工登录的结果。真实结论是:**能不能自愈取决于目标机配置,工具既不检查也不告知**。
### 3.3 P2:一致性与体验
| # | 问题 | 证据 |
|---|---|---|
| 1 | ~~`get_activity_history` 无分页,一次返回 **501 条**~~ **已修复,见 §8** | 直接冲爆上下文,且内容含大量个人浏览/求职/签证页面 |
| 2 | `authStatus` 只在 `search_hosts`/`list_all_hosts` 出现,`list_online_hosts` 没有;`myself` 组 6 台全为 `unauthorized` 却可正常写入 | MCP 侧未按授权状态做门禁 |
| 3 | 时间口径三套并存 | `list_files.mtime` 是 epoch 整数;`host_list_scheduled_tasks.lastRun` 是 `"2026-10-25 03:38:42"`;`list_network_connections.state` 是 `5` + `"ESTABLISHED"`。主机 `last_seen` 显示 `2026-10-30 01:27`,审计日志同一时刻显示 `18:47`,**差 6 小时以上** |
| 4 | 降级工具与首选工具字段命名不一致 | `list_services`: `binary_path` / `start_type: "Demand-Start"`;`host_list_win32_services`: `binaryPath` / `startType: "Demand Start"`。进程总数 354 vs 351(枚举口径不同) |
| 5 | `get_keylog` 名为键盘记录,实际返回**剪贴板快照** | 内容是 `[Title:] / [Time:] / [Clipboard:]`,无击键;文档提到的 `offlineRecord` 字段未出现 |
| 6 | `host_control_process` 的 `state` 返回进程名 | `{"action":"freeze", "state":"notepad.exe"}`;且此处 `verified: true` 含义是"进程还在",与其它工具"动作已确认"不一致 |
| 7 | `remote_block_input` 报 `blocked: true`,但输入仍可用 | 60 秒窗口内 ESC 与右键均生效;工具自己已声明"只代表命令已送达",**无法确认是否真的锁住** |
| 8 | 能力位不可信 | `ubuntu-24` 的 `remoteControl: true`,但 `screen` 为 `0:0*0`,`remote_open` 15 秒超时 |
| 9 | `host_list_windows` 返回 1×1 / 0×0 的空标题窗口 | `canSee: true` 但 `width:1, height:1, title:""`,属噪声 |
| 10 | 同一台机多条记录、无法区分 | `A6` 有 2 条在线记录(`ClientDemo.exe` pid 26064 / `test.exe` pid 8668),进程列表里还有第 3 个客户端进程 pid 35052 **没有对应主机记录**;`DESKTOP-A55C0OI` 重启后**同时回线两条**(`3441…` 是 MDLL `test.exe` / `myself` 组,`4665…` 是桌面上的 `YAMA1234567a.exe` / `default` 组);按名搜该机名命中 **28 条**历史记录 |
| 11 | `remote_keyboard.type` 无回执,可能丢字符 | Linux 首次注入(焦点刚切换)得到 `echo LINUX_GUI_O`,输出 `LINUX_GU`;第二次完整。只能靠截图自行复核 |
| 12 | 截屏成本偏高 | 960px 宽 ≈ **67 KB / 张**,持续监管会迅速吃掉上下文,且没有区域裁剪或更省格式 |
| 13 | `mcp_cancel_session` 把自己的请求也列进 `matched` | `request_id: "373" tool: "mcp_cancel_session"` |
| 14 | **已过期客户端仍可正常上线并被操作** | `4665792391648319550` 的 `expiredDate: 20261008`(已过期 3 周),但 `online: true`、`authStatus: authorized_by_super`,`get_host_detail` 正常返回、文件操作可用 |
| 15 | 客户端时钟偏差,服务端只打日志不管 | 审计日志中反复出现 `[92.208.227.255]Please check the client's time`;这正是第 3 条里 `last_seen` 与审计日志差 6 小时的来源 |
## 4. 监管与处置能力评估
### 4.1 能做到的(已验证)
| 能力 | 实测证据 |
|---|---|
| **资产盘点** | 34 台在线 + 3165 台离线,`os` / `client_type` / `group` / `name` / `ip` 组合过滤准确,`total` 与 `totalAll` 自洽(3199 = 34 + 3165) |
| **单机取证** | 进程 351 / 服务 278(运行中 110)/ 驱动 402 / 窗口 24 / 软件 112 / 计划任务 272 / 网络连接 486,字段完整 |
| **可视化确认** | 截屏是真图像,能直接读出桌面文字(本报告中所有 GUI 结论均靠它闭环) |
| **文件处置** | 上传(含目录递归)、下载(SHA-256 逐字节吻合)、C2C(结构保留)、移动、删除,均带 `verified` 复核 |
| **受控处置** | 停/启服务(`Spooler` stop→start,状态复核通过)、运行计划任务(状态转"运行中")、终止进程(`notepad.exe` 已消失)、最小化/还原窗口(截图确证) |
| **GUI 自动化** | Windows:点击地址栏 → 输入 → 回车;Linux:右键菜单 → 点击终端 → 输入 → 执行,均截图确证 |
| **与人沟通** | `chat_open/send/wait/close` 全流程,消息在目标机弹窗显示,截图确证 |
| **占用治理** | `mcp_cancel_session` 把阻塞 40 秒的调用在 4 秒内以 `-32800` 中止 |
| **事后追溯** | 审计日志完整记录每个 MCP 动作,含 `remote-mouse ... norm=(0.300,0.850) px=(515,782)` 这一级细节 |
### 4.2 做不到的
- **横向批量取证**:`ids` 批量全部失效(P0-1),34 台要 34 次往返
- **日志取证**:客户端日志取不到(P0-3)
- **Linux 文件处置**:只能靠裸 shell(P1-3),且裸 shell 无任何护栏
- **管道与过滤**:无法让远端先过滤再回传(P1-5)
- **重启后能否回线**:取决于目标机是否配了自动登录;未配置时必须人工登录,而 `power_action` 既不预检也不告知(P1-9)
- **会话生命周期预判**:终端会静默过期(P1-7)
- **精确锁定目标**:同名主机 28 条、同机 3 个客户端进程,列表视图没有 `clientPath` / `pid` 可供区分(P2-10)
### 4.3 一次具体的处置失手
本次测试中,`power_action reboot` 返回 `came_back=false`。我先后做出两个判断,**两个都是错的**:
| 我的判断 | 实际情况 |
|---|---|
| "设备失联了,需要人工介入"(据此列为 P0) | 设备在 4 分 28 秒后回线 |
| "只是等待窗口太短,设备会自愈" | 回线是**人工登录**的结果——该 VM 未配自动登录,客户端靠 HKCU 启动项、登录后才执行 |
复盘这条链路,暴露的是**工具没把判断依据交出来**:
- 返回里只有 `went_offline` / `came_back` / `elapsed_ms`,**没有"这台会不会自己回来"的任何线索**(自动登录状态、是否有 SYSTEM 级自启动),AI 无法区分"再等等"与"必须喊人";
- 文案把重启归到"关机后需人工开机"那一类,直接把人引向错误结论;
- 没有 `next_step`。
同一个信息缺口下,**AI 和人都只能靠猜**。这不是 AI 的失手,是返回值的信息量不足——而这类"缺口"恰恰是自动化处置最危险的地方:一次重启就能把一台远程设备变成必须到现场(或控制台)才能救回的状态。
## 5. 改进建议
### P0(下一轮必须修)
1. **让每个输出分支都通过自己的 schema**
`get_host_detail` 的 `host` 改为可选、或批量时也返回 `host` 数组;`list_registry` 的 `values` 改为可选。更根本的做法:加一个**契约测试**,对每个工具、每个分支各调一次并用它自己的 output schema 校验。目前 60 个工具里至少 2 个的某个分支是必然失败的,这类问题靠人工回归必然漏。
2. **给日志类工具加分页与裁剪**
`get_client_log` / `get_activity_history` / `get_keylog` 增加 `limit` / `offset`(或 `tail_n` / `since`),默认只回 200 行并在响应里给 `total`。`get_client_log` 尤其应默认 `tail_n=200`——AI 要的是"最近发生了什么",不是 1000 行全量。
3. **修 Linux `get_client_log` 超时**
超时时至少返回已取到的部分快照并置 `truncated=true`,而不是整条失败。
### P1(本轮内应修)
4. **重启前查自动登录,重启后给判断依据**
`power_action` 增加 `check_autologon=true`:读 `HKLM\...\Winlogon` 的 `AutoAdminLogon`,并结合客户端自启动位置(HKLM/HKCU `Run`、启动文件夹、"计算机启动时"触发的计划任务)判断**这台会不会自己回来**;若判定"不会",在结果里明确写"重启后需人工登录,客户端才会回线",让 AI 能先问过用户再动手。
同时:默认 `wait_ms` 提到 300000;返回补 `offline_elapsed_ms` 与 `recommended_wait_ms`;`came_back=false` 时给 `next_step`(如"建议 2 分钟后再查一次 `search_hosts`");文案按 `logout` / `shutdown` / `reboot` 分别措辞。
5. **给 schema 加版本,让"参数不可见"可自解释**
在 `tools/list` 结果里带 `schemaVersion`;当客户端因 `additionalProperties` 拒绝时,服务端无法感知——那就退一步:在工具描述里显式写"若客户端报 unknown property,请重连"。更好的做法是服务端**接受并忽略**未知参数,而不是硬拒。
6. **枚举值统一为 ASCII,或双向兼容**
过滤时同时接受 `"Ready"` 与 `"已准备"`(做一次映射即可),并在 schema 里补 `enum`。`start_type` 的 `"Auto Start"` / `"Auto-Start"` 两套拼法必须统一。
7. **给 POSIX 补文件变更工具,或给裸 shell 加护栏**
首选补 `create_folder` / `move_path` / `delete_path` 的 POSIX 实现(`mkdir -p` / `rename` / `unlink`),复用 Windows 侧的受保护路径策略与 `verified` 复核。若短期不做,至少给 `terminal_exec` 加 `dry_run` 与危险命令二次确认。
8. **放开 `terminal_exec` 的管道限制**
输出哨兵可以改成基于退出码 + 长度前缀的帧协议,不必依赖"命令里不能有 `|`"。这是当前**性价比最高的单点改进**——它同时降低上下文消耗和往返次数。
9. **让删除保护名副其实,或明确标注为建议**
若 `exec_command` / `terminal_exec` 仍可触达系统目录,就应在 `delete_path` 的描述里写"仅为防误触,不是安全边界",避免 AI 误以为已被保护。
10. **会话 TTL 可见**
`mcp_list_sessions` 增加 `expires_in_ms`;`terminal_exec` 在接近过期时返回警告而不是直接 `-32002`。
### P2(体验优化)
11. 时间字段统一附加 ISO 字符串(保留 epoch 以兼容),并修掉 `last_seen` 与审计日志的 6 小时时差。
12. 统一 `list_*` 与 `host_list_*` 的字段命名;长期看应废弃降级版,或让降级版直接复用首选版的 schema。
13. 修 `host_control_process.state`(应返回状态而非进程名);统一 `verified` 语义——"动作已确认"与"目标仍存在"必须分开表达(建议后者改名 `target_present`)。
14. `host_list_windows` 默认过滤 0×0 / 1×1 空标题窗口,加 `include_aux=false`。
15. `search_hosts` 增加 `include_history=false` 默认值或 `dedupe_by_name`,并在列表视图补 `clientPath` / `pid`,让同机多客户端、同名多记录可区分。
16. `authStatus` 补进所有主机列表工具,并明确它是"信息性"还是"门禁性"。
17. 截屏默认给更小缩略图,或支持 `crop` 区域与 `webp`,降低持续监管成本。
18. `remote_keyboard.type` 增加回执(回显被接受的文本)或 `settle_ms` 参数。
19. 主机列表与详情补 `expiredDate`(目前只有 `get_host_detail` 给,且只在 SC 客户端上有),让 AI 能一眼看出"这台已过期";对 `expiredDate` 已过仍在线的情况,至少在 `authStatus` 或独立字段上标注。
20. 客户端时钟偏差(`Please check the client's time`)应从"只记日志"升级为可查询的状态字段,否则 `last_seen` 这类时间戳无法用于判案。
## 6. 给下一轮的一句话
**这套工具"单点很能打,横向很吃力"**——单台机器上的取证、处置、GUI 操作、审计都做得相当扎实,`dry_run` + 复核 + 诚实免责说明的设计水平明显高于同类产品;但一旦要**横向铺开**(批量读、日志取证、Linux 文件操作、重启判定)就立刻撞墙。下一轮优化应把资源集中在这四处,而不是继续加新工具。
## 7. 三个 P0 的修复
三个 P0 都是**声明与实现不一致**,改动集中在服务端;只有 P0-3 的 Linux/macOS 半边需要
客户端补一段。实现细节见 `docs/Mcp_Design.md` §18。
| 编号 | 修法 | 改动位置 |
|---|---|---|
| P0-1 批量调用必失败 | `tools/list` 收尾时给批量只读工具的 `outputSchema` 补 `anyOf:[单机形状, 批量形状]` | `McpInternal.cpp` 新增 `ApplyBatchOutputSchema`;`IsBatchReadOnlyTool` 从 `McpServer.cpp` 移入 `McpInternal.cpp` |
| P0-2 根键分支必失败 | `required` 去掉 `values`,只留 `keys`;根键分支补 `path:""` 使两分支字段一致 | `BuildListRegistryOutputSchema` / `BuildRegistryRoots` |
| P0-3 日志取不到 | 新增 `limit`(默认 200、上限 2000)与 `filter`,从末尾往前取,另有 64 KB 字节预算;返回 `lines_total`/`lines_matched`/`lines_returned`/`truncated`;Linux/macOS 客户端补 `COMMAND_QUERY_LOG` 处理 | `BuildClientLogInputSchema`(新)、`BuildGetClientLog`、`common/ClientLogHandler.h`(新)、`linux/main.cpp`、`macos/main.mm` |
**为什么 P0-1 改在收尾阶段**:三个注册点(`McpServer.cpp` 内联 / `McpMachine` / `McpChat`)
各自 `tools.append`,在收尾统一打补丁才能保证以后新增的批量工具不漏。这与既有的
`ApplyToolAnnotations` 同一位置、同一思路。
**P0-3 的两个症状是两个原因**:Windows 是"取到了但塞不下"(无 limit),Linux 是"根本
取不到"(客户端没有 `COMMAND_QUERY_LOG` 分支,服务端只能等到超时)。只加 limit 不修
客户端,Linux 上的 `get_client_log` 依旧超时;只修客户端不加 limit,Windows 上依旧超上限。
**验证结果(服务端 21:17:21 构建 / 客户端已重编,2026-10-29 21:19–21:21)**:
| 用例 | 结果 |
|---|---|
| `get_host_detail` + `ids`(A6 两条记录) | **通过** `total=2, succeeded=2`,`results[].data.host` 逐台返回 |
| `host_list_processes` + `ids` + `limit=2` | **通过** `succeeded=2`,两台各回 2 条、`total=348` |
| `get_client_log` + `ids`(Win + Linux 混合) | **通过** `succeeded=2`;Windows 1000 行、Linux 14 行,各自独立裁剪 |
| `list_registry` 省略 `path` | **通过** 返回 5 个根键 + `path:""`,不再 `-32602` |
| `list_registry` 带 `path`(HKLM\...\Run) | **通过** 3 个值,无回归 |
| `get_client_log`(Windows,默认参数) | **通过** `lines_total=1000, lines_returned=200, truncated=true`,不再超上限 |
| `get_client_log`(Windows,`limit=3` + `filter=ConnAuth`) | **通过** `lines_matched=28, lines_returned=3` |
| `get_client_log`(Linux Ubuntu24) | **通过** 返回 8 行;客户端日志里可见 `Received 'QUERY_LOG' command` → `Enter ClientLogThread` → `Leave ClientLogThread`,子连接进出成对、无泄漏 |
| `list_files`(单机,验证 anyOf 包装未影响单机路径) | **通过** 正常分页 |
**遗留**:连接器仍缓存着旧的 `get_client_log` inputSchema(不含 `limit`/`filter`),模型侧
直接传这两个参数会被本地校验拦下(`must NOT have additional properties`)。默认参数已经把
P0-3 解决掉,要显式用 `limit`/`filter` 需重连一次连接器——与 §3.2 P1-1 是同一个缓存问题。
## 8. 附带修复:`get_activity_history` 分页(P2-1)
P2-1 与 P0-3 是同一类病——**列表类工具没有裁剪,把上下文当垃圾桶**。既然 `get_client_log`
的分页/预算机制已经就位,这里直接复用同一套。实现细节见 `docs/Mcp_Design.md` §19。
| 改动 | 内容 |
|---|---|
| `inputSchema` | 由 `BuildGetHostDetailInputSchema()`(只有 `{id\|ids}`)换成 `BuildPagedHostListInputSchema()`,补 `limit`(默认 100、上限 1000)与 `offset` |
| `outputSchema` | 追加 `AppendPageOutputProps()`(`total`/`totalAll`/`offset`/`limit`/`hasMore`)与 `truncated` |
| 实现 | 全量拆行结果改名 `all`,再 `ResolvePageWindow` + `ApplyPageWindow` 切出 `records`,`WritePageFields` 回填 |
| `activityHistory` | **按窗口重建**(窗口内 `records` 按行拼接)。原来是 `Dump()` 整包原文,原样返回等于没分页 |
| 字节预算 | 64 KB(与 `get_client_log` 同口径),从窗口末尾裁,保留最新的;裁断时 `truncated=true`,`hasMore` 按 `offset+returned < total` 算 |
| 保底 | 至少留 1 条,避免 `returned=0` 让调用方在同一个 `offset` 上原地打转 |
**顺序语义**:客户端 `ActivityHistory::Loop()` 用 `m_records.push_front(...)`,`Dump()` 又把
进行中的当前窗口拼在最前——返回顺序**天然是「新在前」**。所以 `offset=0` 就是最近 `limit` 条,
不需要先取 `total` 再倒算 offset。这条不是新约定,写进工具描述是为了让模型敢直接用 `offset=0`。
**批量**:本工具在 `IsBatchReadOnlyTool` 名单里,`BuildBatchCall` 摘掉 `ids` 后把其余参数原样
透传,所以 `ids` + `limit` 就是「每台各取最近 N 条」,P0-1 的 `anyOf` 包装自动覆盖新字段。
**验证(服务端 21:34 构建,待重启后实测)**:
| 用例 | 期望 |
|---|---|
| 默认参数(不带 `limit`) | `records` 100 条、`total≈501`、`hasMore=true`,结果体积从约 90 KB 降到约 12 KB |
| `limit=5` | 5 条,且是最新的 5 条(第 1 条时间最晚) |
| `offset=500` | 1 条(尾部最老的那条),`hasMore=false` |
| `ids` + `limit=3` | `succeeded=全数`,每台各 3 条,`results[].data.total` 各自独立 |
| `activityHistory` 与 `records` | 行数与内容一致(不再是整包原文) |
| `offset` 超过 `total` | `records=[]`、`returned=0`、`hasMore=false`,不报错 |
+334
View File
@@ -0,0 +1,334 @@
# 传输层单向 TLS 加密设计(按需加密)
> 版本:v0.7 · 状态:**Go 服务端 + Windows/Linux 客户端已实现并验证;Linux 客户端支持下发即时热切换;MFC 主控端见 `TransportTLS_MFCServer_Design.md`;macOS/Android 未接入** · 日期:2026-10-28(Linux 客户端接入 + 热切换)
> 目标:让 YAMA 设备端口(TCP 6543)在继续兼容老客户端(明文/XOR)的同时,允许新客户端在拿到证书后按需开启**单向 TLS** 加密传输。
> 本期范围:**Go 服务端(`server/go`)+ Windows 客户端 + Linux 客户端**。
>
> 需求原文(三点,逐一对应下文):
> 1. 新客户端**默认不加密**,行为与老客户端完全一致;
> 2. 某些高要求场景,管理员「颁发一个证书给该客户端 + 重启」,该客户端即改走加密;
> 3. 服务端同一端口(6543)同时兼容明文与 TLS 两种客户端,老客户端零改动。
## 1. 目标与范围
### 目标
- 同一 `6543` 端口上,服务端自动区分「明文客户端」与「TLS 客户端」,按连接路由。
- 加密是**按部署、按客户端开关**的:证书(注册表值或文件)在 → TLS;证书不在 → 明文(与老客户端一致)。
- 老客户端(无证书概念)行为不变、零改动。
- 满足 Measure 1 的「传输层真加密 + 抗重放」目标(对 TLS 客户端而言)。
### 非目标(Non-goals,本次不做)
- 不做 **mTLS / 客户端证书**:单向 TLS 不验证客户端证书,客户端身份仍由隧道内的现有登录(`PwdHmac` V1 / `ECDSA` V2)承担。
- 不做传输层 PSK(`YAMA_TRANSPORT_KEY`)方案——本设计改用证书,更贴合「颁发证书」的运维模型。
- 不改应用层协议(flag 帧格式 / XOR / zstd),不做「TLS 内去掉 XOR」的二次精简(后续可选)。
- Windows 客户端**不做**加密开关的运行时热切换(证书只在进程启动时读取一次,改配置需重启——这正是需求)。Linux 客户端例外:服务端下发 166/167 后立即重载信任锚并重连切换(§6.6),语义差异见该节。
- macOS / Android 客户端的 TLS 接入不在本期(Linux 客户端已按同一模式接入,见 §6.6)。
- 不做 **MFC 服务端(`server/2015Remote`)的 TLS 接入**——本期只做 Go 服务端(`server/go`),MFC 主控端延后到阶段 3。
## 2. 现状与复用
### 2.1 当前传输(已核实)
服务端 TCP 传输链路:`server/go/server/server.go` `acceptLoop()`(329–360 行)`Accept` 后 `go handleConnection(conn)`;`handleConnection()`(363–425 行)读入 `ctx.InBuffer`,交给 `protocol.Parser`。
`server/go/protocol/parser.go` `Parse()`(51–85 行):
1. 可选剥离 HTTP-mask(`POST /...\r\n\r\n` 外壳,`common/mask.h` 的 `HttpMask`);
2. `parseHeader()`(88–140 行)调用 `CheckHead()` 识别协议;
3. `parsePacket()`(143–225 行)解头 + XOR 解码 + zstd 解压。
`server/go/protocol/header.go` `CheckHead()`(149–165 行)对前 12 字节依次尝试 8 种头混淆 × 4 种魔数,命中即得 `FlagType`:
| FlagType | 魔数 | 首字节 |
|---|---|---|
| FlagHell(4) | `HELL` | `H`=0x48 |
| FlagShine(1) | `Shine` | `S`=0x53 |
| FlagFuck(2) | `<<FUCK>>` | `<`=0x3C |
| FlagHello(3) | `Hello?` | `H`=0x48 |
| HTTP-mask | `POST ` | `P`=0x50 |
> 注意:上表「首字节」是**解密后**的魔数首字节。实际线上,客户端(`common/header.h` 的 `GetHead`)会用 `time() % 12` 随机选一个混淆方法对前 4 字节魔数加密(仅在 `superAdmin` 命中的 `HellEncoder` 路径;默认 `ProtocolEncoder` 直接发明文 `Shine`)。因此**原始首字节可能是任意值**,包括 `0x16`。这正是 TLS 检测不能只看前两字节、必须再加一字节判据的原因(见 §3.1)。
当前「加密」为 `codec.go` 的 `xorDecoder16`(XOR + 两轮伪随机交换,密钥是明文带内 1~2 字节)+ `header.go` 的 V0~V6 头混淆——**等于明文**。这正是 Measure 1 要解决的。
### 2.2 客户端登录(已核实,隧道内照常)
- V1:`client/KernelManager.cpp:1857` 从配置读 `settings/PwdHmac`(预计算摘要),服务端 `auth.go:240` `VerifyMessage(YAMA_PWD, passcode, hmacSig)` 校验。`YAMA_PWD` 只存在服务端,客户端只有摘要,不持有 `YAMA_PWD`。
- V2:`auth.go:188` ECDSA P-256 验签(`v2:BASE64`),客户端持私钥、服务端持公钥。
### 2.3 关键结论(本设计的基础)
**TLS 作为「透明传输包装」,应用层协议一行不改。** 即:
```
明文客户端: [TCP] = flag 帧 + XOR payload + zstd
TLS 客户端: [TCP][TLS] = { flag 帧 + XOR payload + zstd }
```
服务端 `parser.go`/`codec.go`/`header.go`/handler 全部不动;TLS 客户端解密后的字节流就是同一套协议。唯一新增的是**连接建立时的 TLS 检测与解包**。XOR 套在 TLS 里冗余但无害,保留它换来「应用协议零改动、老新客户端共用同一套代码」。
## 3. 总体方案
### 3.1 同端口共存 + 首字节检测
服务端在 `handleConnection` 开头(`Accept` 之后)偷看连接开头 6 字节:
- 命中 `0x16 0x03 … 0x01`(TLS 握手记录 + TLS 版本号 + 握手类型 ClientHello)→ 交给 `tls.Server` 解包;
- 其它 → 走现有明文路径。
**为何要看第 6 字节**:客户端会随机混淆魔数头(见 §2.1),所以明文连接的前两字节**可能**恰好是 `0x16 0x03`。但混淆只作用于前 4 字节魔数,字节 5 对混淆后的 `HELL` 头恒为 `0x00`,对明文 `Shine`/`POST` 变体是 ASCII 字符——**永远不会是 `0x01`**;而任何 TLS 握手记录里,字节 5 就是握手消息类型,ClientHello 恒为 `0x01`。于是 `0x16 0x03` 加 `b[5]==0x01` 三重判据让误判概率趋近于零。
```
accept
├─ 现有 MaxConnections / per-IP 限流(保持,先于 TLS 握手,廉价拒绝 + 抗握手 DoS)
├─ peek 3 字节
│ ├─ 0x16 0x03 → tls.Server(conn, tlsCfg)(惰性握手,首次 Read 触发)
│ └─ 其它 → 明文
└─ handleConnection(conn) // 不区分明文/TLS,tls.Conn 实现 net.Conn
```
### 3.2 客户端行为
客户端启动时检查「证书文件是否存在」:
- 不在 → 明文(与老客户端完全一致,默认即此);
- 在 → 所有出站 TCP 连接(主连接 + screen/terminal/file 子连接)统一走 TLS。
### 3.3 架构图
```
┌──────────── 被控端(客户端,无证书) ────────────┐
│ TCP ── flag+XOR+zstd ─────────────────────────► │ 明文
└───────────────────────────────────────────────────┘
┌──────────── 被控端(客户端,有证书) ────────────┐
│ TCP ── TLS ── { flag+XOR+zstd } ──────────────► │ 加密
└───────────────────────────────────────────────────┘
│
▼
┌──────────────────────┐
│ 服务端 6543 │
│ peek 首字节路由 │
│ ├─ 0x16 0x03 → TLS │
│ └─ 其它 → 明文 │
│ ── 同一套 parser/handler │
└──────────────────────┘
```
## 4. 证书模型(单向 TLS)
- 服务端持有一张**服务端证书 + 私钥**(可自签名,或由自建 CA 签发)。
- 客户端持有**信任锚证书**(CA 证书,或自签名服务端证书本身)用于在握手时校验服务端。
- 「颁发证书给某客户端」= 把信任锚证书投递到该客户端(**注册表值**,见 §6.1/§9.3)。证书是**共享的信任锚**(不是每个客户端一张唯一证书),「颁发」的本质是**决定给哪个客户端开加密**。
- 单向 TLS **不认证客户端身份**;客户端身份仍由隧道内的登录(V1 `PwdHmac` / V2 ECDSA)承担。
- 信任锚首选存注册表 `Software\<exehash>\settings\tls_cert`(REG_SZ 直接存 PEM 正文);兼容旧方式:`settings.ini` `[settings] tls_cert` 路径,或 exe 同目录 `yama-ca.pem` 文件。
## 5. 服务端改动
### 5.1 配置(`server/go/server/server.go` `Config`)
新增两个字段,均为证书/私钥文件路径;空 = 禁用 TLS(仅明文,向后兼容):
```go
TLSCertFile string // 服务端证书(PEM)
TLSKeyFile string // 服务端私钥(PEM)
```
`cmd/main.go` 读取环境变量(沿用现有 `YAMA_*` 命名):
```go
cfg.TLSCertFile = os.Getenv("YAMA_TLS_CERT")
cfg.TLSKeyFile = os.Getenv("YAMA_TLS_KEY")
```
仅当两者都非空才构建 `*tls.Config`;否则 `s.tlsCfg == nil`,`acceptLoop` 走纯明文。
### 5.2 `tls.Config`
```go
tlsCfg := &tls.Config{
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
// 单向 TLS:不设 ClientAuth / ClientCAs
}
```
### 5.3 `handleConnection` 检测 + 回放
标准 peek 回放:`bufio.Reader` 预读 6 字节,封装成 `bufferedConn`(实现 `net.Conn`,`Read` 委托给 `Reader`),判断后把已读字节一并交给目标。嗅探本身设了 `ReadTimeout` 截止,超时/EOF 则退回原始 conn 走明文,由读循环处理:
```go
func (s *Server) wrapTLS(conn net.Conn) net.Conn {
br := bufio.NewReader(conn)
_ = conn.SetReadDeadline(time.Now().Add(s.config.ReadTimeout)) // 嗅探受超时约束
hdr, err := br.Peek(6)
_ = conn.SetReadDeadline(time.Time{})
if err != nil {
return conn // 超时/EOF:走明文,交由读循环处理
}
bc := &bufferedConn{Conn: conn, r: br}
if isTLSClientHello(hdr) { // 0x16 0x03 且 b[5]==0x01
return tls.Server(bc, s.tlsCfg) // 握手惰性,首次 Read 触发
}
return bc
}
```
### 5.4 握手超时
`handleConnection` 首次 `conn.Read` 会触发 TLS 握手,而它已按 `ReadTimeout` 设了 `SetReadDeadline`,因此握手天然受 `ReadTimeout` 约束,无需额外机制。per-IP 限流(现有)继续在握手前生效,压制握手 DoS。
### 5.5 明确不动的部分
- `parser.go` / `codec.go` / `header.go`:**零改动**。
- `handleConnection` / `processData` / handler 栈:**零改动**(`tls.Conn` 满足 `net.Conn`)。
## 6. 客户端改动
### 6.1 证书检测
启动时(连接前)按优先级找信任锚:① 注册表 `Software\<exehash>\settings\tls_cert`(REG_SZ 存 PEM 正文)→ ② `settings.ini` `[settings] tls_cert` 路径 → ③ exe 同目录 `yama-ca.pem`。找到即走 TLS,否则明文。实现:`client/TlsChannel.cpp` 的 `ReadTrustAnchor()` + `TlsEnabled()`(`std::call_once` 惰性加载、线程安全、幂等)。
Linux 无注册表,信任锚按:① `$XDG_CONFIG_HOME/ghost/yama-ca.pem`(默认 `~/.config/ghost/yama-ca.pem`)→ ② 程序同目录 `yama-ca.pem`。文件**存在即视为已配置**:读取/解析失败一律拒绝连接(fail-closed)。实现:`client/TlsChannelLinux.cpp`。
### 6.2 TLS 栈选型(已定:Schannel)
- **已选 Schannel(Windows 原生 SSPI)**:零第三方依赖/零额外 DLL 部署,`secur32.lib`/`crypt32.lib` 均为系统库(`secur32.lib` 已在 `CFFmpegH264Encoder.cpp:38` 链接)。
- 信任锚(PEM/DER 正文,来自注册表或文件)经 `CryptStringToBinaryA` 解码 → `CertCreateCertificateContext` → 内存 `HCERTSTORE`;握手后 `CertGetCertificateChain` 把服务端证书链到该信任锚,`dwErrorStatus == 0` 才放行(含时间有效性)。**严格钉扎**:链引擎用 `hExclusiveRoot` 只信任该 store,排除系统根库,否则公共 CA 签发的证书也能通过。**fail-closed**。
- 握手凭据:`SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_DEFAULT_CREDS`,`grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT`(与 Go 端 `MinVersion: TLS 1.2` 对齐)。
- 单向 TLS:不提供客户端证书;客户端身份仍由隧道内登录承担。
### 6.3 连接层封装
在 socket 建立后、应用协议首包前插入 TLS 握手(`IOCPClient::ConnectServer`,`m_bConnected` 置位前);`ReceiveData`/`SendTo` 改走 `TlsChannel` 会话。所有出站连接(主连接 + 子连接)统一遵循 TLS 开关,因此子连接同样被加密——服务端按连接检测,天然支持。实现:`client/TlsChannel.{h,cpp}`,接入点 `client/IOCPClient.{h,cpp}`。
### 6.4 关键:无静默降级(fail-closed)
**证书文件存在但握手失败(证书不匹配 / 中间人)时,客户端必须报错并放弃连接,禁止回退到明文。** 否则攻击者可制造降级。这必须写进实现与测试。
### 6.5 实现要点:Schannel 流模式 `DecryptMessage` 的缓冲重组
Schannel 流模式(`ISC_REQ_STREAM`)下,`DecryptMessage` 会把输入的那段 `SECBUFFER_DATA`
**重组**为 4 段输出,而不是就地解密到原偏移:
| 索引 | 类型 | 内容 |
|---|---|---|
| `bufs[0]` | `SECBUFFER_STREAM_HEADER` | TLS 记录头(5) + 显式 nonce(8) |
| `bufs[1]` | `SECBUFFER_DATA` | **明文** |
| `bufs[2]` | `SECBUFFER_STREAM_TRAILER` | 认证标签 |
| `bufs[3]` | `SECBUFFER_EXTRA` | 下一条记录的剩余密文(如有) |
因此客户端 `Recv` 必须从 `bufs[1].pvBuffer`/`bufs[1].cbBuffer` 取明文、`EXTRA` 从 `bufs[3]`
取。若误用 `bufs[0]`(记录头+nonce)或从原缓冲首字节取数,会把 TLS 记录头 `17 03 03 …`
当作明文交给协议解析器(表现为 `Unknown header`)。`Send` 方向相反:`EncryptMessage` 用
`STREAM_HEADER/DATA/TRAILER` 三段布局,本就正确。这一处是联调阶段实际踩到的、唯一的方向性
不对称 bug,已修复。
### 6.6 Linux 客户端实现(OpenSSL,2026-10-28)
- **选型**:OpenSSL(`libssl`)。Linux 构建早已因 `libsign.a` 链接 `libcrypto`,只多链一个 `OpenSSL::SSL`,不引入新的运行时依赖包(同一 OpenSSL 3 包提供 `libcrypto.so.3` / `libssl.so.3`)。
- **代码组织**:`client/TlsChannel.h` 按平台分派(`_WIN32` → Schannel,`__linux__ && !__ANDROID__` → OpenSSL),Windows 分支内容不变;实现文件为 `client/TlsChannelLinux.cpp`。`YAMA_TLS_CHANNEL` 宏标注「本平台有 TLS 通道」,`IOCPClient` 用它替代原先的 `#ifdef _WIN32`,因此主连接与子连接共用同一接线点。macOS/Android 不定义该宏,维持明文。
- **语义对齐**:`TLS 1.2` 钉扎(min=max,与 `SP_PROT_TLS1_2_CLIENT` 及两套服务端一致);单向 TLS、不提供客户端证书、不校主机名、不做吊销检查;`SSL_VERIFY_PEER` + 只含信任锚的 `X509_STORE`(不含系统根库,严格钉扎),握手内完成链校验,失败即断开(fail-closed)。
- **缓冲差异**:OpenSSL 自己管理记录缓冲,不需要 Schannel 的 `m_raw`/`m_pending`;一次 `SSL_read` 交付不完的明文留在 `SSL` 内部,接收线程在 `select` 前用 `SSL_pending() || SSL_has_pending()` 优先消费,否则剩余字节会被 2 秒 `select` 超时卡住。
- **下发/撤销**:`COMMAND_TLS_ENABLE`(166) 的 PEM 正文写入 `~/.config/ghost/yama-ca.pem`(目录 0700、文件 0600、临时文件 + rename 原子替换);`COMMAND_TLS_DISABLE`(167) 删除该文件(含程序目录同名回退文件)。写入前先用 OpenSSL 解析一遍,不是合法证书就整包拒绝并保留原状态。
- **热切换(与 Windows 的唯一语义差异)**:落盘后立即 `TlsReload()` 重建 `SSL_CTX` 并更新开关,然后断开主连接、由外层重连循环用新传输方式重连——**主控端菜单点下去几秒内就生效**,不需要重启客户端(Windows 客户端仍需重启进程)。
- 状态不再是 `std::call_once`,而是 `g_stateMtx` 保护的 `{g_tlsEnabled, g_tlsError, g_tlsCtx}`;`TlsEnabled()/TlsLoadError()/TlsReload()/Handshake()` 都在这把锁下读写。
- **已建立的连接不受影响**:`SSL_new` 会递增 `SSL_CTX` 引用计数,`TlsReload` 释放旧 ctx 后旧的 `SSL` 仍然安全(已用「连接保持打开时撤销锚」验证)。
- **只在传输方式真的变了(明文↔TLS)时才重连**;仅换锚(例如证书轮换,仍是 TLS)不打断现有会话,新锚从下一条新连接生效。
- 热重载遇到坏锚时**保留原状态**并记日志,不把正在工作的客户端打死(下次启动仍按 fail-closed 语义)。
- 重连由 `DataProcess`(接收线程)只置 `g_needReconnect` 标志,由主心跳线程 `Disconnect()` 后走外层重连循环——避免在接收线程里关 socket 与主线程发送竞争。
- **代价**:此刻若正处于远程桌面/文件传输会话,主连接重建会中断该会话(子连接随之失效)。这是「立即生效」的固有代价。
- **上报**:登录 `szReserved[19]`(`RES_TLS`)填 `TlsEnabled() ? 1 : 0`,主控端主机信息显示 Y/N。热切换后重连会重新登录,登录前用 `RefreshLoginTls()` 刷新该字段,主控端在线列表的 TLS 列随之翻转。
## 7. 兼容矩阵
| 客户端 | 服务端行为 | 结果 |
|---|---|---|
| 老客户端(无证书概念) | 明文路径 | 与现状完全一致 |
| 新客户端 · 无证书 | 明文路径 | 与老客户端行为一致(默认) |
| 新客户端 · 有证书 | TLS 路径 | 全量加密(主 + 子连接) |
服务端 TLS 未配置(`YAMA_TLS_CERT/KEY` 为空)时,一切与现状一致,TLS 客户端握手自然失败(fail-closed)。
## 8. 安全考量
- **TLS 提供**:机密性、完整性、服务端身份(客户端校验)、抗重放(TLS record 序号 + nonce)。即对 TLS 客户端而言,Measure 1(真加密 + 防重放)达成。
- **TLS 不提供**(单向):客户端证书身份——仍由隧道内登录承担;对「未颁证客户端」不强制加密(这是本设计刻意保留的兼容性,也是薄弱点:部署安全性取决于最弱客户端)。
- **明文前导**:TLS ClientHello 前几字节明文(协议固有),仅暴露「这是 TLS 客户端」,不含业务数据;客户端不设 SNI(连接目标是 IP,无域名)。
- **子连接**:客户端统一走 TLS,screen/terminal/file 子连接一并加密;对应 Measure 2 的「源 IP 绑定」降级为纵深防御,不再是唯一防线。
- **证书轮换**:重签服务端证书后,需向已颁证客户端重新投递新信任锚(或在证书到期前提前过渡)。自签名建议 `-days 3650`,到期前统一更换。
- **协议强度**:`MinVersion` 固定 TLS 1.2+,套件用 Go 默认安全集(`tls.Config` 默认已排除弱套件)。
## 9. 部署与运维
### 9.1 生成证书
自签名(最简,客户端信任锚即 `yama-server.crt`):
```bash
openssl req -x509 -newkey rsa:2048 -nodes \
-keyout yama-server.key -out yama-server.crt \
-days 3650 -subj "/CN=yama-server"
```
或自建 CA + 签服务端证书(便于轮换,客户端信任锚为 `ca.crt`):
```bash
openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.crt -days 3650 -subj "/CN=yama-ca"
openssl req -newkey rsa:2048 -nodes -keyout server.key -out server.csr -subj "/CN=yama-server"
openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 3650
```
### 9.2 服务端
```bash
YAMA_TLS_CERT=/etc/yama/server.crt \
YAMA_TLS_KEY=/etc/yama/server.key \
./server_linux_amd64 ...
```
### 9.3 客户端「颁发 + 重启」
首选:把信任锚 PEM 正文写入注册表值 `Software\<exehash>\settings\tls_cert`(REG_SZ),重启客户端:
```powershell
$pem = Get-Content -Raw 'C:\path\yama-ca.pem'
New-Item -Path 'HKCU:\Software\<exehash>\settings' -Force | Out-Null
Set-ItemProperty -Path 'HKCU:\Software\<exehash>\settings' -Name 'tls_cert' -Value $pem -Type String
```
- `<exehash>` = 客户端 exe 全路径小写后的 FNV 哈希(`common/iniFile.h` 的 `GetRegistryName()`)。
- 客户端以服务(SYSTEM)运行时,注册表落在会话用户的 `HKEY_USERS\<SID>`(`GetCurrentUserRegistryKey()`)。
- REG_SZ 直接存 PEM 正文(含换行);客户端动态读取,不受 `iniFile::GetStr` 512 字节固定缓冲限制。
兼容旧方式:把信任锚复制到客户端目录并命名为 `yama-ca.pem`(或经 `settings.ini` `[settings] tls_cert` 指向),重启客户端。
Linux 客户端:把信任锚放到 `~/.config/ghost/yama-ca.pem`(或程序同目录 `yama-ca.pem`),重启客户端生效。MFC 主控端的「启用/停用 TLS 传输」指令对选中主机下发时也会写/删该文件,**且 Linux 客户端会立即热切换并重连**(无需重启,见 §6.6);Windows 客户端仍需重启。
移除注册表值(或删除文件)并重启即退回明文。远程下发/撤销:Windows 经 `COMMAND_TLS_ENABLE/DISABLE` 写注册表(重启生效),Linux 写/删上述配置文件(立即生效)。
## 10. 测试计划
1. **检测单元**:`isTLSClientHello` 对 `0x16 0x03 … 0x01`(TLS 1.2/1.3 ClientHello)/ `POST ` / `Shine` / 混淆 `HELL`(首两字节恰好 `0x16 0x03` 但 `b[5]==0x00`)/ 短于 6 字节 等判定的单测(已实现 `server/go/server/tls_test.go`)。
2. **TLS 未配置**:不设 `YAMA_TLS_*` → 纯明文,行为与现状一致。
3. **明文回归**:老客户端 + 新客户端(无证书)均走明文,登录/屏幕/终端/文件全链路不回归。
4. **TLS 加密**:新客户端(有证书)→ 握手成功,登录/屏幕/终端/文件子连接全部在 TLS 内跑通;抓包确认 payload 不可读。
5. **混合并发**:明文与 TLS 客户端同时在线,互不干扰。
6. **fail-closed**:客户端有证书但服务端证书不匹配 / 中间人 → 客户端报错断开,**不**回退明文。
7. **握手超时 / 限流**:恶意慢握手被 `ReadTimeout` + per-IP 限流压制。
## 11. 分期与回滚
- **阶段 1(Go 服务端,本期优先)**:`Config` + `tls.Config` + `acceptLoop` 检测回放;明文路径零改动。可独立上线、独立验证——用 `openssl s_client` 或 Go 测试客户端即可联调 TLS 链路,无需真实客户端配合。
- **阶段 2(Windows 客户端)**:证书检测 + TLS 栈 + fail-closed。
- **阶段 2b(Linux 客户端)**:OpenSSL 实现,复用同一接线点与协议语义(2026-10-28 完成)。
- **阶段 3(MFC 服务端 `server/2015Remote`,延后)**:与 Go 服务端同款的 TLS 检测 + 解包接入。设计稿见 `docs/TransportTLS_MFCServer_Design.md`。
- **回滚**:服务端清空 `YAMA_TLS_CERT/KEY` 即回到纯明文;客户端删除注册表 `tls_cert` 值(或 `yama-ca.pem` 文件)即回明文。
## 12. 待定问题
1. ~~客户端 TLS 栈最终选型~~ → **已定 Schannel**(见 §6.2,2026-10-13 落地)。
2. ~~信任锚文件固定名(`yama-ca.pem`)是否需可配置~~ → **已改为注册表 `tls_cert` 值优先、文件回退**(见 §6.1/§9.3,2026-10-14)。
3. 是否同步把「TLS 内去掉 XOR」列为后续精简项(当前保留 XOR,换取零协议改动)。
4. ~~Linux / macOS / Android 客户端的 TLS 接入排期~~ → **Linux 已接入(OpenSSL,2026-10-28)**;macOS / Android 待定(macOS 需 Security.framework 或自带 OpenSSL,Android 需在 NDK 内构建 OpenSSL)。
+280
View File
@@ -0,0 +1,280 @@
# MFC 服务端(server/2015Remote)单向 TLS 加密设计
> 版本:v0.3 · 状态:**已实施并验证(屏幕 + 终端联调通过)** · 日期:2026-10-15
> 上游依赖:`docs/TransportTLS_Design.md`(Go 服务端 + Windows 客户端,已实现并验证)。
> 本期范围:**MFC 服务端 `server/2015Remote` 的传输层加密**(加载证书+私钥、握手、加解密、新旧客户端并存)。
> 显式排除(本次不做,但须预埋接缝):① MFC 的 MCP 式配置 UI;② 「向在线主机下发是否启用加密传输」的指令;③ 客户端运行时热切换。
>
> **已拍板的三个决策(2026-10-14,见 §12)**:
> 1. 握手采用 **方案 A(专用短命阻塞线程)**;
> 2. 身份文件采用 **PEM + CNG(`CertPath` + `KeyPath`)**,与 Go 服务端共用同一对密钥;私钥须为 **PKCS#8**;
> 3. 配置 **新建 `[tls]` 节**(`Enabled` / `CertPath` / `KeyPath`)。
>
> 需求原文(已确认):
> 1. MFC 服务端有一个类似 MCP 的配置,可选启用传输层加密;启用时需指定一对密钥(证书 + 私钥);
> 2. 启用后,可向在线主机发送「是否启用加密传输」的指令 —— **UI 与新指令属后期内容**;
> 3. **新旧客户端都须支持**:同一端口同时兼容明文(老客户端)与 TLS(新客户端)。
## 1. 目标与范围
### 目标
- MFC 服务端在同一个 TCP 端口(6543)上,按连接自动区分「明文客户端」与「TLS 客户端」,路由到各自路径。
- TLS 客户端解密后的字节流 == 同一套应用协议(flag 帧 + XOR + zstd),**协议解析/解压/解码零改动**。
- 老客户端(无 TLS 概念)行为不变、零改动。
- 服务端「启用 TLS」是**配置驱动**的:未配证书 → 纯明文;配了证书 → 新旧并存。
### 非目标(Non-goals,本次不做)
- 不做 **mTLS / 客户端证书**:单向 TLS,客户端身份仍由隧道内登录(V1 `PwdHmac` / V2 `ECDSA`)承担。
- 不做「TLS 内去掉 XOR」的二次精简(与上游设计一致,保留 XOR 换取零协议改动)。
- 不做 **UI**:不新增配置对话框、不加「启用加密」复选框、不加证书/私钥路径选择控件。
- 不做 **「向在线主机下发启用/撤销加密」指令**:不下发信任锚、不发加密开关指令、不改客户端运行时状态。
- 不做 KCP/UDP 传输(`IOCPKCPServer`)的 TLS 接入(本期只做 TCP 设备端口;KCP 另行评估)。
## 2. 现状与复用(IOCP 数据流 + 四个接缝)
MFC 服务端 TCP 接收链路:`OnAccept`(`IOCPServer.cpp:1144`)`accept` 后 `AllocateContext`(`:1289`)分配 `CONTEXT_OBJECT`,绑定 IOCP,`PostRecv`(`:1268`)投递首个 `WSARecv`(`:1278`,收进 `wsaInBuf`→`szBuffer[PACKET_LENGTH]`,`:1215`)。收满后 `HandleIO(IORead)`(`:746`)→ `OnClientReceiving`(`:892`)→ `ParseReceivedData`(`:796`)。
原始 socket 字节在整套流程里各只有**一个入口**和**一个出口**,这是 TLS 能做成「过滤器」而非「改写」的根本原因:
| 接缝 | 位置 | 作用 |
|---|---|---|
| ① 收包咽喉点 | `IOCPServer.cpp:805` `InCompressedBuffer.WriteBuffer(szBuffer, dwTrans)` | 原始字节进入协议解析的**唯一**位置(`szBuffer` 全文件仅此一处消费) |
| ② 发包咽喉点 | `IOCPServer.cpp:1000` `WSASend(...wsaOutBuffer...)` | `OutCompressedBuffer` 上行的**唯一**位置 |
| ③ 嗅探点 | `OnAccept`→`PostRecv`;`OnClientInitializing`(`:790`)现为空桩 `return TRUE` | 首次收到数据处,可挂 ClientHello 判定 |
| ④ 状态字段 | `Server.h:332` `CONTEXT_OBJECT`(`szBuffer`/`wsaInBuf`/`InCompressedBuffer`/`InDeCompressedBuffer`/`OutCompressedBuffer`/`Parser` 等,`:359-398`) | 新增 TLS 会话指针 + 标志位 |
**关键结论(本设计的基础)**:TLS 作为「透明传输包装」,加解密插在 ①② 两处,③ 做新旧分流,④ 加一个 per-connection 状态。`ParseReceivedData` 内的 `Parse`/解压/`Decode`、`WriteContextData` 内的 `Encode`/压缩/掩码,**全部不动**。这与上游 Go 服务端「`tls.Conn` 满足 `net.Conn`、parser 零改动」是同一策略(见上游 §2.3)。
## 3. 总体方案
### 3.1 按连接嗅探(与 Go 服务端同款判定)
首次收到数据后,只看 `szBuffer` 前 6 字节:
- 命中 `0x16 0x03 … 0x01`(TLS 握手记录 + TLS 版本号 + ClientHello)→ TLS 路径;
- 其它 → 明文路径(老客户端透明,一行不改)。
判据与 Go 端 `isTLSClientHello`(`0x16 0x03` 且 `b[5]==0x01`)**完全一致**,理由也一致:客户端会随机混淆魔数头(见上游 §2.1),明文前两字节可能恰为 `0x16 0x03`,但字节 5 对混淆头恒非 `0x01`,故三重判据误判率趋近于零。
### 3.2 数据路径 = 条件过滤器
```
OnAccept → PostRecv
│
首次 IORead 完成(嗅探 szBuffer[0..5])
┌─────┴─────┐
明文(其它) TLS(0x16 0x03 .. 0x01)
│ │
ParseReceivedData TLS 握手(AcceptSecurityContext)
(现状,零改动) │ 成功
│ ▼
│ 握手后:IORead → DecryptMessage → 明文 → InCompressedBuffer.WriteBuffer
│ 发送:OutCompressedBuffer → EncryptMessage → WSASend
└────────── 同一套 Parse/Encode/解压/压缩 ──────────┘
```
明文连接与握手后的 TLS 连接,下游共用同一套 `Parse`/`Encode`/解压/压缩。唯一差别是 ①② 两处各多一个 `if (tls) 加解密 else 直通` 分支。
## 4. 配置设计(含未来 UI/指令的预埋)
### 4.1 配置面(本次定键名,UI 后期加)
MFC 服务端配置走 `THIS_CFG`(`config`/`iniFile`,`GetInt`/`GetStr(section,key,default)`,见 `2015Remote.cpp:481-543` 用法)。新增 `[tls]` 节,三键(**已拍板 PEM + CNG**,见 §5.6、§12):
```ini
[tls]
Enabled = 0 ; 是否启用传输层加密(0/1)
CertPath = "" ; 服务端证书路径(PEM,-----BEGIN CERTIFICATE-----)
KeyPath = "" ; 服务端私钥路径(PEM PKCS#8,-----BEGIN PRIVATE KEY-----)
```
三键都是**短字符串路径**,不落 PEM 正文,故不受 `iniFile::GetStr` 512 字节固定缓冲限制(该限制只在「存 PEM 正文」时才成问题,客户端已为此单独绕行,见上游 §6.1)。
### 4.2 未来不返工的四条硬约束(本次预埋)
1. **配置单一访问器**:TLS 开关与身份路径只经一个中心对象 `ServerTlsIdentity` 暴露:`Load(config&)` / `IsEnabled()` / `IsReady()` / `IsLoadError()` / `Cred()`。未来 UI 改配置、指令查询「我当前是否加密态」都走这同一个入口,禁止代码里散落 `GetInt("Enabled")`。
2. **身份加载做成可重入,绝不用 `std::call_once`**:`ServerTlsIdentity::Load(config&)` 每次调用重新加载证书+私钥并重建凭据句柄。本次启动时调一次;未来「轮换证书 / 开关切换」可再调。这是对客户端 `TlsEnabled()` 用 `std::call_once` 一次读死、不可热切换(见上游 §6.1 与 `docs/tls-cert-push-revoke-deferred` 相关记忆)的**主动规避**。
3. **「我是否 TLS 就绪」是全局只读态,与每条连接的 TLS 态分开**:`ServerTlsIdentity::IsEnabled()`(全局配置态)/ `IsReady()`(身份加载成功)与 per-connection 的「该连接是否走 TLS/握手是否完成」是两个概念。未来指令/UI 只碰前者。
4. **按连接嗅探本身就是为混合上线准备的**:服务端开 TLS 后,没切换的旧主机照样明文连、已切换的走 TLS。未来「下发开启指令」只改客户端行为,服务端传输层不用动。
## 5. 服务端改动详述
### 5.1 `CONTEXT_OBJECT` 字段(`Server.h`,加 4 项)
```cpp
// 每连接传输层状态(单向 TLS,见 §5.2);跨线程(握手线程写 TLS_Ready,工作线程读)用 atomic 保序
enum ServerTlsState {
TLS_Unclassified = 0, // 尚未收到足够字节判定(缓冲 tlsPreClassify)
TLS_Plain = 1, // 明文客户端,直通现有解析路径
TLS_Handshaking = 2, // TLS 客户端,握手线程阻塞 AcceptSecurityContext 中
TLS_Ready = 3, // TLS 握手完成,收包解密 / 发包加密
};
ServerTlsSession* tls = nullptr; // 懒分配;握手完成后承载加解密状态
std::atomic<int> tlsState{ TLS_Unclassified }; // ServerTlsState
std::vector<BYTE> tlsPreClassify; // 分类前缓冲的首批字节(嗅探 ClientHello 头)
bool bSendPending = false; // 发送在途抑制(见 §5.5);受 SendLock 保护
void FreeTls(); // delete tls; tls = NULL;(定义在 ServerTlsSession.cpp,避免本头拖入 Schannel)
```
生命周期见 §5.7:`InitMember` 时复位 `tlsState`/`tlsPreClassify`/`tls`,析构 / 回收时 `FreeTls()`。
### 5.2 嗅探与预分类缓冲
首次 `IORead` 完成时(`OnClientReceiving` 开头,`ParseReceivedData` 之前)判定:
- `dwTrans >= 6`:看 `szBuffer[0..5]`,一次定死明文/TLS;
- `dwTrans < 6`(TCP 把 ClientHello 头分片,极罕见但须正确):把这 `dwTrans` 字节追加进 `tlsPreClassify`,`PostRecv` 继续收,直到攒够 6 字节再判定。判定后清空 `tlsPreClassify`。
明文连接判定后,把 `tlsPreClassify`(如有)+ 本次 `szBuffer` 一并按现状喂给 `ParseReceivedData`,保证分片字节不丢。
### 5.3 握手(已拍板方案 A)
服务端握手需 `AcceptSecurityContext`(Schannel 入站),与客户端 `InitializeSecurityContext`(出站)**不通用**,需新写。数据阶段的 `DecryptMessage`/`EncryptMessage` 是同步缓冲变换,与异步收发包天然兼容,两个方案都复用。
**方案 A:专用握手线程(阻塞式,已实施)**
- 首次 `IORead` 判定为 TLS 后,此刻 `WSARecv` 已因完成回调结束、socket 上**无 pending overlapped 操作**,可安全转交一个短命线程做阻塞握手。
- 线程内用**与客户端 `TlsChannel::Handshake` 同型的阻塞 Schannel 循环**跑 `AcceptSecurityContext`(`TlsChannel.cpp` 已证明该模式可靠),把已收到的 ClientHello 字节(`tlsPreClassify`,可能是分片)作为初始输入,后续 handshake 航程走阻塞 `recv`/`send`;握手前把 socket 切回阻塞态并设 15s 收发超时。
- 成功 → `tlsState.store(TLS_Ready)`,`PostRecv` 投递首个 `IORead`,回到 IOCP 正常流程;失败 → 关连接(fail-closed,§8)。
- 优点:复用客户端已验证的阻塞 Schannel 代码形态、状态最少;缺点:每个 TLS 连接多一个短命线程(仅在握手期间存活)。
**方案 B:异步状态机(无额外线程,更贴合 IOCP)**
- 握手由 `IORead`/`IOWrite` 完成回调推进:每次回调喂一段握手字节给 `AcceptSecurityContext`,按其返回(`SEC_I_CONTINUE_NEEDED` → 继续收/发;`SEC_E_OK` → 完成)驱动下一动作。
- 优点:无额外线程、与现有 IOCP 事件循环同构;缺点:状态管理明显更重,需把「握手待收/待发/完成」编码进 per-connection 状态。
**已拍板(2026-10-14)**:采用 **方案 A**(简单、复用客户端阻塞 Schannel 经验、风险低)。方案 B 留作后续压测发现短命线程开销不可接受时再演进;二者切换只影响 §5.3,不影响 ①②④ 的过滤器设计。
### 5.4 收包解密(接缝 ①,`ParseReceivedData` 之上)
`OnClientReceiving` 里,明文与 TLS 分叉:
```cpp
int st = ContextObject->tlsState.load(std::memory_order_acquire);
if (st == TLS_Ready) {
// 1) 把 szBuffer[0..dwTrans] 喂给 DecryptMessage,得到明文 plain、长度 n
// 2) 处理 SECBUFFER_EXTRA:多余密文留存到 tls 对象内部缓冲(m_raw),下次续解(见上游 §6.5)
// 3) plain 为空(记录分片未齐)→ PostRecv 继续收;否则 ContextObject->InCompressedBuffer.WriteBuffer(plain.data(), n);
} else {
ContextObject->InCompressedBuffer.WriteBuffer(szBuffer, dwTrans); // 现状,零改动
}
```
即 ① 从「一行直写」变成「条件分支」,明文侧原文不动。解密缓冲重组(`STREAM_HEADER/DATA/TRAILER/EXTRA` 四段布局)已在上游 §6.5 踩过坑、给出正确写法,服务端直接沿用(`ServerTlsSession::Decrypt` 内维护 `m_raw` 续解缓冲)。
### 5.5 发包加密(接缝 ②,`OnClientPreSending` 之上)
`OutCompressedBuffer` 是「可能残留上一轮未发完密文」的可变缓冲:异步 `WSASend` 在途时,新明文由 `WriteContextData` 追加在尾部。因此 `OnClientPreSending`(`IOCPServer.cpp`)**只加密本次新追加的尾部明文**,而非整个缓冲:
1. 追加前记 `oldLen = OutCompressedBuffer.GetBufferLength()`;
2. `WriteContextData` 追加新明文后,`plainLen = totalLen - oldLen`,只对 `GetBuffer(oldLen)` 起的 `plainLen` 字节调用 `tls->Encrypt` 得密文 `wire`;
3. `TruncateBuffer(oldLen)` 回退尾部明文(**不用 `ClearBuffer`**:后者会 `DeAllocateBuffer`,可能 `VirtualFree` 正在被在途 `WSASend` 引用的底层内存),再 `WriteBuffer(wire)` 追加新密文。
这样 `OutCompressedBuffer` 始终保持一串合法 TLS 记录。若把整个缓冲重新加密,会把旧密文二次加密,客户端解密后得到「旧 TLS 记录」→ `Unknown header 17 03 03`。
**发送唤醒的并发抑制(`bSendPending`)**:`OnClientPreSending` 每次 `Send2Client` 若都 `PostQueuedCompletionStatus(IOWrite, 0)`,则每个 `OnClientPostSending(ctx, 0)` 都会对整个缓冲再发起一次 `WSASend`;背靠背小包(终端 `resize → COMMAND_NEXT → resize`)会触发多个并发 `WSASend` 读到同一段可变内存,产出重复/错位密文(客户端 `DecryptMessage` 失败,`WSAGetLastError()` 残留 `6001 = ERROR_DECRYPTION_FAILED`)。故新增 `bool bSendPending`(受 `SendLock` 保护):仅在 `!bSendPending` 时投递 IOWrite 并置位;`OnClientPostSending` 在缓冲排空(最后一个 `WSASend` 完成)或发送失败时清零;`InitMember` 复用对象池时复位。在途 `WSASend` 的完成回调会看到排空后仍残留的新数据并继续发送,无需再投递。后续 `OnClientPostSending` 的部分发送循环照旧——它发送的已是密文字节,逐段 `WSASend` 天然成立。
### 5.6 证书/私钥加载(Schannel 入站凭据,已拍板 PEM+CNG)
`AcquireCredentialsHandle` 取 `SCHANNEL_CRED`(入站)时需一个**已绑定私钥的证书**。已拍板用 **PEM + CNG**(与 Go 端 `YAMA_TLS_CERT/KEY` 同构,服务端与 Go 共用同一对密钥):
- **证书**:`CryptStringToBinaryA(CRYPT_STRING_ANY)` 把 PEM 解为 DER → `CertCreateCertificateContext(X509_ASN_ENCODING)`。
- **私钥(仅 PKCS#8)**:Schannel 入站凭据要求私钥是**「能按名重开」的持久化键**——`NCryptImportKey` 产出的是匿名临时键,绑定 `CERT_NCRYPT_KEY_HANDLE_PROP_ID` 后 Schannel 仍拿不到(`AcquireCredentialsHandle` 返回 `SEC_E_NO_CREDENTIALS` `0x8009030e`)。因此:
1. **导入临时键并导出裸 BLOB**:`NCryptOpenStorageProvider(MS_KEY_STORAGE_PROVIDER)` + `NCryptImportKey(NCRYPT_PKCS8_PRIVATE_KEY_BLOB)` 得临时键(`hProvider` 不能传 NULL——默认提供者解析实测返回 `NTE_INVALID_HANDLE` `0x80090026`,须显式打开 KSP);再 `NCryptSetProperty(NCRYPT_EXPORT_POLICY_PROPERTY=ALLOW_PLAINTEXT_EXPORT|ALLOW_EXPORT)` 后 `NCryptExportKey(BCRYPT_RSAFULLPRIVATE_BLOB)` 得裸 RSA 私钥 BLOB。
2. **写入持久化键**:`NCryptCreatePersistedKey(BCRYPT_RSA_ALGORITHM, "YamaServerTlsKey", AT_KEYEXCHANGE, NCRYPT_OVERWRITE_KEY_FLAG)` → `NCryptSetProperty(BCRYPT_RSAFULLPRIVATE_BLOB)` → `NCryptFinalizeKey`。`NCryptSetProperty` 只认裸 BLOB、不认 PKCS#8(直接设 `NCRYPT_PKCS8_PRIVATE_KEY_BLOB` 实测 `NTE_NOT_SUPPORTED` `0x80090029`)。
3. **按名绑定**:`CertSetCertificateContextProperty(CERT_KEY_PROV_INFO_PROP_ID, CRYPT_KEY_PROV_INFO{ pwszContainerName="YamaServerTlsKey", pwszProvName=MS_KEY_STORAGE_PROVIDER, dwProvType=0, dwKeySpec=AT_KEYEXCHANGE })`。Schannel 经 `CryptAcquireCertificatePrivateKey` 按名在 KSP 里重开该键。
- **入站凭据**:`AcquireCredentialsHandleA("Microsoft Unified Security Protocol Provider", SECPKG_CRED_INBOUND, &SCHANNEL_CRED{ cCreds=1, paCred=&cert, grbitEnabledProtocols=SP_PROT_TLS1_2_SERVER, dwFlags=NO_DEFAULT_CREDS })`。
关键点:**私钥必须是 PKCS#8**(`-----BEGIN PRIVATE KEY-----`);若拿到的是 PKCS#1(`-----BEGIN RSA/EC PRIVATE KEY-----`),用
`openssl pkcs8 -topk8 -nocrypt -in server.key -out server.key` 转换。证书上下文生命周期交给进程级 `g_cert`,持久化键句柄交给 `g_persistedKey`;`FreeIdentity` 里按序 `FreeCredentialsHandle` → `CertFreeCertificateContext` → `NCryptDeleteKey`(`NCryptDeleteKey` 会同时释放句柄,勿再 `NCryptFreeObject`)。
### 5.7 生命周期(context 池化复用)
`CONTEXT_OBJECT` 经 `AllocateContext`(`:1311`)从 `m_ContextFreePoolList` **复用**、`InitMember`(`:1314`)复位。故 TLS 状态必须在 `InitMember` 里清空 `tlsPreClassify`、`FreeTls()`、复位 `tlsState`(`store(TLS_Unclassified)`)与 `bSendPending=false`(避免上次连接残留的在途标志抑制新连接发送),并在 `~CONTEXT_OBJECT`(`Server.h:346`)`FreeTls()`。否则「前一个 TLS 连接的状态漏给下一个明文连接」会直接导致解析错乱。这是唯一需要跨过 `InitMember`/析构两处做的生命周期接线。
### 5.8 明确不动的部分
- `ParseReceivedData` 内的 `Parse`/解压/`Decode`、`WriteContextData` 内的 `Encode`/压缩/掩码:**零改动**。
- `HeaderParser` / `context`(`context.h`)协议层:**零改动**。
- `OnAccept` / `PostRecv` / `AllocateContext` / `RemoveStaleContext` 主结构:**零改动**(仅新增 TLS 分支与字段复位)。
- KCP / UDP 传输(`IOCPKCPServer`):**零改动**(不在本期范围)。
## 6. 新老客户端兼容矩阵
| 客户端 | 服务端 TLS 状态 | 服务端行为 | 结果 |
|---|---|---|---|
| 老客户端(无 TLS 概念) | 未配置 | 明文路径 | 与现状完全一致 |
| 老客户端 | 已配置 | 嗅探判为明文 → 明文路径 | 与现状完全一致(透明) |
| 新客户端 · 无证书 | 未配置 / 已配置 | 明文路径 | 与老客户端一致(默认) |
| 新客户端 · 有证书 | 已配置 | 嗅探判为 TLS → 握手 → 加密 | 全量加密 |
| 新客户端 · 有证书 | 未配置 | 嗅探判为 TLS → 无证书可握手 → **关连接(fail-closed)** | 拒绝(见 §8) |
## 7. 与未来「下发/撤销指令 + UI」的接缝
本次不实现 UI 与指令,但通过 §4.2 四条约束预留干净接缝。二者未来的分工与依赖:
- **UI**:在 MFC 配置对话框(类 MCP)里加「启用传输加密 + 指定一对密钥」,写入 `[tls]` 三键 → 调 `ServerTlsIdentity::Load(config&)` 重载 → `IsEnabled()` 即时生效。**只碰 §4.2 第 1/2 点,不碰传输层。**
- **「向在线主机下发启用/撤销加密」指令**:服务端侧是一条新的命令通道(遍历在线连接广播),客户端侧是**运行时热切换**——收到指令后热加载/删除信任锚、断开重连走新通道。
**必须先说破的跨端依赖**:这条指令真正的大头在**客户端**——客户端目前读 `tls_cert` 是进程启动读一次、`std::call_once`、**不可热切换**(见上游 §6.1 及 `docs/tls-cert-push-revoke-deferred` 记忆)。因此「下发/撤销」落地时,客户端要先把 `TlsEnabled()` 的一次读死改成「指令驱动的热重载」。**这与本次服务端传输层正交**——只要 §4.2 第 2/3 点把服务端状态做成可重载、可中心化查询,未来就能干净接上,无需回头改本次代码。
## 8. 安全考量
- **TLS 提供**:机密性、完整性、服务端身份(客户端校验)、抗重放(TLS record 序号 + nonce)。对 TLS 客户端而言,Measure 1(真加密 + 防重放)达成,与 Go 端一致。
- **TLS 不提供**(单向):客户端身份——仍由隧道内登录承担。
- **服务端 fail-closed**:服务端收到 TLS ClientHello 但自身未配证书/身份加载失败 → **直接关连接**,禁止把 TLS 字节当协议去解析(否则新客户端握手失败重试 + 服务端狂报解析错)。与客户端 fail-closed 语义对称(见上游 §6.4)。
- **握手 DoS**:TLS 握手有 CPU 开销,须受 per-IP 限流(现有)保护;方案 A 的短命握手线程还须加握手超时(`SSPI` 握手期间设 socket 收发超时,超时关连接)。
- **部署顺序**(关键):**MFC 服务端证书必须与客户端 CA 一起(或先于)上线**。否则「新客户端(已钉 CA)连旧 MFC 服务端(无证书)」→ 客户端 fail-closed 直接拒绝,表现为「升级客户端后连不上老服务端」。这是设计使然,部署/文档须写明。
- **私钥安全**:服务器私钥只在握手时由 Schannel 内部签名使用(ECDHE)或解密预主密钥(RSA),不参与业务数据加解密;私钥文件应最小权限存放、不落日志。真正的长期秘密(CA 私钥)平时离线,仅在签发/轮换服务器证书时使用。
## 9. 部署与运维
生成服务端身份(与 Go 端 §9.1 的 `server.crt` + `server.key` 完全同一对密钥;私钥须 PKCS#8):
```bash
# 若私钥是 PKCS#1(-----BEGIN RSA/EC PRIVATE KEY-----),先转 PKCS#8:
openssl pkcs8 -topk8 -nocrypt -in server.key -out server.key
```
MFC 服务端配置(直接指向与 Go 端相同的 PEM 文件):
```ini
[tls]
Enabled = 1
CertPath = C:\YAMA\server.crt
KeyPath = C:\YAMA\server.key
```
重启 MFC 服务端即生效(本次仅启动时读一次,热切换待未来 UI)。删除 `[tls]` 节或置 `Enabled=0` 即回纯明文。
## 10. 测试计划
1. **嗅探单元**:`0x16 0x03 .. 0x01`(TLS 1.2/1.3 ClientHello)/ 明文首包 / 混淆头(首两字节 `0x16 0x03` 但 `b[5]!=0x01`)/ 首包 <6 字节分片 的判定。
2. **TLS 未配置**:`Enabled=0` 或无证书 → 纯明文,行为与现状一致(老 + 新无证书客户端回归)。
3. **明文回归**:老客户端全链路(登录/屏幕/终端/文件)不回归。
4. **TLS 加密**:新客户端(有证书)连 MFC 服务端 → 握手成功,登录/屏幕/终端/文件子连接全部在 TLS 内跑通;抓包确认 payload 不可读。
5. **混合并发**:明文与 TLS 客户端同时在线,互不干扰(对应未来过渡期)。
6. **fail-closed 双向**:① 服务端未配证书但收到 ClientHello → 关连接不误解析;② 客户端有证书但服务端证书不匹配 → 客户端断开不回退明文。
7. **握手超时 / 限流**:恶意慢握手被超时 + per-IP 限流压制。
8. **连接复用**:一条 TLS 连接断开后,context 回池再被明文连接复用,TLS 状态已复位、无泄漏(§5.7)。
## 11. 分期与回滚
- **本期(MFC 服务端传输加密,已实施)**:`ServerTlsIdentity`(PEM+CNG 加载)+ `CONTEXT_OBJECT` 字段(`tlsState` 枚举)+ 嗅探/预分类 + 握手(方案 A)+ ①收包解密 + ②发包加密 + 生命周期复位。可独立验证——用 `openssl s_client` 或复用 Go 端测试客户端联调,无需真实客户端配合。
- **后续 A(UI)**:MCP 式配置对话框 + 重载 `ServerTlsIdentity`。
- **后续 B(下发/撤销指令)**:服务端指令通道 + **客户端热切换**(客户端 `TlsEnabled()` 改指令驱动,见 §7)。
- **回滚**:服务端 `[tls] Enabled=0` 即回纯明文,无需改客户端(客户端无证书时本就明文)。
## 12. 已拍板决策与仍待定问题
**已拍板(2026-10-14)**:
1. **握手方案**:采用 **方案 A(专用阻塞线程)**,见 §5.3。
2. **身份文件格式**:采用 **PEM + CNG(`CertPath` + `KeyPath`,私钥 PKCS#8)**,与 Go 服务端共用同一对密钥,见 §5.6。
3. **配置节名**:新建 **`[tls]` 节**,键 `Enabled` / `CertPath` / `KeyPath`,见 §4.1。
**仍待定**:
1. **KCP/UDP 传输是否也要 TLS**:本期不含,另行评估。
2. **MFC 的 MCP 式配置 UI**:显式排除,见 §7;落地时只碰 §4.2 第 1/2 点。
+1
View File
@@ -69,6 +69,7 @@ YAMA 主界面由以下部分组成:
| 执行程序 | 下载执行、上传执行 |
| 修改备注 | 编辑主机备注 |
| 修改分组 | 更改所属分组 |
| 复制名称 | 复制选中主机的名称(有备注取备注),多选时用分号分隔 |
> **注意**:文件管理、远程终端、进程管理等功能通过**工具栏图标**打开
+481
View File
@@ -0,0 +1,481 @@
# WebSocket 传输设计(受限出站端口下经反代接入)
> 版本:v1.0(已实现并本地验证) · 日期:2026-10-30
> 目标:客户端的出站被限制在 80 / 443 / 8080 等少数端口,且这些端口都不归主控所有时,
> 仍能让客户端连上服务端;同时把 nginx 侧改动压到最小(只加一个 server 块或一个 location)。
>
> 需求原文:
> 1. 「我的客户端连接服务端时端口被限制……只能借助于已有端口分流,比如 nginx 的端口。
> 但是我的客户端目前是 TCP 流量。调研一下怎么解决」
> 2. 「我的客户端连接到 xxx.com:6543, 但是 6543 不允许出站」
> 3. 「6543 我可以修改,但是只能改为 80,443,8080,但是这些端口都已经在使用」
> 4. 「B 方案更适合目前场景。xxx.com 的 nginx 配置尽量少改,不要大改」
>
> 已核实前提:客户端当前**都已启用 TLS**。服务端两套实现均可接入:Go 版(`server/go`)
> 与 MFC 版(`server/2015Remote`,见 §4.2)。
## 1. 方案选型
| 方案 | 做法 | 结论 |
|---|---|---|
| A. 占用 8080 | 把主控端口改到 8080 直连 | 否决:8080 已被别的应用占用 |
| **B. WebSocket over nginx 443** | 客户端把应用字节流套进 WS 帧,经 nginx `server_name` + `location /api/ws` 转发到 127.0.0.1:6543 | **采用** |
| C. 租新端口 | 换一台能出站的机器/端口 | 否决:出站白名单是客户端侧策略,换端口仍被拦 |
B 方案的关键点:WS 升级只是一次普通 HTTP 请求,nginx 现有的 443 已经能承载;
真正的应用协议完全不变,只是「字节流外面多了一层帧」。
## 2. 协议号与形态
`common/commands.h`:
| 值 | 枚举 | 形态 |
|---|---|---|
| 5 | `PROTO_WS` | 裸 WebSocket(明文;反代把明文 upgrade 转发到主控端口) |
| 6 | `PROTO_WSS` | WebSocket over TLS(**客户端经反代 443 接入,推荐**) |
| 7 | `PROTO_HTTPS` | 从未在生成界面出现过,故 5 让给 WS(原值 5,见下方风险) |
`WS_UPGRADE_PATH` = `/api/ws`:客户端请求的 Upgrade 路径,反代的 `location` 必须与之对齐;
服务端默认接受任意路径,`YAMA_WS_PATH` 只用于把路径收窄。
传输层位置(自下而上):TCP → TLS(可选)→ **WebSocket 帧** → 既有应用协议(Shine/HELL 头、
XOR、zstd、HTTP 伪装层)。WS 与 HTTP 伪装的 `MaskType` 互斥:选 WS 时用 `MaskTypeNone`。
> 兼容性:`PROTO_HTTPS` 从 5 移到 7。它在 `NewNetClient` 里本来就被直接拒绝、生成界面也从未
> 提供,因此不存在已发布客户端带 5 号协议的情况。
>
> 但这是**协议号复用**:从此任何历史落盘 / 历史配置里的 `proto=5` 一律按 `PROTO_WS` 解释。
> 老客户端与老服务端之间若曾有 `5` 的任何含义,都会在这次升级后变成 WS。
## 3. 客户端实现
新增 `client/WsChannel.h`(**头文件实现**,各平台工程文件不必改动):
- `Handshake(sock, host, port, path, &err)`:发 `GET <path> HTTP/1.1` + `Upgrade: websocket`,
期望 `HTTP/1.1 101`;`Sec-WebSocket-Key` 用固定值(它只用于让中间设备识别这是 WS 握手,
安全由隧道内登录与 TLS 承担)。
- `Send`:一次 `SendTo` 写一帧(FIN + binary,**客户端帧必须掩码**,RFC 6455 §5.3),
与 Go 端 `wsConn.Write` 的「一次 Write 一帧」对齐,包边界与发出时一致。
- `Recv`:在帧载荷上做流式读取(`m_remaining` 记录剩余、`m_maskPos` 记录掩码位置),
ping 自动回 pong,close 回 close 并按正常关闭返回 0,跨帧边界的应用层包不会丢。
- `HasPending()`:帧载荷只解析了一半、或 WSS 下 TLS 会话里还压着已解密明文时返回 true,
让接收线程在 `select` 之前优先消费(否则只能等 2 秒超时)。
- 并发写:`Recv` 里要为 ping/close 回写控制帧,与发送线程的数据帧是两条并发的写路径。
`WriteFrame` 用 `m_sendMtx` 串行化,并把整帧(帧头 + 掩码载荷)放进一个复用缓冲区、
一次 `SendAll` 写出——若头体分两次写,两帧会互相穿插,对端从此解帧错位。
接线(`IOCPClient.h` / `.cpp`):`ReceiveData` / `SendTo` / `HasPendingData` 三处在
`m_useTls` 之前判 `m_useWs`;`ConnectServer` 在 socket 选项之后、`m_bConnected = TRUE` 之前
完成 `TLS 握手 → WS 握手`,`Disconnect` 清 `m_useWs` 并 `m_ws.Reset()`。
- 握手超时:`connect()` 之后、TLS/WS 握手之前给 socket 设 **15 s** `SO_RCVTIMEO`/`SO_SNDTIMEO`,
握手结束(成功路径)立刻清零。`WsChannel::Handshake` 是同步逐字节读 101 响应的;没有这道
保护时,对端接受 TCP 却不回数据(反代上游黑洞)会让 `StartClient` 的重连循环永久停摆。
服务端两个握手线程用的是同一个 15 s。
- `m_useWs` / `m_useTls` / `WsChannel::m_ready` 均为 `std::atomic<bool>`:写的一方是连接线程,
读的一方是接收/发送线程(`Disconnect` 也可能从接收线程侧清)。
- 帧掩码由 `WsChannel` 私有的 xorshift64 在 `m_sendMtx` **内**生成:不能用全局 `rand()`
——`HttpMask` 的构造函数里有 `srand(time(nullptr))`,会在同进程内重置全局序列,而收、发两个
线程都会写帧。
- 不校验 `Sec-WebSocket-Accept`(设计上由 TLS + 隧道内登录承担)。明文 `PROTO_WS` 下这意味着
中间人可以伪造 101 接管字节流——这正是「裸 WS 只适合内网」的另一半理由。
- 没有 `conn` 的构造路径(Linux / macOS / Android 的 `main` 都是 `new IOCPClient(exit, false)`)
拿不到外壳注入的 `CONNECT_ADDRESS`,协议由 `IOCPClient::SetDefaultProto()` 显式给出;
三个平台的 `main` 都在进入重连循环前调一次。不调则保持 `-1`、按明文直连——那正是
「配置成 WS 却毫无反应」的来源,所以这里留了一行日志便于排查。
### 3.1 信任模型:不换锚,靠 SNI 分流
客户端证书校验仍是**钉死信任锚**(Windows:`CertCreateCertificateChainEngine` + `hExclusiveRoot`
手动建链;Linux:`SSL_VERIFY_PEER` + 自定义 `X509_STORE`;均**不校主机名**)。因此
「经 nginx 接入」不能随便换成网站自己的证书——那会校验失败。
于是给 nginx 一个**独立 `server_name`**(如 `ws.xxx.com`)并挂主控自己的证书,客户端靠
**SNI** 让 nginx 选中这个 server 块:
- Windows Schannel:`InitializeSecurityContextA(..., pszTargetName = sni, ...)`(TlsChannel.cpp)
- Linux OpenSSL:`SSL_set_tlsext_host_name(ssl, sni)`(TlsChannelLinux.cpp)
- 只在 `PROTO_WSS` 且地址是域名时传;直连主控端口时保持原样(不发明 SNI),行为与改造前一致。
Host 头同理:用**配置里的地址(域名)**,而不是解析后的 IP——子连接只拿到 IP,必须回到
`CONNECT_ADDRESS::GetFirstServerIP()` 取。地址里填分号分隔的多个地址时取第一个,因此经反代
接入只应填一个域名。
### 3.2 回退与 fail-closed
传输方式只由信任锚决定(进程内缓存,服务端下发后可热重载,见 §3.3):
| 情形 | 行为 |
|---|---|
| 有锚 + `PROTO_WSS` / 直连主控端口 | TLS 握手;**握手或证书校验失败即断开**(fail-closed) |
| **无锚 + `PROTO_WSS`** | **回退为明文 WebSocket**:客户端还没被「颁发」证书,先打通隧道;服务端下发锚后自动升级(见下) |
| 有锚但加载失败(损坏/为空) | 拒绝连接(fail-closed)——管理员已「颁发」证书,不能静默回退明文 |
| 无锚 + `PROTO_WS` | 明文(本来如此) |
| 有锚 + `PROTO_WS` | **仍是明文**(显式选择的形态,见下) |
| 平台无 TLS(macOS / Android 未定义 `YAMA_TLS_CHANNEL`)+ `PROTO_WSS` | 直接断开并打日志:没有热切换路径,回退只会让人误以为在加密 |
| WS 握手失败 | 断开,`Mprintf` 里带上服务端返回的状态行 |
回退的判据是「本机**根本没有**信任锚」这一可观测状态,而不是握手中途失败——TLS 握手
失败、证书链校验失败、WS 握手失败一律断开。因此中间人最多能让「尚未下发锚」的客户端
留在明文(此时本来也没有可校验的锚),无法把已经持锚的客户端拉回明文。
升级路径(服务端菜单「TLS 传输 → 启用」,`COMMAND_TLS_ENABLE` + PEM 正文):客户端把锚
落盘(Windows 注册表 `settings\tls_cert`;Linux `~/.config/ghost/yama-ca.pem`),调用
`TlsReload()` 重建 TLS 上下文,**只在传输方式真正变化(明文 ↔ TLS)时**断开重连,之后
的新连接自动走 WSS;仅换一张证书(仍是 TLS)不打断现有会话。两平台都是立即生效,
不再需要重启进程。撤销(`COMMAND_TLS_DISABLE`)同理反向切换。
> 部署含义:「先明文、之后升级为 WSS」要求同一个 `地址:端口` 既能吃明文 WS 也能吃 TLS
> ——Go 服务端的设备端口正是这样(`wrapTLS` → `wrapWebSocket` 两级嗅探,见 §4)。由
> nginx 终止 TLS 的部署做不到:443 只收 TLS,明文回退会直接失败,这种拓扑必须先把证书
> 配到 nginx 上再出包。(对应的两个 nginx 监听端口也无法互替,地址是出包时写死的。)
`PROTO_WS` 的定位不变:它是**显式选择的明文形态**(§5.2 的 80 端口明文反代、内网直连),
即便客户端配了信任锚也不叠加 TLS,否则该路径永远不可达——选择 WS 是出包时的决定,
不存在远端可触发的降级。
### 3.3 信任锚热重载
`TlsEnabled()` / `TlsLoadError()` 首次调用时加载锚,之后读写的是受 `TlsReload` 保护的
进程级状态(Windows 原来用 `std::call_once` 缓存到进程结束,无法热切换;现改为互斥量,
与 Linux 版语义一致):
- 重建失败(锚存在但无效)→ **保持现有状态不变**,只记一行日志:一次坏下发不该打死正在
工作的客户端;下次启动仍会 fail-closed。
- 重建成功 → 互换 store / 链引擎并释放旧的。Windows 的证书校验(`VerifyServerCert`)
在整个校验过程中持同一把锁,因此旧句柄不会在别的线程手里被释放。
- 回环验证:Linux 由 `linux/main.cpp::ApplyTlsAnchorChange`、Windows 由
`client/KernelManager.cpp::ApplyTlsAnchorChange` 调用,两者都只在 `TlsEnabled()`
前后值发生变化时 `Disconnect()`,让重连循环用新传输方式重新登录。
## 4. 服务端实现
### 4.1 Go 服务端(`server/go`)
`server/go/server/ws.go`,在 `handleConnection` 里分层嗅探:
```
raw conn --wrapTLS(嗅 0x16 0x03)--> [TLS] --wrapWebSocket(嗅 "GET ")--> [WS 帧]
```
- 非 WS 连接:`bufferedConn` 原样返回,既有客户端零影响;嗅探用 `Peek`,不消耗字节。
- WS 连接:解析请求头、校验 `Upgrade`/`Connection`/`Sec-WebSocket-Key`,`YAMA_WS_PATH`
非空时再校验路径;通过后回 101 并返回 `wsConn`。
- `wsConn`:`Read` 在帧载荷上流式返回,`Write` 一次一帧(`net.Buffers` writev 拼头与体),
处理客户端掩码、控制帧(ping/pong/close),`Close` 发 close 帧并设 1 秒写超时。
- 反代信任:仅当对端 IP 落在 `TrustedProxies`(默认回环)内才采信 `X-Forwarded-For` /
`X-Real-IP`,取到的真实 IP 用于 `Context.GetPeerIP()`、`hub.Device.PeerIP` 与 ConnAuth
子连接的源 IP 绑定。
- 真实 IP 取 `X-Forwarded-For` 的**最后一段**(nginx 的 `$proxy_add_x_forwarded_for` 把
它实际看到的地址追加在末尾,客户端自己塞在开头的段一律无视;与 `web/ws.go` 的 `clientIP`
同一规则),没有 XFF 时才退回 `X-Real-IP`。
- 每 IP 限流分两段:**直连对端**在 `acceptLoop` 里、起 goroutine 和任何嗅探读之前就计数
(否则一个只建连接不发字节的对端能白占 goroutine 和缓冲直到 `ReadTimeout`);**反代后面
的设备**在 `handleConnection` 里按上报的真实 IP 计数(否则所有设备共用一个回环额度)。
环境变量:
| 变量 | 说明 |
|---|---|
| `YAMA_WS_PATH` | 只接受该路径的 upgrade(空 = 任意路径) |
| `YAMA_TRUSTED_PROXIES` | 允许上报真实 IP 的代理地址,逗号分隔的 IP/CIDR,默认 `127.0.0.0/8,::1/128` |
### 4.2 MFC 服务端(`server/2015Remote`)
MFC 服务端此前就在设备端口上嗅探 TLS(首字节 `0x16 0x03` → `ServerTlsSession`),
WS 叠在同一层状态机之上,**与 TLS 是分层而不是并列**(`wss` = TLS 里的 WebSocket):
```
子套接字 -- TLS 嗅探 --+-- 明文 --+-- "GET " 嗅探 --+-- WS 帧 --+--> ParseReceivedData
| | |
+-- TLS ---+----------------+(WSS 时帧在解密的明文里判)
```
新增两个文件,其余改动都在既有握手/收发路径上:
| 文件 | 职责 |
|---|---|
| `ServerWsSession.h/.cpp` | 每连接 WS 会话:升级握手(逐行解析、8 KiB 上限、`Sec-WebSocket-Accept`)、流式解帧(不整帧缓冲,大帧按片交付)、控制帧(ping→pong、close 回显后断开)、转发真实 IP |
| `IOCPServer.cpp` | `WsHandshakeThreadProc` / `StartWsHandshake`(专用阻塞线程,与 TLS 握手线程同一模式)、`DispatchPlain`(明文/WSS 共用入口)、`OnClientPreSending` 里的「先封帧、再 TLS 加密」 |
- 状态机:`ServerWsState { WS_Undecided → WS_Handshaking → WS_Ready | WS_None }` 与既有的
`ServerTlsState` 并存;`CONTEXT_OBJECT` 复用(`InitMember`)时一并复位并释放会话。
- 判定点:**明文的第一段有 ≥6 字节**才开始分类(与 ClientHello 嗅探同一下限),
避免把「请求头还没到齐」误判掉;阈值内的字节攒在 `wsPreClassify` 里(与 TLS 嗅探的
`tlsPreClassify` 分开,两者服务不同状态机,串行使用但字段不共用)。
- 升级线程与 TLS 握手线程同构:`FIONBIO=0`(该套接字常是非阻塞的,`ioctlsocket` 会以
`WSAEINVAL` 失败),15 s 收发超时,遇 `WSAEWOULDBLOCK` 用 `select` 等可读/可写再试;
线程持有一枚 `IoRefCount`,结束后把 socket 交还 IOCP(`PostRecv`)。升级响应之后同批
字节里若已带客户端首帧(WSS 分批解密时常见),先在交还前喂给解帧路径。
- 发送方向:`OnClientPreSending` 里把本次新追加的尾部封成一帧(`TruncateBuffer` +
`WriteBuffer`,与既有的「只加密新尾部」同一手法规避在途数据),然后才走 TLS 加密;
控制帧应答(pong / close 回显)走同一条发送路径(`SendWsReplies`,持 `SendLock`)。
- 反代真实 IP:**仅当直接对端是回环地址**时才采信 `X-Forwarded-For` 的**最后一段**
(`X-Real-IP` 兜底),且必须是 IP 字面量;结果写回 `PeerName`,在线列表、封禁与
白名单看到的就是设备本身。非回环对端的转发头一律忽略(防伪造)。
- 两段式限流(与 Go 端 `limitDirectPeer` / `handleConnection` 同构):accept 阶段按
`getpeername` 计数——那一次对经反代的连接**没有意义**(反代同机时对端是回环地址,
`IPWhitelist` 对回环恒为 true,黑名单/封禁/计数全部不生效)。升级完成后在
`WsHandshakeThreadProc` 里按**真实设备 IP** 重做一次黑名单 / 封禁检查与计数,超阈值
直接 fail-closed。直连连接(无转发头)只在 accept 阶段计一次,不重复计。
反代**异机**部署时转发头不被采信(见 §8),此时需把反代地址加进白名单,否则所有设备
共用反代 IP 那一个计数桶。
- fail-closed 的两处:握手期间(`wsState == WS_Handshaking`)收到 IORead 直接断开(判断
放在 `OnClientReceiving` 最开头,WSS 下 `tlsState` 已是 `TLS_Ready`,放在 TLS 分支之后
就不生效);`wsState == WS_Ready` 但会话已关时,应用字节**丢弃而不是裸发**,否则对端
解帧错位;同时对该 socket 做一次 `shutdown(SD_BOTH)`,让挂起的 recv 立刻返回 0 字节,
由接收路径走正常的 `-2` 收尾(不在这里直接 `RemoveStaleContext`——调用方往往本身就
持有 `IoRefCount`,自己等自己会超时,且可能把已回收复用的上下文交回给调用者)。
- 既有客户端零影响:非 `GET ` 首包在攒够 6 字节后原样进入 `ParseReceivedData`。
- 收尾一致:`dwTrans == 0`(对端 FIN)在 `TLS_Unclassified` / `TLS_Ready` / `TLS_Plain`
三条分支上都必须 `RemoveStaleContext`。WS 改造把 `TLS_Plain` 的 `ParseReceivedData`
换成 `DispatchPlain` 后,`DispatchPlain` 对空数据返回「已处理」,这个判断一度丢了,
连接会停在 CLOSE_WAIT 直到 keepalive(3 分钟),期间占着 IOCP 上下文、一枚挂起的
`WSARecv` 和限流槽。现已补回。
## 5. nginx 最小改动
前提:客户端地址填 `ws.xxx.com`、端口 **443**、协议选 **WebSocket+TLS**。
DNS 加一条 `ws.xxx.com` → 同一台机器即可(共用 443,靠 SNI + Host 分流,**不动**现有站点块)。
```nginx
# 新增一个 server 块;证书用主控自己的那份(就是客户端钉的锚,与 6543 的 YAMA_TLS_CERT 同一文件)
server {
listen 443 ssl; # nginx ≥1.25.1 可另加一行 http2 on;
server_name ws.xxx.com;
ssl_certificate /etc/nginx/certs/yama.crt;
ssl_certificate_key /etc/nginx/certs/yama.key;
location /api/ws {
proxy_pass http://127.0.0.1:6543; # 主控设备端口
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; # 让服务端拿到设备真实 IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_buffering off; # 长连接必须关缓冲
proxy_read_timeout 86400s; # 空闲心跳间隔远小于此,防止被掐
proxy_send_timeout 86400s;
}
}
```
若该域名现有的 443 证书**正好就是客户端钉的那份**,可以连 server 块都不加,
只把上面 `location /api/ws { ... }` 贴进现有 443 块里。
### 5.1 站点与主控用两张不同证书时
实际部署里 `xxx.com` 的 443 证书(网站那张)和 6543 用的证书(客户端钉的锚)**是两张**。
同一端口放两张证书没问题,nginx 按 **SNI** 选 server 块:
| 客户端填的地址 | 客户端发的 SNI | nginx 选中 | 出示的证书 | 结果 |
|---|---|---|---|---|
| `xxx.com` | `xxx.com` | 网站块 | 网站的证书 | **握手失败**(不是钉的锚) |
| `ws.xxx.com` | `ws.xxx.com` | 主控块 | 6543 那张 | 通过 |
所以设备端必须用**另一个名字**(`ws.xxx.com`,或任何解析到同机、nginx 里能单独成块的名字):
- DNS:加一条 `ws.xxx.com` A 记录;若已有泛解析 `*.xxx.com` 则无需改动。
- `ssl_certificate` 指向**与 Go 服务端 `YAMA_TLS_CERT` 完全相同的那个文件**(Go 端若配的是
fullchain,这里也用 fullchain)。证书内容稍有不同(换过一张、少了中间证书)就会校验失败。
- 这张证书**不需要覆盖 `ws.xxx.com`**——客户端只验链到钉死的锚,不校主机名(见 §3.1)。
- 不要给主控块加 `default_server`,让网站块继续当默认块,其它访客行为不变。
自查(在服务器上执行,输出应是 6543 那张证书):
```bash
openssl s_client -connect 127.0.0.1:443 -servername ws.xxx.com </dev/null 2>/dev/null \
| openssl x509 -noout -subject -fingerprint -sha256
```
若看到的是网站的证书,说明 SNI 没落到主控块(名字拼错、块没 reload、或客户端地址填的是 `xxx.com`)。
### 5.2 拿不到 `ws.xxx.com` 这种名字时:地址填 IP,用 443 的默认块
结论:**DNS 不是必需的**。SNI 只是 ClientHello 里的一个字符串,nginx 拿它跟 `server_name`
比,不做解析;真正需要 DNS 的只有客户端解析地址这一步。所以换一条路走:
**客户端地址填 IP**(`1.2.3.4`,就是 `xxx.com` 解析出的那个),协议 `WebSocket+TLS`,端口 443。
地址是 IP 字面量时,客户端按 RFC 6066 **不发 SNI**(见 §3.1 的条件),nginx 于是落到 443 的
`default_server` 块——把主控块设成默认块即可。
```nginx
# 主控块:无 SNI(或 SNI 不匹配)时命中,出示客户端钉的那张证书
server {
listen 443 ssl default_server;
server_name _; # 兜底块,不占任何真实域名
ssl_certificate /root/cert/yama.crt; # 与 6543 的 YAMA_TLS_CERT 同一文件
ssl_certificate_key /root/cert/yama.key;
location /api/ws {
proxy_pass http://127.0.0.1:6543;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_buffering off;
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
}
}
```
现有网站块**一个字都不用改**:浏览器访问 `https://xxx.com` 时会发 SNI `xxx.com`,
按名字命中网站块,照旧拿网站的证书。
四个注意点:
- **同一 `地址:端口` 只能有一个 `default_server`**。若网站块原本写了
`listen 443 ssl default_server;`,把那里的 `default_server` 去掉(`nginx -t` 会直接报
duplicate default server)。
- 若默认块上设了 `ssl_reject_handshake on;`(有的加固模板会这么写),把它删掉,否则无 SNI 的连接被直接拒。
- IPv6 的默认块是独立的:若还有 `listen [::]:443`,默认块要么同样加 `[::]:443 default_server`,
要么保持 IPv4 即可(本客户端只连 AF_INET)。
- 代价是地址里写死 IP:换机器/换 IP 要重出客户端。站点域名不变、只是 `xxx.com` 的 A 记录
换 IP 时,旧客户端会连到旧机器。
> 还有两条退路,代价更大,一般不用:
> - 走 **80 端口明文**:把 `location /api/ws` 贴进现有 80 块,客户端选 `PROTO_WS`。没有证书问题,
> 但整条隧道是明文(只剩既有 XOR/Shine 混淆)。
> - 给客户端加一个「SNI/Host 单独覆盖」的配置项,让地址仍是域名、SNI 用一个不存在的名字。
> 需要改代码和重新出客户端,只有在必须保留域名地址时才值得做。
要点:
- `proxy_http_version 1.1` + 两条 `Upgrade` 头缺一不可,否则 nginx 会把升级请求当普通请求代理。
- 关 `proxy_buffering`,否则 nginx 攒包,画面与控制会明显延迟。
- `X-Real-IP` / `X-Forwarded-For` 只有在服务端的 `YAMA_TRUSTED_PROXIES` 覆盖 `127.0.0.1`
时才被采信(默认已覆盖)。
## 6. 部署清单
1. 服务端:**无需改动**即可接受 WS 升级(两套实现都是同端口嗅探)。Go 版可选加环境变量
`YAMA_WS_PATH=/api/ws`(不设 = 任意路径)、`YAMA_TRUSTED_PROXIES`(默认够用);MFC 版
不校验路径,转发头只信回环对端(§4.2)。
2. nginx:按 §5 加 server 块或 location,`nginx -t && nginx -s reload`。
3. DNS:`ws.xxx.com` 指向该机器。
4. 生成客户端:协议选 `WebSocket+TLS`,地址填 `ws.xxx.com`,端口 443。
5. 日志确认:
- Go 服务端 `WebSocket transport on device port enabled: path=/api/ws`、
`WebSocket device from <真实 IP>`;MFC 服务端 `[WS] ... upgraded via reverse proxy,
real client <真实 IP>`(仅回环对端且带转发头时才有这一行);
- 客户端 `[WS] WebSocket 已就绪: ws.xxx.com:443/api/ws (TLS)`。
## 7. 验证方法(本次已做)
- `server/go`:`go test ./...` 全绿,`ws_test.go` 覆盖升级、隧道、ping/pong、1 MiB 大帧、
坏握手拒绝、转发 IP(含「XFF 末尾优先 / 开头伪造被无视」)、信任代理解析,以及
「无换行的超长请求行在 8 KiB 上限处被拒」;`server_test.go` 覆盖直连对端在嗅探前即计入
每 IP 上限、回环反代被豁免。
- 客户端:`client/WsChannel.h` 用一份**独立的 Python 最小 WS 服务端**(std lib 实现,非同一套
代码)交叉验证:1/5/125/126/130/4096/70000 字节全部往返一致、`Host: localhost:18080`
正确、客户端帧带掩码、服务端主动 ping 被回 pong。
- 并发写:另一份 Python 校验端一边每 5 帧发一次 ping、一边逐帧校验 3000×300 字节的载荷,
客户端同时从发送线程写数据帧、从接收线程回 pong。修复前在 ~40 帧处即出现解帧错位
(`BAD_PAYLOAD`/发送失败),修复后 3000 帧全部逐字节正确。
- 互操作:把该测试客户端直接指向真实 Go 服务端(`-port 16543`,`YAMA_WS_PATH=/api/ws`),
服务端日志出现 `WebSocket device from 127.0.0.1`,握手通过。
- MFC 服务端(Debug x64,设备端口 6543,同时开着 TLS):
- 独立 Python 最小客户端对 6543 跑 9 项断言全通过:101 状态行、`Sec-WebSocket-Accept`
与 `base64(sha1(key+GUID))` 一致、`Upgrade`/`Connection` 回显、ping→pong(服务端帧不带
掩码)、数据帧后连接保持、close 回显、**升级请求跨两个 TCP 段**仍升级成功、**帧与升级
请求粘在同一段**里也能解出;同一套断言加 `ssl` 包一层(TLSv1.2 ECDHE-RSA-AES256-GCM)
再跑一遍全通过,即 WSS。
- 转发头:`X-Forwarded-For: 198.51.100.7, 203.0.113.9` 时日志记
`[WS] 127.0.0.1 upgraded via reverse proxy, real client 203.0.113.9`(取最后一段)。
- 端到端:让 Debug 服务端向真实客户端下发它自己的 payload(其中配置为 `PROTO_WS`),
客户端日志 `[WS] WebSocket 已就绪: 127.0.0.1:6543/api/ws` → 登录 → 收到主控配置
(1000 字节)→ 上线列表出现该设备并长时间保活(心跳往返即双向数据帧都在工作)。
- 信任锚热重载(Windows):独立 harness(`tlsreload_test.cpp` + 真实 `TlsChannel.cpp`,锚
走 exe 同目录 `yama-ca.pem`)覆盖 6 个场景全部通过:无锚→明文、有效锚→TLS、坏锚首次
加载→fail-closed、无锚→下发锚后重载生效(明文→TLS)、坏锚重载→保持 TLS 不中断、撤销
锚→回到明文。Linux 侧的热重载此前已随 `TlsTrustAnchorSave/Remove` 实现。
- 构建:`ghost` x64/x86 Debug、`ServerDll.dll`、MFC 服务端 Debug x64、Linux
`IOCPClient.cpp` / `TlsChannelLinux.cpp` 语法检查均通过。
## 8. 限制与非目标
- **MFC 服务端与 Go 服务端都已实现设备端口的 WS 嗅探**,生成界面里的协议选项两边通用;
差别只在细节:MFC 侧不校验 upgrade 路径(`/api/ws` 只是客户端习惯,反代转到哪个路径都行)。
每 IP 限流两边都是**两段式**(直连对端 / 反代后的真实设备),见 §4.1 与 §4.2。
- MFC 侧的转发头信任范围是**回环对端**(与 Go 的默认 `TrustedProxies` 一致);反代与服务端
不同机部署时,要么让反代用 Proxy Protocol v2(既有的 `ParseProxyProtocolV2` 会先改
`PeerName`),要么把反代地址加进白名单——WS 层不采信非回环对端的转发头。此时限流按
「反代 IP」那一个桶算,**务必把反代地址加进白名单**,否则阈值一响就是全体设备一起被封。
- 试用模式的 WAN 入站检测(`m_bTrialMode && !IsPrivateIPv4Str(clientIP)`)在 accept 时判定,
经反代接入时 `clientIP` 是反代地址(回环或内网),该合规检查会被绕过;转发真实 IP 要到
升级线程里才有。若这是硬性合规要求,需单独评估(本特性未改变这一点,只是让它的漏检更
容易发生)。
- 裸 `PROTO_WS` 是明文,只适合内网或回环(nginx 已在同一台机器上终止 TLS 的情形用 WSS 即可)。
- macOS / Android 客户端没有 TLS 实现,只能选 `PROTO_WS`(明文),走不了 443。
- 经反代接入时地址只应填**一个域名**(多地址取第一个做 Host/SNI)。
- 不改应用协议、不改 MCP、不改 Web 控制台。
## 9. 远程协议切换(在线列表右键 → 协议切换)
动机:客户端在线升级只换 DLL,外壳每次注入的连接配置仍是编译时的 TCP 直连入口,所以
「已经在跑」的机器没法被搬到反代入口上。协议切换就是补这一环:由主控下发一次命令,客户端
把新入口落盘并重连,此后(含再次在线升级)都按落盘的入口连。
- 菜单:与「实验功能」平级、紧跟在它下面,三个单选项 `直连 TCP / WS / WSS`。单选状态取
选中主机连接的真实传输(`context::GetProtocol()`:`TCP`/`WS`/`WSS`),不取客户端自报。
选中主机的客户端没有能力位 `CLIENT_CAP_PROTO_SWITCH(0x0020)` 时整组置灰(只有 Windows
客户端实现了该命令)。
- 命令:`COMMAND_SET_PROTO = 177`,载荷 `ProtoSwitchPacket`(113 字节:`proto` + 反代
`host[100]` + `port[8]` + `certLen`),WS/WSS 后面再跟反代信任锚 PEM 正文;`host`/`port`
全空表示「还原到安装时的直连入口」。
- 服务端:WS/WSS 先弹输入框问反代入口(`域名:端口`,记住上次填的 `[ws] Entry`);WSS 额外
要求 `ServerTlsIdentity::IsReady()` 并读取 `[tls] CertPath` 的 PEM 一并下发——没有锚的
客户端会把 WSS 降级成明文 WS,等于静默降级,所以直接拒绝。
- 客户端落盘(`settings` 下):`proto_override` / `entry_host` / `entry_port` /
`entry_try_at` 为当前覆盖;`base_*` 是首次切换时记下的安装入口(「还原」用它);`prev_*`
是每次切换前的入口(自动回退用它)。重连循环在建连前 `ApplyProtoSwitch` 覆盖入口——位置
在「外壳注入完配置之后、建连之前」,因此换 DLL 也压不回去。(该函数返回 `void`:它既写
配置也改 `CONNECT_ADDRESS`,返回值无法表达「部分完成」,早期版本里的 `return false`
只是提前退出,调用方一直忽略它。)
- 撤销自动回退的判据是**登录被接受**,不是「连接建立」。客户端在收到
`CMD_MASTERSETTING` 时把当前连接标记为已登录(服务端只有在把本机加入在线列表之后才下发
它),重连循环每轮心跳都检查一次,命中才 `ConfirmProtoSwitch` 把 `entry_try_at` 清零。
只看 `IsConnected()` 是不够的:那只是 TCP/TLS/WS 握手完成,新入口能建连但登录始终不被
接受(选错后端 / 反代指到别的 WS 服务 / 服务端登录阶段丢弃)时,提前撤销会让自动回退
永久失效,客户端卡在错误入口反复重连。
- 随包下发的信任锚先落盘再 `TlsReload`;**加载失败即放弃本次切换**——回滚 `tls_cert`、
不写 `proto_override`/`entry_*`、不断连,并把失败原因用 `ClientMsg` 回报操作端。否则客户端
会进入 `TlsLoadError()` 的 fail-closed 状态,切过去只是「新入口连不上,等 5 分钟回退」。
- 自动回退:新入口 5 分钟内一直登不上,回到 `prev_*` 并把它改写成新的覆盖(不是清空,否则
下一轮会落进「还原」分支又跳回直连入口)。分享实例(`m_bShared`)忽略该命令——它的入口
由分享方控制。
- `ProtoSwitchPacket::certLen` 不做字节序转换:当前服务端与 Windows 客户端同为小端,无影响;
将来若出现大端平台的客户端,需要补一次 `ntohl`/`htonl`。
## 10. 审查遗留(已知边界,未改动)
以下条目来自 PR 审查,记录在此以免重复讨论。带「已处理」的是复查后**已经改掉**的,
留在这里说明当时的判断,其余评估后保留现状:
- **`GetPeerName(SOCKET)` 只走 `sockaddr_in`(IPv4)**:`ServerWsSession.cpp::IsLoopbackPeer`
里的 `::1` / `::ffff:127.0.0.1` 分支目前是死代码。将来若监听 IPv6,转发头信任也需要跟着
改,否则会静默失效。
- **`tlsPreClassify` 名不副实**:已处理——WS 的 "GET " 前缀缓冲拆成独立的 `wsPreClassify`,
`tlsPreClassify` 回归 ClientHello 嗅探单一职责(两条路径仍按先后串行,互不重叠)。
- **`WsChannel::Reset()` 与接收线程的帧状态**:已处理——`Disconnect()` 可能来自心跳/命令线程,
不只是接收线程,所以 `Reset()` 现在只翻转原子的 `m_ready`;`m_remaining` / `m_masked` /
`m_maskPos` 改由 `ResetFrames()` 清,且只在 `Handshake()` 里(连接线程、接收线程尚未起来)
调用。这样这几个字段始终只有一个线程访问,不用加锁。
- **客户端单帧载荷上限 256 MB**(`WsChannel::kMaxFramePayload`,与 `ServerWsSession` 同值):
超过即按错误断开。没有上限时一个错误长度字段就能把 `m_remaining` 定在天文数字上,
连接「活着但永远收不到新包」。正常业务的最大单包远小于此值。
- **`DispatchPlain` 对明文首包引入「攒够 6 字节再解析」**:这是既有路径的行为变更。当前首包
是登录包(远大于 6 字节),实际无影响;极端情况下(<6 字节的合法首包)会多等一轮收包。
- **客户端不校验 `Sec-WebSocket-Accept`**:见 §3;明文 WS 下中间人可伪造 101,已在 §8 明确
裸 WS 只适合内网。
- **Go `wrapWebSocket` 的 `Peek`**:已改为即使 `ReadTimeout == 0` 也用 `wsHandshakeTimeout`
(10 s,取与 `ReadTimeout` 的较小值)封顶,慢速对端不再能长期占住 goroutine 与限流槽。
+5 -2
View File
@@ -26,8 +26,10 @@ include_directories(../compress)
# 添加可执行文件
set(SOURCES
main.cpp
ScreenPreview.cpp # 屏幕预览(缩略图)抓屏,见 ScreenPreview.h
../client/Buffer.cpp
../client/IOCPClient.cpp
../client/TlsChannelLinux.cpp # Linux 客户端单向 TLS(OpenSSL),见 client/TlsChannel.h
../client/sign_shim_unix.cpp
)
add_executable(ghost ${SOURCES})
@@ -45,9 +47,10 @@ target_link_libraries(ghost PRIVATE "${CMAKE_SOURCE_DIR}/lib/libzstd.a")
# 该库由 SimplePlugins 仓库本地构建后放置于 lib/,构建机需先准备好
target_link_libraries(ghost PRIVATE "${CMAKE_SOURCE_DIR}/lib/libsign.a")
# libsign.a 内部使用 OpenSSL HMAC,需要在最终可执行链接 libcrypto
# libsign.a 内部使用 OpenSSL HMAC,需要在最终可执行链接 libcrypto;
# 客户端传输层 TLS(client/TlsChannelLinux.cpp)另需 libssl。
find_package(OpenSSL REQUIRED)
target_link_libraries(ghost PRIVATE OpenSSL::Crypto)
target_link_libraries(ghost PRIVATE OpenSSL::Crypto OpenSSL::SSL)
# 链接 dl 库(dlopen/dlsym 用于运行时加载 X11)
target_link_libraries(ghost PRIVATE dl)
+52 -1
View File
@@ -5,6 +5,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
## 功能特性
- **远程桌面** - 实时屏幕截图传输,支持鼠标/键盘控制,支持多种压缩算法
- **屏幕预览** - 服务端双击主机弹缩略图、在线列表缩略图、MCP `get_screenshot`
- **远程终端** - 基于 PTY 的交互式 Shell
- **文件管理** - 远程文件浏览、上传、下载
- **进程管理** - 查看和管理远程进程
@@ -25,8 +26,11 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
| 系统信息采集 | main.cpp | `LoginServer.cpp` | ✅ 完整 |
| 守护进程 | daemonize() | Windows 服务 | ✅ 完整 |
| 剪贴板同步 | `ClipboardHandler.h` | `ScreenManager.cpp` | ✅ 服务端↔Linux |
| V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔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` 指定,落盘后回执) |
| 配置持久化 | `LinuxConfig` | INI 文件 | ✅ 完整 |
| MCP 远程管理 | 复用 `SystemManager.h` / `PTYHandler.h` / `ScreenHandler.h` | 服务端 MCP | ✅ 档 1:`kill_process`、`exec_command`、`terminal_open/exec/close`、`remote_open/close/mouse/keyboard/clipboard`(服务端放开门禁,客户端协议本已实现) |
### 未实现
@@ -160,6 +164,53 @@ make -j$(nproc)
kill $(cat ~/.config/ghost/ghost.pid)
```
## 远程升级
服务端选中一台 Linux 主机后点「升级程序」,即可把新的 `ghost` 推下去并自动重启。
### 服务端准备
按以下优先级取 ELF,前一级拿不到才看下一级:
| 顺序 | 来源 | 说明 |
|-----|------|------|
| 1 | `settings.ini` 的 `[settings] LinuxClientPath` | 显式指定。配了但读不到会直接报错,不会偷偷换成别的版本 |
| 2 | 服务端**程序目录**下的 `ghost_linux_amd64` | 换个文件即可,不必重编服务端 |
| 3 | 服务端 `res\ghost_linux` | 项目通用的外部资源目录 |
| 4 | 内嵌资源 `IDR_LINUX_GHOST` | 编译进服务端 exe(构建时取 `linux/ghost`),磁盘上什么都不用放 |
```ini
[settings]
LinuxClientPath=C:\build\ghost
```
第 4 级是编译时的快照,想换版本要么放到第 1~3 级,要么重编服务端。
只接受 64 位 x86_64 ELF(`ELFCLASS64` + `EM_X86_64`),其它文件会在下发前被拒绝并提示。
### 下发格式
```
[COMMAND_UPDATE:1][size:8 LE][ELF:size][md5:32 ASCII 小写 hex]
```
Windows 客户端的同名命令没有摘要(走内存加载器/更新器),LNX 多出 32 字节 MD5。
### 客户端行为
1. 校验长度、ELF magic、`e_machine` 与本机自身 ELF 头一致、MD5 匹配;
2. 在自身所在目录写临时文件 `.<名字>.new.<pid>`(0755)并 `fsync`;
3. 用 `rename()` 原子替换正在运行的二进制(Linux 允许替换执行中的 inode),
旧版本保留为 `<名字>.old`;
4. `fork` + `setsid` + 关闭继承的 fd + 等待老进程退出,再用**原始命令行** `execv` 新版本;
老进程以 `g_bExit = S_CLIENT_UPDATE` 正常退出,服务端立刻看到断线重连。
前提:客户端所在目录对运行用户可写(否则报「cannot create ...: Permission denied」)。
任何一步失败都不会退出进程,原因会写进客户端日志并发到服务端消息栏
(`Linux client update failed`)。
回滚:把 `ghost.old` 拷回 `ghost` 并重启即可(它会在下次升级时被覆盖)。
## 常见问题
### Q: 远程桌面功能不工作
+1 -264
View File
@@ -5,6 +5,7 @@
#include "ClipboardHandler.h"
#include "common/FileTransferV2.h"
#include "X264Encoder.h"
#include "X11Loader.h"
#include <dlfcn.h>
#include <sys/stat.h>
#include <thread>
@@ -50,68 +51,6 @@ struct MSG64_LNX {
};
#pragma pack(pop)
// X11 类型前向声明(避免 #include <X11/Xlib.h>)
typedef struct _XDisplay Display;
typedef unsigned long XID;
typedef XID Window;
typedef XID Drawable;
typedef XID Pixmap;
typedef struct _XGC *GC;
struct XImage {
int width, height;
int xoffset;
int format;
char *data;
int byte_order;
int bitmap_unit;
int bitmap_bit_order;
int bitmap_pad;
int depth;
int bytes_per_line;
int bits_per_pixel;
unsigned long red_mask;
unsigned long green_mask;
unsigned long blue_mask;
// 后续字段省略,XDestroyImage 通过函数指针释放
void *obdata;
struct funcs {
void *p[8]; // create_image, destroy_image, ...
} f;
};
// X11 错误处理(防止 BadMatch 等错误导致进程退出)
static int x11_error_handler(Display* dpy, void* evt)
{
// 忽略所有 X11 错误,由调用方检查返回值
return 0;
}
// XCreateGC 需要的 XGCValues 结构体(布局与 Xlib 一致)
struct XGCValues_LNX {
int function;
unsigned long plane_mask;
unsigned long foreground;
unsigned long background;
int line_width;
int line_style;
int cap_style;
int join_style;
int fill_style;
int fill_rule;
int arc_mode;
unsigned long tile; // Pixmap = XID
unsigned long stipple; // Pixmap = XID
int ts_x_origin;
int ts_y_origin;
unsigned long font; // Font = XID
int subwindow_mode;
};
// X11 GC 常量
#define GCSubwindowMode (1L<<15)
#define IncludeInferiors 1
// ============== 屏幕算法常量 ==============
// 常量定义已移至 commands.h: ALGORITHM_GRAY, ALGORITHM_DIFF, ALGORITHM_H264, ALGORITHM_RGB565
@@ -390,208 +329,6 @@ static unsigned long VKtoKeySym(unsigned int vk)
}
}
// XFixes cursor image structure (for cursor type detection)
struct XFixesCursorImage {
short x, y;
unsigned short width, height;
unsigned short xhot, yhot;
unsigned long cursor_serial;
unsigned long* pixels;
// Atom cursor_name; // Only in XFixes 2.0+
};
// X11 函数指针类型
typedef Display* (*fn_XOpenDisplay)(const char*);
typedef int (*fn_XCloseDisplay)(Display*);
typedef XImage* (*fn_XGetImage)(Display*, Drawable, int, int, unsigned int, unsigned int, unsigned long, int);
typedef int (*fn_XDestroyImage)(XImage*);
typedef int (*fn_XSetErrorHandler)(int (*)(Display*, void*));
typedef Pixmap (*fn_XCreatePixmap)(Display*, Drawable, unsigned int, unsigned int, unsigned int);
typedef int (*fn_XFreePixmap)(Display*, Pixmap);
typedef GC (*fn_XCreateGC)(Display*, Drawable, unsigned long, void*);
typedef int (*fn_XFreeGC)(Display*, GC);
typedef int (*fn_XCopyArea)(Display*, Drawable, Drawable, GC, int, int, unsigned int, unsigned int, int, int);
typedef int (*fn_XDefaultDepth)(Display*, int);
typedef int (*fn_XSync)(Display*, int);
typedef unsigned long (*fn_XKeysymToKeycode)(Display*, unsigned long);
typedef int (*fn_XFlush)(Display*);
typedef int (*fn_XClearArea)(Display*, Window, int, int, unsigned int, unsigned int, int);
typedef int (*fn_XQueryPointer)(Display*, Window, Window*, Window*, int*, int*, int*, int*, unsigned int*);
typedef int (*fn_XFree)(void*);
// XTest 扩展函数指针类型(用于模拟鼠标/键盘输入)
typedef int (*fn_XTestFakeMotionEvent)(Display*, int, int, int, unsigned long);
typedef int (*fn_XTestFakeButtonEvent)(Display*, unsigned int, int, unsigned long);
typedef int (*fn_XTestFakeKeyEvent)(Display*, unsigned int, int, unsigned long);
// XFixes 扩展函数指针类型(用于光标类型检测)
typedef int (*fn_XFixesQueryExtension)(Display*, int*, int*);
typedef XFixesCursorImage* (*fn_XFixesGetCursorImage)(Display*);
// X11 动态加载包装
class X11Loader
{
public:
fn_XOpenDisplay pXOpenDisplay;
fn_XCloseDisplay pXCloseDisplay;
fn_XGetImage pXGetImage;
fn_XDestroyImage pXDestroyImage;
// Xlib 宏的替代:通过偏移读取 Display 内部结构
// 这些函数通过 dlsym 获取
typedef int (*fn_XDefaultScreen)(Display*);
typedef int (*fn_XDisplayWidth)(Display*, int);
typedef int (*fn_XDisplayHeight)(Display*, int);
typedef Window (*fn_XRootWindow)(Display*, int);
fn_XDefaultScreen pXDefaultScreen;
fn_XDisplayWidth pXDisplayWidth;
fn_XDisplayHeight pXDisplayHeight;
fn_XRootWindow pXRootWindow;
// Pixmap 相关(解决合成窗口管理器下 XGetImage BadMatch 问题)
fn_XSetErrorHandler pXSetErrorHandler;
fn_XCreatePixmap pXCreatePixmap;
fn_XFreePixmap pXFreePixmap;
fn_XCreateGC pXCreateGC;
fn_XFreeGC pXFreeGC;
fn_XCopyArea pXCopyArea;
fn_XDefaultDepth pXDefaultDepth;
fn_XSync pXSync;
fn_XKeysymToKeycode pXKeysymToKeycode;
fn_XFlush pXFlush;
fn_XClearArea pXClearArea;
fn_XQueryPointer pXQueryPointer;
fn_XFree pXFree;
// XTest 扩展(用于模拟输入)
fn_XTestFakeMotionEvent pXTestFakeMotionEvent;
fn_XTestFakeButtonEvent pXTestFakeButtonEvent;
fn_XTestFakeKeyEvent pXTestFakeKeyEvent;
// XFixes 扩展(用于光标类型检测)
fn_XFixesQueryExtension pXFixesQueryExtension;
fn_XFixesGetCursorImage pXFixesGetCursorImage;
X11Loader() : m_handle(nullptr), m_xtst_handle(nullptr), m_xfixes_handle(nullptr)
{
pXOpenDisplay = nullptr;
pXCloseDisplay = nullptr;
pXGetImage = nullptr;
pXDestroyImage = nullptr;
pXDefaultScreen = nullptr;
pXDisplayWidth = nullptr;
pXDisplayHeight = nullptr;
pXRootWindow = nullptr;
pXSetErrorHandler = nullptr;
pXCreatePixmap = nullptr;
pXFreePixmap = nullptr;
pXCreateGC = nullptr;
pXFreeGC = nullptr;
pXCopyArea = nullptr;
pXDefaultDepth = nullptr;
pXSync = nullptr;
pXKeysymToKeycode = nullptr;
pXFlush = nullptr;
pXClearArea = nullptr;
pXQueryPointer = nullptr;
pXFree = nullptr;
pXTestFakeMotionEvent = nullptr;
pXTestFakeButtonEvent = nullptr;
pXTestFakeKeyEvent = nullptr;
pXFixesQueryExtension = nullptr;
pXFixesGetCursorImage = nullptr;
}
bool Load()
{
m_handle = dlopen("libX11.so.6", RTLD_LAZY);
if (!m_handle) m_handle = dlopen("libX11.so", RTLD_LAZY);
if (!m_handle) return false;
pXOpenDisplay = (fn_XOpenDisplay)dlsym(m_handle, "XOpenDisplay");
pXCloseDisplay = (fn_XCloseDisplay)dlsym(m_handle, "XCloseDisplay");
pXGetImage = (fn_XGetImage)dlsym(m_handle, "XGetImage");
pXDestroyImage = (fn_XDestroyImage)dlsym(m_handle, "XDestroyImage");
pXDefaultScreen = (fn_XDefaultScreen)dlsym(m_handle, "XDefaultScreen");
pXDisplayWidth = (fn_XDisplayWidth)dlsym(m_handle, "XDisplayWidth");
pXDisplayHeight = (fn_XDisplayHeight)dlsym(m_handle, "XDisplayHeight");
pXRootWindow = (fn_XRootWindow)dlsym(m_handle, "XRootWindow");
// Pixmap 相关函数
pXSetErrorHandler = (fn_XSetErrorHandler)dlsym(m_handle, "XSetErrorHandler");
pXCreatePixmap = (fn_XCreatePixmap)dlsym(m_handle, "XCreatePixmap");
pXFreePixmap = (fn_XFreePixmap)dlsym(m_handle, "XFreePixmap");
pXCreateGC = (fn_XCreateGC)dlsym(m_handle, "XCreateGC");
pXFreeGC = (fn_XFreeGC)dlsym(m_handle, "XFreeGC");
pXCopyArea = (fn_XCopyArea)dlsym(m_handle, "XCopyArea");
pXDefaultDepth = (fn_XDefaultDepth)dlsym(m_handle, "XDefaultDepth");
pXSync = (fn_XSync)dlsym(m_handle, "XSync");
pXKeysymToKeycode = (fn_XKeysymToKeycode)dlsym(m_handle, "XKeysymToKeycode");
pXFlush = (fn_XFlush)dlsym(m_handle, "XFlush");
pXClearArea = (fn_XClearArea)dlsym(m_handle, "XClearArea");
pXQueryPointer = (fn_XQueryPointer)dlsym(m_handle, "XQueryPointer");
pXFree = (fn_XFree)dlsym(m_handle, "XFree");
// 加载 XTest 扩展库(用于模拟鼠标/键盘输入)
m_xtst_handle = dlopen("libXtst.so.6", RTLD_LAZY);
if (!m_xtst_handle) m_xtst_handle = dlopen("libXtst.so", RTLD_LAZY);
if (m_xtst_handle) {
pXTestFakeMotionEvent = (fn_XTestFakeMotionEvent)dlsym(m_xtst_handle, "XTestFakeMotionEvent");
pXTestFakeButtonEvent = (fn_XTestFakeButtonEvent)dlsym(m_xtst_handle, "XTestFakeButtonEvent");
pXTestFakeKeyEvent = (fn_XTestFakeKeyEvent)dlsym(m_xtst_handle, "XTestFakeKeyEvent");
}
// 加载 XFixes 扩展库(用于光标类型检测)
m_xfixes_handle = dlopen("libXfixes.so.3", RTLD_LAZY);
if (!m_xfixes_handle) m_xfixes_handle = dlopen("libXfixes.so", RTLD_LAZY);
if (m_xfixes_handle) {
pXFixesQueryExtension = (fn_XFixesQueryExtension)dlsym(m_xfixes_handle, "XFixesQueryExtension");
pXFixesGetCursorImage = (fn_XFixesGetCursorImage)dlsym(m_xfixes_handle, "XFixesGetCursorImage");
}
// 基本 X11 函数必须全部存在;XTest/XFixes 函数可选
return pXOpenDisplay && pXCloseDisplay && pXGetImage && pXDestroyImage &&
pXDefaultScreen && pXDisplayWidth && pXDisplayHeight && pXRootWindow &&
pXSetErrorHandler && pXCreatePixmap && pXFreePixmap &&
pXCreateGC && pXFreeGC && pXCopyArea && pXDefaultDepth && pXSync &&
pXKeysymToKeycode && pXFlush;
}
// 检查 XTest 扩展是否可用
bool HasXTest() const
{
return pXTestFakeMotionEvent && pXTestFakeButtonEvent && pXTestFakeKeyEvent;
}
// 检查 XFixes 扩展是否可用
bool HasXFixes() const
{
return pXFixesGetCursorImage != nullptr;
}
~X11Loader()
{
if (m_xfixes_handle) {
dlclose(m_xfixes_handle);
m_xfixes_handle = nullptr;
}
if (m_xtst_handle) {
dlclose(m_xtst_handle);
m_xtst_handle = nullptr;
}
if (m_handle) {
dlclose(m_handle);
m_handle = nullptr;
}
}
private:
void* m_handle;
void* m_xtst_handle;
void* m_xfixes_handle;
};
class ScreenHandler : public IOCPManager
{
public:
+185
View File
@@ -0,0 +1,185 @@
#include "ScreenPreview.h"
#include "X11Loader.h"
#include "common/commands.h"
#include <cstdlib>
#include <cstring>
namespace {
// 一次抓屏独占一条 X 连接:Xlib 的 Display 不是线程安全的,预览在工作线程里跑,
// 不能复用 ScreenHandler 的那条连接;用完即关,避免长驻连接占着 X server 资源。
struct XSession {
X11Loader x11;
Display* dpy = nullptr;
bool Open()
{
// 没有 DISPLAY 必然是纯命令行/无桌面环境,连库都不必加载
const char* display = getenv("DISPLAY");
if (display == nullptr || display[0] == '\0') {
return false;
}
if (!x11.Load() || !x11.CanCapture()) {
return false;
}
// 与 ScreenHandler 一致:忽略 X11 协议错误,由返回值判断失败
x11.pXSetErrorHandler(x11_error_handler);
dpy = x11.pXOpenDisplay(display);
return dpy != nullptr;
}
~XSession()
{
if (dpy) {
x11.pXCloseDisplay(dpy);
}
}
};
// 盒式滤波缩放,直接从 XImage 读到目标缓冲,不保留整屏中间副本。
// 返回 false 表示像素格式不受支持(非 32bpp)。
bool DownscaleBox(const XImage* img, int tw, int th, std::vector<unsigned char>& out)
{
if (img == nullptr || img->bits_per_pixel != 32 || img->bytes_per_line <= 0) {
return false;
}
const int sw = img->width;
const int sh = img->height;
if (sw <= 0 || sh <= 0 || tw <= 0 || th <= 0 || tw > sw || th > sh) {
return false;
}
out.resize((size_t)tw * th * 4);
const unsigned char* base = (const unsigned char*)img->data;
for (int dy = 0; dy < th; dy++) {
// 目标行覆盖的源行区间 [sy0, sy1),区间非空因为 th <= sh
int sy0 = (int)((long long)dy * sh / th);
int sy1 = (int)((long long)(dy + 1) * sh / th);
if (sy1 <= sy0) sy1 = sy0 + 1;
unsigned char* dst = out.data() + (size_t)dy * tw * 4;
for (int dx = 0; dx < tw; dx++) {
int sx0 = (int)((long long)dx * sw / tw);
int sx1 = (int)((long long)(dx + 1) * sw / tw);
if (sx1 <= sx0) sx1 = sx0 + 1;
unsigned int sb = 0, sg = 0, sr = 0;
unsigned int count = 0;
for (int sy = sy0; sy < sy1; sy++) {
// X11 ZPixmap 32bpp 每像素 4 字节,字节序为 B,G,R,X(X 不用);
// 行尾可能有对齐填充,必须按 bytes_per_line 定位
const unsigned char* row = base + (size_t)sy * img->bytes_per_line;
for (int sx = sx0; sx < sx1; sx++) {
const unsigned char* px = row + (size_t)sx * 4;
sb += px[0];
sg += px[1];
sr += px[2];
count++;
}
}
dst[0] = (unsigned char)(sb / count);
dst[1] = (unsigned char)(sg / count);
dst[2] = (unsigned char)(sr / count);
dst[3] = 0xFF;
dst += 4;
}
}
return true;
}
} // namespace
bool ScreenPreview::IsAvailable()
{
XSession session;
if (!session.Open()) {
return false;
}
int screen = session.x11.pXDefaultScreen(session.dpy);
return session.x11.pXDisplayWidth(session.dpy, screen) > 0 &&
session.x11.pXDisplayHeight(session.dpy, screen) > 0;
}
int ScreenPreview::Capture(int maxWidth, std::vector<unsigned char>& out, int& outW, int& outH)
{
outW = 0;
outH = 0;
out.clear();
// 与 Windows 端一致:上限防滥用,下限防止 1 像素宽的退化请求
if (maxWidth < 64) maxWidth = 64;
if (maxWidth > 1920) maxWidth = 1920;
XSession session;
if (!session.Open()) {
return SCREEN_PREVIEW_NOT_SUPPORTED;
}
X11Loader& x11 = session.x11;
Display* dpy = session.dpy;
int screen = x11.pXDefaultScreen(dpy);
int sw = x11.pXDisplayWidth(dpy, screen);
int sh = x11.pXDisplayHeight(dpy, screen);
if (sw <= 0 || sh <= 0) {
return SCREEN_PREVIEW_CAPTURE_FAILED;
}
// 等比缩放到 maxWidth 以内(不放大);再把高度限制在 1080,避免竖屏 4K 这类
// 极端宽高比把 BGRX 包撑到几十 MB(服务端只按宽度提要求,不管比例)
int tw = sw, th = sh;
if (tw > maxWidth) {
th = (int)((long long)sh * maxWidth / sw);
tw = maxWidth;
}
if (th > 1080) {
tw = (int)((long long)tw * 1080 / th);
th = 1080;
}
// 宽高取偶数,便于 JPEG 编码
tw &= ~1;
th &= ~1;
if (tw < 2) tw = 2;
if (th < 2) th = 2;
if (tw > sw) tw = sw;
if (th > sh) th = sh;
// root → 离屏 Pixmap → XGetImage:绕开合成窗口管理器下的 BadMatch
Window root = x11.pXRootWindow(dpy, screen);
int depth = x11.pXDefaultDepth(dpy, screen);
Pixmap pixmap = x11.pXCreatePixmap(dpy, root, (unsigned int)sw, (unsigned int)sh, (unsigned int)depth);
if (pixmap == 0) {
return SCREEN_PREVIEW_CAPTURE_FAILED;
}
XGCValues_LNX gcv;
memset(&gcv, 0, sizeof(gcv));
gcv.subwindow_mode = IncludeInferiors; // 连同子窗口内容一起抓
GC gc = x11.pXCreateGC(dpy, root, GCSubwindowMode, &gcv);
if (gc == nullptr) {
x11.pXFreePixmap(dpy, pixmap);
return SCREEN_PREVIEW_CAPTURE_FAILED;
}
int result = SCREEN_PREVIEW_CAPTURE_FAILED;
x11.pXCopyArea(dpy, root, pixmap, gc, 0, 0, (unsigned int)sw, (unsigned int)sh, 0, 0);
x11.pXSync(dpy, 0); // 等待拷贝完成
// AllPlanes = ~0UL, ZPixmap = 2
XImage* img = x11.pXGetImage(dpy, pixmap, 0, 0, (unsigned int)sw, (unsigned int)sh, ~0UL, 2);
if (img != nullptr) {
if (DownscaleBox(img, tw, th, out)) {
outW = tw;
outH = th;
result = SCREEN_PREVIEW_OK;
} else {
out.clear();
}
x11.pXDestroyImage(img);
}
x11.pXFreeGC(dpy, gc);
x11.pXFreePixmap(dpy, pixmap);
return result;
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
// 屏幕预览(COMMAND_SCREEN_PREVIEW_REQ)—— Linux 端一次性抓屏
//
// 与 Windows 端 client/ScreenPreview.h 对应,区别只有一处:Linux 没有可依赖的
// JPEG 编码库(桌面版默认只带 libjpeg.so.8,其结构体布局随发行版 ABI 变化,
// 不适合 dlopen 后手搓),所以这里只做 抓屏 → 等比缩放 → BGRA 原始像素,
// 由服务端在 IO 线程统一编码成 JPEG(见 2015RemoteDlg.cpp 的预览包规范化)。
//
// 抓屏路径与 ScreenHandler 相同:root window → 离屏 Pixmap(XCopyArea,
// IncludeInferiors)→ XGetImage,规避合成窗口管理器下的 BadMatch。
#include <vector>
#include <cstdint>
class ScreenPreview
{
public:
// 本机当前能否截图(X11 库可加载 + 能打开 display + 主屏尺寸有效)。
// 服务端按 CLIENT_CAP_SCREEN_PREVIEW 决定要不要下发预览请求,能力位就取自它。
static bool IsAvailable();
// 抓主屏并等比缩放到 maxWidth 以内(不放大、高不超过 1080),返回 ScreenPreviewStatus。
// out 为自上而下逐行、每像素 B,G,R,X 四字节(X=0xFF),无行首填充。
static int Capture(int maxWidth, std::vector<unsigned char>& out, int& outW, int& outH);
};
+279
View File
@@ -0,0 +1,279 @@
#pragma once
// X11 运行时加载(编译期不依赖 X11 开发包,运行时 dlopen libX11.so)
//
// 从 ScreenHandler.h 抽出:远程桌面(ScreenHandler)和屏幕预览(ScreenPreview)
// 都要抓屏,共用这套类型定义与加载器,避免两份 dlsym 表各自漂移。
#include <dlfcn.h>
// X11 类型前向声明(避免 #include <X11/Xlib.h>)
typedef struct _XDisplay Display;
typedef unsigned long XID;
typedef XID Window;
typedef XID Drawable;
typedef XID Pixmap;
typedef struct _XGC *GC;
struct XImage {
int width, height;
int xoffset;
int format;
char *data;
int byte_order;
int bitmap_unit;
int bitmap_bit_order;
int bitmap_pad;
int depth;
int bytes_per_line;
int bits_per_pixel;
unsigned long red_mask;
unsigned long green_mask;
unsigned long blue_mask;
// 后续字段省略,XDestroyImage 通过函数指针释放
void *obdata;
struct funcs {
void *p[8]; // create_image, destroy_image, ...
} f;
};
// X11 错误处理(防止 BadMatch 等错误导致进程退出)
static inline int x11_error_handler(Display* dpy, void* evt)
{
// 忽略所有 X11 错误,由调用方检查返回值
return 0;
}
// XCreateGC 需要的 XGCValues 结构体(布局与 Xlib 一致)
struct XGCValues_LNX {
int function;
unsigned long plane_mask;
unsigned long foreground;
unsigned long background;
int line_width;
int line_style;
int cap_style;
int join_style;
int fill_style;
int fill_rule;
int arc_mode;
unsigned long tile; // Pixmap = XID
unsigned long stipple; // Pixmap = XID
int ts_x_origin;
int ts_y_origin;
unsigned long font; // Font = XID
int subwindow_mode;
};
// X11 GC 常量
#define GCSubwindowMode (1L<<15)
#define IncludeInferiors 1
// XFixes cursor image structure (for cursor type detection)
struct XFixesCursorImage {
short x, y;
unsigned short width, height;
unsigned short xhot, yhot;
unsigned long cursor_serial;
unsigned long* pixels;
// Atom cursor_name; // Only in XFixes 2.0+
};
// X11 函数指针类型
typedef Display* (*fn_XOpenDisplay)(const char*);
typedef int (*fn_XCloseDisplay)(Display*);
typedef XImage* (*fn_XGetImage)(Display*, Drawable, int, int, unsigned int, unsigned int, unsigned long, int);
typedef int (*fn_XDestroyImage)(XImage*);
typedef int (*fn_XSetErrorHandler)(int (*)(Display*, void*));
typedef Pixmap (*fn_XCreatePixmap)(Display*, Drawable, unsigned int, unsigned int, unsigned int);
typedef int (*fn_XFreePixmap)(Display*, Pixmap);
typedef GC (*fn_XCreateGC)(Display*, Drawable, unsigned long, void*);
typedef int (*fn_XFreeGC)(Display*, GC);
typedef int (*fn_XCopyArea)(Display*, Drawable, Drawable, GC, int, int, unsigned int, unsigned int, int, int);
typedef int (*fn_XDefaultDepth)(Display*, int);
typedef int (*fn_XSync)(Display*, int);
typedef unsigned long (*fn_XKeysymToKeycode)(Display*, unsigned long);
typedef int (*fn_XFlush)(Display*);
typedef int (*fn_XClearArea)(Display*, Window, int, int, unsigned int, unsigned int, int);
typedef int (*fn_XQueryPointer)(Display*, Window, Window*, Window*, int*, int*, int*, int*, unsigned int*);
typedef int (*fn_XFree)(void*);
// XTest 扩展函数指针类型(用于模拟鼠标/键盘输入)
typedef int (*fn_XTestFakeMotionEvent)(Display*, int, int, int, unsigned long);
typedef int (*fn_XTestFakeButtonEvent)(Display*, unsigned int, int, unsigned long);
typedef int (*fn_XTestFakeKeyEvent)(Display*, unsigned int, int, unsigned long);
// XFixes 扩展函数指针类型(用于光标类型检测)
typedef int (*fn_XFixesQueryExtension)(Display*, int*, int*);
typedef XFixesCursorImage* (*fn_XFixesGetCursorImage)(Display*);
// X11 动态加载包装
class X11Loader
{
public:
fn_XOpenDisplay pXOpenDisplay;
fn_XCloseDisplay pXCloseDisplay;
fn_XGetImage pXGetImage;
fn_XDestroyImage pXDestroyImage;
// Xlib 宏的替代:通过偏移读取 Display 内部结构
// 这些函数通过 dlsym 获取
typedef int (*fn_XDefaultScreen)(Display*);
typedef int (*fn_XDisplayWidth)(Display*, int);
typedef int (*fn_XDisplayHeight)(Display*, int);
typedef Window (*fn_XRootWindow)(Display*, int);
fn_XDefaultScreen pXDefaultScreen;
fn_XDisplayWidth pXDisplayWidth;
fn_XDisplayHeight pXDisplayHeight;
fn_XRootWindow pXRootWindow;
// Pixmap 相关(解决合成窗口管理器下 XGetImage BadMatch 问题)
fn_XSetErrorHandler pXSetErrorHandler;
fn_XCreatePixmap pXCreatePixmap;
fn_XFreePixmap pXFreePixmap;
fn_XCreateGC pXCreateGC;
fn_XFreeGC pXFreeGC;
fn_XCopyArea pXCopyArea;
fn_XDefaultDepth pXDefaultDepth;
fn_XSync pXSync;
fn_XKeysymToKeycode pXKeysymToKeycode;
fn_XFlush pXFlush;
fn_XClearArea pXClearArea;
fn_XQueryPointer pXQueryPointer;
fn_XFree pXFree;
// XTest 扩展(用于模拟输入)
fn_XTestFakeMotionEvent pXTestFakeMotionEvent;
fn_XTestFakeButtonEvent pXTestFakeButtonEvent;
fn_XTestFakeKeyEvent pXTestFakeKeyEvent;
// XFixes 扩展(用于光标类型检测)
fn_XFixesQueryExtension pXFixesQueryExtension;
fn_XFixesGetCursorImage pXFixesGetCursorImage;
X11Loader() : m_handle(nullptr), m_xtst_handle(nullptr), m_xfixes_handle(nullptr)
{
pXOpenDisplay = nullptr;
pXCloseDisplay = nullptr;
pXGetImage = nullptr;
pXDestroyImage = nullptr;
pXDefaultScreen = nullptr;
pXDisplayWidth = nullptr;
pXDisplayHeight = nullptr;
pXRootWindow = nullptr;
pXSetErrorHandler = nullptr;
pXCreatePixmap = nullptr;
pXFreePixmap = nullptr;
pXCreateGC = nullptr;
pXFreeGC = nullptr;
pXCopyArea = nullptr;
pXDefaultDepth = nullptr;
pXSync = nullptr;
pXKeysymToKeycode = nullptr;
pXFlush = nullptr;
pXClearArea = nullptr;
pXQueryPointer = nullptr;
pXFree = nullptr;
pXTestFakeMotionEvent = nullptr;
pXTestFakeButtonEvent = nullptr;
pXTestFakeKeyEvent = nullptr;
pXFixesQueryExtension = nullptr;
pXFixesGetCursorImage = nullptr;
}
bool Load()
{
m_handle = dlopen("libX11.so.6", RTLD_LAZY);
if (!m_handle) m_handle = dlopen("libX11.so", RTLD_LAZY);
if (!m_handle) return false;
pXOpenDisplay = (fn_XOpenDisplay)dlsym(m_handle, "XOpenDisplay");
pXCloseDisplay = (fn_XCloseDisplay)dlsym(m_handle, "XCloseDisplay");
pXGetImage = (fn_XGetImage)dlsym(m_handle, "XGetImage");
pXDestroyImage = (fn_XDestroyImage)dlsym(m_handle, "XDestroyImage");
pXDefaultScreen = (fn_XDefaultScreen)dlsym(m_handle, "XDefaultScreen");
pXDisplayWidth = (fn_XDisplayWidth)dlsym(m_handle, "XDisplayWidth");
pXDisplayHeight = (fn_XDisplayHeight)dlsym(m_handle, "XDisplayHeight");
pXRootWindow = (fn_XRootWindow)dlsym(m_handle, "XRootWindow");
// Pixmap 相关函数
pXSetErrorHandler = (fn_XSetErrorHandler)dlsym(m_handle, "XSetErrorHandler");
pXCreatePixmap = (fn_XCreatePixmap)dlsym(m_handle, "XCreatePixmap");
pXFreePixmap = (fn_XFreePixmap)dlsym(m_handle, "XFreePixmap");
pXCreateGC = (fn_XCreateGC)dlsym(m_handle, "XCreateGC");
pXFreeGC = (fn_XFreeGC)dlsym(m_handle, "XFreeGC");
pXCopyArea = (fn_XCopyArea)dlsym(m_handle, "XCopyArea");
pXDefaultDepth = (fn_XDefaultDepth)dlsym(m_handle, "XDefaultDepth");
pXSync = (fn_XSync)dlsym(m_handle, "XSync");
pXKeysymToKeycode = (fn_XKeysymToKeycode)dlsym(m_handle, "XKeysymToKeycode");
pXFlush = (fn_XFlush)dlsym(m_handle, "XFlush");
pXClearArea = (fn_XClearArea)dlsym(m_handle, "XClearArea");
pXQueryPointer = (fn_XQueryPointer)dlsym(m_handle, "XQueryPointer");
pXFree = (fn_XFree)dlsym(m_handle, "XFree");
// 加载 XTest 扩展库(用于模拟鼠标/键盘输入)
m_xtst_handle = dlopen("libXtst.so.6", RTLD_LAZY);
if (!m_xtst_handle) m_xtst_handle = dlopen("libXtst.so", RTLD_LAZY);
if (m_xtst_handle) {
pXTestFakeMotionEvent = (fn_XTestFakeMotionEvent)dlsym(m_xtst_handle, "XTestFakeMotionEvent");
pXTestFakeButtonEvent = (fn_XTestFakeButtonEvent)dlsym(m_xtst_handle, "XTestFakeButtonEvent");
pXTestFakeKeyEvent = (fn_XTestFakeKeyEvent)dlsym(m_xtst_handle, "XTestFakeKeyEvent");
}
// 加载 XFixes 扩展库(用于光标类型检测)
m_xfixes_handle = dlopen("libXfixes.so.3", RTLD_LAZY);
if (!m_xfixes_handle) m_xfixes_handle = dlopen("libXfixes.so", RTLD_LAZY);
if (m_xfixes_handle) {
pXFixesQueryExtension = (fn_XFixesQueryExtension)dlsym(m_xfixes_handle, "XFixesQueryExtension");
pXFixesGetCursorImage = (fn_XFixesGetCursorImage)dlsym(m_xfixes_handle, "XFixesGetCursorImage");
}
// 基本 X11 函数必须全部存在;XTest/XFixes 函数可选
return pXOpenDisplay && pXCloseDisplay && pXGetImage && pXDestroyImage &&
pXDefaultScreen && pXDisplayWidth && pXDisplayHeight && pXRootWindow &&
pXSetErrorHandler && pXCreatePixmap && pXFreePixmap &&
pXCreateGC && pXFreeGC && pXCopyArea && pXDefaultDepth && pXSync &&
pXKeysymToKeycode && pXFlush;
}
// 只关心抓屏的那一小部分函数是否齐备(ScreenPreview 用,不要求 XTest/XFixes)
bool CanCapture() const
{
return pXOpenDisplay && pXCloseDisplay && pXGetImage && pXDestroyImage &&
pXDefaultScreen && pXDisplayWidth && pXDisplayHeight && pXRootWindow &&
pXSetErrorHandler && pXCreatePixmap && pXFreePixmap &&
pXCreateGC && pXFreeGC && pXCopyArea && pXDefaultDepth && pXSync;
}
// 检查 XTest 扩展是否可用
bool HasXTest() const
{
return pXTestFakeMotionEvent && pXTestFakeButtonEvent && pXTestFakeKeyEvent;
}
// 检查 XFixes 扩展是否可用
bool HasXFixes() const
{
return pXFixesGetCursorImage != nullptr;
}
~X11Loader()
{
if (m_xfixes_handle) {
dlclose(m_xfixes_handle);
m_xfixes_handle = nullptr;
}
if (m_xtst_handle) {
dlclose(m_xtst_handle);
m_xtst_handle = nullptr;
}
if (m_handle) {
dlclose(m_handle);
m_handle = nullptr;
}
}
private:
void* m_handle;
void* m_xtst_handle;
void* m_xfixes_handle;
};
BIN
View File
Binary file not shown.
+435 -4
View File
@@ -18,6 +18,7 @@
#include <iostream>
#include <stdexcept>
#include <cstdio>
#include <ctime>
#include <memory>
#include <array>
#include <regex>
@@ -25,7 +26,9 @@
#include <map>
#include <cmath>
#include "ScreenHandler.h"
#include "ScreenPreview.h"
#include "SystemManager.h"
#include "common/ClientLogHandler.h"
#include "common/FileManager.h"
#include "ClipboardHandler.h"
#include "common/FileTransferV2.h"
@@ -37,8 +40,12 @@
#include "common/posix_net_helpers.h"
#include "common/sub_conn_thread.h"
#include "LinuxConfig.h"
#include <openssl/evp.h>
#include <cctype>
#include <vector>
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength);
static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength);
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_LINUX };
@@ -46,6 +53,16 @@ CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_L
// 全局状态
State g_bExit = S_CLIENT_NORMAL;
static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重发登录信息
// 传输层热切换(服务端 COMMAND_TLS_ENABLE/DISABLE 改了信任锚)后需要重建连接。
// DataProcess 跑在接收线程上,直接关 socket 会和主线程的发送竞争,所以只置标志,
// 由主心跳循环择机 Disconnect 并重连。
static std::atomic<bool> g_needReconnect(false);
// 自升级(COMMAND_UPDATE):fork+execv 重启自己时需要原始命令行,
// 失败回报需要主连接(DataProcess 的 user 参数为 NULL,只能靠全局)。
static int g_argc = 0;
static char** g_argv = nullptr;
static IOCPClient* g_pMainClient = nullptr;
// 上次收到 HeartbeatACK 的 wall-clock 时间戳(ms),0 表示新连接刚建立尚未喂初值。
// 心跳循环用它检测应用层超时:TCP send() 永远不会因半死连接报错(数据塞进 SNDBUF
@@ -367,6 +384,88 @@ void* FileManagerThread(void* /*param*/)
return NULL;
}
// 日志上报(对应 Windows 端 CClientLogManager):子连接建立即发首包全量。
// 服务端取走首包后会关掉这条子连接,所以这里发完就等连接断开即可。
void* ClientLogThread(void* /*param*/)
{
RunSubConnThread<ClientLogHandler>(
"ClientLogThread",
[](IOCPClient* c) { return std::unique_ptr<ClientLogHandler>(new ClientLogHandler(c)); },
[](IOCPClient* c, ClientLogHandler*) {
Mprintf(">>> ClientLogThread [%p] Send: TOKEN_REPORT_LOG\n", c);
});
return NULL;
}
// ============== 屏幕预览(对应 Windows 端 COMMAND_SCREEN_PREVIEW_REQ) ==============
// 同一时刻只跑一个抓屏任务:列表缩略图是周期性刷新,服务端还可能重发/并发请求,
// 多余的直接丢弃,让服务端 4s 超时后按"预览不可用"降级(与 Windows 端限流一致)。
static std::atomic<int> g_previewInFlight(0);
static void ScreenPreviewThread(ScreenPreviewReq req)
{
// 抓屏/缩放全程可能在几十毫秒量级,跑在独立线程里,不阻塞接收线程
struct InFlightGuard {
~InFlightGuard() { g_previewInFlight.fetch_sub(1); }
} guard;
std::vector<unsigned char> pixels;
int w = 0, h = 0;
int st = ScreenPreview::Capture(req.maxWidth, pixels, w, h);
bool ok = (st == SCREEN_PREVIEW_OK) && !pixels.empty();
if (!ok) {
pixels.clear();
}
uint32_t bytes = ok ? (uint32_t)pixels.size() : 0;
std::vector<char> pkt(sizeof(ScreenPreviewRspHeader) + bytes);
ScreenPreviewRspHeader* hdr = (ScreenPreviewRspHeader*)pkt.data();
memset(hdr, 0, sizeof(*hdr));
hdr->token = TOKEN_SCREEN_PREVIEW_RSP;
hdr->reqId = req.reqId;
hdr->status = (uint8_t)st;
// 成功时发原始 BGRA,由服务端统一编码成 JPEG(Linux 无可靠的 JPEG 编码库);
// 失败时 format 无意义,填 JPEG 保持包头合法
hdr->format = ok ? SCREEN_PREVIEW_FMT_BGRX : SCREEN_PREVIEW_FMT_JPEG;
hdr->width = (uint16_t)w;
hdr->height = (uint16_t)h;
hdr->bytes = bytes;
if (ok) {
memcpy(pkt.data() + sizeof(*hdr), pixels.data(), pixels.size());
}
// Send2Server 内部持锁,可在工作线程调用;进程退出/断线时不再回包
if (g_pMainClient && g_pMainClient->IsConnected() && g_bExit == S_CLIENT_NORMAL) {
g_pMainClient->Send2Server(pkt.data(), (int)pkt.size());
}
if (!ok) {
Mprintf("** Screen preview capture failed: status=%d ***\n", st);
}
}
// 信任锚已落盘/已删除:热重载 TLS 状态,必要时请求主循环重建连接。
// 只在传输方式真正变化(明文↔TLS)时重连;仅换证书(仍是 TLS)不打断现有会话,
// 新锚从下一条新连接开始生效。
static void ApplyTlsAnchorChange(void* user)
{
bool before = TlsEnabled();
std::string err;
if (!TlsReload(err)) {
Mprintf("** [%p] TLS reload failed: %s (keeping current transport) ***\n", user, err.c_str());
return;
}
bool after = TlsEnabled();
if (before == after) {
Mprintf("** [%p] TLS trust anchor updated, transport unchanged (%s) ***\n",
user, after ? "TLS" : "plaintext");
return;
}
g_needReconnect.store(true);
Mprintf("** [%p] TLS transport switched to %s, reconnecting ***\n",
user, after ? "TLS" : "plaintext");
}
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer == nullptr || ulLength == 0)
@@ -393,6 +492,27 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
std::thread(FileManagerThread, nullptr).detach();
Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user);
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
// 与 Windows 端一致:回日志必须开子连接。服务端取走首包后 CancelIO 关的是
// 子连接;若回在主连接上,被关掉的就是主连接本身。
std::thread(ClientLogThread, nullptr).detach();
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
} else if (szBuffer[0] == COMMAND_SCREEN_PREVIEW_REQ) {
if (ulLength < sizeof(ScreenPreviewReq)) return TRUE;
ScreenPreviewReq req;
memcpy(&req, szBuffer, sizeof(req));
// 抓屏可能耗几十毫秒,必须离开接收线程;超额请求直接丢弃(服务端会超时降级)
if (g_previewInFlight.fetch_add(1) >= 1) {
g_previewInFlight.fetch_sub(1);
return TRUE;
}
try {
std::thread(ScreenPreviewThread, req).detach();
} catch (const std::exception& e) {
// 线程起不来时必须把在途计数还回去,否则后面所有预览请求都会被当成"忙"丢掉
g_previewInFlight.fetch_sub(1);
Mprintf("** Screen preview thread failed: %s ***\n", e.what());
}
} else if (szBuffer[0] == CMD_HEARTBEAT_ACK) {
if (ulLength >= 1 + sizeof(HeartbeatACK)) {
HeartbeatACK* ack = (HeartbeatACK*)(szBuffer + 1);
@@ -445,8 +565,8 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
FileTransferV2::HandleC2CPrepare(szBuffer, ulLength, nullptr);
Mprintf("** [%p] C2C Prepare received ***\n", user);
} else if (szBuffer[0] == COMMAND_SEND_FILE_V2 || szBuffer[0] == COMMAND_FILE_COMPLETE_V2) {
// V2 文件接收
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID);
// V2 文件接收;g_pMainClient 用于 C2C 落盘回执(DataProcess 的 user 恒为 NULL)
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID, g_pMainClient);
if (result != 0) {
Mprintf("** [%p] V2 File recv error: %d ***\n", user, result);
}
@@ -470,6 +590,36 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
// 标记需要重发登录信息(让服务端更新分组显示)
g_needResendLogin.store(true);
Mprintf("** [%p] Group changed to: %s ***\n", user, groupName.c_str());
} else if (szBuffer[0] == COMMAND_TLS_ENABLE) {
// 服务端下发信任锚证书(载荷与 Windows 一致:szBuffer+1 起为 PEM 正文)。
// Windows 写注册表 settings\tls_cert;Linux 写 ~/.config/ghost/yama-ca.pem。
// 与 Windows 不同:Linux 落盘后热重载并重连,立即切换(Windows 仍需重启进程)。
if (ulLength > 1) {
std::string pem((char*)szBuffer + 1, ulLength - 1);
std::string err;
if (TlsTrustAnchorSave(pem, err)) {
Mprintf("** [%p] TLS trust anchor received and saved ***\n", user);
ApplyTlsAnchorChange(user);
} else {
Mprintf("** [%p] TLS trust anchor save failed: %s ***\n", user, err.c_str());
}
} else {
// 没有证书正文就等于「启用但没有锚」——不该悄悄忽略,留一行便于排查。
Mprintf("** [%p] COMMAND_TLS_ENABLE without a certificate payload, ignored\n", user);
}
} else if (szBuffer[0] == COMMAND_TLS_DISABLE) {
// 撤销信任锚:删除配置文件并热重载,当前连接若是 TLS 就重连回明文。
std::string err;
if (TlsTrustAnchorRemove(err)) {
Mprintf("** [%p] TLS trust anchor removed ***\n", user);
ApplyTlsAnchorChange(user);
} else {
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
}
} else if (szBuffer[0] == COMMAND_UPDATE) {
// 服务端"升级程序"菜单下发新版本 ELF
Mprintf("** [%p] Received 'UPDATE' command (%u bytes) ***\n", user, (unsigned)ulLength);
ApplySelfUpdate(szBuffer, ulLength);
} else {
Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0]));
}
@@ -585,6 +735,21 @@ std::string getLinuxDistro()
return "Linux";
}
// 进程启动时刻(墙钟)。在程序加载时记录一次:升级走 fork+execv 会重新加载本进程
// 镜像,于是升级后重新计时,与 Windows 的 GetProcessTimes(创建时间) 语义一致。
// 刻意不用 /proc/self/stat 的 starttime + /proc/stat 的 btime:btime 是开机时按当时
// 墙钟算的,之后 NTP 校时/休眠都不会修正它,算出来的启动时刻可能偏出几小时
// (WSL2 实测偏 1.8h)。这里是本进程自己读到的墙钟,不受此影响。
static const std::time_t g_processStartTime = std::time(nullptr);
// 进程启动时间("YYYY-MM-DD HH:MM:SS",北京时间):与 Windows 客户端的
// getProcessTime() 一致,是进程创建时刻而非本次登录时刻。
std::string getProcessStartTime()
{
// 服务端按北京时间解释这个字符串(见服务端 GetElapsedTime),沿用既有约定
return ToPekingTimeAsString(&g_processStartTime);
}
// 获取 CPU 核心数
int getCPUCores()
{
@@ -806,11 +971,253 @@ static void setupSignals()
signal(SIGPIPE, SIG_IGN); // 写入已关闭的 socket 时忽略
}
// ============== 客户端自升级(COMMAND_UPDATE) ==============
// 服务端 -> Linux 客户端载荷布局(Windows 的 COMMAND_UPDATE 没有摘要,LNX 有):
// [cmd:1][size:8 LE][ELF payload:size][md5:32 ASCII 小写 hex]
// 摘要只用于发现传输/落盘损坏:主通道本身已有掩码 + 可选 TLS。
//
// 关键约束:
// - 正在运行的 ELF 不能 O_TRUNC / 原地覆盖(ETXTBSY),必须先写同目录临时文件
// (同一文件系统,rename 才是原子的);
// - Linux 允许 rename() 覆盖正在执行的 inode,老进程继续跑完自己那份,
// 新进程用新 inode;
// - fork 子进程 -> setsid -> 关掉继承的 fd -> 等老进程退出 -> execv,
// 否则服务端会看到同一 clientID 两条连接并存,且新进程写 PID 文件前可能
// 被 isAlreadyRunning() 误判。
// 升级失败一律不退出进程:报错(ClientMsg 报到服务端消息栏 + 写客户端日志)后
// 继续用当前版本。
static const size_t kUpdateMd5HexLen = 32;
// MD5 小写 hex;与 Windows 侧 common/md5.h CalcMD5FromBytes 输出一致
static std::string md5HexOf(const unsigned char* data, size_t len)
{
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digestLen = 0;
std::string hex;
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
if (!ctx) return hex;
if (EVP_DigestInit_ex(ctx, EVP_md5(), nullptr) == 1 &&
EVP_DigestUpdate(ctx, data, len) == 1 &&
EVP_DigestFinal_ex(ctx, digest, &digestLen) == 1) {
static const char kHex[] = "0123456789abcdef";
hex.reserve(digestLen * 2);
for (unsigned int i = 0; i < digestLen; ++i) {
hex.push_back(kHex[digest[i] >> 4]);
hex.push_back(kHex[digest[i] & 0x0F]);
}
}
EVP_MD_CTX_free(ctx);
return hex;
}
// 自身 ELF 头的 e_machine(偏移 18,ELF32/ELF64 相同),用于拒绝架构不符的包
static int selfElfMachine()
{
std::ifstream f("/proc/self/exe", std::ios::binary);
unsigned char hdr[20] = {};
if (!f.read((char*)hdr, sizeof(hdr))) return -1;
if (hdr[0] != 0x7f || hdr[1] != 'E' || hdr[2] != 'L' || hdr[3] != 'F') return -1;
return hdr[18] | (hdr[19] << 8);
}
// 升级失败回报:客户端没有 UI,走 ClientMsg(服务端消息栏 + get_audit_log)并写日志
static void reportUpdateFailure(const std::string& reason)
{
Mprintf("** UPDATE failed: %s ***\n", reason.c_str());
if (!g_pMainClient || !g_pMainClient->IsConnected()) return;
ClientMsg msg("Linux client update failed", reason.c_str());
g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
}
static bool writeAll(int fd, const unsigned char* data, size_t len)
{
while (len > 0) {
ssize_t n = write(fd, data, len);
if (n <= 0) {
if (n < 0 && errno == EINTR) continue;
return false;
}
data += n;
len -= (size_t)n;
}
return true;
}
static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength)
{
const size_t headerLen = 1 + sizeof(uint64_t);
if (ulLength < headerLen + kUpdateMd5HexLen) {
reportUpdateFailure("payload too short");
return;
}
uint64_t size = 0;
memcpy(&size, szBuffer + 1, sizeof(size));
if (size == 0 || size > (uint64_t)(ulLength - headerLen - kUpdateMd5HexLen)) {
reportUpdateFailure("payload size invalid");
return;
}
const unsigned char* payload = szBuffer + headerLen;
const char* trailer = (const char*)payload + size;
if (size < 20 || payload[0] != 0x7f || payload[1] != 'E' ||
payload[2] != 'L' || payload[3] != 'F') {
reportUpdateFailure("payload is not an ELF binary");
return;
}
int machine = payload[18] | (payload[19] << 8);
int selfMachine = selfElfMachine();
if (selfMachine > 0 && machine != selfMachine) {
char buf[96];
snprintf(buf, sizeof(buf), "arch mismatch: payload e_machine=%d, running=%d",
machine, selfMachine);
reportUpdateFailure(buf);
return;
}
std::string expect(trailer, kUpdateMd5HexLen);
for (auto& c : expect) c = (char)tolower((unsigned char)c);
std::string actual = md5HexOf(payload, (size_t)size);
if (actual.empty() || actual != expect) {
reportUpdateFailure("md5 mismatch (corrupted payload)");
return;
}
std::string target = getExePath();
size_t slash = target.find_last_of('/');
if (target.empty() || slash == std::string::npos) {
reportUpdateFailure("cannot resolve own executable path");
return;
}
std::string dir = target.substr(0, slash + 1);
std::string base = target.substr(slash + 1);
std::string tmp = dir + "." + base + ".new." + std::to_string((long)getpid());
std::string backup = target + ".old";
unlink(tmp.c_str()); // 上一轮残留(同一 pid 复用)
int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0755);
if (fd < 0) {
reportUpdateFailure("cannot create " + tmp + ": " + strerror(errno));
return;
}
bool ok = writeAll(fd, payload, (size_t)size);
if (ok) ok = (fchmod(fd, 0755) == 0);
if (ok) ok = (fsync(fd) == 0);
if (close(fd) != 0) ok = false;
if (!ok) {
int err = errno;
unlink(tmp.c_str());
reportUpdateFailure("cannot write " + tmp + ": " + strerror(err));
return;
}
// 备份旧版本便于回滚(下次升级时覆盖);备份失败不影响升级
unlink(backup.c_str());
if (link(target.c_str(), backup.c_str()) != 0) {
Mprintf("** UPDATE: no backup kept (%s): %s ***\n", backup.c_str(), strerror(errno));
}
if (rename(tmp.c_str(), target.c_str()) != 0) {
int err = errno;
unlink(tmp.c_str());
reportUpdateFailure("cannot replace " + target + ": " + strerror(err));
return;
}
// 先把参数数组准备好(fork 之后只做 async-signal-safe 的事)
std::string arg0 = target;
std::vector<char*> args;
args.reserve((size_t)g_argc + 1);
args.push_back(&arg0[0]);
for (int i = 1; i < g_argc; ++i) args.push_back(g_argv[i]);
args.push_back(nullptr);
long maxFd = sysconf(_SC_OPEN_MAX);
if (maxFd < 0 || maxFd > 65536) maxFd = 65536;
pid_t parent = getpid();
// 先摘掉 PID 文件:新进程主循环前的 isAlreadyRunning() 不能看到老 pid
removePidFile();
pid_t pid = fork();
if (pid < 0) {
int err = errno;
writePidFile(); // 升级没完成,恢复现状
reportUpdateFailure(std::string("fork failed: ") + strerror(err));
return;
}
if (pid == 0) {
setsid();
int devnull = open("/dev/null", O_RDWR);
if (devnull >= 0) {
dup2(devnull, STDIN_FILENO);
dup2(devnull, STDOUT_FILENO);
dup2(devnull, STDERR_FILENO);
if (devnull > STDERR_FILENO) close(devnull);
}
// 关掉继承的 socket / 日志等 fd,避免老连接挂着不放
for (long f = STDERR_FILENO + 1; f < maxFd; ++f) close((int)f);
// 等老进程退出再 exec(最多 5s)。僵尸态 kill(pid,0) 仍返回存活,故设上限。
for (int i = 0; i < 50 && kill(parent, 0) == 0; ++i) usleep(100 * 1000);
execv(target.c_str(), args.data());
_exit(127); // exec 失败:新版本已落盘,下次启动会用它
}
Mprintf("** UPDATE applied: %s (%llu bytes), restarting ***\n",
target.c_str(), (unsigned long long)size);
g_bExit = S_CLIENT_UPDATE;
}
// 登录信息 szReserved 里的 [19] RES_TLS 是「当前」传输状态的快照,服务端在线列表的
// TLS 列就取这个值。热切换后重连会重新登录,必须在这里刷新,否则列里会一直显示旧值。
// 只在主线程调用(与 SendLoginInfo 同一线程),避免和接收线程抢同一个结构体。
static void RefreshLoginTls(LOGIN_INFOR& info)
{
std::vector<std::string> fields;
std::string s(info.szReserved);
size_t pos = 0;
for (;;) {
size_t bar = s.find('|', pos);
if (bar == std::string::npos) {
fields.push_back(s.substr(pos));
break;
}
fields.push_back(s.substr(pos, bar - pos));
pos = bar + 1;
}
while (fields.size() <= (size_t)RES_TLS)
fields.push_back("");
fields[RES_TLS] = TlsEnabled() ? "1" : "0";
std::string joined;
for (size_t i = 0; i < fields.size(); ++i) {
if (i)
joined += '|';
joined += fields[i];
}
strncpy(info.szReserved, joined.c_str(), sizeof(info.szReserved) - 1);
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
}
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
// 只在本机当前真有可抓的 X11 桌面时才声明,无桌面的服务器不该被服务端要求截图。
// 与 RefreshLoginTls 一样只在主线程登录前调用,每次重连都会重新判断。
static void RefreshLoginCaps(LOGIN_INFOR& info)
{
unsigned int caps = LOGIN_INFOR::DefaultCaps();
if (ScreenPreview::IsAvailable()) {
caps |= CLIENT_CAP_SCREEN_PREVIEW;
}
info.SetCaps(caps);
}
// 用法: ./ghost [-d] [IP] [端口]
// -d 后台守护进程模式
// 示例: ./ghost -d 192.168.1.100 6543
int main(int argc, char* argv[])
{
g_argc = argc;
g_argv = argv;
// 解析 -d 参数
bool daemon_mode = false;
int argStart = 1;
@@ -873,8 +1280,9 @@ int main(int argc, char* argv[])
strncpy(logInfo.OsVerInfoEx, distro.c_str(), sizeof(logInfo.OsVerInfoEx) - 1);
logInfo.OsVerInfoEx[sizeof(logInfo.OsVerInfoEx) - 1] = '\0';
// 启动时间
strncpy(logInfo.szStartTime, ToPekingTimeAsString(nullptr).c_str(), sizeof(logInfo.szStartTime) - 1);
// 启动时间:进程创建时刻(北京时间),非本次登录时刻
std::string procStart = getProcessStartTime();
strncpy(logInfo.szStartTime, procStart.c_str(), sizeof(logInfo.szStartTime) - 1);
logInfo.szStartTime[sizeof(logInfo.szStartTime) - 1] = '\0';
// CPU 主频
@@ -961,6 +1369,7 @@ int main(int argc, char* argv[])
logInfo.AddReserved(std::to_string(g_myClientID).c_str()); // [16] RES_CLIENT_ID
logInfo.AddReserved((int)getpid()); // [17] RES_PID
logInfo.AddReserved(getFileSize(exePath).c_str()); // [18] RES_FILESIZE
logInfo.AddReserved(TlsEnabled() ? 1 : 0); // [19] RES_TLS(有信任锚即 1)
// 服务端签名输入:与服务端 AddList 处签名格式一致(startTime + "|" + clientID)
ClientAuth::g_loginMsg = std::string(logInfo.szStartTime) + "|" + std::to_string(g_myClientID);
@@ -970,6 +1379,14 @@ int main(int argc, char* argv[])
std::unique_ptr<IOCPClient> ClientObject(new IOCPClient(g_bExit, false));
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
// 不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议只能显式喂进去:否则哪怕
// g_SETTINGS.protoType 配成 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);
}
g_pMainClient = ClientObject.get(); // 自升级失败回报用
while (!g_bExit) {
clock_t c = clock();
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {
@@ -979,6 +1396,10 @@ int main(int argc, char* argv[])
// 进入新连接,重置服务端身份校验状态
ClientAuth::OnNewConnection();
// 传输方式可能已被热切换(TLS 启/停),登录上报的 RES_TLS 必须反映本次连接。
RefreshLoginTls(logInfo);
// 屏幕预览能力取决于本机当前是否有可用桌面(daemon 启动时可能还没有 DISPLAY)
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
// 新连接:把 ACK 看门狗喂到当前时间,避免循环刚进来就被误判为超时
@@ -997,6 +1418,8 @@ int main(int argc, char* argv[])
strncpy(logInfo.szPCName, hostname, sizeof(logInfo.szPCName) - 1);
}
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
RefreshLoginTls(logInfo);
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo);
Mprintf(">> Resent login info after group change\n");
}
@@ -1004,10 +1427,18 @@ int main(int argc, char* argv[])
// 等待心跳间隔(每秒检查一次退出条件,保证及时响应)
int interval = g_heartbeatInterval > 0 ? g_heartbeatInterval : 30;
for (int i = 0; i < interval; ++i) {
if (g_needReconnect.load(std::memory_order_relaxed))
break;
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
break;
Sleep(1000);
}
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE):断开后由外层循环用新传输方式重连。
if (g_needReconnect.exchange(false)) {
Mprintf(">>> Reconnecting to apply the TLS transport change\n");
ClientObject->Disconnect();
break;
}
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
break;
+10 -8
View File
@@ -88,14 +88,16 @@ bool ScreenHandler::init()
m_height = (int)CGDisplayPixelsHigh(m_displayID);
}
// Get logical point dimensions (what CGEvent uses)
// NSScreen provides logical dimensions
NSScreen* mainScreen = [NSScreen mainScreen];
if (mainScreen) {
NSRect frame = [mainScreen frame];
m_logicalWidth = (int)frame.size.width;
m_logicalHeight = (int)frame.size.height;
} else {
// 逻辑尺寸必须取自「实际抓屏的那块屏」(CGMainDisplayID)。CGEvent 的鼠标坐标是
// 全局显示坐标(points),而我们发给服务端的是这块屏的编码像素。
// [NSScreen mainScreen] 取的是菜单栏/焦点窗口所在屏:合盖外接显示器时它仍可能是
// 已停用的内置屏(例如 13" MacBook Air 的 1470x956),与抓屏的外置屏(1280x1024)
// 不是同一块屏。用错尺寸会让每个注入点变成 p * (logical / encode),表现为从左上角
// 起线性增长、且 x/y 各轴独立的鼠标偏移(见 ScreenHandler::OnReceive 的换算)。
CGRect bounds = CGDisplayBounds(m_displayID);
m_logicalWidth = (int)(bounds.size.width + 0.5);
m_logicalHeight = (int)(bounds.size.height + 0.5);
if (m_logicalWidth <= 0 || m_logicalHeight <= 0) {
// Fallback: use physical dimensions
m_logicalWidth = m_width;
m_logicalHeight = m_height;
+33 -4
View File
@@ -23,6 +23,7 @@
#include "../common/client_auth_state.h"
#include "../common/posix_net_helpers.h"
#include "../common/sub_conn_thread.h"
#include "../common/ClientLogHandler.h"
#import "Permissions.h"
#import "ScreenHandler.h"
#import "InputHandler.h"
@@ -271,11 +272,14 @@ static std::string normalizeExePathLower(const std::string& path)
// Get screen resolution
static std::string getScreenResolution()
{
NSScreen* mainScreen = [NSScreen mainScreen];
if (mainScreen) {
NSRect frame = [mainScreen frame];
// 用主显示器的全局显示坐标(points),与 CGEvent 注入坐标同一空间,也和
// ScreenHandler 抓屏所用的 CGMainDisplayID 保持一致。
// [NSScreen mainScreen] 在合盖接外置显示器时仍可能返回内置屏(如 1470x956),
// 上报后会让服务端以为主机分辨率是内置屏尺寸。
CGRect bounds = CGDisplayBounds(CGMainDisplayID());
if (bounds.size.width > 0 && bounds.size.height > 0) {
return [NSString stringWithFormat:@"1:%dx%d",
(int)frame.size.width, (int)frame.size.height].UTF8String;
(int)(bounds.size.width + 0.5), (int)(bounds.size.height + 0.5)].UTF8String;
}
return "0:0x0";
}
@@ -718,6 +722,19 @@ void* FileManagerworkingThread(void* /*param*/)
return NULL;
}
// 日志上报(对应 Windows 端 CClientLogManager):子连接建立即发首包全量。
// 服务端取走首包后会关掉这条子连接,发完等连接断开即可。
void* ClientLogworkingThread(void* /*param*/)
{
RunSubConnThread<ClientLogHandler>(
"ClientLogworkingThread",
[](IOCPClient* c) { return std::unique_ptr<ClientLogHandler>(new ClientLogHandler(c)); },
[](IOCPClient* c, ClientLogHandler*) {
Mprintf(">>> ClientLogworkingThread [%p] Send: TOKEN_REPORT_LOG\n", c);
});
return NULL;
}
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer == nullptr || ulLength == 0)
@@ -744,6 +761,11 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
std::thread(FileManagerworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user);
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
// 与 Windows 端一致:回日志必须开子连接(服务端取走首包后 CancelIO 关的是
// 子连接;若回在主连接上,被关掉的就是主连接本身)。
std::thread(ClientLogworkingThread, nullptr).detach();
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
} else if (szBuffer[0] == COMMAND_C2C_PREPARE) {
// C2C 准备接收通知
FileTransferV2::HandleC2CPrepare(szBuffer, ulLength, nullptr);
@@ -920,6 +942,13 @@ int main(int argc, const char* argv[])
// Create client
auto ClientObject = std::make_unique<IOCPClient>(g_bExit, false);
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
// 同 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);
}
// Main event loop
NSLog(@"Starting main loop...");
Binary file not shown.
File diff suppressed because it is too large. Load diff
+53 -9
View File
@@ -43,18 +43,30 @@ typedef struct DllInfo {
typedef struct FileTransformCmd {
CLock Lock;
std::map<std::string, uint64_t> CmdTime;
void PutCmd(const std::string& str)
// md5 -> (目标客户端源 IP, 登记时间)。源 IP 绑定:只有与 PutCmd 登记时同源 IP 的
// 子连接才能消费该 md5,防止异常客户端在别的 IP 上冒用文件传输指令。
std::map<std::string, std::pair<std::string, uint64_t>> CmdInfo;
void PutCmd(const std::string& str, const std::string& peerIP)
{
Lock.Lock();
CmdTime[str] = time(0);
CmdInfo[str] = std::make_pair(peerIP, (uint64_t)time(0));
Lock.Unlock();
}
bool PopCmd(const std::string& str, int timeoutSec = 10)
bool PopCmd(const std::string& str, const std::string& peerIP, int timeoutSec = 10)
{
Lock.Lock();
bool valid = CmdTime.find(str) != CmdTime.end() && time(0) - CmdTime[str] < timeoutSec;
CmdTime.erase(str);
auto it = CmdInfo.find(str);
if (it == CmdInfo.end()) {
Lock.Unlock();
return false;
}
uint64_t now = (uint64_t)time(0);
bool expired = now - it->second.second >= (uint64_t)timeoutSec;
bool matched = it->second.first == peerIP;
// 过期或成功消费才删除;源 IP 不匹配(冒用)保留,让合法客户端在 TTL 内仍可取回。
bool valid = !expired && matched;
if (expired || valid)
CmdInfo.erase(it);
Lock.Unlock();
return valid;
}
@@ -109,6 +121,13 @@ bool SupportsFileTransferV2(context* ctx);
// 找不到主连接或老客户端:默认 CP936(覆盖 95% 简中/英语 ASCII 老客户端)。
UINT GetClientEncoding(context* ctx);
// 获取客户端「进程名/路径」编码 (CP_UTF8 或 936)。
// 与 GetClientEncoding 不同:Windows 客户端的进程名/路径由 A 接口
// (Process32FirstA / QueryFullProcessImageNameA 等)生成,恒为客户端系统
// ANSI(简中=GBK/936),不随 CLIENT_CAP_UTF8 转 UTF-8;仅 LNX/MAC 走 UTF-8。
// 与 McpServer::BuildListProcesses 的判定保持一致。
UINT GetProcessListEncoding(context* ctx);
// 服务端待续传的传输信息
struct PendingTransferV2 {
uint64_t clientID;
@@ -216,6 +235,9 @@ public:
VOID AddList(CString strIP, CString strAddr, CString strPCName, CString strOS, CString strCPU, CString strVideo, CString strPing,
CString ver, CString startTime, std::vector<std::string>& v, CONTEXT_OBJECT* ContextObject);
VOID ShowMessage(CString strType, CString strMsg);
// 消息中含 UTF-8(如地理位置)时使用:消息列经 LVM_SETITEMTEXTW 写宽字符串,
// 避免 UTF-8 在 ANSI 日志列表里被按 GBK 显示成乱码(Böblingen → B枚blingen)。
VOID ShowMessageW(const CStringW& strType, const CStringW& strMsg);
VOID CreatStatusBar();
VOID CreateToolBar();
VOID CreateNotifyBar();
@@ -351,9 +373,8 @@ public:
// ===== 文件传输速度配置([transfer] 节,ChunkKb / DurationMs) =====
// 主控端 UI 偏好,持久化走 THIS_CFG。上传方向读 THIS_CFG(重启主控端生效);
// 下载方向经 CMD_FILE_SPEED 下发到被控端(下次打开文件管理/远程桌面会话生效)。
// 下载方向随 MasterSettings 下发(新连接登录即收到,改档后立即推送给在线客户端)。
void OnFileTransferSpeed(); // 高级→文件传输速度
void SendFileSpeedCommand(); // 把当前档位经主连接下发给被控端
void SendThumbnailRequest(class context* ctx);// 发一次缩略图请求
void CacheThumbnail(uint64_t clientID, const BYTE* jpeg, size_t bytes);
void ClearThumbnailCacheEntry(uint64_t clientID);
@@ -391,6 +412,16 @@ public:
std::string m_v2KeyPath; // V2 密钥文件路径
void RebuildFilteredIndices(); // 重建过滤索引
context* GetContextByListIndex(int iItem); // 根据列表索引获取 context(考虑分组过滤)
// 按 clientID 把选中项恢复到它们当前所在的行号。虚拟列表的选中项是按行号保存的,
// 而 m_HostList 会随主机上下线重排,同一个行号重排后往往指向另一台主机。
void RestoreSelectionByIds(const std::vector<uint64_t>& ids);
// 本次命令的目标主机:右键菜单派发期间(m_CtxMenuTargets 非空)以 clientID 快照为准,
// 否则取列表当前选中项。调用方需持有 m_cs。
std::vector<context*> ResolveCommandTargets();
// 右键菜单发起时锁定的目标主机(clientID 快照)。菜单弹出到命令真正执行之间还会插入
// MessageBoxL / DoModal 等模态框,模态循环里 WM_TIMER 照常派发、列表照常重排,命令
// 处理函数若在那之后再按行号读选中项,就会读到另一台主机。只在 UI 线程访问。
std::vector<uint64_t> m_CtxMenuTargets;
// 启发式 ID 迁移:新客户端首次上线时,按 (ComputerName, ProgramPath) 在 m_ClientMap
// 里找老条目,若唯一匹配则把元数据(备注/位置/级别/授权)拷贝到 newId。
@@ -432,7 +463,7 @@ public:
bool IsDllRequestLimited(const std::string& ip);
void RecordDllRequest(const std::string& ip);
CMenu m_MainMenu;
CBitmap m_bmOnline[69];
CBitmap m_bmOnline[76];
uint64_t m_superID;
std::map<HWND, CDialogBase *> m_RemoteWnds;
FileTransformCmd m_CmdList;
@@ -522,6 +553,13 @@ public:
afx_msg void OnExperimentFileManager();
afx_msg void OnExperimentPrivateScreen();
afx_msg void OnExperimentDrawingBoard();
afx_msg void OnExperimentTlsEnable();
afx_msg void OnExperimentTlsDisable();
// 协议切换(在线列表右键菜单,与「实验功能」平级):直连 TCP / WS / WSS
afx_msg void OnProtoSwitchTcp();
afx_msg void OnProtoSwitchWs();
afx_msg void OnProtoSwitchWss();
VOID SwitchSelectedProtocol(UINT nID);
afx_msg void OnOnlineDelete();
afx_msg void OnOnlineUpdate();
afx_msg void OnAbout();
@@ -598,6 +636,9 @@ public:
void ChooseScreenPreviewParams(context* ctx, WORD& maxWidth, BYTE& jpegQuality) const;
// 发起预览请求;reqId 应与 m_PreviewReqId 同步
void SendScreenPreviewRequest(context* ctx, WORD reqId, WORD maxWidth, BYTE jpegQuality);
// 预览响应规范化:Linux 客户端回原始 BGRA(SCREEN_PREVIEW_FMT_BGRX),在 IO 线程入口
// 统一转成 JPEG,下游(浮窗/列表缩略图/MCP)只处理 JPEG。返回 false 表示畸形包,应丢弃。
static bool NormalizeScreenPreviewPacket(std::vector<BYTE>& pkt);
// 收到 TOKEN_SCREEN_PREVIEW_RSP(在主线程处理)
afx_msg LRESULT OnPreviewResponse(WPARAM wParam, LPARAM lParam);
afx_msg void OnOnlineUnauthorize();
@@ -619,6 +660,7 @@ public:
afx_msg void OnMsglogLoginNotify();
afx_msg void OnMsglogBanIP();
afx_msg void OnMsglogUnbanIP();
afx_msg void OnMsglogWhitelistIP();
afx_msg void OnOnlineAddWatch();
afx_msg void OnNMCustomdrawOnline(NMHDR* pNMHDR, LRESULT* pResult);
afx_msg void OnOnlineRunAsAdmin();
@@ -687,6 +729,7 @@ public:
afx_msg void OnCancelShare();
afx_msg void OnWebRemoteControl();
afx_msg void OnMcpSettings();
afx_msg void OnTlsCertificate();
afx_msg void OnConnectionManage();
afx_msg void OnProxyPortAutorun();
afx_msg void OnScreenpreviewLoop();
@@ -697,6 +740,7 @@ public:
afx_msg LRESULT OnSplitterMoved(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnSplitterReleased(WPARAM wParam, LPARAM lParam);
afx_msg void OnCopyClientInfo();
afx_msg void OnOnlineCopyName();
afx_msg void OnOnlineActiveWnd();
afx_msg void OnEnableDevDebug();
afx_msg void OnOnlineClientLog();
+21 -3
View File
@@ -328,7 +328,12 @@
<ClInclude Include="KeyBoardDlg.h" />
<ClInclude Include="LangManager.h" />
<ClInclude Include="McpServer.h" />
<ClInclude Include="McpTlsProxy.h" />
<ClInclude Include="McpChat.h" />
<ClInclude Include="McpInternal.h" />
<ClInclude Include="McpMachine.h" />
<ClInclude Include="McpSettingsDlg.h" />
<ClInclude Include="TlsCertificateDlg.h" />
<ClInclude Include="NetworkDlg.h" />
<ClInclude Include="NotifyConfig.h" />
<ClInclude Include="NotifyManager.h" />
@@ -339,17 +344,16 @@
<ClInclude Include="PluginSettingsDlg.h" />
<ClInclude Include="PreviewTipWnd.h" />
<ClInclude Include="TriggerSettingsDlg.h" />
<ClInclude Include="proxy\HPSocket.h" />
<ClInclude Include="proxy\HPTypeDef.h" />
<ClInclude Include="proxy\ProxyConnectServer.h" />
<ClInclude Include="proxy\ProxyMapDlg.h" />
<ClInclude Include="proxy\SocketInterface.h" />
<ClInclude Include="pwd_gen.h" />
<ClInclude Include="RegisterDlg.h" />
<ClInclude Include="Resource.h" />
<ClInclude Include="ScreenSpyDlg.h" />
<ClInclude Include="SearchBarDlg.h" />
<ClInclude Include="Server.h" />
<ClInclude Include="ServerTlsSession.h" />
<ClInclude Include="ServerWsSession.h" />
<ClInclude Include="ServicesDlg.h" />
<ClInclude Include="ConnectionsDlg.h" />
<ClInclude Include="SettingDlg.h" />
@@ -395,7 +399,12 @@
<ClCompile Include="WebService.cpp" />
<ClCompile Include="HostJson.cpp" />
<ClCompile Include="McpServer.cpp" />
<ClCompile Include="McpTlsProxy.cpp" />
<ClCompile Include="McpChat.cpp" />
<ClCompile Include="McpInternal.cpp" />
<ClCompile Include="McpMachine.cpp" />
<ClCompile Include="McpSettingsDlg.cpp" />
<ClCompile Include="TlsCertificateDlg.cpp" />
<ClCompile Include="..\..\client\MemoryModule.c">
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Release|x64'">NotUsing</PrecompiledHeader>
<PrecompiledHeader Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">NotUsing</PrecompiledHeader>
@@ -457,6 +466,8 @@
<ClCompile Include="ZstaPickerDlg.cpp" />
<ClCompile Include="IOCPKCPServer.cpp" />
<ClCompile Include="IOCPServer.cpp" />
<ClCompile Include="ServerTlsSession.cpp" />
<ClCompile Include="ServerWsSession.cpp" />
<ClCompile Include="IOCPUDPServer.cpp" />
<ClCompile Include="IPHistoryDlg.cpp" />
<ClCompile Include="KeyBoardDlg.cpp" />
@@ -526,8 +537,12 @@
<Image Include="res\Bitmap\BrowseWnd.bmp" />
<Image Include="res\Bitmap\CancelShare.bmp" />
<Image Include="res\Bitmap\ClientLog.bmp" />
<Image Include="res\Bitmap\CopyName.bmp" />
<Image Include="res\Bitmap\DesktopQuality.bmp" />
<Image Include="res\Bitmap\Disclaimer.bmp" />
<Image Include="res\Bitmap\DrawingBoard.bmp" />
<Image Include="res\Bitmap\FileManager.bmp" />
<Image Include="res\Bitmap\FileSpeed.bmp" />
<Image Include="res\Bitmap\Forbidden.bmp" />
<Image Include="res\bitmap\compress.bmp" />
<Image Include="res\Bitmap\Copy.bmp" />
@@ -563,6 +578,7 @@
<Image Include="res\Bitmap\PluginConfig.bmp" />
<Image Include="res\Bitmap\PortProxyAuto.bmp" />
<Image Include="res\Bitmap\PortProxyStd.bmp" />
<Image Include="res\Bitmap\PreviewQuality.bmp" />
<Image Include="res\Bitmap\PrivacyShield.bmp" />
<Image Include="res\Bitmap\PrivateScreen.bmp" />
<Image Include="res\Bitmap\proxy.bmp" />
@@ -576,6 +592,8 @@
<Image Include="res\Bitmap\Shutdown.bmp" />
<Image Include="res\Bitmap\Snapshot.bmp" />
<Image Include="res\Bitmap\SpeedDesktop.bmp" />
<Image Include="res\Bitmap\TlsDisable.bmp" />
<Image Include="res\Bitmap\TlsEnable.bmp" />
<Image Include="res\Bitmap\Trial.bmp" />
<Image Include="res\Bitmap\Trigger.bmp" />
<Image Include="res\Bitmap\unauthorize.bmp" />
@@ -21,6 +21,9 @@
<ClCompile Include="InputDlg.cpp" />
<ClCompile Include="ZstaPickerDlg.cpp" />
<ClCompile Include="IOCPServer.cpp" />
<ClCompile Include="ServerTlsSession.cpp" />
<ClCompile Include="ServerWsSession.cpp" />
<ClCompile Include="McpTlsProxy.cpp" />
<ClCompile Include="KeyBoardDlg.cpp" />
<ClCompile Include="Loader.c" />
<ClCompile Include="proxy\ProxyConnectServer.cpp" />
@@ -88,7 +91,11 @@
<ClCompile Include="TriggerSettingsDlg.cpp" />
<ClCompile Include="HostJson.cpp" />
<ClCompile Include="McpServer.cpp" />
<ClCompile Include="McpChat.cpp" />
<ClCompile Include="McpInternal.cpp" />
<ClCompile Include="McpMachine.cpp" />
<ClCompile Include="McpSettingsDlg.cpp" />
<ClCompile Include="TlsCertificateDlg.cpp" />
<ClCompile Include="CClientLog.cpp" />
<ClCompile Include="CActivityDialog.cpp" />
<ClCompile Include="LogSearchBar.cpp" />
@@ -119,11 +126,8 @@
<ClInclude Include="ZstaPickerDlg.h" />
<ClInclude Include="IOCPServer.h" />
<ClInclude Include="KeyBoardDlg.h" />
<ClInclude Include="proxy\HPSocket.h" />
<ClInclude Include="proxy\HPTypeDef.h" />
<ClInclude Include="proxy\ProxyConnectServer.h" />
<ClInclude Include="proxy\ProxyMapDlg.h" />
<ClInclude Include="proxy\SocketInterface.h" />
<ClInclude Include="pwd_gen.h" />
<ClInclude Include="RegisterDlg.h" />
<ClInclude Include="Resource.h" />
@@ -155,6 +159,9 @@
</ClInclude>
<ClInclude Include="IOCPUDPServer.h" />
<ClInclude Include="Server.h" />
<ClInclude Include="ServerTlsSession.h" />
<ClInclude Include="ServerWsSession.h" />
<ClInclude Include="McpTlsProxy.h" />
<ClInclude Include="CDrawingBoard.h" />
<ClInclude Include="IOCPKCPServer.h" />
<ClInclude Include="..\..\common\ikcp.h" />
@@ -200,7 +207,11 @@
<ClInclude Include="PreviewTipWnd.h" />
<ClInclude Include="TriggerSettingsDlg.h" />
<ClInclude Include="McpServer.h" />
<ClInclude Include="McpChat.h" />
<ClInclude Include="McpInternal.h" />
<ClInclude Include="McpMachine.h" />
<ClInclude Include="McpSettingsDlg.h" />
<ClInclude Include="TlsCertificateDlg.h" />
<ClInclude Include="CClientLog.h" />
<ClInclude Include="CActivityDialog.h" />
<ClInclude Include="LogSearchBar.h" />
@@ -355,5 +366,12 @@
<Image Include="res\Bitmap\FileManager.bmp" />
<Image Include="res\Bitmap\PrivacyShield.bmp" />
<Image Include="res\Bitmap\DrawingBoard.bmp" />
<Image Include="res\Bitmap\TlsEnable.bmp" />
<Image Include="res\Bitmap\TlsDisable.bmp" />
<Image Include="res\Bitmap\DesktopQuality.bmp" />
<Image Include="res\Bitmap\PreviewQuality.bmp" />
<Image Include="res\Bitmap\FileSpeed.bmp" />
<Image Include="res\Bitmap\Disclaimer.bmp" />
<Image Include="res\Bitmap\CopyName.bmp" />
</ItemGroup>
</Project>
+17
View File
@@ -337,3 +337,20 @@ VOID CBuffer::CommitWrite(ULONG writtenSize)
m_Ptr += writtenSize;
LeaveCriticalSection(&m_cs);
}
// 截断缓冲区到指定有效长度(仅回退写指针,不移动/释放底层内存)。有效长度指「当前读取
// 位置之后的字节数」,与 GetBufferLength 一致;请求值超出现有有效长度时收敛到现有长度。
VOID CBuffer::TruncateBuffer(ULONG effectiveLen)
{
EnterCriticalSection(&m_cs);
if (m_Base == NULL) {
LeaveCriticalSection(&m_cs);
return;
}
ULONG totalDataLen = (ULONG)(m_Ptr - m_Base);
ULONG cur = (totalDataLen > m_ulReadOffset) ? (totalDataLen - m_ulReadOffset) : 0;
if (effectiveLen > cur)
effectiveLen = cur;
m_Ptr = m_Base + m_ulReadOffset + effectiveLen;
LeaveCriticalSection(&m_cs);
}
Loaded 100 of 214 files, more files were not shown because too many files have changed in this diff. Show more