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
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-30 23:07:48 +01:00
1 parent 96f1bacd43
commit cbb84809d8
2 files changed
+164 -64

No files matched your search

+154 -64
View File
@@ -4797,7 +4797,36 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
// 刷新菜单显示
DrawMenuBar();
SubMenu->TrackPopupMenu(TPM_LEFTALIGN, Point.x, Point.y, this);
// 菜单是模态的,TrackPopupMenu 期间 WM_TIMER 照常派发:这期间只要有主机上下线,
// 列表就会重排(ApplySort/erase),而虚拟列表的选中项是按行号保存的,行号的含义
// 随之改变;命令处理函数又是点击那一刻才按行号解析主机。于是「对 A 主机点的菜单」
// 会落到重排后占据同一行的 B 主机上。这里先按 clientID 记住用户选中的主机,
// 菜单返回后把选中项恢复到这些主机的当前行号,最后才派发命令。
std::vector<uint64_t> selectedIds;
EnterCriticalSection(&m_cs);
POSITION selPos = m_CList_Online.GetFirstSelectedItemPosition();
while (selPos) {
int selItem = m_CList_Online.GetNextSelectedItem(selPos);
context* selCtx = GetContextByListIndex(selItem);
if (selCtx) selectedIds.push_back(selCtx->GetClientID());
}
LeaveCriticalSection(&m_cs);
// TPM_RETURNCMD:由我们自己在恢复选中项之后再派发命令。用 Win32 入口是因为
// CMenu::TrackPopupMenu 的返回值被声明成 BOOL,拿命令 ID 只能靠隐式截断。
UINT cmd = ::TrackPopupMenu(SubMenu->GetSafeHmenu(), TPM_LEFTALIGN | TPM_RETURNCMD,
Point.x, Point.y, 0, GetSafeHwnd(), nullptr);
if (cmd != 0) {
// 恢复选中项只是让界面显示与目标一致;真正的目标是下面这份 clientID 快照。
// 处理函数里往往还要先弹确认框/输入框,模态期间列表会再重排一次,所以不能让
// 处理函数回头按行号读选中项。保存外层值是为了应对嵌套弹出的菜单。
RestoreSelectionByIds(selectedIds);
std::vector<uint64_t> outer = std::move(m_CtxMenuTargets);
m_CtxMenuTargets = selectedIds;
SendMessage(WM_COMMAND, (WPARAM)cmd, 0);
m_CtxMenuTargets = std::move(outer);
}
*pResult = 0;
}
@@ -4911,11 +4940,8 @@ VOID CMy2015RemoteDlg::SwitchSelectedProtocol(UINT nID)
// 选中主机的能力校验:老客户端不认识 COMMAND_SET_PROTO,收到只会丢弃。
int selected = 0, unsupported = 0;
EnterCriticalSection(&m_cs);
POSITION pos = m_CList_Online.GetFirstSelectedItemPosition();
while (pos) {
int item = m_CList_Online.GetNextSelectedItem(pos);
context* ctx = GetContextByListIndex(item);
if (!ctx || !ctx->IsLogin()) continue;
for (context* ctx : ResolveCommandTargets()) {
if (!ctx->IsLogin()) continue;
++selected;
if (!ctx->SupportsProtoSwitch()) ++unsupported;
}
@@ -5218,20 +5244,17 @@ void CMy2015RemoteDlg::OnOnlineDelete()
if (IDYES != MessageBoxL(_T("确定删除选定的被控计算机吗?"), _T("提示"), MB_ICONQUESTION | MB_YESNO))
return;
// 确认框是模态的,期间列表可能已经重排;目标在锁内一次性锁定,后面发指令和
// 移除列表两步都用这份结果,避免两处按行号各自解析出不同的主机。
EnterCriticalSection(&m_cs);
std::vector<context*> targets = ResolveCommandTargets();
LeaveCriticalSection(&m_cs);
BYTE bToken = COMMAND_BYE; //向被控端发送一个COMMAND_SYSTEM
SendSelectedCommand(&bToken, sizeof(BYTE)); //Context PreSending PostSending
EnterCriticalSection(&m_cs);
// 收集选中的索引(从大到小排序,避免删除时索引变化问题)
std::vector<int> selectedItems;
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
selectedItems.push_back(m_CList_Online.GetNextSelectedItem(Pos));
}
std::sort(selectedItems.rbegin(), selectedItems.rend());
for (int iItem : selectedItems) {
context* ctx = GetContextByListIndex(iItem);
for (context* ctx : targets) {
if (!ctx) continue;
CString strIP = ctx->GetClientData(ONLINELIST_IP);
@@ -5278,18 +5301,14 @@ VOID CMy2015RemoteDlg::OnOnlineWindowManager()
// 是否继续远程控制:如果选择多个,则继续;如果选择单个且用户锁屏无SYSTEM权限,则提示
BOOL CMy2015RemoteDlg::ShouldRemoteControl()
{
context* ContextObject = nullptr;
EnterCriticalSection(&m_cs);
int count = m_CList_Online.GetSelectedCount();
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
CString activeWnd, userName;
if (Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
ContextObject = GetContextByListIndex(iItem);
if (ContextObject) {
activeWnd = ContextObject->GetClientData(ONLINELIST_LOGINTIME);
userName = ContextObject->GetAdditionalData(RES_USERNAME);
}
int count = 0;
EnterCriticalSection(&m_cs);
std::vector<context*> targets = ResolveCommandTargets();
count = (int)targets.size();
if (!targets.empty()) {
activeWnd = targets[0]->GetClientData(ONLINELIST_LOGINTIME);
userName = targets[0]->GetAdditionalData(RES_USERNAME);
}
LeaveCriticalSection(&m_cs);
if (count == 1 && userName != "SYSTEM" && activeWnd.Find("Locked") == 0) {
@@ -5498,11 +5517,7 @@ void CMy2015RemoteDlg::OnOnlineBuildClient()
VOID CMy2015RemoteDlg::SendSelectedCommand(PBYTE szBuffer, ULONG ulLength, contextModifier cb, void* user)
{
EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while(Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
for (context* ContextObject : ResolveCommandTargets()) {
if (!ContextObject->IsLogin() && szBuffer[0] != COMMAND_BYE)
continue;
if (szBuffer[0] == COMMAND_UPDATE) {
@@ -7581,6 +7596,95 @@ context* CMy2015RemoteDlg::GetContextByListIndex(int iItem)
return m_HostList[realIdx];
}
// 按 clientID 把选中项恢复到它们当前所在的行号。
//
// 主机列表是虚拟列表(LVS_OWNERDATA),选中项按**行号**保存,而行号的含义会随
// m_HostList 重排而改变:上下线时 OnTimer 会 ApplySort() + RebuildFilteredIndices(),
// 主机下线时 RemoveFromHostList() 直接 erase,两者都会让行号整体位移。
// 右键菜单是模态的,TrackPopupMenu 期间 WM_TIMER 照常派发,所以用户在菜单里点下去
// 时,行号很可能已经指向另一台主机;命令处理函数又是点击那一刻才按行号解析主机
// (GetContextByListIndex),结果就是「对 A 主机点的菜单」落到了 B 主机上。
//
// 调用方在弹菜单前用 clientID 记住用户选中的主机,菜单返回后调用本函数把选中项搬回
// 这些主机,再派发命令,命令处理函数看到的就还是用户当初选的那批主机。
//
// 菜单打开期间下线的主机已不在列表里,无法恢复,其选中项被丢弃:处理函数会看到
// 「没选中」并给出提示,而不是误操作另一台主机——这是安全的失败方式。
void CMy2015RemoteDlg::RestoreSelectionByIds(const std::vector<uint64_t>& ids)
{
int firstRow = -1;
{
CLock lock(m_cs);
// 先清空全部选中(-1 表示作用于所有行)
m_CList_Online.SetItemState(-1, 0, LVIS_SELECTED);
for (uint64_t id : ids) {
auto it = m_ClientIndex.find(id);
if (it == m_ClientIndex.end()) continue; // 该主机已下线
const size_t hostIdx = it->second;
if (hostIdx >= m_HostList.size()) continue;
// 索引映射若因并发更新而陈旧,宁可不选,也不能选到别的主机
if (!m_HostList[hostIdx] || m_HostList[hostIdx]->GetClientID() != id) continue;
// 在过滤索引里找它的当前显示行
int row = -1;
for (size_t fi = 0; fi < m_FilteredIndices.size(); ++fi) {
if (m_FilteredIndices[fi] == hostIdx) {
row = (int)fi;
break;
}
}
if (row < 0) continue; // 被当前分组过滤排除
m_CList_Online.SetItemState(row, LVIS_SELECTED, LVIS_SELECTED);
if (firstRow < 0) firstRow = row;
}
}
// 滚动和重绘会同步触发绘制,放到锁外,不占着主机列表锁
if (firstRow >= 0) {
m_CList_Online.SetItemState(firstRow, LVIS_FOCUSED, LVIS_FOCUSED);
m_CList_Online.EnsureVisible(firstRow, FALSE);
}
// 重排期间列表用了 LVSICF_NOINVALIDATEALL,可见行可能还是旧内容,补一次重绘
m_CList_Online.Invalidate(FALSE);
}
// 取本次命令要作用的主机。
//
// 平时就是列表里的选中项;右键菜单派发期间 m_CtxMenuTargets 非空,此时以快照为准。
// 原因:菜单点击到命令真正执行之间还夹着 MessageBoxL / DoModal 等模态框,模态循环里
// WM_TIMER 照常派发,列表会 ApplySort/erase 重排,此时再按行号读选中项就会读到另一台
// 主机。快照按 clientID 保存,与行号无关。
//
// 调用方需持有 m_cs(本函数内部不加锁)。
std::vector<context*> CMy2015RemoteDlg::ResolveCommandTargets()
{
std::vector<context*> targets;
if (!m_CtxMenuTargets.empty()) {
targets.reserve(m_CtxMenuTargets.size());
for (uint64_t id : m_CtxMenuTargets) {
auto it = m_ClientIndex.find(id);
if (it == m_ClientIndex.end()) continue; // 菜单打开期间已下线
const size_t hostIdx = it->second;
if (hostIdx >= m_HostList.size()) continue;
context* ctx = m_HostList[hostIdx];
// 索引映射若因并发更新而陈旧,宁可不操作,也不能操作到别的主机
if (!ctx || ctx->GetClientID() != id) continue;
targets.push_back(ctx);
}
return targets;
}
POSITION pos = m_CList_Online.GetFirstSelectedItemPosition();
while (pos) {
context* ctx = GetContextByListIndex(m_CList_Online.GetNextSelectedItem(pos));
if (ctx) targets.push_back(ctx);
}
return targets;
}
// 从 m_HostList 中移除 context 并更新索引映射。
//
// 重要:MarkDeviceOffline / m_ActiveWndW.erase 等"主机下线"副作用必须**只在
@@ -8822,16 +8926,15 @@ void CMy2015RemoteDlg::OnOnlineHostnote()
BOOL modified = FALSE;
uint64_t key = 0;
EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
// 输入框是模态的,期间列表可能已重排,目标按 clientID 还原,避免备注写到别的主机
for (context* ContextObject : ResolveCommandTargets()) {
m_ClientMap->SetClientMapData(ContextObject->GetClientID(), MAP_NOTE, dlg.m_str);
// 虚拟列表:刷新该行以显示新备注
m_CList_Online.RedrawItems(iItem, iItem);
modified = TRUE;
}
if (modified) {
// 虚拟列表:整表重绘,让新备注显示出来
m_CList_Online.Invalidate(FALSE);
}
LeaveCriticalSection(&m_cs);
if (modified) {
m_ClientMap->SaveToFile(GetDbPath());
@@ -11525,11 +11628,8 @@ void CMy2015RemoteDlg::OnOnlineRunAsAdmin()
if (MessageBoxL("确定要以管理员权限重新启动目标应用程序吗?\n此操作可能触发 UAC 账户控制。",
"提示", MB_ICONQUESTION | MB_YESNO) == IDYES) {
EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
// 确认框期间列表可能已重排,目标按 clientID 还原
for (context* ContextObject : ResolveCommandTargets()) {
BYTE token = CMD_RUNASADMIN;
ContextObject->Send2Client(&token, sizeof(token));
}
@@ -11573,20 +11673,17 @@ void CMy2015RemoteDlg::OnOnlineUninstall()
if (IDYES != MessageBoxL(_T("确定卸载选定的被控程序吗?"), _T("提示"), MB_ICONQUESTION | MB_YESNO))
return;
// 确认框是模态的,期间列表可能已经重排;目标在锁内一次性锁定,后面发指令和
// 移除列表两步都用这份结果,避免两处按行号各自解析出不同的主机。
EnterCriticalSection(&m_cs);
std::vector<context*> targets = ResolveCommandTargets();
LeaveCriticalSection(&m_cs);
BYTE bToken = TOKEN_UNINSTALL;
SendSelectedCommand(&bToken, sizeof(BYTE));
EnterCriticalSection(&m_cs);
// 收集选中的索引(从大到小排序,避免删除时索引变化问题)
std::vector<int> selectedItems;
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
selectedItems.push_back(m_CList_Online.GetNextSelectedItem(Pos));
}
std::sort(selectedItems.rbegin(), selectedItems.rend());
for (int iItem : selectedItems) {
context* ctx = GetContextByListIndex(iItem);
for (context* ctx : targets) {
if (!ctx) continue;
CString strIP = ctx->GetClientData(ONLINELIST_IP);
@@ -11771,11 +11868,8 @@ void CMy2015RemoteDlg::MachineManage(MachineCommand type)
{
if (MessageBoxL("此操作需客户端具有管理员权限,确定继续吗? ", "提示", MB_ICONQUESTION | MB_YESNO) == IDYES) {
EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
// 确认框期间列表可能已重排,目标由 ResolveCommandTargets 按 clientID 还原
for (context* ContextObject : ResolveCommandTargets()) {
BYTE token[32] = { TOKEN_MACHINE_MANAGE, type };
ContextObject->Send2Client(token, sizeof(token));
}
@@ -12847,13 +12941,9 @@ void CMy2015RemoteDlg::ProxyClientTcpPort(bool isStandard, bool autoRun)
info->Schedule.Mode = autoRun ? SCH_MODE_STARTUP : SCH_MODE_NONE;
FrpcParam param(key.c_str(), timestamp, ip.c_str(), serverPort, localPort, remotePort);
EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
BOOL sent = FALSE;
const char* validDate = isStandard ? "Jan 29 2026" : "Dec 22 2025";
while (Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ctx = GetContextByListIndex(iItem);
if (!ctx) continue;
for (context* ctx : ResolveCommandTargets()) {
if (!ctx->IsLogin())
continue;
CString bits = ctx->GetAdditionalData(RES_PROGRAM_BITS);
+10
View File
@@ -412,6 +412,16 @@ public:
std::string m_v2KeyPath; // V2 密钥文件路径
void RebuildFilteredIndices(); // 重建过滤索引
context* GetContextByListIndex(int iItem); // 根据列表索引获取 context(考虑分组过滤)
// 按 clientID 把选中项恢复到它们当前所在的行号。虚拟列表的选中项是按行号保存的,
// 而 m_HostList 会随主机上下线重排,同一个行号重排后往往指向另一台主机。
void RestoreSelectionByIds(const std::vector<uint64_t>& ids);
// 本次命令的目标主机:右键菜单派发期间(m_CtxMenuTargets 非空)以 clientID 快照为准,
// 否则取列表当前选中项。调用方需持有 m_cs。
std::vector<context*> ResolveCommandTargets();
// 右键菜单发起时锁定的目标主机(clientID 快照)。菜单弹出到命令真正执行之间还会插入
// MessageBoxL / DoModal 等模态框,模态循环里 WM_TIMER 照常派发、列表照常重排,命令
// 处理函数若在那之后再按行号读选中项,就会读到另一台主机。只在 UI 线程访问。
std::vector<uint64_t> m_CtxMenuTargets;
// 启发式 ID 迁移:新客户端首次上线时,按 (ComputerName, ProgramPath) 在 m_ClientMap
// 里找老条目,若唯一匹配则把元数据(备注/位置/级别/授权)拷贝到 newId。