d8048979e3445d23e49331e27988f1fc2efb9c97
274
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d8048979e3 |
Feature: Report activity history on Linux clients
Implement COMMAND_QUERY_ACTIVITY -> TOKEN_REPORT_ACTIVITY with two backends picked at startup. With a desktop, a sampler thread reads the foreground window every second and books dwell time like the Windows client: under five seconds is dropped, five idle minutes close the window, the last 500 records stay newest first, each line being "[YYYY-MM-DD HH:MM:SS] [title] duration". It uses its own ActivityChecker because an Xlib connection cannot be shared with the heartbeat thread, and it is stopped before main's locals go away. A reachable X server is not enough: the window backend is only chosen when the root window carries _NET_SUPPORTING_WM_CHECK, so Xvfb or a bare X without an EWMH window manager falls back to the headless backend instead of sampling a window id that never appears. Without a desktop the answer is computed on demand: logins from "last -n 100 -F" plus bash/zsh history of root and /home/*, tagged [登录] or [命令] after a [来源] header. Both halves are merged and sorted by timestamp; three fifths of the budget goes to logins and reboot records are capped at ten, since a WSL or container writes one reboot per start. activity_commands=0 drops the command half. A single detached thread builds and sends it, only while the main link is up. The MCP gate now admits Linux for get_activity_history and documents both shapes. test/unit/linux covers the parsers, ordering and UTF-8 truncation; 15 cases pass. Co-Authored-By: deepseek-flash |
||
|
|
5f40f3726c |
Fix: React to slow-frame congestion and keep remote audio recoverable
The adaptive quality controller counted only complete frames per second, so when a single frame took several seconds to arrive the sample was 0 fps and the throughput criterion abstained forever: Ultra and High kept flipping while a foreground video played. The audio watchdog had the opposite problem: it rebuilt the WASAPI capture every three seconds on an idle endpoint, and its sleep detector measured the whole loop including a blocking send. Sample the last ten seconds in a ring buffer and feed the criterion a windowed rate, guarded so a scroll burst, a stale window or a few KB clock patch is not mistaken for congestion. Apply the same per-frame floor to the one-second fallback and to the post-downgrade local-bottleneck probe. Normalize delayed timer ticks by real elapsed milliseconds, and make the 40 second upgrade-failure window outlast the resolution cooldown it has to cross. On the client, rebuild only when an audio session is actually rendering, and rebuild immediately when the captured endpoint is no longer the default output; refresh the sleep timestamps on failed as well as successful init. Tests cover the window and fallback helpers directly; the full suite passes 845/845, and both the Debug server and Debug client build. Co-Authored-By: deepseek-flash |
||
|
|
4309865570 |
UI: Give the share/transfer dialog labels a full-width row
The address label was 81 dialog units wide at x=8 while the combo box starts at 93, and the prompt set at runtime - an IP:PORT hint that also mentions the optional wss:// prefix - is far wider than that. The static clipped it at its edge, so the rest of the hint looked hidden behind the input field; with the English or German translation almost the whole sentence disappeared. The days label had the same 81-unit width. Move both labels onto their own full-width rows above their controls and shift the combo box, days field, checkbox and buttons down to fit. The dialog grows from 105 to 128 units and the days field narrows from 201 to 80 units, so every translation stays on one line. The share variant still hides the days row, leaving the same gap it had before. The share and transfer dialogs share this template, so both are fixed. Co-Authored-By: deepseek-flash |
||
|
|
a628c19341 |
Fix: repaint the remote desktop after a window resize
OnSize only refreshed the cached client rect, letterbox offsets and zoom factors; it never asked for a repaint. Windows invalidates a window only when the client area grows, so restoring a maximized viewer marks nothing invalid. Since the dialog stops erasing its background after the first frame and has no periodic repaint timer, the sole remaining repaint source is a change on the remote screen. A static remote desktop therefore kept the maximized picture - cropped, not following the window - until something moved on the far end. Call InvalidateRect(NULL, FALSE) at the end of OnSize whenever the client area is non-empty, so every size change (restore, fullscreen transitions and interactive resizing) recomputes the layout and repaints once. It is a no-op while the window is hidden; CHideScreenSpyDlg::OnSize calls the base handler, so it inherits the same behaviour. Verified on a Debug build against a live test client: the maximized client (1920x1009) renders 63/64 px side bars and the restored one (717x355) 43/43 px, matching ComputeAdaptiveLayout (renderW=631, offsetX=43). Co-Authored-By: deepseek-flash |
||
|
|
49ba0c4850 |
Fix: keep the floating toolbar open while its quality menu is up
With the toolbar unpinned, CheckMousePosition() runs from the full-screen timer every 50ms and slides the bar out once the cursor leaves the edge band. The quality menu drops from the button's bottom edge, so its first item already sits past the monTop + m_nHeight + 10 threshold: the bar retracted the moment the user moved onto the menu, taking the menu with it. A m_bMenuOpen flag now suspends the retract decision while TrackPopupMenu is running. The menu's modal loop still dispatches the parent's WM_TIMER, so without this the bar animates away under it. The flag is set and cleared around the call, so behaviour is unchanged once the menu closes or is dismissed with Esc. Only the quality menu opens a popup, so nothing else needed the flag. Verified: debug server build, 0 errors, ToolbarDlg.cpp rebuilt. UI not exercised. |
||
|
|
6b87a31c6f |
UI: explain dangerous operations, screen modes and host filtering
Four items from a user-side review of the master. The common thread: the UI
now says what it is about to do instead of leaving the user to guess.
Confirm boxes. Logout, restart, shutdown, delete host and uninstall client
all asked "are you sure" without naming the action or the hosts, so a
multi-selection could not be checked. DescribeTargetHosts() lists
"note (or computer name) (ip)" capped at five lines, and the default button
is No. The preview is dropped before the modal box and targets are
re-resolved after it, since the list can reshuffle in between.
Screen modes. High Speed / Ultra Speed became High Quality (DXGI +
differential: lossless, bandwidth hungry) and Smooth (GDI + H264: lossy,
cheap). TranslateMenu looks menus up by displayed text, so the .rc entries,
the FeatureLimitsDlg item names and the language pack keys changed together.
Host filter. The Ctrl+F bar was find-next; it now filters as you type over
IP, location, note, OS and version, and Esc clears the filter. The status
line reads "filtered: N / M total" while active. Commands still resolve by
clientID and m_FilteredIndices still maps row to m_HostList index, so no
command path changes. SearchBarDlg drops from 446 to 312 lines.
Quality changes. The adaptive level now shows its reason for twenty seconds
("Good (high latency)") instead of silently changing. The full-screen info
bar was a fixed 170px, so that reason was clipped; the width is now measured
from the text with the same font that paints it, 170 becoming the floor and
16px quantisation so changing digits do not jitter the window. Cosmetic
only: no threshold, hysteresis, cooldown or lock-out logic is touched.
Verified: debug server build, 0 errors; new strings present in .res and in
the exe. UI not exercised - the debug master would fight the running release
master for the listening port in Bin/settings.ini.
|
||
|
|
a190c21217 |
Feature: make remote desktop tuning per client
The tuning switches lived in the master's Advanced menu and were saved globally, so two hosts could not use different settings. The client already sends ScreenSettings when a remote desktop starts, so the state belongs there: the four items now sit in the remote desktop window's system menu, directly below Screen quality, and are saved per client. ScreenSettings had a 40-byte Reserved area at offset 56; four bytes became TuningFlags, keeping the struct at 100 bytes with Capabilities at 96. A new Capabilities bit marks a value written by a versioned master; old clients, and new clients never configured, report 0 and are not trusted. CMD_SCREEN_TUNING now ends with a version byte. A five-byte command comes from an older master that does not know the server-only adaptive bit: the client applies those three bits to the session but does not save them. A fresh client starts at 0, so an old master still gets pre-feature behaviour; the new master's 0xE default is persisted on its first session. The per-client master copy stays as the old-client fallback, and the old global [settings] Tuning* keys are honoured when neither exists, so an explicit opt-out survives the migration. Verified on the Debug server with the in-process test client: a fresh client stored 0xE on first use; toggling VBV wrote 0xF to both sides; after deleting the master copy and reopening, the menu restored VBV from the client report. Co-Authored-By: deepseek-flash |
||
|
|
f96e4a7320 |
Fix: recover remote desktop audio after dropped formats and sleep
The client's audio thread starts before the capture thread sends TOKEN_BITMAPINFO, so its first packet - the only one carrying the AudioFormat - reaches the master before CScreenSpyDlg exists and is dropped as an unknown command. Without a format the master cannot open waveOut, and the client re-announced only on an audio off/on, so a remote desktop opened with audio enabled stayed silent until the toolbar button was toggled twice. The master now asks for a re-announce when data arrives with no format on record (CMD_AUDIO_CTRL enable, persist=0, one request per 2 s, 15 attempts max), and the client attaches the format to its next packet. Entering Modern Standby tears down the render endpoint. The client got AUDCLNT_E_DEVICE_INVALIDATED and rebuilt its loopback capture in that same instant; the new client initialized and started fine but was bound to the dying audio engine, so after resume GetNextPacketSize returned zero packets forever without error, and only a fresh screen session recovered. The audio thread now measures its own loop gap (GetTickCount64 plus wall clock, 2 s; a normal pass is ~10 ms) and rebuilds the capture client after the machine was frozen, waits a second after an invalidation, and rebuilds on an audio off-to-on. The master rebuilds waveOut on resume from WM_POWERBROADCAST. The format recovery was verified live; the resume recovery is build-verified and awaits a field check on a sleeping machine. Co-Authored-By: deepseek-flash |
||
|
|
74d64fec87 |
Fix: keep remote desktop audio alive when the playback device drops
Remote desktop audio could stop permanently after an idle period and only came back by closing and reopening the remote desktop. The ring buffer and WAVEHDRs were shared without locking between the IOCP worker thread (OnAudioData) and the UI thread (MM_WOM_DONE): headers were queued twice (waveOutWrite returning WAVERR_STILLPLAYING 33) and the non-atomic m_nRingDataLen underflowed, leaving the buffer "full" of stale data. Audio state is now serialized by a recursive m_AudioMutex, and opening, resetting and closing the waveOut device happens only on the window's UI thread: waveOutReset/Close can re-enter the MM_WOM_* handlers on that thread, and a lock-holding worker would deadlock against the UI thread. Workers post WM_AUDIO_INIT_DEVICE instead. Rebuilds are triggered by format changes, waveOutWrite failures (throttled to 2 s), MM_WOM_CLOSE with a 1 s guard against our own close notices, and a 2-second retry while audio is enabled. Failed header preparation now tears the device down instead of leaving a handle that rejects every write. The client re-creates its Opus encoder when the endpoint channel count or sample rate changes, downmixes more than two channels, and clamps oversized WASAPI packets to the PCM staging buffer. Web audio forwarding still runs outside the lock and is gated exactly as before. Verified by building the Debug x64 server and client; the silence scenario itself was not reproduced at runtime. Co-Authored-By: deepseek-flash |
||
|
|
4884b080e8 |
Improve: default the x264 bitrate cap off and label it for weak links
The cap is capped CRF (VBV): when a frame needs more bits than the profile's nominal bitrate allows, x264 has to raise QP to stay under the ceiling. Scenes with lots of change (video, scrolling, window dragging) therefore lose detail and look blurry, while static scenes stay sharp - the cap only bites on motion. That trade is worth it on intercontinental or otherwise constrained links, where an uncapped frame can take seconds to transmit and stall everything queued behind it, but it is a pure quality loss on a LAN. The tuning item now defaults to unchecked, so a master sends 0x3 (GDI no-sleep and send pacing) by default; machines that already stored TuningX264Vbv keep their explicit choice. The menu entry is renamed to "x264 码率封顶 (VBV,仅限洲际弱网)" and the en_US, zh_TW and de_DE translations were updated to match the new source string. Only newly opened remote desktops pick up the flag, since CMD_SCREEN_TUNING is sent when the session starts. Verified by rebuilding the Debug x64 server and client, and by finding the new menu and translation strings in the built binary. Co-Authored-By: deepseek-flash |
||
|
|
f77b18aa68 |
Feature: run a test client inside the master from the Advanced menu
The Advanced menu now ends with Run Test Program. It copies the kernel payload that was already read into memory, points its CONNECT_ADDRESS at 127.0.0.1:<listen port>, and loads it with MemoryLoadLibrary inside the master process, so this machine comes online as a controlled host -- no second machine is needed to try remote desktop or file transfer. A worker thread waits for the client to exit, then frees the module and re-enables the item. Only one instance runs at a time: the item is grayed while it does, and stopping it means uninstalling the test host from the online list. The loaded copy carries LOCAL_TEST_CLIENT_MAGIC in szFuture. The client uses that mark to refuse the commands that would otherwise hit the host process or the whole machine: uninstall (no self_del), update, run as admin, ban, share/assign, and shutdown/reboot/logoff. It also skips auth-kernel detection, which GetModuleFileName(NULL) would misjudge inside the master. Renames szFututre to szFuture and documents that the first 16 bytes of the reserved tail are now claimed, with a static_assert so it cannot silently shrink below the magic. Translations for en_US, zh_TW and de_DE, plus the HIDE_MENU_RUN_TEST feature flag and its row in the limits dialog. Verified on a Debug master: the item is last and has its icon, one click brings the host online, a second click is refused, uninstall stops it in about a second and the master survives, re-run works, and exiting the master with a live test client takes 2.6s (3.0s baseline). Co-Authored-By: deepseek-flash |
||
|
|
cc9ce35c4d |
Feature: export the built-in TLS certificate from the settings dialog
The built-in certificate lives only inside the server config as base64 DER, so there was no way to take it elsewhere -- to install it as a custom certificate on another machine, or to hand it to a proxy. The TLS certificate dialog now has an Export Certificate button next to the Built-in Certificate checkbox. It is enabled only while that box is checked. Clicking it opens a save dialog and writes two PEM files: the chosen .crt and a .key with the same base name in the same directory. The key is PKCS#8 and unencrypted; the success message says so. If the certificate has not been generated yet (box checked but the dialog not applied), the export generates it first, the same way OK does, then refreshes the expiry text. If the key cannot be written, the certificate written just before it is deleted, so no half pair is left. Translations added for en_US, zh_TW and de_DE; en_US and zh_TW are also embedded resources, so the server was rebuilt. Verified: Debug x64 server builds clean. Drove the dialog on a running Debug instance over window messages -- the button, its label and its enabled state track the checkbox. The PEM writer was checked against OpenSSL (x509 -subject, pkey -check) using the same CryptoAPI flags. The save dialog itself was not automated end to end. Co-Authored-By: deepseek-flash |
||
|
|
6a51116873 |
Fix: repair two quality-switch regressions (monitor jump, H264 stall)
Every quality change restarts the capturer on both sides, and two defects showed up along that path. Monitor jump: on a multi-monitor client the view moved to another monitor. switchScreen=false means "reuse the index", but index is the *next* monitor to switch to, not the one being shown. Track `current` and read it on the non-switch path; the switch path still advances. H264 stall: switching from RGB565/DIFF back to H264 froze the view for up to ten seconds. The client encoder kept its reference frames across the gap, so it emitted P frames the server could not decode until the next natural IDR. It is now rebuilt on the first H264 frame after an algorithm or tuning change. The rebuild is requested with an atomic dirty flag that the capture thread consumes in ensureEncoder(), because resetting the encoder from the network thread raced with encode(). On the server, ApplyQualityLevel() only sets m_bResolutionChanging when the client will really restart the capture: it compares the target maxWidth with the client's reported bitmap width (cached atomically on TOKEN_BITMAPINFO) and stays conservative while a previous resize is still in flight. The fallback timeout drops from 5s to 1s, flushes the decoder and asks the client for a keyframe (COMMAND_SCREEN_KEYFRAME_REQ). Verified: Debug client and server build clean; the 1920-wide High->Good switch no longer waits out the gate. Not yet retested on a live session. Co-Authored-By: deepseek-flash |
||
|
|
d6b04a98f0 |
Feature: throughput criterion for adaptive quality, plus anti-oscillation
Adaptive quality only looked at RTT, so a short RTT over a narrow pipe read as "excellent": at 20-40ms it picks Ultra/High (DIFF/RGB565), both with bitRate == 0, and never steps down. One 1080p RGB565 frame is 4.15 MB -- 1.66s of transmission on 20 Mbps. Adds GetTargetQualityLevelByLoad(): congestion needs both fps < 60% of baseline and bytes/frame still near the nominal bitrate, because a static screen has a near-zero byte rate on any link. Merged with the RTT result as max() -- averaging lets a good RTT mask a narrow pipe. Step-down is 3 confirmations and jumps straight to the level the throughput can carry (capped at +2); step-up stays RTT-only, so the criterion is one-way and the worst case is one level too low instead of a 30s/15s oscillation. Anti-oscillation, all inside the switch: RTT hysteresis (85%/115% dead band against the target level's threshold), failed step-up pinned for 3 minutes, cooldowns 3s -> 10s down / 15s up, counters interrupt each other, and a hard limit of 6 changes per 5 minutes. Server-only, no client change. m_ulBytesThisSecond had to be fixed first: it is accumulated before the switch, so file transfer, audio and clipboard counted as screen traffic; added m_ulScreenBytesThisSecond for the four frame cases. Also gates a real bug in the 10s post-step-down probe that disabled the criterion permanently on a static screen. Default on (same migration caveat as the other four). Unticking takes the original path unchanged. Verified on Debug: 27 hysteresis cases and the load cases pass, menu defaults correct; not yet measured end to end. |
||
|
|
ab83f5d685 |
Feature: persist file manager transfer history
History used to jump to the last directory merely visited, and lived only in memory. Now it is recorded only when a transfer actually starts (the four copy/transfer handlers) and persisted as an MRU list of the last 10 directories in THIS_CFG [file_history], keyed "local" plus one key per clientID. Paths are stored verbatim; '|' joins the list. The history handlers read the head of that list; the rest is kept for the future dropdown. Also translated the four zh_TW status messages, which were still simplified copies. Server-only; no protocol or client change. Co-Authored-By: deepseek-flash |
||
|
|
ca4e85826f |
Feature: remote desktop tuning flags, on by default with per-item opt-out
Adds "Advanced -> Remote desktop tuning" with three independently checkable items, all enabled by default: x264 bitrate cap (VBV) TUNING_X264_VBV 0x1 GDI capture: no slice delay TUNING_GDI_NO_SLEEP 0x2 Send pacing FPS floor TUNING_PACE_FPS_FLOOR 0x4 Unticking an item clears its bit and restores the pre-commit behaviour exactly, so the escape hatch is one click per measure -- no rebuild, no config edit. Each bit is independent; a problem with one does not force turning all three off. Plumbing -------- Menu state -> [settings] Tuning* -> CMy2015RemoteDlg::GetScreenTuningFlags() -> CScreenSpyDlg::SendScreenTuning() (right after TOKEN_BITMAPINFO) -> CMD_SCREEN_TUNING = 178 [cmd:1][flags:4 LE] -> CScreenManager::OnReceive -> m_nTuningFlags -> ScreenCapture::SetTuningFlags Why it is safe to send to old clients: CScreenManager::OnReceive has no default branch in its switch, so an unknown command falls straight out (verified). 178 was unassigned (177 = COMMAND_SET_PROTO, 199 = TOKEN_DECRYPT), and the enum re-anchors explicitly so nothing auto- increments onto it. Flags are sent even when all-zero on purpose: the client's flag lives in CScreenManager, which survives closing and reopening the remote desktop window on the same connection. Without the zero send, unticking the menu would leave the previous flags in effect. Per-measure notes ----------------- VBV: capped CRF (peak = target, 0.5s buffer, init 0.9). The hardware paths already cap via rc_max_rate (1.5x, 1s buffer); this is tighter and only affects x264. After an IDR the buffer drains and takes up to 0.5s to refill, so a brief quality dip follows every keyframe -- if that shows up, relaxing to 1.5x/1s would match NVENC/QSV. GDI: keeps the 50-line BitBlt slicing (large single BitBlts hit driver limits) and only drops the 5ms sleep between slices -- 1080p is 22 slices = a forced 110ms per frame against a 50ms budget at 20fps. Pacing: clamps s0 to 2x the base interval instead of 4x (2fps -> 4fps), taken as max(2x base, 1000/MaxFPS) so it never exceeds the configured MaxFPS. The growth/decay code itself is untouched. This one works against the loop's own congestion signal, so it is the first to untick if a bad link feels laggier rather than smoother. SetTuningFlags only rebuilds the encoder when TUNING_ENCODER_BITS (currently just VBV) changes -- the GDI and pacing bits are read live by the capture and send threads, and rebuilding for them would drop an IDR and visibly flash the picture. Defaults: the on-by-default value lives in the third argument of THIS_CFG.GetInt(), which only applies when the key is absent. A machine that already has an explicit 0 keeps it, so the flip is not retroactive and a test machine can end up with a mixed state. Verified on the Debug build: with no Tuning* keys all three items start checked; unticking VBV alone leaves the other two checked and survives a restart; en_US/de_DE/zh_TW translations all resolve. Not yet measured end to end on a real remote desktop session. |
||
|
|
1e336113a5 |
Feature: trial code can replace an existing licence, plus two UI refinements
三处独立的小改动,都在服务端 UI 层。 1) 试用软件:已有授权码时不再直接拒绝 原来 OnMasterTrail 一发现 settings\Password 非空就弹一句提示然后 return,用户 没有任何办法切回试用模式。现在把提示改成询问「是否更新试用口令?」,选「是」 继续走原有流程(合规声明 → 写 master/BindType/Password/PwdHmac/SN),原有授权 码被覆盖;选「否」保持原授权不变,与改动前行为一致。 2) 语言对话框显示语言包目录 语言选择框下面加一行只读信息:标签 + 可选中复制的只读编辑框。目录存在时显示 GetFullPathName 解析后的绝对路径(配置默认值是相对路径 ./lang,直接显示看不出 实际位置);未设置或目录不存在时显示「内置/预设」,此时只有内嵌的 en_US / zh_TW 可用。 对话框是 DLGTEMPLATE 手工拼的动态模板,.rc 里没有对应资源:高度 75→92、 cdit 4→6、OK/Cancel 下移到 y=67。标签 cx 取 120 而非 55,否则英文 "Language pack folder:"(约 70 DLU)和德语 "Sprachpaketordner:" 会被裁掉; 编辑框带 WS_BORDER,手工拼的控件没有资源编辑器那种默认边框。 3) 远程交谈:没选中主机时不弹确认框 OnChat 原来无条件弹「确定开始远程交谈吗?」,但没选主机时 SendSelectedCommand 的目标列表为空,确认了也发不出去。改为先判断再弹。用 GetFirstSelectedItemPosition 而不是 ResolveCommandTargets:后者要读 m_ClientIndex / m_HostList,网络线程会并发修改,UI 线程裸调不安全,而 SendSelectedCommand 内部本来就持 m_cs 调过一次;这个 API 就是 ResolveCommandTargets 里的同一个判定。m_CtxMenuTargets 判断保留——右键菜单 派发期间目标存在那个快照里,列表选中项可能为空。 三份语言文件各补 3 条译文(含第 1 条的询问文案)。德语沿用 ASCII 化写法 (fuer / ueberschrieben),因为 GBK 存不下变音字母。 已在 Debug 版实测:语言对话框两个分支(路径 / 内置预设)截图确认无裁剪、按钮 在框内;远程交谈未选主机时 PostMessage ID_TALK_MANAGE 后不产生任何窗口。 |
||
|
|
356aa27108 |
Feature: Reject MCP tool calls the target client cannot handle
tools/list 不带参数,无法按目标设备过滤工具列表。60 个工具里有 33 个只在 Windows 客户端上有实现,模型无从得知,只能下发命令后白等超时。 DispatchSingleHostTool 开头按 kToolPlatforms 表核对目标主机平台,不匹配立刻 返回 -32005;批量路径经由同一函数自动覆盖。主机不存在或离线时放行,把 -32002 留给工具自己报,避免同一个问题出现两种错误码。 支持面是刻意设计的阶梯:win 60/60、lnx 27、mac 16、apk 10。60 个工具全部含 win,所以 Windows 客户端永远不会被这道门禁拒绝,行为与改动前完全一致。 平台表按服务端实际放行来标,不按客户端能力标。两处会分叉的地方: - exec_command / terminal_* / kill_process:macOS 客户端有实现(main.mm:753 的 ShellworkingThread、SystemManager 的 KILLPROCESS),但服务端刻意拦着 (McpServer.cpp:3652「macOS 本轮不开放」、6870),故标 win+lnx。 - list_windows:Linux/macOS 的 SystemManager 都有 COMMAND_WSLIST 分支,但 BuildListWindows 把命令发在主连接上,而这两个平台的主循环只处理 COMMAND_SYSTEM (起子连接),WSLIST 只在子连接里才被处理,走不到。实测 Linux 上直接超时 -32001。那两个 case 是给 SystemDlg 用的,故标 win。 copy_files_c2c 是唯一的非对称工具(源端必须 Windows,目标端可 win/lnx/mac, 反向不支持),用 roles 按参数名分别声明,C++ 侧 CollectTargetReqs 对应处理。 配套 mcp/tools.json(60 个工具,version 2)与 tools/mcp_tools/ 下的抓取、生成、 比对、校验脚本。check_platform_table.py 校验 C++ 表、tools.json、instructions 三方一致,并把「Windows 全量」做成不变式。 已在 A6(Windows 11)与 Ubuntu24(Linux)上实测:Windows 侧 14/14 通过且无误拒, Linux 侧 11 项拒绝全部命中门禁,copy_files_c2c win->lnx 成功、lnx->win 被拒。 开关 McpPlatformGuard(默认 1),关闭只失去提前拦截,不影响任何执行路径。 |
||
|
|
8c0351b45b |
fix(server): show UTF-8 process names correctly in the connections dialog
The connections dialog decoded procName with CA2T(x, CP_UTF8). In this MBCS build CA2T expands to CA2A, whose nCodePage argument ATL explicitly ignores (atlconv.h: "(void)nCodePage") - the call just memcpy's the bytes. So the UTF-8 process names sent by the client were copied verbatim into a CString and rendered as GBK: Chinese names turned into mojibake while pure-ASCII names looked fine, since UTF-8 and GBK coincide there. Display via the established pattern instead (same as the client list and the process manager): convert UTF-8 to UTF-16 with MultiByteToWideChar and write the item text with LVM_SETITEMTEXTW, bypassing the ANSI code page entirely. This also keeps Chinese names readable on servers running a non-Chinese ACP. The sort key keeps the raw UTF-8 bytes: byte-wise comparison of UTF-8 equals code-point order, and no characters can be lost in conversion. |
||
|
|
d3c165de79 |
fix(feature-limits): keep flags above bit 31 on 32-bit builds
CCheckListBox keeps its own per-row state in the item data slot and exposes a DWORD_PTR user field inside it, so every flag this dialog stored travelled through a value that is only 32 bits wide in a Win32 build. On a 32-bit server, each menu and context row at bit 32 or above therefore came back as zero: 26 entries in the 主菜单 tab, from 插件请求 to DLL内嵌TLS证书, and 14 in the 右键菜单 tab, from 虚拟屏幕(插件) to 执行代码. Ticking one wrote nothing into the generated master, and reopening the dialog showed it unticked again. The narrowing never produced a warning because C4244 is listed in DisableSpecificWarnings for all four configurations, and the x64 build, where DWORD_PTR is 64 bits wide, was unaffected. Store the row's index into the tab's item vector instead of the flag itself, and have CollectFlags() look the flag up in that vector, so the value never narrows in either architecture. The vector index also survives the compile-time skips in PopulateList and needs no change when the flags grow into a second 64-bit word. Verified by building the Debug server for x64 and x86. Co-Authored-By: deepseek-flash |
||
|
|
c66f410831 |
Feature: Embed the server TLS certificate in delivered DLLs
Add a "高级 → DLL内嵌TLS证书" toggle (off by default, persisted as
[settings] EmbedTlsInDll). When it is on, ReadKernelDll patches the server's
current TLS anchor into the ServerDll and ShellCode payloads, so clients that
come online through the loaders start their own session over TLS without
waiting for an online push. The plaintext DLL loader in client/main.c is
untouched; only the DLL's fresh connection is protected. The write happens
after SetServer and before CalcMD5FromBytes, and the anchor records the host
part of the master address rather than "ip:port" because the client matches
the anchor against its configured address set. TinyRun has no anchor block and
keeps working as before.
Toggling the switch, and confirming the certificate dialog, rebuild the six
payloads in place, so no server restart is needed after a certificate change.
The payload pointers are replaced as a whole, and the network threads that read
them (SendServerDll and TOKEN_GETVERSION) now take a dedicated critical section
for the full duration of use.
COMMAND_UPDATE no longer clears the tls_disabled marker on the client. Now that
any delivered DLL may carry the anchor, "the payload has an anchor" no longer
means the operator opted this host into TLS, and clearing the marker would
silently flip a host that was explicitly set to plaintext onto TLS against a
plaintext path. Re-enabling TLS stays an explicit action through
COMMAND_TLS_ENABLE and COMMAND_SET_PROTO, which still clear the marker.
Menu and notice strings were added to en_US, zh_TW and de_DE, and the embedded
TLS design document records the new switch and the revised update semantics.
The new menu entry also takes a feature-limits slot so a subordinate master
can hide it like every other 高级 item (see
|
||
|
|
454d25d37f |
fix(share): carry the transport in the share and assign payloads
The share payload was host:port:shine and carried no transport at all, so a
shared client fell back to its baked-in protoType. Share instances also skip
ApplyProtoSwitch (ClientDll.cpp:810), so a client upgraded to WSS was shared
to a TLS front end as raw TCP and looped on HTTP/1.1 400.
Extend both payloads with an optional trailing transport field:
share : host:port:shine[:transport]
assign : host:port:days:shine[:transport]
The field is omitted when the source protocol is not TCP/WS/WSS, so HTTP/UDP/
KCP hosts keep their previous behaviour instead of being silently downgraded
to plain TCP.
- server: add SelectedShareTransport(), share it between OnOnlineShare and
OnOnlineAssignTo, and accept a tcp:// ws:// wss:// prefix in the address.
- client: parse the field on both paths and persist the assigned value to
settings/master_transport, clearing it when the field is absent.
- share_list: dedup on host:port instead of the whole record, so re-sharing
a host with a different transport replaces the stale entry.
- assign: guard bToken[_MAX_PATH] against the longer payload.
- lang: translate the reworded prompt and the three new messages in en_US,
zh_TW and de_DE.
Transport is pinned at share time and does not follow a later protocol switch
on the master link; the m_bShared gate stays as-is on purpose.
|
||
|
|
951b4072e5 |
Feature: Embed the master's TLS certificate in generated clients
When the server has TLS enabled, the builder can now bake its certificate into the client it produces, so a distributed client speaks TLS on its very first connection instead of waiting for the anchor to be pushed after a plaintext login. The dialog gets a checkbox (IDC_CHECK_TLS_ANCHOR) that is only enabled for payloads and protocols where an embedded anchor makes sense; the choice is remembered even when the control flips to disabled and back, so switching protocols cannot silently undo a deliberate opt-out. Every label variant stays short enough to fit the 196 DLU field, including the German ones. A template that predates the anchor block no longer aborts generation: it warns, clears the checkbox and produces a plain client, so a master upgraded without rebuilding the ghost/ServerDll resources does not block every build. The certificate lands in a fixed 4 KiB block (magic, version, length, FNV-1a hash, master address, PEM) carved out of the payload at build time. The client reads its trust anchor from four sources in order: the tls_disabled marker, the certificate the server pushed into the registry, a PEM file next to the executable, and finally the embedded block. The embedded block only applies to a connection whose target matches the master recorded at generation time, compared as an address set: an exact string match when only one address is configured, or an intersection of resolved IPv4 addresses otherwise. A transferred, shared or parallel instance falls back to the old plaintext first-connect path instead of pinning itself to a certificate it can never verify. That decision is made per connection, not per process: shared and parallel instances are threads inside a single client process, so a process-wide flag let whichever instance connected first decide for all of them, and the first load of the TLS state cached that answer for good. The TLS layer now keeps two cached states (embedded anchor allowed, and not allowed), picks one per handshake, and reports the anchor source of that handshake for the login capability bit. Matching by resolved address also keeps parallel mode working, where the connection goes to the single IP the domain pool selected while the configured master is a domain or a list. Server side, generated and updated payloads get the block written in place; the client reports the capability bit on login so the console can tell which hosts are already TLS-only on first connect. Loading the anchor decodes every PEM block in the chain rather than just the leaf, and an anchor that exists but fails to load keeps the old fail-closed behaviour. A pushed anchor only reconnects when the transport of the live connection actually changes, judged against that connection's own target rather than the process-wide switch. This was verified end to end against a freshly generated client with an empty registry: the first connection was a TLS 1.2 ClientHello 0.2 s after start, and a four-certificate fullchain loaded all four blocks. Re-verified after the per-connection rework with the anchor block patched into a debug client: with a matching master the first bytes are a ClientHello, with a foreign master the client logs the skip and sends plaintext, and a domain master resolves to the IP it connects to and still matches. A master domain that no longer resolves falls back to plaintext within a second and is not looked up again for a minute, instead of stalling every reconnect on a DNS timeout while holding the lock the certificate verification needs. Co-Authored-By: deepseek-flash |
||
|
|
c4021e1fc9 |
Feature: Ship a built-in TLS certificate so encryption works out of the box
A fresh install used to require openssl before the server could speak TLS: two empty paths in [tls] meant the identity failed to load and every ClientHello was refused. TLS is now on by default and, when no custom certificate is configured, the server generates its own self-signed one the first time it needs it -- RSA-2048, SHA-256, CN=yama-server, CA:TRUE, valid for ten years from one day before now. Plaintext clients are untouched, since the device port still splits plaintext from TLS by sniffing the first six bytes of a connection. The certificate and its PKCS#8 private key are stored side by side in the config under [tls] BuiltinCert / BuiltinKey as single-line base64 DER. Single line, because the server has two config backends -- the registry for Release, settings.ini for a Debug master -- and only a line without newlines means the same read/write code serves both. That in turn required fixing the registry reader: iniFile::GetStr copied into a 512 byte stack buffer, so a 1.5 KB value came back as a truncated or empty string. The two-phase dynamic read now lives in common/iniFile.h as ReadRegistryValueSz / ReadRegistrySz, and the copy that client/TlsChannel.cpp had been carrying for its own trust anchor is gone. This also makes the built-in certificate self-checking: Ensure() re-reads what it just wrote and fails loudly if the round trip did not survive. Import has to go through NCRYPT_PKCS8_PRIVATE_KEY_BLOB, matching the import path in BuildIdentityFromDer. NCRYPT_PKCS8_PRIV_KEY_INFO_BLOB, which most samples reach for, is not implemented by the Microsoft Software KSP and returns NTE_INVALID_PARAMETER; a probe confirmed it, and the export type that works is the one the importer already expected. Building an identity is now split into a file front-end (PEM, fullchain, PKCS#1 hints) and a shared DER core, so the built-in and file paths cannot drift apart. That key also exposed a second problem worth fixing here. The identity binds its private key to the certificate by name -- CRYPT_KEY_PROV_INFO with pwszContainerName -- and Schannel resolves that name on every handshake through CryptAcquireCertificatePrivateKey. With the fixed name "YamaServerTlsKey", two server processes under the same Windows user shared one key slot: whichever loaded last overwrote it, and the other process's next handshake picked up a private key that does not match its certificate. That is exactly the debug-plus-release pairing used here, and defaulting to a built-in certificate is what makes it reachable, since the debug instance no longer points at the same PEM as the release instance. The name is now the base name plus the first six bytes of the certificate's SHA-1 thumbprint, e.g. YamaServerTlsKey-c0d469eae8a4: different certificates get different keys, instances sharing one certificate still share one key. MCP picks this up too. The effective name goes to the trace log so a collision is visible without a debugger. A stale key from an older build may still sit in the key store under the old name; nothing references it and it is not deleted automatically, since a running instance of an older build could be using it. The trust anchor still has to be pushed. The client pins exactly one root through an exclusive-root chain engine and checks no host name, so a self-signed CA:TRUE leaf chains cleanly to itself -- but only if the client is told about it. That is the existing 启用 TLS / 切换到 WSS command, which now takes the PEM from ServerTlsIdentity::AnchorPem instead of re-reading the configured cert file, so it reports the same certificate the server actually serves for both sources. Losing the stored certificate (cleared registry, new Windows user) regenerates it, and every client must be re-pushed the anchor. Two places that used to fall back to [tls] CertPath now skip that fallback while the built-in certificate is active: the MCP HTTPS front end at startup and the prefill in its settings dialog. A self-signed certificate cannot pass validation at a public MCP client, and the retained CertPath is only a leftover from switching back to a custom certificate, so pretending to use it would fail later with a worse message. MCP HTTPS with empty paths already fails closed with a log line. The TLS dialog gains a 内置证书 checkbox, ticked by default and unticked when certificate paths are present; ticking it greys out the path rows without clearing them, and shows either "generated on first use" or the expiry date read back from the stored certificate. Saving writes four keys -- Enabled, UseBuiltIn, CertPath, KeyPath -- and an explicit UseBuiltIn keeps the paths from being used as an implicit switch. Every reader of [tls] Enabled now defaults to 1, so the menu check, the dialog and the loader agree on a fresh install. The status bar panes on 无 / 有 grew a third state, 内置, and the pane width is measured across all three. Translations were added to en_US, zh_TW and de_DE; skipping the German file would have left the new dialog text in Chinese there, as de_DE is loaded from disk rather than embedded. Verified with the debug server against openssl s_client. Both the generated built-in certificate (CN=yama-server) and an existing custom one (CN=localhost) complete a TLS 1.2 handshake with the pinned certificate, and their log lines show distinct key names, c0d469eae8a4 and 272f2adfb19c. An unmodified client still runs in plaintext without an anchor, an existing custom certificate deployment behaves exactly as before, and client and server both build clean at Debug x64. Co-Authored-By: deepseek-flash |
||
|
|
4f9bfb0fdc |
fix(server): stop two remote-input paths from killing the server
Both bugs let a remote peer terminate the server process: the first needs no credentials at all, the second needs only a malicious client. 1) cpp-httplib 0.14.3 -- unauthenticated DoS via Content-Length Content-Length was parsed with strtoull, which accepts a leading sign, so "-1" wrapped around to ULLONG_MAX. read_content then treated that as an oversized body and called skip_content_with_length(strm, ULLONG_MAX), a loop that only exits after consuming 18 EB -- a client trickling bytes never trips the read timeout, so the worker thread is stuck forever. With ThreadPool(32) that is 32 connections to wedge the whole server. Body parsing runs before the MCP token check, so no token is required. Backported from upstream 0.51.0/0.64.0 as parse_content_length_strict(): only plain decimal digits are accepted and overflow is rejected. Upgrading the library instead is not possible -- 0.25.0+ requires _WIN32_WINNT >= 0x0A00 (Win10) while this project targets 0x0602 (Win8), and the last Win8-compatible release (0.20.0) predates the fix. Verified: negative, leading-plus, overflow and trailing-garbage values now all return 400; 40 concurrent "-1" requests are rejected in under 50 ms with the thread pool still healthy; plain and chunked requests are unaffected. 2) HideScreenSpyDlg::JPG_BMP -- malformed JPEG terminated the process The decoder was set up with libjpeg's default error_exit, which calls exit(EXIT_FAILURE). Since the input is a JPEG stream sent by the remote client, one structurally invalid frame killed the whole server. Replaced with a setjmp/longjmp handler that turns fatal errors into "return false", matching this function's existing failure paths. Warnings still go through emit_message, so truncated-but-recoverable images behave exactly as before. Verified against 36 malformed samples: 19 used to terminate the process, none do now (the same 19 return false), and valid JPEGs decode identically. 3) Drop the dead file_server.h An older HTTP file-serving implementation, superseded by WebService.cpp and referenced by nothing: no include anywhere, no instantiation, no entry in the vcxproj or any build script. Removing it keeps the real HTTP attack surface -- httplib's /mcp plus WebService -- unambiguous for anyone auditing this code. |
||
|
|
8807321f1d |
Feature: Bring feature limits in line with the current menus
The "feature limits" dialog offered by 主控生成 had drifted well behind the UI: a whole 高级 menu, five toolbar buttons and a couple of dozen context menu entries could not be restricted at all, and several items were listed under names that no longer appear anywhere. The three tabs now follow the real resources. Menu items are listed in the order of IDR_MENU_MAIN and carry the same text minus accelerators; the toolbar covers all 19 IDR_TOOLBAR_MAIN buttons; the context menu lists the nested 实验功能 / 客户管理 / 远程控制 / 机器管理 / 客户代理 / 执行程序 entries individually and the two runtime-built ones (协议切换, 执行代码) as groups. That makes 57 / 19 / 46 items, each with its own bit; new bits were added at the end of each field so the existing positions stay put. Enforcement was extended to match, and while wiring it up one long-standing bug surfaced: DeleteMenu(MF_BYCOMMAND) only reaches items of the menu it is called on, so hiding an entry of a nested popup had always been a no-op. Nested items are now deleted through their own submenu handle, and a popup whose items are all hidden is removed together with its parent entry, so no empty popup is left behind. 协议切换 is inserted relative to where 实验功能 ended up, which keeps it next to it either way; 执行代码 is simply skipped when restricted. The missing labels were added to en_US, zh_TW and de_DE. Co-Authored-By: deepseek-flash |
||
|
|
559681ea01 |
Feature: Show TLS and MCP state in the server status bar
The main window's status bar now carries two short panes between the host count and the FRP address. The first reports whether the server identity is loaded, using the same ServerTlsIdentity::IsReady() check the rest of the UI uses, so a menu that claims TLS is on cannot leave the bar saying otherwise when the certificate failed to load. The second reports whether MCP is enabled and, while it is, which protocol the endpoint speaks: (HTTP) or (HTTPS) according to McpHttps. Both panes follow the existing 60 second statistics tick, and toggling either switch in its dialog refreshes them at once instead of leaving the bar stale until the next tick. Pane widths are measured from the widest text each pane can show in the current language instead of hardcoded pixels, and the measurement selects the status bar's own font: DEFAULT_GUI_FONT is about 8% narrower than the Segoe UI the bar paints with, which would have clipped "MCP: ... (HTTPS)" at higher display scaling. Switching HTTP/HTTPS keeps the column width steady, and turning MCP off lets it shrink again. The MCP settings dialog was also missing translations for several of its labels, the file write switch among them, which is why they stayed Chinese in the English UI. Those keys, together with the status bar ones, are added to all three language files. Co-Authored-By: deepseek-flash |
||
|
|
e99092ca70 | Release v1.4.2 | ||
|
|
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 |
||
|
|
6a3d536d38 |
fix(server): keep the build dialog's default protocol at TCP
Commit
|
||
|
|
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 |
||
|
|
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 |
||
|
|
99db28e2e2 | Feature: Let the operator switch a live client's transport from the online list | ||
|
|
cc891e3670 | Feature: Sniff WebSocket upgrades on the MFC server's device port | ||
|
|
d4f312c9d8 | Feature: Tunnel the device protocol through a reverse proxy over WebSocket | ||
|
|
1d875ddbd1 |
Feature: Add a "Copy Name" item to the online host context menu
The online list already lets an operator copy everything about a host through "Copy Client Info", but there was no quick way to grab just the names, which is what people actually paste into a chat or a ticket. The new menu item sits directly below "Edit Group" and copies the names of all selected hosts to the clipboard, separated by semicolons. "Name" means what the first column of the list shows: the remark when one has been set, otherwise the computer name. The column text is CP_ACP, so the handler decodes it the same way OnGetdispinfo does; that keeps the copied text identical to what is on screen, including for Chinese remarks. Clipboard writing reuses the existing UTF-8 based SetClipboardText helper instead of growing a third copy of the same CF_UNICODETEXT code. The item also gets its own 16x16 icon (two stacked cards with text bars, drawn on the usual 240,240,240 background) loaded into a newly added m_bmOnline[75] slot, and translations were added for English, German and Traditional Chinese so the item does not fall back to simplified Chinese when another UI language is active. The user manual and the resource README were updated to match. Co-Authored-By: deepseek-flash |
||
|
|
dcb5ae25c6 |
Fix: Paginate get_activity_history results
The tool was the only list-type tool without pagination. The client keeps ACTIVITY_HISTORY_MAX=500 records and Dump() prepends the in-progress window, so a single call returned up to 501 lines of "[time] [title] duration" -- enough to blow up the caller's context, especially since titles carry personal browsing history. Records come back newest-first (m_records uses push_front and the current window is prepended), so the standard limit/offset window applies directly: offset=0 is the most recent page, no need to read total first and count backwards. That ordering is now stated in the tool description so the model can rely on it. - inputSchema: BuildGetHostDetailInputSchema -> BuildPagedHostListInputSchema (adds limit, default 100 / max 1000, and offset) - outputSchema: append AppendPageOutputProps plus truncated - implementation: rename the full split to `all`, slice via ResolvePageWindow and ApplyPageWindow, write back with WritePageFields - activityHistory is rebuilt from the window instead of returning the whole Dump() text -- otherwise the raw copy would bypass pagination entirely - 64 KB byte budget (same as get_client_log), trimmed from the end so the newest records survive; hasMore is computed as offset+kept < total rather than hardcoded true, since a single oversized tail record must not claim there is another page Batch calls need no extra work: the tool is already in IsBatchReadOnlyTool, and BuildBatchCall forwards limit/offset to each host, so ids + limit means "the latest N records of every host". Compiles clean; not yet exercised against a running server (the exe was locked by the live instance). Verification cases are listed in docs/Mcp_Test_Report_2026-10-29.md section 8. |
||
|
|
56a937fabb |
Fix: Three blocking defects found by the MCP tool survey
The survey in docs/Mcp_Test_Report_2026-10-29.md turned up three P0s, each
of which stopped a whole capability rather than degrading it. Two of them
were the same mistake: the input schema promised something the output
schema then rejected. The third was an output with no size limit, plus a
client that never implemented the command at all.
Batch calls could never succeed. A call carrying ids[] goes through
BuildBatchCall, which returns {tool, total, succeeded, failed, skipped,
results[]}; every tool declares only the single-host shape. The client
validates structuredContent against that declaration, so any batch call
failed with -32602: data must have required property 'host' - the input
schema advertises ids, the output schema kills it. Tools/call cannot fix
this one call at a time, so ApplyBatchOutputSchema runs at the end of
tools/list, next to ApplyToolAnnotations, and rewrites the schema of every
tool in the batch list to {type: object, anyOf: [single, batch]}. Placing
it at the end is what makes it cover all three registration points
(inline, McpMachine, McpChat) and any tool added later. IsBatchReadOnlyTool
moved from McpServer.cpp to McpInternal.cpp for the same reason: the list
is now read by tools/call and tools/list, and the two must not drift.
list_registry failed whenever path was omitted. The root-key branch
returns keys only, while the output schema listed values in required as
well, so the first usage the documentation describes - omit path, get the
five root keys - could not work. values is no longer required and the
schema says it is absent in that branch. The root branch also returns
path: "" now, so both branches carry the same field set and callers need
not branch.
get_client_log was unusable on both platforms, for two unrelated reasons.
Windows returned the whole 1000-line ring buffer, 90,473 characters, over
the client's result limit: fetched, then not deliverable. Linux and macOS
timed out because their clients never handled COMMAND_QUERY_LOG at all -
only client/ClientLogManager.cpp does - so TOKEN_REPORT_LOG never arrived.
Adding a limit alone would have left Linux broken; fixing the client alone
would have left Windows over the limit.
The server now takes limit (default 200, max 2000) and filter, and reads
backwards from the end: troubleshooting wants the last thing that happened,
not the first line after boot. A 64 KB byte budget sits under the line
count, because one line can be a stack dump; when the final line alone
exceeds it, the tail is returned and truncated says so. Responses carry
lines_total, lines_matched, lines_returned and truncated. The timeout
message now names the likely cause and two ways around it instead of
saying only "Timeout waiting for client log".
The POSIX clients get common/ClientLogHandler.h, a counterpart to the
Windows CClientLogManager, and one line each in linux/main.cpp and
macos/main.mm. It must open a sub-connection: MessageHandle's
TOKEN_REPORT_LOG branch takes the first packet and then calls CancelIO on
that connection, so answering on the main connection would close the main
connection and drop the client offline.
Verified against a server built at 21:17:21 with both clients rebuilt. A
batch get_host_detail over the two A6 records returns succeeded=2 with
per-host data; host_list_processes with ids returns 2 of 2, which exercises
the McpMachine registration point rather than the inline one; a mixed
Windows/Linux batch of get_client_log returns 2 of 2. list_registry with
no path returns the five root keys and path ""; with a path it still
returns its values. get_client_log on Windows goes from 1000 lines to 200
with truncated=true, and limit=3 with filter=ConnAuth yields 28 matched and
3 returned. On Ubuntu 24.04 it returns logs at all, and the client's own
log shows Enter ClientLogThread, TOKEN_REPORT_LOG, then Leave about a
second later when the server cancels the connection - paired, no leak.
The connector still caches an old input schema for get_client_log, so
limit and filter are rejected locally until it reconnects; the defaults
already cover the P0, and this is the same cache problem as the
copy_files_c2c.overwrite entry in the report's P1 list.
docs/Mcp_Design.md section 18 records the implementation and the reasoning;
section 7 of the test report carries the verification table.
Co-Authored-By: deepseek-flash
|
||
|
|
dc4fd792f6 |
Feature: Implement the Linux screen preview response
The Linux client now answers COMMAND_SCREEN_PREVIEW_REQ, so a host with an X11 desktop gets a thumbnail when it is double-clicked in the online list, a frame in the list's Preview column, and an image from the MCP get_screenshot tool. Previously only Windows clients advertised the capability and Linux hosts showed "预览不可用" after a four second wait. The client does not encode JPEG. Stock desktops ship libjpeg.so.8 whose struct layout is the distribution's ABI (JPEG_LIB_VERSION 80), while the in-tree jpeglib.h is libjpeg-turbo 3.1.1 (62), and libturbojpeg is not installed by default; dlopening the system library against that header fails with "Wrong JPEG library version: library is 80, caller expects 62". Instead the client sends raw pixels in a new screen preview format, SCREEN_PREVIEW_FMT_BGRX: top-down rows of B,G,R,X with no row padding, already scaled to the requested width. The server re-encodes to JPEG at the single ingress point, so the preview popup, the list thumbnail cache and the MCP tool keep consuming JPEG only. Capture follows the path ScreenHandler already uses: root window copied into an offscreen pixmap with an IncludeInferiors GC, then XGetImage, which avoids BadMatch under compositing window managers. The X11 type declarations and the dlopen loader moved out of ScreenHandler.h into linux/X11Loader.h so both users share one dlsym table. The full-size image is never materialized: a box filter reads straight from the XImage rows (honouring bytes_per_line) into the output buffer, scales to maxWidth without upscaling, and clamps the height to 1080 so a portrait 4K desktop cannot produce a 26 MB packet. Rows and columns come out even, which they are for JPEG anyway. The capability bit is now honest about the runtime. LOGIN_INFOR grows DefaultCaps()/SetCaps(), and the client recomputes the bits before every login and re-login: CLIENT_CAP_SCREEN_PREVIEW is set only when DISPLAY is present and the X server actually opens. A headless host therefore gets -32005 "Host does not support screen preview" from MCP instead of a timeout, and a host whose session appears after boot picks it up on the next reconnect. Requests are handled on a detached worker thread behind a single-flight guard (matching the Windows client), so a slow XGetImage never stalls the receive thread and a burst of requests degrades to "no preview" rather than queueing. If the worker thread cannot be created, the guard is released again, so one failure cannot leave every later request rejected as busy until the client restarts. The MCP design note claimed the capability was declared by Windows only, and the get_screenshot tool description said the same; both now say what the code does (Windows always, Linux when a display is reachable). Server side, NormalizeScreenPreviewPacket runs in MessageHandle before the MCP handoff and the PostMessage to the UI thread. It validates that width/height are within the values the server itself can ask for and that bytes equals width*height*4, converts with a stack Gdiplus::Bitmap over the packet's own pixels (no copy, and no DEBUG_NEW trouble), and rewrites the header to JPEG. The encoder output is read back by seeking the stream rather than GlobalSize, so the packet carries no heap-block padding after the EOI marker. Malformed packets are dropped; failure statuses pass through untouched so the existing code can report them. Tested against a Debug server with the WSL Ubuntu 24.04 build as the client. get_screenshot returned valid JPEGs at max_width 480 (480x142, 1.7 KB) and 1920 (1920x570, 17.9 KB), repeatably; the list showed a thumbnail for the GUI client and N/A for a second copy started without DISPLAY, which also answered -32005. The box filter and the BGRX to JPEG conversion were checked separately with quadrant fixtures: the browser over the synthetic B,G,R,X buffer recovers red/green/blue/white in the right channels and the downscale averages, handles non-integer ratios and row padding, and rejects 24bpp and upscaling. The captured frames come out black under WSLg because Xwayland keeps no root pixmap there; that is the compositor, not this code, and Xorg sessions capture normally. Co-Authored-By: deepseek-flash |
||
|
|
5bff9df3fc |
Improve: Harden the self-implemented SOCKS5 proxy listener
Follow-up to the HP-Socket replacement: the four items the first pass deliberately left out, plus two defects that the new tests turned up. The listener now binds 127.0.0.1 instead of INADDR_ANY. The dialog only ever points the user (and the Chrome shortcut) at 127.0.0.1, and an unauthenticated SOCKS5 port open on every interface is an open proxy. The SOCKS5 handshake is parsed as a byte stream. The previous code assumed one callback carried exactly one message, which happens to hold for curl and Chrome but not in general: a greeting split across segments was answered twice, and a CONNECT request followed by tunnel data in the same read dropped the trailing bytes. Each connection now keeps a pending buffer and a four-state machine (greeting, request, connecting, tunnel), and bytes that arrive before CONNECT_RESULT are replayed to the client once the tunnel opens, after the SOCKS5 reply. Flow control: the listener takes a PROXYCANRECVPROC callback that is consulted before each recv. The dialog answers it from the main connection's send queue, so a download that outruns the client link pauses the local read instead of growing the server's buffer. A 300MB transfer through the tunnel peaks 150KB above the idle working set. Handshake watchdog: sessions that stall in greeting/request/connecting are dropped after 30 seconds; established tunnels are left alone. Two defects in the log path, both surfaced by the watchdog test. Logging every 32KB chunk produced roughly 9000 posted messages for a 300MB transfer, which starved the UI thread's timers (the first watchdog run never fired) and could overflow the message queue; and every line re-set the whole 256KB text into the read-only edit. Transfers now log cumulative progress once per second and a per-connection total at teardown, panes are refreshed at most every 100ms from a dirty flag, and a failed PostMessage no longer leaks its CString. Localization: the new session-log strings were also added to en_US.ini, zh_TW.ini and de_DE.ini (16 keys each, GBK, kept in the existing FormatL section). Two of the lines were reworded instead of translated as-is: the close notice now says what happened (the client asked to close, or the downlink send failed) rather than printing the protocol token name, and the throughput arrows are now << and >> because CIniParser splits an entry at the first '=', so the old <== and ==> could never have served as keys. Testing: curl IPv4 and hostname tunnels, 4MB and 300MB transfers byte-identical, byte-at-a-time and pipelined handshakes, refused target (REP=5), SOCKS client killed mid-transfer, client process killed mid-transfer (dialog closes, port released), 20 parallel connections, five open/close cycles with no handle or thread growth, and the 30s handshake timeout. The dialog log was checked at runtime with Language=en_US and renders in English only. Co-Authored-By: deepseek-flash |
||
|
|
45e1dd9f6c |
Feature: Implement the proxy mapping listener without HP-Socket
The proxy mapping dialog ("代理映射") depended on HP-Socket: three vendored
SDK headers (4787 lines) plus #pragma comment(lib) lines pulling in four
prebuilt lib/DLL variants, all guarded by ENABLE_HPSOCKET, which has been 0
since the initial commit -- so the feature was dead code that only answered
"This feature is unavailable due to HPSocket disabled" and no build of this
repository ever ran it.
Replace that dependency with a small listener built on blocking sockets and
select, which is the same approach the client's CProxyManager and the
server's own SimpleWebSocket already take. The accept loop polls every
200 ms so Shutdown can return without closing a socket another thread is
selecting on, and each accepted connection gets a relay thread that only
has to recv and hand bytes to the dialog. Connection sockets are closed by
their relay thread alone; Disconnect only raises a stop flag and calls
shutdown() under the same lock the relay thread takes before closesocket,
so a recycled handle is never shut down by mistake. Finished threads are
parked in a graveyard and joined by the accept thread, which keeps the
thread handle count flat across open/close cycles.
ProxyMapDlg keeps the SOCKS5 state machine it had, but now stores its
per-connection state in a map keyed by the connection id instead of
relying on HP-Socket's GetConnectionExtra, and it logs through a posted
window message rather than touching CEdit from worker threads. The two log
panes in IDD_PROXY are ES_READONLY, so EM_REPLACESEL was silently ignored
(the original code had the same latent bug); the dialog now keeps the pane
text itself and writes it with SetWindowText, bounded to 256 KB per pane.
The vcxproj and filters lose the three SDK headers, and the dialog gate in
OnOpenProxyDialog loses its ENABLE_HPSOCKET check.
Tested against a Debug server with a Debug Windows client on the same
host: curl through the listener succeeds over both the IPv4 and the
hostname ATYP paths, a 4 MB transfer arrives byte-identical, a refused
target maps to SOCKS5 reply 5, killing the client mid-transfer closes the
dialog and releases the port, and five open/close cycles leave the server's
handle and thread counts unchanged.
Co-Authored-By: deepseek-flash
|
||
|
|
13c02fe50b |
Feature: Skip already-present targets in copy_files_c2c
The destination writes every chunk unconditionally, so a second call with the same arguments re-sent the whole file and returned exactly the same result as the first. Measured on an 11 MB log: the target's mtime moved and the entry count did not, and the caller had no way to tell a real transfer from a repeat. upload_file and download_file already answer this with overwrite/skipped; copy_files_c2c was the one that did not. The skip decision has to be made on the server, because the receiving end does not check whether the file exists. Before opening the transfer, a default call now lists one level of dst_dir through ListRemoteTopLevelNames - the helper upload_file already uses - and drops the paths whose basename is already there. If everything is dropped the call returns success without creating a transfer id at all, so no host is occupied and nothing is sent. overwrite=true restores the old unconditional behaviour. Name comparison follows the destination filesystem: folded on Windows, exact on POSIX. That needed a foldCase parameter on the helper, defaulted to true so upload_file keeps its behaviour. dst_dir is handed to the listing without its trailing separator, because the client concatenates "%s\*.*" and a trailing one produces "C://*.*", which FindFirstFile rejects. search_file hit the same thing. No protocol change and no client change: the packet layout, the receiver and both client platforms are untouched. Verified against a real server (build 2026-10-29 14:34:33) with a Windows 11 source and both an Ubuntu 24.04 and a Windows 11 destination. A second default call returns file_count=0, skipped=1, an empty transfer_id and skip_check_failed=false with the target's mtime unchanged; overwrite=true advances the mtime (1793276909 -> 1793281657) and reports skipped=0; a call into a non-existent directory creates it and lands the file flat; a Windows destination folds case, so a placeholder SETTINGS.INI makes a later settings.ini skip, while a POSIX destination leaves both files side by side. One documented case does not hold, and the expectation was mine rather than the code's. "Destination occupied by another tool" was supposed to fail the pre-check and still transfer with skip_check_failed=true, but BeginC2CTransfer consults the same m_Pending registry for src_id and dst_id, so the transfer is refused with -32003 before the fallback can carry it. The other door - a directory that can be written but not listed - showed the pre-check succeeding instead of failing: the Linux client reports EACCES as an empty directory rather than TOKEN_FILE_LIST_ERROR, so the call goes on to overwrite. skip_check_failed is therefore a timeout backstop that is hard to reach deliberately; the field stays, and 14.9.2 no longer claims that a busy host reaches the fallback. Section 14.9 of the design doc records the contract, those results, and one wrong turn worth keeping: an earlier round concluded that single-file C2C nested the whole absolute path under dst_dir, and added receiver-side hardening for it. The nesting came from the ad-hoc JSON-RPC test harness, which passed JSON on the command line where the shell folded \\ into \/ before Python parsed it, so the source client received a path with no backslashes left and its basename fallback - which looks for a backslash - returned the whole path. The same file sent through the real MCP client produces a clean basename. That hardening has been reverted; the defect was in the test, not the product. Co-Authored-By: deepseek-flash |
||
|
|
1c832ff7f2 |
Feature: Add MCP cancellation, progress notifications and dry runs
P11 closes the plan's last batch, entirely on the server side: no client change is required for any of it. Long-running tools now expose a cancellation flag that every wait loop checks in 500 ms slices. A cancelled tool returns through the cleanup branch it already had (late first packets still get absorbed, sub connections still get closed, pending entries still get deleted), so there is no second cleanup path to keep in sync, and the host is released within a second. Three sources set the flag: notifications/cancelled (matched on the exact JSON-RPC id, with a fallback to the display form so a request_id copied out of the session list round-trips), mcp_cancel_session (by request_id, host id or session id), and a failed SSE write when the client has gone away. The dispatcher rewrites a cancel-induced failure to -32800 so callers do not mistake it for a host fault. tools/call requests carrying _meta.progressToken are answered as text/event-stream on the same POST: the tool runs on its own thread and both the notifications/progress events and the final JSON-RPC response go out through one chunked provider. Requests without a token are unchanged. download_file reports files done vs. expected, upload_file reports bytes sent vs. total. Two new local-only tools, mcp_list_sessions and mcp_cancel_session, list and cancel in-flight sessions (calls, pending one-shots, terminal, remote control, file transfer, chat). They are deliberately not gated by the feature switches or readonly mode, since that is the only way out of a stuck request. The -32003 busy message now names the occupier: "Device busy: ... (tool=download_file, elapsed=12s)". power_action gains wait/wait_ms to verify the result against the main connection's presence (went_offline, came_back, elapsed_ms); not seeing the transition is reported as ok, not as a failure. kill_process, operate_window and the four host_control_* tools accept dry_run, which validates the target against one fresh snapshot and returns what would be affected without sending anything. Validation rejections now use -32012; -32008 stays as documented historical alias. One implementation note worth recording: the per-thread call context uses FLS, not thread_local. Any static thread_local in this server crashes the process about a second after start, because some threads come from shellcode/MemoryModule images that never ran PE TLS initialisation. Verified against a real Debug server and a real Windows client over MCP: the smoke test now passes 104 checks with 0 failures, including cancellation releasing the host in under a second, the cancelled request returning -32800, notifications/cancelled returning 202, 63 progress events with exact byte counts for a 64 MB upload, and a cleanly terminated SSE stream. Not exercised in this pass: power_action's wait=true path (it would take the test host down) and the -32006 readonly/switch-off section (every switch was on during the run). Co-Authored-By: deepseek-flash |
||
|
|
3d388f8e45 |
Feature: Add remote_block_input to MCP remote control
A GUI automation run is interrupted the moment a person at the host touches the mouse, and locking the host's keyboard and mouse is the standard answer. The client already implements COMMAND_SCREEN_BLOCK_INPUT and the MFC screen window already sends it, so the tool needs no client change: it puts the same two-byte packet [COMMAND_SCREEN_BLOCK_INPUT][0|1] on the hidden screen sub-connection that remote_open established. The gate is remote_open's own - McpRemoteControl=1 and McpReadonly=0 - because the ability to lock someone out deserves exactly the same door as the ability to drive their desktop, and Linux and Android clients are refused with -32005: they have no branch for this packet at all and would silently ignore it. Locking a host out is only acceptable if every way back in is closed, so the session now carries its own lock state and three paths release it. block=false releases it directly. block=true always carries a deadline (max_block_ms, default 300000, clamped to 1000..3600000) and a watchdog thread started with the MCP server sweeps every 500ms for expired locks, sends the release and records it; the next remote_block_input reports it as auto_unblocked so the model learns that its lock lapsed instead of assuming it is still held. remote_close and the idle reclaim both send block=false before they tear the sub-connection down, because once that connection is gone the server has no channel left and a live client process stays blocked - all three release paths write an audit line, since none of them is something a person can see. The send happens outside the MCP lock, and the watchdog takes the session's busy flag while it releases, so it cannot interleave with an injection or race a close; a failed send keeps the lock marked and retries five seconds later rather than hammering a dead connection every tick, and a session that dies under the watchdog is erased the same way an injection would erase it. Verified against a real Windows client over MCP on a Debug x64 build: block then unblock, block with a 1.5-2s deadline left to expire and reported back as auto_unblocked with the watchdog audit entry at the expected second, block with a ten-minute deadline then remote_close with "(input lock forced off)" in the audit, and the five refusals (missing block, non-boolean block, max_block_ms out of range, unknown session, offline host). The smoke test gained [4d] for those refusals; 54 checks pass. Two limits are worth stating plainly. BlockInput only works when the calling process is elevated (or UIAccess), the client ignores the API's return value, so on an ordinary client the lock silently does nothing and the tool can only promise that the command was delivered - both the tool description and the server instructions say so. And the idle-reclaim release, like the two verified paths, is only exercised at a 300s idle timeout; it shares the same send helper and was reviewed rather than timed out live. Bin/settings.ini was restored byte-exact and the Release instance was left alone. Co-Authored-By: deepseek-flash |
||
|
|
27b5431130 |
Feature: Add the file-write tools behind their own switch
P10-B adds delete_path, move_path and create_folder, and the switch they need. Reusing McpFileTransfer would have been wrong: uploading overwrites a file, deleting destroys a tree, and an operator who wants one may well not want the other. McpFileWrite is therefore a separate key, off by default, wired the way every other switch is - read from settings.ini at startup, reported as get_server_status.switches.file_write, and exposed with its own checkbox in the MCP settings dialog. The tools additionally require readonly to be off: a read-only server has no business modifying a host. No client change was needed: COMMAND_DELETE_FILE, COMMAND_DELETE_DIRECTORY, COMMAND_CREATE_FOLDER and COMMAND_RENAME_FILE already existed in the Windows file manager. The chain reuses the file-manager sub-connection and adds a phase - the main connection asks for the drive list, the sub-connection's first packet hands it to OnDriveList which sends the write command, and the client's TOKEN_*_FINISH ack moves the pending request from phase 0 to 1, where the tool sends COMMAND_LIST_FILES for the parent so the ack and the confirmation share one timeout. Only the IO thread touches the sub-connection; the tool thread just waits on the shared condvar, which keeps the sub-connection's lifetime out of its reach. The confirmation exists because the client answers unconditionally: it ignores the return values of DeleteFile, MoveFile and MakeSureDirectoryPathExists and there is no error token. ok therefore only means "the command arrived", and verified is the real answer - true when the parent listing shows the expected post-state, false when it shows the opposite, null when the listing itself did not come back (timeout or disconnect), since reporting that as false would be a lie. Linux, macOS and Android hosts are refused outright: those clients decode these paths as GBK while the server speaks UTF-8 to them for list_files, so a non-ASCII path would corrupt rather than fail. Paths are validated as UTF-8, converted to GBK exactly once, and reject %VAR%, relative paths, drive and share roots, and - for delete_path and for move_path's source - the Windows, Program Files, ProgramData, $Recycle.Bin and System Volume Information trees. create_folder gets no system-directory ban, because writing there is the same permission upload_file already has. Two defects surfaced while exercising this against a real client: create_folder's wire path has to end with a backslash, because MakeSureDirectoryPathExists treats a non-terminated last component as a file name and only creates the intermediate levels; and ResolveFileOpVerified(LookupInListing(...), isDir, ...) read isDir before the lookup ever set it - argument evaluation order is unspecified and MSVC evaluates right to left - so every create_folder reported verified=false even when the directory existed. Verified on a Debug x64 build against a Windows client over MCP: nested create_folder, upload, rename, delete, delete a tree, the failure shapes (delete with recursive=false on a directory, create_folder onto an existing file name, delete of a non-existent target) and every refusal (drive root, C:\Windows\Temp, C:\Users, %TEMP%, relative, empty, over-long, from==to, offline host, non-numeric id), with a Chinese-named directory created, renamed and deleted end to end; no file-manager window appeared in the server process during any of it. The smoke test gained section [4c], opt-in through -FileWriteDir, which asserts verified and never ok and walks a sandbox through the same path; two runs passed 69 checks with the sandbox removed afterwards. Bin/settings.ini was restored byte-exact and the Release instance was left alone. Co-Authored-By: deepseek-flash |
||
|
|
bb55f52b29 |
Feature: Add instructions, capability reporting and filters to MCP
P10-A is the first batch of the next MCP phase: the server now tells a model
how it expects to be driven instead of leaving the rules to be inferred from
per-tool descriptions.
initialize carries the instructions field that MCP 2025-06-18 defines, in
five sections: where host ids come from, which switch hides which tool, what
each error code implies for the next action, typical orchestrations, and
safety. Every statement was checked against the implementation rather than
derived from the tool descriptions, and four did not survive: the host_*
family only supports name/pid filters in part (named per tool now), read-only
mode does not hide host_set_remark and host_set_watch_level (they touch only
the local host store and are refused with -32006 when called), -32003 is one
lock keyed by device id rather than one per capability, and there is no
"screen stream" tool to pick instead of get_screenshot. The string is built
from u8 literals because the project compiles with /execution-charset:.936.
get_host_detail returns a capabilities object (platform, screenPreview,
remoteControl, fileTransferV2, c2cPaths, registry), each flag tied to a gate
that already exists in the dispatcher, so a model no longer discovers a
host's limits by calling and reading -32005. remoteControl mirrors the two
conditions remote_* actually applies (Windows or Linux, and not
multi-monitor), not the preview bit. Making the flags honest exposed
list_registry rejecting only LNX and MAC, so an APK host passed and then
waited out the timeout; it now uses the same is-Windows predicate the bit is
computed from. That predicate existed as identical local copies in
McpMachine.cpp and McpChat.cpp and now lives in McpInternal.
list_processes and list_windows take an optional name and pid, filtered on
the server before the page window is applied, with total counting matches
and totalAll still reporting the unfiltered count. The two tools get their
own schema builder so list_services does not advertise a filter it would
silently ignore, and the pid descriptions differ because a pid means the
process itself for one tool and its owner for the other.
get_keylog gains set_offline and clear, the two commands the client already
implements on the keyboard sub-connection but nothing on the MCP side ever
sent, plus offlineRecord from the ready packet's byte 1. Both writes are
gated on McpReadonly=0 and validated before COMMAND_KEYBOARD goes out, so a
refused call cannot leave a running keyboard session behind; the tool's
annotations change from read-only to writable and destructive, and the
server instructions gain the matching sentence.
Four capabilities are exposed twice through two different sub-connection
chains, so each pair's descriptions now say which one to reach for first and
when the other is the only option: the host_* trio carries more fields and
filters on the server, the list_* trio is the McpMachine=0 fallback, and
operate_window is the only one that can close a window. No tool was merged:
the split is what lets McpMachine be switched off on its own. search_file's
description drops the stale MAX_PATH-overflow warning (fixed in
|
||
|
|
6bfa4294cc |
Feature: Switch a Linux client's transport TLS at runtime
The server's TLS menu already wrote the trust anchor into the Windows client's registry and expected a restart. The Linux client grew the same command handling (166/167) but, like Windows, only read the anchor once at startup, so enabling or disabling TLS still meant restarting it. Both handlers now take effect immediately. TlsChannelLinux.cpp no longer initialises through std::call_once. The process-level state (context, enabled, load error) lives behind a mutex and TlsReload() rebuilds it from whatever anchor file is on disk, so TlsEnabled() reflects the new transport as soon as the anchor is written or removed. In-flight sessions survive the swap because SSL_new increments the SSL_CTX reference count; the unit test pins that down by keeping an established TLS connection open across a reload that frees the old context. A reload that hits a bad anchor keeps the previous state and only logs: one bad push should not brick a working client, and the next start is still fail-closed. The pushed PEM is parsed before it is written for the same reason -- a corrupt anchor on disk would lock the client out of the server with no way to correct it remotely. Only a real transport flip (plaintext <-> TLS) asks for a reconnect. An anchor swap alone, as in a certificate rotation, leaves the current session alone and applies to the next connection. The receive thread never closes the socket itself; it sets g_needReconnect and the main heartbeat loop disconnects so the outer reconnect loop can re-handshake, matching how the heartbeat timeout path already works. IOCPClient now latches the transport per connection (m_useTls) at handshake time instead of consulting TlsEnabled() on every send and receive. Without the latch, the second or so between the reload and the reconnect would push plaintext into an established TLS session, or the reverse, producing protocol errors for no reason. RES_TLS (szReserved[19]) is refreshed right before each login, including the resend after a group change, so the TLS column on the server flips with the transport instead of showing the value from process start. The confirmation dialogs now say what each platform does, with translations in en_US, zh_TW and de_DE; the keys carry the literal \n escape the INI parser understands. Ending a sub-connection is not an error. OpenSSL 3 classifies a peer that closes without close_notify as an unexpected-EOF protocol error, so every terminal or file transfer session logged an SSL_read failure on the real servers even though Recv promises 0 for a plain close and neither side sends close_notify. SSL_OP_IGNORE_UNEXPECTED_EOF restores the intended semantics. Verified with the reload unit test (RELOAD-OK, covering the in-flight connection across a context swap, garbage payload rejection and a broken anchor keeping TLS alive), an abrupt-close test (recv now returns 0 instead of SOCKET_ERROR) and end to end against a protocol-faithful fake server that signs MasterSettings with libsign: plaintext login, 166, TLS reconnect with RES_TLS=1, 167, plaintext reconnect with RES_TLS=0. The Linux client, the Debug Windows client and the Debug MFC server all build. The cost is inherent to taking effect immediately: a remote session in progress is dropped when the transport changes, and the MFC server briefly shows the client as a duplicate login until the old connection is reaped and the standby entry is promoted. Co-Authored-By: deepseek-flash Co-Authored-By: Claude Code <noreply@anthropic.com> |
||
|
|
c11df75225 |
Fix: Report the real runtime instead of a timezone skew in host info
The host info popup showed a constant "7h" runtime for every Linux host. szStartTime carries no timezone marker and the two sides disagree: the Windows client sends its own wall clock (client/LoginServer.cpp getProcessTime), while the Linux and Android clients send Beijing time unconditionally (linux/main.cpp and common/commands.h ToPekingTimeAsString hardcode UTC+8). GetElapsedTime then built the base time with CTime as local time and subtracted it from the local clock, so on any server that is not at UTC+8 the start time landed in the future; the absolute value turned that skew into a plausible-looking duration (UTC+1 gives exactly 7h). GetElapsedTime now picks the reference "now" by client type: LNX and APK are compared against the current Beijing time, everything else keeps using the local clock. A start time in the future now clamps to 0 instead of being mirrored, so a clock disagreement shows as unknown rather than as a fake runtime. The Linux client also reported the wrong thing entirely: it sent the current time at login, not the process start time, so the value was always about zero whenever the timezones happened to agree. It now records its own wall clock once at load and reports Beijing time built from it, matching the semantics of the Windows client. An upgrade forks a new process, so the counter restarts after an upgrade as expected. The first implementation read /proc/self/stat starttime plus /proc/stat btime, which looked like the exact equivalent of the Windows call, but btime is computed from the wall clock at boot and never corrected when NTP later steps the clock, so on WSL2 it drifted by 1.8h. Recording the value in the process itself has no such failure mode. Verified against a Debug server with a WSL Ubuntu 24.04 client and a Windows client: the popup now reports "2.3m" for a Linux process started 2.3 minutes earlier (previously 7h), the startup timestamp is the process load time in Beijing time, and the Windows host still reports 14s right after it connects. Co-Authored-By: deepseek-flash |
||
|
|
4d2abf34d0 |
Feature: Support the Tier 1 MCP tools on Linux clients
All of these tools already had a working wire protocol on the Linux
client (SystemManager.h, common/PTYHandler.h, ScreenHandler.h); only the
server-side client-type gates rejected LNX hosts. kill_process,
exec_command, terminal_open/exec/close and remote_open/close/mouse/
keyboard/clipboard now accept LNX and reject only MAC (plus APK where it
applied). No client change, no capability bit.
exec_command and terminal_exec needed platform-aware plumbing because a
POSIX shell understands none of the Windows constructs: the sentinel is
now "PS1=" / the command / "echo __MCP_DONE_<nonce>__$?" over the Linux
PTY, with output decoded as UTF-8. The PS1= line exists because
interactive bash prints its prompt after every line it reads, which
otherwise leaks into stdout; its echo sits ahead of the command echo and
is removed together with it. The Windows ConPTY and legacy non-PTY forms
are unchanged.
The default command whitelist is now platform-specific: identically named
POSIX commands can write files or change system state (find -exec,
sort -o, hostname), so kDefaultCmdWhitelistPosix only lists commands that
stay read-only even with arguments. env is deliberately excluded, since
"env <program>" runs arbitrary programs and would defeat the whitelist
entirely. An explicit McpCmdWhitelist still overrides both platforms. The
forbidden metacharacter set is split the same way: on Linux it covers
& | < > ; backtick and $( / ${ / !, where ! triggers history expansion in
interactive bash. ^ is not a POSIX metacharacter, so read-only commands
like "grep -v ^# /etc/hosts" are accepted on Linux while Windows keeps
rejecting them.
Input injection had to be sent one MSG64 per COMMAND_SCREEN_CONTROL
packet. The protocol allows batching and the Windows client handles it,
but linux/ScreenHandler.h only processes the first message of a packet,
so a batch left key_press stuck down (X11 autorepeat), click
half-pressed and type emitting only its first character. Splitting the
packets is equivalent for Windows, which processes one message at a time
anyway, and keeps already-deployed Linux clients working without an
upgrade.
Verified on a Debug server against a WSL Ubuntu 24.04 client and a
Windows client: exec_command returned real exit codes (0/1/2) with clean
output, -32007/-32008 negatives, and the POSIX-only ^ allowance;
persistent terminals kept cwd and environment, returned 1 for false and
the last exit code for ";" chains, and closed idempotently; kill_process
killed a test process, returned an empty remaining list and skipped
pid 1; remote_open reported 3840x1140, remote_mouse mapped (0.5,0.5) to
(1920,570), xev showed balanced press/release pairs for keys and buttons,
and a Chinese clipboard round-trip came back as UTF-8. The Windows
regression of the same tools was unchanged, including the multi-monitor
gate on remote_open.
Co-Authored-By: deepseek-flash
|
||
|
|
3a158a241c |
Feature: Support upload_file and download_file on Linux and macOS hosts
Both tools used to reject LNX/MAC targets outright. The server now gates on the target client type instead: a POSIX target must pass an absolute POSIX remote path without a backslash or a ".." segment (-32602 otherwise), while Windows targets keep their exact previous behaviour. upload_file needed no new client command; the POSIX receiver already handles COMMAND_SEND_FILE_V2 and derives the destination from the packet name. It now also reports a real receiver_ack: the upload session records dstClientID/transferID, and OnC2CRecvResult matches the 176 acknowledgement from Linux targets, so a destination write failure becomes -32011 and a missing ack (with bytes in flight) becomes -32001. download_file needed two pieces on the POSIX side, both shared by Linux and macOS through common/FileTransferV2.h: a FileCompletePacketV2 per file with a streaming SHA-256 (new self-contained common/sha256_posix.h, since BCrypt is Windows-only) so the server can count completed files and verify digests, and a TOKEN_DOWNLOAD_ERROR reply when the requested paths do not exist or are denied, which the server maps to -32009/-32010 within milliseconds instead of waiting for the stall watchdog. Zero-byte files were lost when uploading to POSIX targets because the worker sends no data chunk for them and the complete packet carries no path, so the receiver had nothing to create. The server now injects a zero-length final chunk for each empty file, only for POSIX targets; Windows targets keep their existing behaviour. Also fixes a download completion edge case found while testing: the client decides entry order, so a directory may arrive after all files (an empty subdirectory, for example), and the directory branch only completed when the directory count alone covered totalFiles. The check is now filesDone + directoryCount >= totalFiles. Verified end to end against a WSL Linux client and a Windows client: upload and download of a tree with a 3 MB binary, a Chinese filename, an empty file and an empty subdirectory all round-trip with matching SHA-256; the documented error paths (-32602, -32009, -32011, -32001) and the Windows upload/download/C2C regressions were exercised as well. Co-Authored-By: deepseek-flash |