Fix: make UDP and KCP clients stay online
Plain UDP gave every datagram a fresh context and destroyed it after parsing, while the heartbeat handler posted that pointer to the UI thread, so UpdateActiveWindow read freed memory. Login also stored that short-lived context, so later heartbeats carried a zero client id and every UDP host timed out. The UDP server now owns one persistent context per client address and dispatches every datagram through it: the receive buffer is cleared per packet, the map is capped and idle addresses evicted, and Disconnect only erases and marks the context so the last reference deletes it. COMMAND_BYE no longer closes the shared receive socket, a failed receive re-posts itself, and UDP previews are capped to thumbnail size. The KCP client returned ikcp_send's 0 for a successful send, so the caller resent login forever and never started heartbeats; it now reports the accepted length, and a duplicate login re-sends MasterSettings. Two follow-up fixes in the same area: ReleaseIoRef keeps fetch_sub paired with exchange so a concurrent Disconnect cannot strand a marked context at zero refs; UpdateUserEvent drops posted heartbeats while closing instead of touching a context the UDP server may have destroyed. TCP behavior is otherwise unchanged. Verified: Debug build, UDP previews and heartbeats work, KCP logs in once and reports its active window. Server link hits the known LNK1104 from the running exe. Co-Authored-By: Tencent Hunyuan Hy
This commit is contained in:
1 parent
d48f236385
commit
914553ab4e
8 files changed
+280
-30
No files matched your search
@@ -1929,6 +1929,23 @@ VOID CMy2015RemoteDlg::AddList(CString strIP, CString strAddr, CString strPCName
|
||||
if (ctx == ContextObject) {
|
||||
LeaveCriticalSection(&m_cs);
|
||||
Mprintf("上线消息 - 主机已经存在 [1]: same context. IP= %s\n", data[ONLINELIST_IP]);
|
||||
// 只有 UDP/KCP 会复用同一个上下文:客户端重连后重发 TOKEN_LOGIN 时
|
||||
// 必须补发一次 MasterSettings,否则 IsLoginAcked 不置位,表现为无限
|
||||
// 重连、上线日志刷屏、心跳不启动。TCP 走新上下文,保持原有行为
|
||||
//(Linux/macOS 改分组后同连接重发登录不会再额外收到配置包)。
|
||||
const std::string proto = ContextObject->GetProtocol();
|
||||
if (proto != "UDP" && proto != "KCP")
|
||||
return;
|
||||
std::string signMessage(const std::string& privateKey, BYTE* msg, int len);
|
||||
MasterSettings copy = m_settings;
|
||||
std::string msg = startTime;
|
||||
msg += "|" + std::to_string(ContextObject->GetClientID());
|
||||
auto signature = signMessage("", (BYTE*)msg.c_str(), msg.length());
|
||||
size_t sigLen = signature.size();
|
||||
if (sigLen > sizeof(copy.Signature))
|
||||
sigLen = sizeof(copy.Signature);
|
||||
memcpy(copy.Signature, signature.data(), sigLen);
|
||||
SendMasterSettings(ContextObject, copy);
|
||||
return;
|
||||
}
|
||||
if (!ctx->GetClientData(ONLINELIST_IP).IsEmpty()) {
|
||||
@@ -4310,6 +4327,12 @@ void CMy2015RemoteDlg::CheckHeartbeat()
|
||||
ContextObject->CancelIO();
|
||||
// 使用延迟队列删除,由定时器统一处理刷新
|
||||
m_PendingOffline.push_back(port);
|
||||
// UDP 上下文由 UDP 服务端的地址映射持有,宿主列表移除后交还释放。
|
||||
// 只对 UDP 生效,不改动 TCP/KCP 原有的回收路径。
|
||||
CONTEXT_OBJECT* co = static_cast<CONTEXT_OBJECT*>(ContextObject);
|
||||
if (co->GetProtocol() == "UDP" && co->GetServer() != nullptr) {
|
||||
co->GetServer()->Disconnect(co);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4622,7 +4645,12 @@ void CMy2015RemoteDlg::Release()
|
||||
for (auto i=m_HostList.begin(); i!=m_HostList.end(); ++i) {
|
||||
context* ContextObject = *i;
|
||||
ContextObject->Send2Client(&bToken, sizeof(BYTE));
|
||||
ContextObject->Destroy();
|
||||
// UDP 上下文归 UDP 服务端的地址映射所有:这里 Destroy 会把它从映射
|
||||
// 摘除并立即删除,列表中的指针随即悬空(随后 ServePair::Destroy 还会
|
||||
// 再碰映射)。退出时统一交给服务端释放即可。
|
||||
if (ContextObject->GetProtocol() != "UDP") {
|
||||
ContextObject->Destroy();
|
||||
}
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
m_ClientMap->SaveToFile(GetDbPath());
|
||||
@@ -7748,7 +7776,8 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
// UpdateUserEvent 处理完后配对 fetch_sub 释放。
|
||||
ContextObject->IoRefCount.fetch_add(1);
|
||||
if (!g_2015RemoteDlg->PostMessageA(WM_UPDATE_ACTIVEWND, 0, (LPARAM)ContextObject)) {
|
||||
ContextObject->IoRefCount.fetch_sub(1); // 投递失败,退回引用,避免泄漏
|
||||
// 投递失败,退回引用;UDP 上下文若已被标记删除,由这次释放完成销毁
|
||||
ContextObject->ReleaseIoRef();
|
||||
}
|
||||
break;
|
||||
case TOKEN_SCREEN_PREVIEW_RSP: {
|
||||
@@ -7799,9 +7828,15 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
break;
|
||||
}
|
||||
case COMMAND_BYE: { // 主机下线【L】
|
||||
CancelIo((HANDLE)ContextObject->sClientSocket);
|
||||
closesocket(ContextObject->sClientSocket);
|
||||
Sleep(10);
|
||||
if (ContextObject->GetProtocol() != "UDP") {
|
||||
CancelIo((HANDLE)ContextObject->sClientSocket);
|
||||
closesocket(ContextObject->sClientSocket);
|
||||
Sleep(10);
|
||||
} else if (ContextObject->GetServer() != nullptr) {
|
||||
// UDP 的 sClientSocket 是服务端共享的接收 socket,关掉会让所有 UDP
|
||||
// 客户端失联。这里只把该地址的上下文从映射里摘除。
|
||||
ContextObject->GetServer()->Disconnect(ContextObject);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case TOKEN_DRAWING_BOARD: { // 远程画板【x】
|
||||
@@ -8194,6 +8229,11 @@ LRESULT CMy2015RemoteDlg::OnUserToOnlineList(WPARAM wParam, LPARAM lParam)
|
||||
if (ContextObject == NULL || isClosed) {
|
||||
return -1;
|
||||
}
|
||||
// 该 UDP 上下文已被下线(心跳超时/删除主机)摘除并标记删除,迟到的登录包
|
||||
// 不能再把它塞回宿主列表,否则引用归零销毁后列表里留下悬空指针。
|
||||
if (ContextObject->DeleteWhenIdle.load()) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
try {
|
||||
strIP = ContextObject->GetPeerName().c_str();
|
||||
@@ -8626,13 +8666,21 @@ LRESULT CMy2015RemoteDlg::OnUserOfflineMsg(WPARAM wParam, LPARAM lParam)
|
||||
LRESULT CMy2015RemoteDlg::UpdateUserEvent(WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
CONTEXT_OBJECT* ctx = (CONTEXT_OBJECT*)lParam;
|
||||
if (ctx) {
|
||||
UpdateActiveWindow(ctx);
|
||||
// 释放 TOKEN_HEARTBEAT 投递延迟消息时占用的引用计数(与那里的 fetch_add 配对)。
|
||||
// 必须在 UpdateActiveWindow 完全返回后再释放,保证整个处理期间对象不被回收。
|
||||
ctx->IoRefCount.fetch_sub(1);
|
||||
// 退出过程中 UI 消息队列可能残留心跳投递的裸指针,而 UDP 上下文此时已被
|
||||
// IOCPUDPServer::Destroy() 释放;任何访问(包括 GetProtocol 和 ReleaseIoRef)
|
||||
// 都会是 use-after-free。与 OnUserToOnlineList 一致,退出中直接丢弃消息。
|
||||
// 此时归还引用已无意义:UDP 对象由服务端统一销毁,TCP 对象由连接池在退出
|
||||
// 流程中回收,两者都不依赖这条残留消息的引用计数。
|
||||
if (!ctx || isClosed) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
UpdateActiveWindow(ctx);
|
||||
// 释放 TOKEN_HEARTBEAT 投递延迟消息时占用的引用计数(与那里的 fetch_add 配对)。
|
||||
// 必须在 UpdateActiveWindow 完全返回后再释放,保证整个处理期间对象不被回收。
|
||||
// UDP 上下文可能已被标记为“引用归零即删除”,由这次释放完成销毁。
|
||||
ctx->ReleaseIoRef();
|
||||
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
@@ -10588,7 +10636,15 @@ void CMy2015RemoteDlg::OnListClick(NMHDR* pNMHDR, LRESULT* pResult)
|
||||
tip->SetReqId(m_PreviewReqId);
|
||||
SendScreenPreviewRequest(ctx, m_PreviewReqId, maxWidth, jpegQ);
|
||||
// 4 秒未收到 → 在浮窗里标"预览不可用"
|
||||
SetTimer(TIMER_PREVIEW_ARRIVAL, 4000, nullptr);
|
||||
// 非 TCP 主链路(UDP/KCP)需要更长的等待:大预览要传几十个分片,
|
||||
// 4 秒在弱网/首次发送时容易误判超时。TCP 保持原来的 4 秒。
|
||||
WORD previewWaitMs = 4000;
|
||||
if (ctx) {
|
||||
const std::string proto = ctx->GetProtocol();
|
||||
if (proto == "UDP" || proto == "KCP")
|
||||
previewWaitMs = 6000;
|
||||
}
|
||||
SetTimer(TIMER_PREVIEW_ARRIVAL, previewWaitMs, nullptr);
|
||||
}
|
||||
} else {
|
||||
delete tip;
|
||||
@@ -10766,9 +10822,32 @@ bool CMy2015RemoteDlg::NormalizeScreenPreviewPacket(std::vector<BYTE>& pkt)
|
||||
return true;
|
||||
}
|
||||
|
||||
namespace {
|
||||
// UDP 主链路:服务端接收缓冲只有 8KB,且超过 ~1200 字节就会 IP 分片、丢失率陡增。
|
||||
// 把预览压到和"缩略图列"同一量级(120px / q60,通常 3–6KB),保证整包能送达;
|
||||
// TCP/KCP 有流式重组,不受此限制。
|
||||
// 非 TCP 主链路对预览大小有硬限制:
|
||||
// - UDP:服务端接收缓冲只有 8KB,且超过 ~1200 字节就会分片;压到缩略图量级;
|
||||
// - KCP:虽然可靠,但预览响应(数十 KB)会把同一 KCP 流堵住——心跳排在它后面,
|
||||
// 表现为“预览超时 + RTT 暴涨到数秒”(实测 7s)。压到 240px,几个分片即可送达。
|
||||
// TCP 有独立子连接和流式调度,不受此限制。
|
||||
void ClampPreviewForLossyTransport(context* ctx, WORD& maxWidth, BYTE& jpegQuality)
|
||||
{
|
||||
if (!ctx)
|
||||
return;
|
||||
const std::string proto = ctx->GetProtocol();
|
||||
const WORD limit = (proto == "UDP") ? 120 : (proto == "KCP") ? 240 : 0;
|
||||
if (limit == 0 || maxWidth <= limit)
|
||||
return;
|
||||
maxWidth = limit;
|
||||
if (jpegQuality > 60) jpegQuality = 60;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void CMy2015RemoteDlg::SendScreenPreviewRequest(context* ctx, WORD reqId, WORD maxWidth, BYTE jpegQuality)
|
||||
{
|
||||
if (!ctx) return;
|
||||
ClampPreviewForLossyTransport(ctx, maxWidth, jpegQuality);
|
||||
ScreenPreviewReq req;
|
||||
memset(&req, 0, sizeof(req));
|
||||
req.cmd = COMMAND_SCREEN_PREVIEW_REQ;
|
||||
@@ -10782,6 +10861,7 @@ void CMy2015RemoteDlg::SendScreenPreviewRequestEx(context* ctx, WORD reqId, WORD
|
||||
BYTE jpegQuality, const ScreenPreviewReqEx& ex)
|
||||
{
|
||||
if (!ctx) return;
|
||||
ClampPreviewForLossyTransport(ctx, maxWidth, jpegQuality);
|
||||
BYTE buf[sizeof(ScreenPreviewReq) + sizeof(ScreenPreviewReqEx)] = {};
|
||||
ScreenPreviewReq req;
|
||||
memset(&req, 0, sizeof(req));
|
||||
|
||||
Reference in new issue
Block a user