11 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
38 changed files with 1714 additions and 394 deletions

No files matched your search

+35
View File
@@ -378,6 +378,41 @@ 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**
+35
View File
@@ -378,6 +378,41 @@ 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**
+35
View File
@@ -378,6 +378,41 @@ 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**
+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()) {
+26 -14
View File
@@ -373,6 +373,11 @@ DWORD WINAPI AutoRun(LPVOID param)
{
do {
TestRun(NULL, 0);
// 旧工作线程还没退完时 TestRun 会立刻返回(此时连日志都不打,见其内部的
// SetServer 返回值判断),不睡就会满速空转、白占一个核且毫无提示。
// 只在真会空转的条件下睡,正常重启路径零延迟。
if (S_SERVER_EXIT == g_MyApp.g_bExit && g_MyApp.IsThreadRun())
Sleep(20);
} while (S_SERVER_EXIT == g_MyApp.g_bExit);
if (g_MyApp.g_Connection->ClientType() == CLIENT_TYPE_SHELLCODE) {
@@ -415,8 +420,11 @@ extern "C" __declspec(dllexport) void TestRun(char* szServerIP,int uPort)
ClientApp& app(g_MyApp);
CONNECT_ADDRESS& settings(*(app.g_Connection));
if (app.IsThreadRun()) {
settings.SetServer(szServerIP, uPort);
Mprintf("TestRun SetServer[%s:%d]\n", szServerIP ? szServerIP : "", uPort);
// 只在地址真的变了才记日志。主控端重启后,加载器和 AutoRun 会反复调用本函数
// 直到旧工作线程退完,每次都打一行会把客户端 1000 行环形日志冲光。
// SetServer 返回 false 表示地址没变,同时也涵盖 TestRun(NULL, 0)(空地址直接返回)。
if (settings.SetServer(szServerIP, uPort))
Mprintf("TestRun SetServer[%s:%d]\n", szServerIP ? szServerIP : "", uPort);
return;
}
app.SetThreadRun(TRUE);
@@ -620,10 +628,10 @@ void ClearAllProtoSwitchKeys(iniFile& cfg)
cfg.SetStr("settings", k, "");
}
// 在每次建连前应用入口覆盖;返回 true 表示本次用的覆盖入口。
// 覆盖撤销(还原命令 / 自动回退)→ 回到安装时的直连入口;
// 新入口超时(entry_try_at 未清零)→ 回退到切换前的入口并撤销覆盖。
bool ApplyProtoSwitch(iniFile& cfg, CONNECT_ADDRESS& s)
// 在每次建连前应用入口覆盖(就地改写 s,并落盘必要的状态)。没有返回值:它既会改 s 也会
// 改配置,用「是否用了覆盖入口」当返回值会与副作用矛盾——自动回退分支照样改写了 settings,
// 却没法用一个 bool 表达,调用方也确实不需要这个信息。
void ApplyProtoSwitch(iniFile& cfg, CONNECT_ADDRESS& s)
{
if (!g_bootCaptured) {
g_bootCaptured = true;
@@ -637,7 +645,7 @@ bool ApplyProtoSwitch(iniFile& cfg, CONNECT_ADDRESS& s)
ClearAllProtoSwitchKeys(cfg);
Mprintf("[proto-switch] injected entry changed (%s -> %s), cleared stale switch state\n",
baseHost.c_str(), g_bootHost.c_str());
return false;
return;
}
const std::string proto = cfg.GetStr("settings", "proto_override");
@@ -652,13 +660,13 @@ bool ApplyProtoSwitch(iniFile& cfg, CONNECT_ADDRESS& s)
s.protoType = (char)baseProto;
Mprintf("[proto-switch] restored direct entry %s:%d proto=%d\n", host.c_str(), port, baseProto);
}
return false;
return;
}
const int p = atoi(proto.c_str());
if (!IsSwitchableProto(p)) {
ClearAllProtoSwitchKeys(cfg); // 坏值:撤销覆盖,按注入配置走
return false;
return;
}
// 自动回退:切换后一直没登录成功(entry_try_at 由服务端下发时写入,登录成功后清零)
@@ -686,7 +694,7 @@ bool ApplyProtoSwitch(iniFile& cfg, CONNECT_ADDRESS& s)
Mprintf("[proto-switch] new entry unreachable and no previous entry, override dropped\n");
}
cfg.SetStr("settings", "entry_try_at", "0");
return false;
return;
}
const std::string host = cfg.GetStr("settings", "entry_host");
@@ -694,7 +702,6 @@ bool ApplyProtoSwitch(iniFile& cfg, CONNECT_ADDRESS& s)
if (!host.empty() && port > 0)
s.SetServer(host.c_str(), port);
s.protoType = (char)p;
return true;
}
// 新入口登录成功:撤销自动回退计时。入口覆盖本身保留——后续重连一直用它。
@@ -816,13 +823,18 @@ DWORD WINAPI StartClient(LPVOID lParam)
while (ClientObject->IsRunning() && ClientObject->IsConnected() && !ClientObject->SendLoginInfo(login))
WAIT_n(app.m_bIsRunning(&app), 5 + time(0)%10, 200);
WAIT_n(app.m_bIsRunning(&app)&& ClientObject->IsRunning() && ClientObject->IsConnected(), 10, 200);
// 协议切换:新入口已经打通(登录包发出且连接仍在),撤销自动回退计时
if (ClientObject->IsConnected())
ConfirmProtoSwitch(cfg);
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);
+49 -1
View File
@@ -391,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);
}
@@ -467,10 +470,41 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
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。
const int protoType = m_conn ? (int)(unsigned char)m_conn->protoType : -1;
// 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;
@@ -550,6 +584,20 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
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;
Mprintf("连接服务端成功: %s:%d.\n", m_sCurIP.c_str(), (int)port);
+22 -2
View File
@@ -39,6 +39,7 @@
#endif
#include "IOCPBase.h"
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <chrono>
@@ -207,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;
@@ -289,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
@@ -342,14 +357,19 @@ protected:
// WebSocket 传输(PROTO_WS / PROTO_WSS):ConnectServer 里握手成功时置位,
// Disconnect 时清除。与 m_useTls 一样按连接锁定,Send/Recv 不再现查 protoType。
WsChannel m_ws;
bool m_useWs = false;
// 收发分处两个线程:连接线程写、接收/发送线程读。形式上必须是原子量(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 会话(或反过来),白白制造协议错误。
bool m_useTls = false;
std::atomic<bool> m_useTls{false};
#endif
BOOL m_bWorkThread;
HANDLE m_hWorkThread;
+18 -2
View File
@@ -944,10 +944,21 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
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))
Mprintf("[proto-switch] trust anchor reload failed: %s\n", err.c_str());
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) {
@@ -1231,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()) {
+1 -11
View File
@@ -125,17 +125,7 @@ private:
bool IsWorkstationLocked()
{
HDESK hInput = OpenInputDesktop(0, FALSE, GENERIC_READ);
// 如果无法打开桌面,可能是因为桌面已经切换到 Winlogon
if (!hInput) return true;
char name[256] = {0};
DWORD needed;
bool isLocked = false;
if (GetUserObjectInformationA(hInput, UOI_NAME, name, sizeof(name), &needed)) {
isLocked = (_stricmp(name, "Winlogon") == 0);
}
CloseDesktop(hInput);
return isLocked;
return ::IsWorkstationLocked();
}
};
+16
View File
@@ -156,6 +156,22 @@ HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess)
return hInputDesktop;
}
bool IsWorkstationLocked()
{
HDESK hInput = OpenInputDesktop(0, FALSE, GENERIC_READ);
// 打不开输入桌面,通常就是已经切到 Winlogon(锁屏)
if (!hInput) return true;
char name[256] = { 0 };
DWORD needed = 0;
bool isLocked = false;
if (GetUserObjectInformationA(hInput, UOI_NAME, name, sizeof(name), &needed)) {
isLocked = (_stricmp(name, "Winlogon") == 0);
}
CloseDesktop(hInput);
return isLocked;
}
// 返回新桌面句柄,如果没有变化返回NULL
HDESK IsDesktopChanged(HDESK currentDesk, DWORD accessRights)
{
+4
View File
@@ -15,6 +15,10 @@
HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess = 0);
// 工作站是否已锁屏(输入桌面切到 Winlogon)。锁屏时 DXGI 桌面复制在部分环境会卡在
// 初始化里不返回,抓屏初始化需要据此提前走 GDI。
bool IsWorkstationLocked();
HDESK IsDesktopChanged(HDESK currentDesk, DWORD accessRights);
bool SwitchToDesktopIfChanged(HDESK& currentDesk, DWORD accessRights);
+18
View File
@@ -866,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)
{
+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;
}
};
+34 -1
View File
@@ -467,6 +467,26 @@ static BOOL RestoreConsoleSession()
return FALSE;
}
// 进程所在会话是否已断开(RDP 断开后没有显示输出)。
// 这种会话里 DXGI 桌面复制拿不到帧,部分驱动上连初始化都不返回,必须走 GDI。
// Session 0 是服务会话,没有「断开」这个概念,直接返回 FALSE。
static BOOL IsCurrentSessionDisconnected()
{
DWORD sessionId = 0;
if (!ProcessIdToSessionId(GetCurrentProcessId(), &sessionId) || sessionId == 0)
return FALSE;
WTS_CONNECTSTATE_CLASS* pState = NULL;
DWORD bytes = 0;
if (!WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSConnectState,
(LPSTR*)&pState, &bytes) || !pState) {
return FALSE;
}
const BOOL disconnected = (*pState == WTSDisconnected);
WTSFreeMemory(pState);
return disconnected;
}
void CScreenManager::InitScreenSpy()
{
int DXGI = USING_GDI;
@@ -551,7 +571,20 @@ void CScreenManager::InitScreenSpy()
}
}
SAFE_DELETE(m_ScreenSpyObject);
if ((USING_DXGI == DXGI && IsWindows8orHigher())) {
// 锁屏(输入桌面切到 Winlogon)或会话已断开时,当前会话没有可用的交互桌面:
// DXGI 桌面复制拿不到帧,部分环境(无 GPU 的 Server、断开/锁定的 RDP 会话)
// 甚至会在初始化里卡死不返回 —— 那样 InitScreenSpy 走不完,WorkThreadProc 里
// 紧随其后的 SendBitMapInfo() 永远发不出去,主控端一直等不到 TOKEN_BITMAPINFO,
// 连远程桌面窗口都不会弹。GDI 的 BitBlt 不依赖桌面变化,这些情况下照样能抓,
// 所以直接走 GDI。
const BOOL locked = IsWorkstationLocked();
const BOOL disconnected = IsCurrentSessionDisconnected();
const bool noDesktop = (USING_DXGI == DXGI && (locked || disconnected));
if (noDesktop) {
Mprintf("CScreenManager: no interactive desktop (locked=%d, disconnected=%d), use GDI instead of DXGI\n",
(int)locked, (int)disconnected);
}
if ((USING_DXGI == DXGI && IsWindows8orHigher() && !noDesktop)) {
m_isGDI = FALSE;
auto s = new ScreenCapturerDXGI(algo, DEFAULT_GOP, all, m_ScreenSettings.EncodeLevel, rect, switchScreen);
if (s->IsInitSucceed()) {
+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;
+2 -2
View File
@@ -103,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
//
VS_VERSION_INFO VERSIONINFO
FILEVERSION 1,0,4,1
FILEVERSION 1,0,4,2
PRODUCTVERSION 1,0,0,1
FILEFLAGSMASK 0x3fL
#ifdef _DEBUG
@@ -121,7 +121,7 @@ BEGIN
BEGIN
VALUE "CompanyName", "FUCK THE UNIVERSE"
VALUE "FileDescription", "A GHOST"
VALUE "FileVersion", "1.0.4.1"
VALUE "FileVersion", "1.0.4.2"
VALUE "InternalName", "ServerDll.dll"
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
VALUE "OriginalFilename", "ServerDll.dll"
BIN
View File
Binary file not shown.
+2
View File
@@ -305,6 +305,8 @@ bool TlsChannel::VerifyServerCert()
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);
+55 -9
View File
@@ -18,6 +18,9 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include <ctime>
#include <atomic>
#include <mutex>
#include <string>
#include <vector>
@@ -48,13 +51,12 @@ public:
void SetTls(TlsChannel* tls) { m_tls = tls; }
#endif
// 每次连接前清理上一轮的帧状态。
// 让 Recv/Send 立刻失效。**可由任意线程调用**(Disconnect 可能来自心跳/命令线程,
// 不只是接收线程),因此这里只碰原子量;帧解析状态留给 ResetFrames()——它只在
// Handshake 里、接收线程还没起来时清。
void Reset()
{
m_ready = false;
m_remaining = 0;
m_masked = false;
m_maskPos = 0;
}
bool IsReady() const { return m_ready; }
@@ -64,7 +66,7 @@ public:
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());
@@ -254,6 +256,8 @@ private:
}
// 读帧头(含扩展长度与掩码键)。服务端发来的帧不应带掩码,带了也照样解。
static const long long kMaxFramePayload = 256LL * 1024 * 1024;
bool ReadHeader(SOCKET sock, unsigned char& opcode, long long& frameLen)
{
unsigned char h[2] = { 0, 0 };
@@ -281,6 +285,12 @@ private:
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;
@@ -320,13 +330,18 @@ private:
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)(rand() & 0xFF);
mask[i] = (unsigned char)((r >> (8 * i)) & 0xFF);
memcpy(hdr + hn, mask, 4);
hn += 4;
std::lock_guard<std::mutex> lock(m_sendMtx);
// 复用同一个缓冲区:发送热路径上每帧不再分配一个新 vector。
m_frame.resize((size_t)hn + (size_t)len);
char* frame = m_frame.data();
@@ -341,13 +356,44 @@ private:
#ifdef YAMA_TLS_CHANNEL
TlsChannel* m_tls = NULL; // WSS 时指向 IOCPClient 的 TLS 会话
#endif
bool m_ready = false;
// 会话是否就绪。收、发分处两个线程,且 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 };
+7
View File
@@ -501,6 +501,13 @@ BOOL Run(const char* argv1, int argv2, const std::string &runCmd)
// 卸载 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);
+85 -6
View File
@@ -43,6 +43,9 @@ XOR、zstd、HTTP 伪装层)。WS 与 HTTP 伪装的 `MaskType` 互斥:选 W
> 兼容性:`PROTO_HTTPS` 从 5 移到 7。它在 `NewNetClient` 里本来就被直接拒绝、生成界面也从未
> 提供,因此不存在已发布客户端带 5 号协议的情况。
>
> 但这是**协议号复用**:从此任何历史落盘 / 历史配置里的 `proto=5` 一律按 `PROTO_WS` 解释。
> 老客户端与老服务端之间若曾有 `5` 的任何含义,都会在这次升级后变成 WS。
## 3. 客户端实现
@@ -65,6 +68,22 @@ XOR、zstd、HTTP 伪装层)。WS 与 HTTP 伪装的 `MaskType` 互斥:选 W
`m_useTls` 之前判 `m_useWs`;`ConnectServer` 在 socket 选项之后、`m_bConnected = TRUE` 之前
完成 `TLS 握手 → WS 握手`,`Disconnect` 清 `m_useWs` 并 `m_ws.Reset()`。
- 握手超时:`connect()` 之后、TLS/WS 握手之前给 socket 设 **15 s** `SO_RCVTIMEO`/`SO_SNDTIMEO`,
握手结束(成功路径)立刻清零。`WsChannel::Handshake` 是同步逐字节读 101 响应的;没有这道
保护时,对端接受 TCP 却不回数据(反代上游黑洞)会让 `StartClient` 的重连循环永久停摆。
服务端两个握手线程用的是同一个 15 s。
- `m_useWs` / `m_useTls` / `WsChannel::m_ready` 均为 `std::atomic<bool>`:写的一方是连接线程,
读的一方是接收/发送线程(`Disconnect` 也可能从接收线程侧清)。
- 帧掩码由 `WsChannel` 私有的 xorshift64 在 `m_sendMtx` **内**生成:不能用全局 `rand()`
——`HttpMask` 的构造函数里有 `srand(time(nullptr))`,会在同进程内重置全局序列,而收、发两个
线程都会写帧。
- 不校验 `Sec-WebSocket-Accept`(设计上由 TLS + 隧道内登录承担)。明文 `PROTO_WS` 下这意味着
中间人可以伪造 101 接管字节流——这正是「裸 WS 只适合内网」的另一半理由。
- 没有 `conn` 的构造路径(Linux / macOS / Android 的 `main` 都是 `new IOCPClient(exit, false)`)
拿不到外壳注入的 `CONNECT_ADDRESS`,协议由 `IOCPClient::SetDefaultProto()` 显式给出;
三个平台的 `main` 都在进入重连循环前调一次。不调则保持 `-1`、按明文直连——那正是
「配置成 WS 却毫无反应」的来源,所以这里留了一行日志便于排查。
### 3.1 信任模型:不换锚,靠 SNI 分流
客户端证书校验仍是**钉死信任锚**(Windows:`CertCreateCertificateChainEngine` + `hExclusiveRoot`
@@ -182,7 +201,8 @@ WS 叠在同一层状态机之上,**与 TLS 是分层而不是并列**(`wss`
- 状态机:`ServerWsState { WS_Undecided → WS_Handshaking → WS_Ready | WS_None }` 与既有的
`ServerTlsState` 并存;`CONTEXT_OBJECT` 复用(`InitMember`)时一并复位并释放会话。
- 判定点:**明文的第一段有 ≥6 字节**才开始分类(与 ClientHello 嗅探同一下限),
避免把「请求头还没到齐」误判掉;阈值内的字节攒在 `tlsPreClassify` 里。
避免把「请求头还没到齐」误判掉;阈值内的字节攒在 `wsPreClassify` 里(与 TLS 嗅探的
`tlsPreClassify` 分开,两者服务不同状态机,串行使用但字段不共用)。
- 升级线程与 TLS 握手线程同构:`FIONBIO=0`(该套接字常是非阻塞的,`ioctlsocket` 会以
`WSAEINVAL` 失败),15 s 收发超时,遇 `WSAEWOULDBLOCK` 用 `select` 等可读/可写再试;
线程持有一枚 `IoRefCount`,结束后把 socket 交还 IOCP(`PostRecv`)。升级响应之后同批
@@ -193,7 +213,25 @@ WS 叠在同一层状态机之上,**与 TLS 是分层而不是并列**(`wss`
- 反代真实 IP:**仅当直接对端是回环地址**时才采信 `X-Forwarded-For` 的**最后一段**
(`X-Real-IP` 兜底),且必须是 IP 字面量;结果写回 `PeerName`,在线列表、封禁与
白名单看到的就是设备本身。非回环对端的转发头一律忽略(防伪造)。
- 两段式限流(与 Go 端 `limitDirectPeer` / `handleConnection` 同构):accept 阶段按
`getpeername` 计数——那一次对经反代的连接**没有意义**(反代同机时对端是回环地址,
`IPWhitelist` 对回环恒为 true,黑名单/封禁/计数全部不生效)。升级完成后在
`WsHandshakeThreadProc` 里按**真实设备 IP** 重做一次黑名单 / 封禁检查与计数,超阈值
直接 fail-closed。直连连接(无转发头)只在 accept 阶段计一次,不重复计。
反代**异机**部署时转发头不被采信(见 §8),此时需把反代地址加进白名单,否则所有设备
共用反代 IP 那一个计数桶。
- fail-closed 的两处:握手期间(`wsState == WS_Handshaking`)收到 IORead 直接断开(判断
放在 `OnClientReceiving` 最开头,WSS 下 `tlsState` 已是 `TLS_Ready`,放在 TLS 分支之后
就不生效);`wsState == WS_Ready` 但会话已关时,应用字节**丢弃而不是裸发**,否则对端
解帧错位;同时对该 socket 做一次 `shutdown(SD_BOTH)`,让挂起的 recv 立刻返回 0 字节,
由接收路径走正常的 `-2` 收尾(不在这里直接 `RemoveStaleContext`——调用方往往本身就
持有 `IoRefCount`,自己等自己会超时,且可能把已回收复用的上下文交回给调用者)。
- 既有客户端零影响:非 `GET ` 首包在攒够 6 字节后原样进入 `ParseReceivedData`。
- 收尾一致:`dwTrans == 0`(对端 FIN)在 `TLS_Unclassified` / `TLS_Ready` / `TLS_Plain`
三条分支上都必须 `RemoveStaleContext`。WS 改造把 `TLS_Plain` 的 `ParseReceivedData`
换成 `DispatchPlain` 后,`DispatchPlain` 对空数据返回「已处理」,这个判断一度丢了,
连接会停在 CLOSE_WAIT 直到 keepalive(3 分钟),期间占着 IOCP 上下文、一枚挂起的
`WSARecv` 和限流槽。现已补回。
## 5. nginx 最小改动
@@ -366,11 +404,16 @@ server {
## 8. 限制与非目标
- **MFC 服务端与 Go 服务端都已实现设备端口的 WS 嗅探**,生成界面里的协议选项两边通用;
差别只在细节:MFC 侧不校验 upgrade 路径(`/api/ws` 只是客户端习惯,反代转到哪个路径都行),
也没有每 IP 限流的「直连/反代两段」细分(沿用既有的按连接数计)。
差别只在细节:MFC 侧不校验 upgrade 路径(`/api/ws` 只是客户端习惯,反代转到哪个路径都行)。
每 IP 限流两边都是**两段式**(直连对端 / 反代后的真实设备),见 §4.1 与 §4.2。
- MFC 侧的转发头信任范围是**回环对端**(与 Go 的默认 `TrustedProxies` 一致);反代与服务端
不同机部署时,要么让反代用 Proxy Protocol v2(既有的 `ParseProxyProtocolV2` 会先改
`PeerName`),要么把反代地址加进白名单逻辑——目前的 WS 层不会采信非回环对端的转发头。
`PeerName`),要么把反代地址加进白名单——WS 层不采信非回环对端的转发头。此时限流按
「反代 IP」那一个桶算,**务必把反代地址加进白名单**,否则阈值一响就是全体设备一起被封。
- 试用模式的 WAN 入站检测(`m_bTrialMode && !IsPrivateIPv4Str(clientIP)`)在 accept 时判定,
经反代接入时 `clientIP` 是反代地址(回环或内网),该合规检查会被绕过;转发真实 IP 要到
升级线程里才有。若这是硬性合规要求,需单独评估(本特性未改变这一点,只是让它的漏检更
容易发生)。
- 裸 `PROTO_WS` 是明文,只适合内网或回环(nginx 已在同一台机器上终止 TLS 的情形用 WSS 即可)。
- macOS / Android 客户端没有 TLS 实现,只能选 `PROTO_WS`(明文),走不了 443。
- 经反代接入时地址只应填**一个域名**(多地址取第一个做 Host/SNI)。
@@ -395,8 +438,44 @@ server {
- 客户端落盘(`settings` 下):`proto_override` / `entry_host` / `entry_port` /
`entry_try_at` 为当前覆盖;`base_*` 是首次切换时记下的安装入口(「还原」用它);`prev_*`
是每次切换前的入口(自动回退用它)。重连循环在建连前 `ApplyProtoSwitch` 覆盖入口——位置
在「外壳注入完配置之后、建连之前」,因此换 DLL 也压不回去;登录成功后
`ConfirmProtoSwitch` 把 `entry_try_at` 清零撤销计时。
在「外壳注入完配置之后、建连之前」,因此换 DLL 也压不回去。(该函数返回 `void`:它既写
配置也改 `CONNECT_ADDRESS`,返回值无法表达「部分完成」,早期版本里的 `return false`
只是提前退出,调用方一直忽略它。)
- 撤销自动回退的判据是**登录被接受**,不是「连接建立」。客户端在收到
`CMD_MASTERSETTING` 时把当前连接标记为已登录(服务端只有在把本机加入在线列表之后才下发
它),重连循环每轮心跳都检查一次,命中才 `ConfirmProtoSwitch` 把 `entry_try_at` 清零。
只看 `IsConnected()` 是不够的:那只是 TCP/TLS/WS 握手完成,新入口能建连但登录始终不被
接受(选错后端 / 反代指到别的 WS 服务 / 服务端登录阶段丢弃)时,提前撤销会让自动回退
永久失效,客户端卡在错误入口反复重连。
- 随包下发的信任锚先落盘再 `TlsReload`;**加载失败即放弃本次切换**——回滚 `tls_cert`、
不写 `proto_override`/`entry_*`、不断连,并把失败原因用 `ClientMsg` 回报操作端。否则客户端
会进入 `TlsLoadError()` 的 fail-closed 状态,切过去只是「新入口连不上,等 5 分钟回退」。
- 自动回退:新入口 5 分钟内一直登不上,回到 `prev_*` 并把它改写成新的覆盖(不是清空,否则
下一轮会落进「还原」分支又跳回直连入口)。分享实例(`m_bShared`)忽略该命令——它的入口
由分享方控制。
- `ProtoSwitchPacket::certLen` 不做字节序转换:当前服务端与 Windows 客户端同为小端,无影响;
将来若出现大端平台的客户端,需要补一次 `ntohl`/`htonl`。
## 10. 审查遗留(已知边界,未改动)
以下条目来自 PR 审查,记录在此以免重复讨论。带「已处理」的是复查后**已经改掉**的,
留在这里说明当时的判断,其余评估后保留现状:
- **`GetPeerName(SOCKET)` 只走 `sockaddr_in`(IPv4)**:`ServerWsSession.cpp::IsLoopbackPeer`
里的 `::1` / `::ffff:127.0.0.1` 分支目前是死代码。将来若监听 IPv6,转发头信任也需要跟着
改,否则会静默失效。
- **`tlsPreClassify` 名不副实**:已处理——WS 的 "GET " 前缀缓冲拆成独立的 `wsPreClassify`,
`tlsPreClassify` 回归 ClientHello 嗅探单一职责(两条路径仍按先后串行,互不重叠)。
- **`WsChannel::Reset()` 与接收线程的帧状态**:已处理——`Disconnect()` 可能来自心跳/命令线程,
不只是接收线程,所以 `Reset()` 现在只翻转原子的 `m_ready`;`m_remaining` / `m_masked` /
`m_maskPos` 改由 `ResetFrames()` 清,且只在 `Handshake()` 里(连接线程、接收线程尚未起来)
调用。这样这几个字段始终只有一个线程访问,不用加锁。
- **客户端单帧载荷上限 256 MB**(`WsChannel::kMaxFramePayload`,与 `ServerWsSession` 同值):
超过即按错误断开。没有上限时一个错误长度字段就能把 `m_remaining` 定在天文数字上,
连接「活着但永远收不到新包」。正常业务的最大单包远小于此值。
- **`DispatchPlain` 对明文首包引入「攒够 6 字节再解析」**:这是既有路径的行为变更。当前首包
是登录包(远大于 6 字节),实际无影响;极端情况下(<6 字节的合法首包)会多等一轮收包。
- **客户端不校验 `Sec-WebSocket-Accept`**:见 §3;明文 WS 下中间人可伪造 101,已在 §8 明确
裸 WS 只适合内网。
- **Go `wrapWebSocket` 的 `Peek`**:已改为即使 `ReadTimeout == 0` 也用 `wsHandshakeTimeout`
(10 s,取与 `ReadTimeout` 的较小值)封顶,慢速对端不再能长期占住 goroutine 与限流槽。
BIN
View File
Binary file not shown.
+7
View File
@@ -1379,6 +1379,13 @@ int main(int argc, char* argv[])
std::unique_ptr<IOCPClient> ClientObject(new IOCPClient(g_bExit, false));
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
// 不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议只能显式喂进去:否则哪怕
// g_SETTINGS.protoType 配成 WS/WSS,也会静默按明文 TCP 直连(日志里一个字都没有)。
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (g_SETTINGS.protoType == PROTO_WS || g_SETTINGS.protoType == PROTO_WSS) {
Mprintf("[WS] 按配置的传输协议连接: proto=%d(WSS 需要 TLS 支持,不支持的平台会 fail-closed)\n",
(int)(unsigned char)g_SETTINGS.protoType);
}
g_pMainClient = ClientObject.get(); // 自升级失败回报用
while (!g_bExit) {
clock_t c = clock();
+7
View File
@@ -942,6 +942,13 @@ int main(int argc, const char* argv[])
// Create client
auto ClientObject = std::make_unique<IOCPClient>(g_bExit, false);
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
// 同 Linux:不传 conn 就取不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (g_SETTINGS.protoType == PROTO_WS || g_SETTINGS.protoType == PROTO_WSS) {
Mprintf("[WS] 按配置的传输协议连接: proto=%d(WSS 需要 TLS 支持,不支持的平台会 fail-closed)\n",
(int)(unsigned char)g_SETTINGS.protoType);
}
// Main event loop
NSLog(@"Starting main loop...");
Binary file not shown.
+157 -65
View File
@@ -4797,7 +4797,36 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
// 刷新菜单显示
DrawMenuBar();
SubMenu->TrackPopupMenu(TPM_LEFTALIGN, Point.x, Point.y, this);
// 菜单是模态的,TrackPopupMenu 期间 WM_TIMER 照常派发:这期间只要有主机上下线,
// 列表就会重排(ApplySort/erase),而虚拟列表的选中项是按行号保存的,行号的含义
// 随之改变;命令处理函数又是点击那一刻才按行号解析主机。于是「对 A 主机点的菜单」
// 会落到重排后占据同一行的 B 主机上。这里先按 clientID 记住用户选中的主机,
// 菜单返回后把选中项恢复到这些主机的当前行号,最后才派发命令。
std::vector<uint64_t> selectedIds;
EnterCriticalSection(&m_cs);
POSITION selPos = m_CList_Online.GetFirstSelectedItemPosition();
while (selPos) {
int selItem = m_CList_Online.GetNextSelectedItem(selPos);
context* selCtx = GetContextByListIndex(selItem);
if (selCtx) selectedIds.push_back(selCtx->GetClientID());
}
LeaveCriticalSection(&m_cs);
// TPM_RETURNCMD:由我们自己在恢复选中项之后再派发命令。用 Win32 入口是因为
// CMenu::TrackPopupMenu 的返回值被声明成 BOOL,拿命令 ID 只能靠隐式截断。
UINT cmd = ::TrackPopupMenu(SubMenu->GetSafeHmenu(), TPM_LEFTALIGN | TPM_RETURNCMD,
Point.x, Point.y, 0, GetSafeHwnd(), nullptr);
if (cmd != 0) {
// 恢复选中项只是让界面显示与目标一致;真正的目标是下面这份 clientID 快照。
// 处理函数里往往还要先弹确认框/输入框,模态期间列表会再重排一次,所以不能让
// 处理函数回头按行号读选中项。保存外层值是为了应对嵌套弹出的菜单。
RestoreSelectionByIds(selectedIds);
std::vector<uint64_t> outer = std::move(m_CtxMenuTargets);
m_CtxMenuTargets = selectedIds;
SendMessage(WM_COMMAND, (WPARAM)cmd, 0);
m_CtxMenuTargets = std::move(outer);
}
*pResult = 0;
}
@@ -4911,11 +4940,8 @@ VOID CMy2015RemoteDlg::SwitchSelectedProtocol(UINT nID)
// 选中主机的能力校验:老客户端不认识 COMMAND_SET_PROTO,收到只会丢弃。
int selected = 0, unsupported = 0;
EnterCriticalSection(&m_cs);
POSITION pos = m_CList_Online.GetFirstSelectedItemPosition();
while (pos) {
int item = m_CList_Online.GetNextSelectedItem(pos);
context* ctx = GetContextByListIndex(item);
if (!ctx || !ctx->IsLogin()) continue;
for (context* ctx : ResolveCommandTargets()) {
if (!ctx->IsLogin()) continue;
++selected;
if (!ctx->SupportsProtoSwitch()) ++unsupported;
}
@@ -4933,7 +4959,9 @@ VOID CMy2015RemoteDlg::SwitchSelectedProtocol(UINT nID)
std::string certPem;
if (!restore) {
CInputDialog dlg(this);
dlg.Init(_TR("协议切换"), _TR("请输入反向代理入口(域名:端口,例如 ws.example.com:443):"));
// 提示语只能用关键信息:IDC_STATIC_INPUT_PROMPT 宽 81 个对话框单位(约 121 px),
// 放不下完整句子,超出的部分会被直接裁掉。
dlg.Init(_TR("协议切换"), _TR("反代入口(域名:端口):"));
dlg.SetHistoryKey("proto_entry");
CString lastEntry = THIS_CFG.GetStr("ws", "Entry", "").c_str();
if (!lastEntry.IsEmpty()) dlg.m_str = lastEntry;
@@ -5216,20 +5244,17 @@ void CMy2015RemoteDlg::OnOnlineDelete()
if (IDYES != MessageBoxL(_T("确定删除选定的被控计算机吗?"), _T("提示"), MB_ICONQUESTION | MB_YESNO))
return;
// 确认框是模态的,期间列表可能已经重排;目标在锁内一次性锁定,后面发指令和
// 移除列表两步都用这份结果,避免两处按行号各自解析出不同的主机。
EnterCriticalSection(&m_cs);
std::vector<context*> targets = ResolveCommandTargets();
LeaveCriticalSection(&m_cs);
BYTE bToken = COMMAND_BYE; //向被控端发送一个COMMAND_SYSTEM
SendSelectedCommand(&bToken, sizeof(BYTE)); //Context PreSending PostSending
EnterCriticalSection(&m_cs);
// 收集选中的索引(从大到小排序,避免删除时索引变化问题)
std::vector<int> selectedItems;
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
selectedItems.push_back(m_CList_Online.GetNextSelectedItem(Pos));
}
std::sort(selectedItems.rbegin(), selectedItems.rend());
for (int iItem : selectedItems) {
context* ctx = GetContextByListIndex(iItem);
for (context* ctx : targets) {
if (!ctx) continue;
CString strIP = ctx->GetClientData(ONLINELIST_IP);
@@ -5276,18 +5301,14 @@ VOID CMy2015RemoteDlg::OnOnlineWindowManager()
// 是否继续远程控制:如果选择多个,则继续;如果选择单个且用户锁屏无SYSTEM权限,则提示
BOOL CMy2015RemoteDlg::ShouldRemoteControl()
{
context* ContextObject = nullptr;
EnterCriticalSection(&m_cs);
int count = m_CList_Online.GetSelectedCount();
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
CString activeWnd, userName;
if (Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
ContextObject = GetContextByListIndex(iItem);
if (ContextObject) {
activeWnd = ContextObject->GetClientData(ONLINELIST_LOGINTIME);
userName = ContextObject->GetAdditionalData(RES_USERNAME);
}
int count = 0;
EnterCriticalSection(&m_cs);
std::vector<context*> targets = ResolveCommandTargets();
count = (int)targets.size();
if (!targets.empty()) {
activeWnd = targets[0]->GetClientData(ONLINELIST_LOGINTIME);
userName = targets[0]->GetAdditionalData(RES_USERNAME);
}
LeaveCriticalSection(&m_cs);
if (count == 1 && userName != "SYSTEM" && activeWnd.Find("Locked") == 0) {
@@ -5496,11 +5517,7 @@ void CMy2015RemoteDlg::OnOnlineBuildClient()
VOID CMy2015RemoteDlg::SendSelectedCommand(PBYTE szBuffer, ULONG ulLength, contextModifier cb, void* user)
{
EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while(Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
for (context* ContextObject : ResolveCommandTargets()) {
if (!ContextObject->IsLogin() && szBuffer[0] != COMMAND_BYE)
continue;
if (szBuffer[0] == COMMAND_UPDATE) {
@@ -7579,6 +7596,95 @@ context* CMy2015RemoteDlg::GetContextByListIndex(int iItem)
return m_HostList[realIdx];
}
// 按 clientID 把选中项恢复到它们当前所在的行号。
//
// 主机列表是虚拟列表(LVS_OWNERDATA),选中项按**行号**保存,而行号的含义会随
// m_HostList 重排而改变:上下线时 OnTimer 会 ApplySort() + RebuildFilteredIndices(),
// 主机下线时 RemoveFromHostList() 直接 erase,两者都会让行号整体位移。
// 右键菜单是模态的,TrackPopupMenu 期间 WM_TIMER 照常派发,所以用户在菜单里点下去
// 时,行号很可能已经指向另一台主机;命令处理函数又是点击那一刻才按行号解析主机
// (GetContextByListIndex),结果就是「对 A 主机点的菜单」落到了 B 主机上。
//
// 调用方在弹菜单前用 clientID 记住用户选中的主机,菜单返回后调用本函数把选中项搬回
// 这些主机,再派发命令,命令处理函数看到的就还是用户当初选的那批主机。
//
// 菜单打开期间下线的主机已不在列表里,无法恢复,其选中项被丢弃:处理函数会看到
// 「没选中」并给出提示,而不是误操作另一台主机——这是安全的失败方式。
void CMy2015RemoteDlg::RestoreSelectionByIds(const std::vector<uint64_t>& ids)
{
int firstRow = -1;
{
CLock lock(m_cs);
// 先清空全部选中(-1 表示作用于所有行)
m_CList_Online.SetItemState(-1, 0, LVIS_SELECTED);
for (uint64_t id : ids) {
auto it = m_ClientIndex.find(id);
if (it == m_ClientIndex.end()) continue; // 该主机已下线
const size_t hostIdx = it->second;
if (hostIdx >= m_HostList.size()) continue;
// 索引映射若因并发更新而陈旧,宁可不选,也不能选到别的主机
if (!m_HostList[hostIdx] || m_HostList[hostIdx]->GetClientID() != id) continue;
// 在过滤索引里找它的当前显示行
int row = -1;
for (size_t fi = 0; fi < m_FilteredIndices.size(); ++fi) {
if (m_FilteredIndices[fi] == hostIdx) {
row = (int)fi;
break;
}
}
if (row < 0) continue; // 被当前分组过滤排除
m_CList_Online.SetItemState(row, LVIS_SELECTED, LVIS_SELECTED);
if (firstRow < 0) firstRow = row;
}
}
// 滚动和重绘会同步触发绘制,放到锁外,不占着主机列表锁
if (firstRow >= 0) {
m_CList_Online.SetItemState(firstRow, LVIS_FOCUSED, LVIS_FOCUSED);
m_CList_Online.EnsureVisible(firstRow, FALSE);
}
// 重排期间列表用了 LVSICF_NOINVALIDATEALL,可见行可能还是旧内容,补一次重绘
m_CList_Online.Invalidate(FALSE);
}
// 取本次命令要作用的主机。
//
// 平时就是列表里的选中项;右键菜单派发期间 m_CtxMenuTargets 非空,此时以快照为准。
// 原因:菜单点击到命令真正执行之间还夹着 MessageBoxL / DoModal 等模态框,模态循环里
// WM_TIMER 照常派发,列表会 ApplySort/erase 重排,此时再按行号读选中项就会读到另一台
// 主机。快照按 clientID 保存,与行号无关。
//
// 调用方需持有 m_cs(本函数内部不加锁)。
std::vector<context*> CMy2015RemoteDlg::ResolveCommandTargets()
{
std::vector<context*> targets;
if (!m_CtxMenuTargets.empty()) {
targets.reserve(m_CtxMenuTargets.size());
for (uint64_t id : m_CtxMenuTargets) {
auto it = m_ClientIndex.find(id);
if (it == m_ClientIndex.end()) continue; // 菜单打开期间已下线
const size_t hostIdx = it->second;
if (hostIdx >= m_HostList.size()) continue;
context* ctx = m_HostList[hostIdx];
// 索引映射若因并发更新而陈旧,宁可不操作,也不能操作到别的主机
if (!ctx || ctx->GetClientID() != id) continue;
targets.push_back(ctx);
}
return targets;
}
POSITION pos = m_CList_Online.GetFirstSelectedItemPosition();
while (pos) {
context* ctx = GetContextByListIndex(m_CList_Online.GetNextSelectedItem(pos));
if (ctx) targets.push_back(ctx);
}
return targets;
}
// 从 m_HostList 中移除 context 并更新索引映射。
//
// 重要:MarkDeviceOffline / m_ActiveWndW.erase 等"主机下线"副作用必须**只在
@@ -8820,16 +8926,15 @@ void CMy2015RemoteDlg::OnOnlineHostnote()
BOOL modified = FALSE;
uint64_t key = 0;
EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
// 输入框是模态的,期间列表可能已重排,目标按 clientID 还原,避免备注写到别的主机
for (context* ContextObject : ResolveCommandTargets()) {
m_ClientMap->SetClientMapData(ContextObject->GetClientID(), MAP_NOTE, dlg.m_str);
// 虚拟列表:刷新该行以显示新备注
m_CList_Online.RedrawItems(iItem, iItem);
modified = TRUE;
}
if (modified) {
// 虚拟列表:整表重绘,让新备注显示出来
m_CList_Online.Invalidate(FALSE);
}
LeaveCriticalSection(&m_cs);
if (modified) {
m_ClientMap->SaveToFile(GetDbPath());
@@ -11523,11 +11628,8 @@ void CMy2015RemoteDlg::OnOnlineRunAsAdmin()
if (MessageBoxL("确定要以管理员权限重新启动目标应用程序吗?\n此操作可能触发 UAC 账户控制。",
"提示", MB_ICONQUESTION | MB_YESNO) == IDYES) {
EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
// 确认框期间列表可能已重排,目标按 clientID 还原
for (context* ContextObject : ResolveCommandTargets()) {
BYTE token = CMD_RUNASADMIN;
ContextObject->Send2Client(&token, sizeof(token));
}
@@ -11571,20 +11673,17 @@ void CMy2015RemoteDlg::OnOnlineUninstall()
if (IDYES != MessageBoxL(_T("确定卸载选定的被控程序吗?"), _T("提示"), MB_ICONQUESTION | MB_YESNO))
return;
// 确认框是模态的,期间列表可能已经重排;目标在锁内一次性锁定,后面发指令和
// 移除列表两步都用这份结果,避免两处按行号各自解析出不同的主机。
EnterCriticalSection(&m_cs);
std::vector<context*> targets = ResolveCommandTargets();
LeaveCriticalSection(&m_cs);
BYTE bToken = TOKEN_UNINSTALL;
SendSelectedCommand(&bToken, sizeof(BYTE));
EnterCriticalSection(&m_cs);
// 收集选中的索引(从大到小排序,避免删除时索引变化问题)
std::vector<int> selectedItems;
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
selectedItems.push_back(m_CList_Online.GetNextSelectedItem(Pos));
}
std::sort(selectedItems.rbegin(), selectedItems.rend());
for (int iItem : selectedItems) {
context* ctx = GetContextByListIndex(iItem);
for (context* ctx : targets) {
if (!ctx) continue;
CString strIP = ctx->GetClientData(ONLINELIST_IP);
@@ -11769,11 +11868,8 @@ void CMy2015RemoteDlg::MachineManage(MachineCommand type)
{
if (MessageBoxL("此操作需客户端具有管理员权限,确定继续吗? ", "提示", MB_ICONQUESTION | MB_YESNO) == IDYES) {
EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
// 确认框期间列表可能已重排,目标由 ResolveCommandTargets 按 clientID 还原
for (context* ContextObject : ResolveCommandTargets()) {
BYTE token[32] = { TOKEN_MACHINE_MANAGE, type };
ContextObject->Send2Client(token, sizeof(token));
}
@@ -12845,13 +12941,9 @@ void CMy2015RemoteDlg::ProxyClientTcpPort(bool isStandard, bool autoRun)
info->Schedule.Mode = autoRun ? SCH_MODE_STARTUP : SCH_MODE_NONE;
FrpcParam param(key.c_str(), timestamp, ip.c_str(), serverPort, localPort, remotePort);
EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
BOOL sent = FALSE;
const char* validDate = isStandard ? "Jan 29 2026" : "Dec 22 2025";
while (Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ctx = GetContextByListIndex(iItem);
if (!ctx) continue;
for (context* ctx : ResolveCommandTargets()) {
if (!ctx->IsLogin())
continue;
CString bits = ctx->GetAdditionalData(RES_PROGRAM_BITS);
+10
View File
@@ -412,6 +412,16 @@ public:
std::string m_v2KeyPath; // V2 密钥文件路径
void RebuildFilteredIndices(); // 重建过滤索引
context* GetContextByListIndex(int iItem); // 根据列表索引获取 context(考虑分组过滤)
// 按 clientID 把选中项恢复到它们当前所在的行号。虚拟列表的选中项是按行号保存的,
// 而 m_HostList 会随主机上下线重排,同一个行号重排后往往指向另一台主机。
void RestoreSelectionByIds(const std::vector<uint64_t>& ids);
// 本次命令的目标主机:右键菜单派发期间(m_CtxMenuTargets 非空)以 clientID 快照为准,
// 否则取列表当前选中项。调用方需持有 m_cs。
std::vector<context*> ResolveCommandTargets();
// 右键菜单发起时锁定的目标主机(clientID 快照)。菜单弹出到命令真正执行之间还会插入
// MessageBoxL / DoModal 等模态框,模态循环里 WM_TIMER 照常派发、列表照常重排,命令
// 处理函数若在那之后再按行号读选中项,就会读到另一台主机。只在 UI 线程访问。
std::vector<uint64_t> m_CtxMenuTargets;
// 启发式 ID 迁移:新客户端首次上线时,按 (ComputerName, ProgramPath) 在 m_ClientMap
// 里找老条目,若唯一匹配则把元数据(备注/位置/级别/授权)拷贝到 newId。
@@ -537,8 +537,12 @@
<Image Include="res\Bitmap\BrowseWnd.bmp" />
<Image Include="res\Bitmap\CancelShare.bmp" />
<Image Include="res\Bitmap\ClientLog.bmp" />
<Image Include="res\Bitmap\CopyName.bmp" />
<Image Include="res\Bitmap\DesktopQuality.bmp" />
<Image Include="res\Bitmap\Disclaimer.bmp" />
<Image Include="res\Bitmap\DrawingBoard.bmp" />
<Image Include="res\Bitmap\FileManager.bmp" />
<Image Include="res\Bitmap\FileSpeed.bmp" />
<Image Include="res\Bitmap\Forbidden.bmp" />
<Image Include="res\bitmap\compress.bmp" />
<Image Include="res\Bitmap\Copy.bmp" />
@@ -574,6 +578,7 @@
<Image Include="res\Bitmap\PluginConfig.bmp" />
<Image Include="res\Bitmap\PortProxyAuto.bmp" />
<Image Include="res\Bitmap\PortProxyStd.bmp" />
<Image Include="res\Bitmap\PreviewQuality.bmp" />
<Image Include="res\Bitmap\PrivacyShield.bmp" />
<Image Include="res\Bitmap\PrivateScreen.bmp" />
<Image Include="res\Bitmap\proxy.bmp" />
@@ -368,5 +368,10 @@
<Image Include="res\Bitmap\DrawingBoard.bmp" />
<Image Include="res\Bitmap\TlsEnable.bmp" />
<Image Include="res\Bitmap\TlsDisable.bmp" />
<Image Include="res\Bitmap\DesktopQuality.bmp" />
<Image Include="res\Bitmap\PreviewQuality.bmp" />
<Image Include="res\Bitmap\FileSpeed.bmp" />
<Image Include="res\Bitmap\Disclaimer.bmp" />
<Image Include="res\Bitmap\CopyName.bmp" />
</ItemGroup>
</Project>
+3 -1
View File
@@ -842,7 +842,9 @@ BOOL CBuildDlg::OnInitDialog()
m_ComboProto.InsertStringL(PROTO_HTTP, "HTTP");
m_ComboProto.InsertStringL(PROTO_RANDOM, "随机");
m_ComboProto.InsertStringL(PROTO_KCP, "KCP");
// 序号即 protoType,中间不能有空洞(下方 GetCurSel 直接当协议值用)
// 序号即 protoType,中间不能有空洞(下方 GetCurSel 直接当协议值用)。
// 该下拉框资源带 CBS_SORT 样式:InsertString 不受它影响,能保持这里的顺序,
// 换成 AddString 会按字母序重排,HTTP 抢到第 0 项,默认协议就错了。
m_ComboProto.InsertStringL(PROTO_WS, "WebSocket");
m_ComboProto.InsertStringL(PROTO_WSS, "WS+TLS");
m_ComboProto.SetCurSel(PROTO_TCP);
+86 -23
View File
@@ -1009,6 +1009,7 @@ BOOL IOCPServer::StartTlsHandshake(CONTEXT_OBJECT* ContextObject)
ContextObject->IoRefCount.fetch_sub(1);
delete ContextObject->tls;
ContextObject->tls = NULL;
delete p; // 线程没跑起来,参数(含挪过来的 initial)由本线程释放
return FALSE;
}
CloseHandle(h);
@@ -1066,23 +1067,46 @@ DWORD WINAPI IOCPServer::WsHandshakeThreadProc(LPVOID lParam)
Mprintf("[WS] %s upgraded via reverse proxy, real client %s\n",
ctx->GetPeerName().c_str(), fwd.c_str());
ctx->SetPeerName(fwd);
}
ctx->wsState.store(WS_Ready, std::memory_order_release);
// 升级响应落盘后,同批字节里可能已经有客户端的第一帧(WSS 分批解密时常见)。
// 必须在交还 IOCP 之前喂给解帧路径,否则要等客户端再发一包——而它正在等我们。
if (!pending.empty()) {
ZSTD_DCtx* dctx = ZSTD_createDCtx();
z_stream z = {};
inflateInit2(&z, 15);
int r = ctx->IsRemoved.load(std::memory_order_acquire) ? 1
: This->DispatchPlain(ctx, pending.data(), (DWORD)pending.size(), dctx, &z);
inflateEnd(&z);
ZSTD_freeDCtx(dctx);
if (r < 0) {
ok = false;
Mprintf("[WS] first frame dispatch failed for %s (closing)\n", ctx->GetPeerName().c_str());
// 两段式限流(与 Go 端 limitDirectPeer / handleConnection 同构)。accept 阶段按
// getpeername 计的那一次对经反代的连接没有意义:反代同机时对端是回环地址,
// IPWhitelist 对回环恒为 true,黑名单 / 封禁 / 计数全部不生效。真实设备 IP 到
// 这里才知道,所以在这里按真实 IP 重做一次。直连连接(fwd 为空)在 accept 阶段
// 已经计过数,不重复计数。
bool blocked = This->IsIPBlacklisted(fwd);
if (!blocked) {
blocked = This->IsIPBanned(fwd);
if (!blocked) {
This->RecordConnection(fwd); // 超阈值时内部会 BanIP
blocked = This->IsIPBanned(fwd); // 本次连接把计数顶过阈值
}
}
if (blocked) {
Mprintf("[WS] real client %s rejected by IP ban/rate limit (fail-closed)\n", fwd.c_str());
ok = false;
}
}
if (ok) {
ctx->wsState.store(WS_Ready, std::memory_order_release);
// 升级响应落盘后,同批字节里可能已经有客户端的第一帧(WSS 分批解密时常见)。
// 必须在交还 IOCP 之前喂给解帧路径,否则要等客户端再发一包——而它正在等我们。
if (!pending.empty()) {
ZSTD_DCtx* dctx = ZSTD_createDCtx();
z_stream z = {};
inflateInit2(&z, 15);
int r = ctx->IsRemoved.load(std::memory_order_acquire) ? 1
: This->DispatchPlain(ctx, pending.data(), (DWORD)pending.size(), dctx, &z);
inflateEnd(&z);
ZSTD_freeDCtx(dctx);
if (r < 0) {
ok = false;
Mprintf("[WS] first frame dispatch failed for %s (closing)\n", ctx->GetPeerName().c_str());
}
}
} else {
ctx->wsState.store(WS_None, std::memory_order_release);
}
} else {
ctx->wsState.store(WS_None, std::memory_order_release);
@@ -1124,6 +1148,7 @@ BOOL IOCPServer::StartWsHandshake(CONTEXT_OBJECT* ContextObject, const std::vect
ContextObject->IoRefCount.fetch_sub(1);
ContextObject->FreeWs();
ContextObject->wsState.store(WS_None, std::memory_order_release);
delete p; // 线程没跑起来,参数(含挪过来的 initial)由本线程释放
return FALSE;
}
CloseHandle(h);
@@ -1132,6 +1157,18 @@ BOOL IOCPServer::StartWsHandshake(CONTEXT_OBJECT* ContextObject, const std::vect
BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans, ZSTD_DCtx* ctx, z_stream* z)
{
// 握手线程独占 socket(TLS 或 WS 升级期间):正常不应出现 IORead,出现即属异常,fail-closed。
// 必须放在函数最开头——WSS 升级时 tlsState 已经是 TLS_Ready,若把判断放在 TLS 分支之后,
// 这段字节会先走解密分支再进 DispatchPlain,被当成业务协议解析,同时与握手线程并发读
// 同一个 socket。放在最前面才能同时覆盖明文与 TLS 两条路径。
if (ContextObject->wsState.load(std::memory_order_acquire) == WS_Handshaking) {
Mprintf("[WS] unexpected IORead during handshake for %s (closing)\n",
ContextObject->GetPeerName().c_str());
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
int st = ContextObject->tlsState.load(std::memory_order_acquire);
// ---- 未分类:按 ClientHello 头嗅探明文 / TLS(见设计文档 §5.2)----
@@ -1210,8 +1247,9 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
return TRUE;
}
// TLS_Handshaking / WS_Handshaking:握手线程独占 socket,正常不应出现 IORead;若出现属异常,fail-closed。
if (st == TLS_Handshaking || ContextObject->wsState.load(std::memory_order_acquire) == WS_Handshaking) {
// TLS_Handshaking:握手线程独占 socket,正常不应出现 IORead;若出现属异常,fail-closed。
// (WS_Handshaking 在函数开头已判定,不在这里。)
if (st == TLS_Handshaking) {
Mprintf("[TLS] unexpected IORead during handshake for %s (closing)\n",
ContextObject->GetPeerName().c_str());
ContextObject->IoRefCount.fetch_sub(1);
@@ -1220,6 +1258,16 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
}
// TLS_Plain:明文直通(原路径)。WS 连接在这里先解帧。
// dwTrans == 0 是对端干净关闭(FIN)。WS 改造前这条分支直接调 ParseReceivedData,
// 它对 dataLen == 0 返回 FALSE 从而拆连接;换成 DispatchPlain 后该语义丢了——0 字节
// 一路返回 1 → PostRecv,而 FIN 已经消费掉,这条连接就停在 CLOSE_WAIT 里,直到
// keepalive(3 分钟)才回收(实测:对端 FIN 后连接一直留在 CLOSE_WAIT,进程不空转)。
// 期间它占着 IOCP 上下文、挂着一枚 WSARecv 和限流槽。这里补回与另外两条分支一致的收尾。
if (dwTrans == 0) {
ContextObject->IoRefCount.fetch_sub(1);
RemoveStaleContext(ContextObject);
return -2;
}
{
int r = DispatchPlain(ContextObject, (const BYTE*)ContextObject->szBuffer, dwTrans, ctx, z);
if (r < 0) {
@@ -1252,13 +1300,14 @@ int IOCPServer::DispatchPlain(CONTEXT_OBJECT* ContextObject, const BYTE* data, D
}
if (ws == WS_Undecided) {
ContextObject->tlsPreClassify.insert(ContextObject->tlsPreClassify.end(), data, data + len);
if (ContextObject->tlsPreClassify.size() < 6) {
// WS 有自己的缓冲(该状态机在 HTTPS 升级 / 反代路径上也会用到),不再借 tlsPreClassify。
ContextObject->wsPreClassify.insert(ContextObject->wsPreClassify.end(), data, data + len);
if (ContextObject->wsPreClassify.size() < 6) {
return 1; // 头还没攒够,继续收
}
std::vector<BYTE> first;
first.swap(ContextObject->tlsPreClassify);
ContextObject->tlsPreClassify.clear();
first.swap(ContextObject->wsPreClassify);
ContextObject->wsPreClassify.clear();
if (first.size() >= 4 && memcmp(first.data(), "GET ", 4) == 0) {
if (!StartWsHandshake(ContextObject, first)) {
Mprintf("[WS] StartWsHandshake failed for %s (fail-closed)\n",
@@ -1399,8 +1448,22 @@ BOOL IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffe
// 客户端解密后得到的是「旧 TLS 记录」→ Unknown header 17 03 03。故只加密本次新追加的尾部。
bool tlsReady = (ContextObject->tlsState.load(std::memory_order_acquire) == TLS_Ready);
// WS(含 WSS):同样只处理本次新追加的尾部——前缀可能还有在途未发完的帧/密文。
bool wsReady = (ContextObject->wsState.load(std::memory_order_acquire) == WS_Ready) &&
ContextObject->ws != NULL && ContextObject->ws->IsOpen();
const bool wsStateReady = (ContextObject->wsState.load(std::memory_order_acquire) == WS_Ready);
if (wsStateReady && (ContextObject->ws == NULL || !ContextObject->ws->IsOpen())) {
// 升级过 WS 但会话已关(Feed 报错 / 收到 close)而状态还没降级:绝不能把应用字节
// 当裸字节发出去,对端会解帧错位。丢弃本次发送,并主动 shutdown 让挂起的 recv
// 立刻返回 0 字节——否则接收路径要等对端 FIN 才醒,期间这条连接既发不出也收不到,
// 只能靠心跳超时兜底(最坏要几分钟)。
//
// 这里不能直接调 RemoveStaleContext:它会等待 IoRefCount 归零,而本函数的调用方
// 常常就处在一个 IoRef 里(发送失败→兜底发送),等于自己等自己,5 秒后超时放行,
// 反而可能把已回收复用的 CONTEXT_OBJECT 交回给调用者。shutdown 是异步且无阻塞的,
// 真正的收尾仍由接收路径的 -2 返回值触发。
Mprintf("[WS] session closed for %s, dropping send\n", ContextObject->GetPeerName().c_str());
shutdown(ContextObject->sClientSocket, SD_BOTH);
return FALSE;
}
bool wsReady = wsStateReady;
ULONG oldLen = (tlsReady || wsReady) ? ContextObject->OutCompressedBuffer.GetBufferLength() : 0;
if (WriteContextData(ContextObject, szBuffer, ulOriginalLength, ContextObject->Zcctx)) {
+6 -1
View File
@@ -429,6 +429,10 @@ public:
// ---- WebSocket 传输层状态(分层在 TLS 之上:WSS = TLS 里的 WS)----
std::atomic<int> wsState{ WS_Undecided }; // ServerWsState
ServerWsSession* ws = nullptr; // 每连接 WS 会话(升级线程独占→就绪后共用)
// WS 升级前的首包缓冲(判定 "GET " 用)。与 tlsPreClassify 刻意分开:两者服务于不同的
// 状态机,此前串行复用同一个 vector(TLS 判定完 move 走再 clear,WS 又塞回来),字段名
// 与用途对不上,排查时容易误读。两条路径仍按先后串行,互不重叠。
std::vector<BYTE> wsPreClassify;
// 子连接身份校验:客户端发 TOKEN_CONN_AUTH 通过验证后置位。
// 主连接(走 TOKEN_LOGIN 流程)不参与此机制。当前阶段宽容(未通过也接受),
@@ -591,9 +595,10 @@ public:
FreeTls();
tlsState.store(TLS_Unclassified, std::memory_order_release);
tlsPreClassify.clear();
// 复用对象池时重置 WebSocket 状态:释放旧会话、回到未判定。
// 复用对象池时重置 WebSocket 状态:释放旧会话、回到未判定、清空首包缓冲。
FreeWs();
wsState.store(WS_Undecided, std::memory_order_release);
wsPreClassify.clear();
// 复用对象池时清空发送进行中标志,避免上次连接残留的 bSendPending 抑制新连接的发送。
bSendPending = false;
}
+1 -1
View File
@@ -46,7 +46,7 @@
// 程序版本号 [建议格式: X.Y.Z]
// 影响:关于对话框、标题栏
#define BRAND_VERSION "1.4.1"
#define BRAND_VERSION "1.4.2"
// 启动画面名称 [建议大写,更有 Logo 感]
// 影响:启动画面 Logo 文字(大号艺术字体渲染)
+13 -1
View File
@@ -279,7 +279,7 @@ Web
通用=Allgemein
高级 (非必填项)=Erweitert (Optional)
提示: 多个上线地址用分号分隔,99个字符以内。仅供学习和自用,严禁用于非法目的使用。=Tipp: Mehrere Adressen durch Semikolons getrennt, max. 99 Zeichen.
提示: WebSocket协议需经反向代理(如nginx 443)转发到主控端口,地址填域名;服务端须为Go版本。=Tipp: WebSocket benoetigt einen Reverse-Proxy (z. B. nginx auf 443), der auf den Steuerungsport weiterleitet; als Adresse die Domain eintragen; der Server muss die Go-Version sein.
提示: WebSocket协议需经反向代理(如nginx 443)转发到主控端口,地址填域名。=Tipp: WebSocket benoetigt einen Reverse-Proxy (z. B. nginx auf 443), der auf den Steuerungsport weiterleitet; als Adresse die Domain eintragen.
; ============================================
; Service Manager
@@ -2115,6 +2115,18 @@ TLS
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=TLS-Transport fuer die ausgewaehlten Hosts deaktivieren?\n(Clients wirken sofort und verbinden sich neu; laufende Sitzungen werden unterbrochen)
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server-TLS-Zertifikat ist nicht aktiviert; TLS-Transport der Clients kann nicht umgeschaltet werden
读取服务端 TLS 证书失败,无法下发=Server-TLS-Zertifikat konnte nicht gelesen werden; Verteilung nicht moeglich
; ===== Protokollwechsel (Protocol Switch) =====
协议切换=Protokollwechsel
直连 TCP=Direktes TCP
WS(经反向代理,明文)=WS (ueber Reverse-Proxy, Klartext)
WSS(经反向代理,TLS)=WSS (ueber Reverse-Proxy, TLS)
反代入口(域名:端口):=Proxy (Domain:Port):
反向代理入口格式不正确,应为 域名:端口=Ungueltiger Reverse-Proxy-Eingang; erwartet wird Domain:Port
服务端未启用 TLS 证书,无法切换到 WSS=Server-TLS-Zertifikat ist nicht aktiviert; Wechsel zu WSS nicht moeglich
读取服务端 TLS 证书失败,无法切换到 WSS=Server-TLS-Zertifikat konnte nicht gelesen werden; Wechsel zu WSS nicht moeglich
选中的主机里有客户端版本不支持协议切换(需要新版客户端)=Einige ausgewaehlte Hosts laufen mit einem Client ohne Protokollwechsel-Unterstuetzung (neuerer Client erforderlich)
确定把选中主机切回直连 TCP 吗?\n(客户端立即断线重连;若直连端口不可达,5 分钟后自动回退到当前入口)=Ausgewaehlte Hosts zurueck auf direktes TCP schalten?\n(Clients verbinden sich sofort neu; ist der direkte Port nicht erreichbar, fallen sie nach 5 Minuten auf den aktuellen Eingang zurueck)
确定切换选中主机的传输协议吗?\n(客户端立即断线重连,正在进行的远程会话会中断;新入口 5 分钟内连不上将自动回退)=Transportprotokoll der ausgewaehlten Hosts umschalten?\n(Clients verbinden sich sofort neu, laufende Sitzungen werden unterbrochen; ist der neue Eingang 5 Minuten lang nicht erreichbar, wird automatisch zurueckgefallen)
白名单=Whitelist
确定将选中日志中的 IP 加入白名单吗?=IP aus den ausgewaehlten Log-Eintraegen zur Whitelist hinzufuegen?
已将 %d 个 IP 加入白名单=%d IP(s) zur Whitelist hinzugefuegt
+1 -1
View File
@@ -2162,7 +2162,7 @@ Y
直连 TCP=Direct TCP
WS(经反向代理,明文)=WS (via reverse proxy, plaintext)
WSS(经反向代理,TLS)=WSS (via reverse proxy, TLS)
请输入反向代理入口(域名:端口,例如 ws.example.com:443):=Enter the reverse proxy entry (host:port, e.g. ws.example.com:443):
ˇ´´úČëżÚ(ÓňĂű:śËżÚ):=Proxy (host:port):
反向代理入口格式不正确,应为 域名:端口=Invalid reverse proxy entry; expected host:port
服务端未启用 TLS 证书,无法切换到 WSS=Server TLS certificate is not enabled; cannot switch to WSS
读取服务端 TLS 证书失败,无法切换到 WSS=Failed to read the server TLS certificate; cannot switch to WSS
+1 -1
View File
@@ -2153,7 +2153,7 @@ Y
直连 TCP=直連 TCP
WS(经反向代理,明文)=WS(經反向代理,明文)
WSS(经反向代理,TLS)=WSS(經反向代理,TLS)
请输入反向代理入口(域名:端口,例如 ws.example.com:443):=請輸入反向代理入口(網域:連接埠,例如 ws.example.com:443):
反代入口(域名:端口):=反代入口(網域:埠):
反向代理入口格式不正确,应为 域名:端口=反向代理入口格式不正確,應為 網域:連接埠
服务端未启用 TLS 证书,无法切换到 WSS=伺服器未啟用 TLS 憑證,無法切換到 WSS
读取服务端 TLS 证书失败,无法切换到 WSS=讀取伺服器 TLS 憑證失敗,無法切換到 WSS
+8 -2
View File
@@ -63,9 +63,15 @@ var (
// reverse proxy (empty otherwise). A failed upgrade returns (nil, "").
func (s *Server) wrapWebSocket(conn net.Conn, peer string) (net.Conn, string) {
br := bufio.NewReader(conn)
if s.config.ReadTimeout > 0 {
_ = conn.SetReadDeadline(time.Now().Add(s.config.ReadTimeout))
// Bound the sniff even when the server has no ReadTimeout: a peer that opens a
// socket and never sends the prefix would otherwise hold the goroutine (and its
// per-IP slot) for as long as it likes. When ReadTimeout is configured and
// shorter, keep the tighter bound.
sniffTimeout := wsHandshakeTimeout
if s.config.ReadTimeout > 0 && s.config.ReadTimeout < sniffTimeout {
sniffTimeout = s.config.ReadTimeout
}
_ = conn.SetReadDeadline(time.Now().Add(sniffTimeout))
hdr, err := br.Peek(len(wsUpgradePrefix))
_ = conn.SetReadDeadline(time.Time{})
if err != nil {
+573 -215
View File
File diff suppressed because it is too large. Load diff