Feature: Transfer a Linux host to another master
The Linux client ignored COMMAND_ASSIGN_MASTER, so a host could not be moved to a different controller the way the Windows client allows. The payload is host:port:days:shine[:transport]; the parsing, record encoding and address application live in a shared header so a macOS client can reuse them unchanged. An assignment only rewrites the connection target. The running session stays up and the next reconnect - a dropped link or a restart - goes to the new master, matching the Windows behaviour. The target and its expiry are stored in a single "transfer" config key, while the address the process started with is kept in memory only: the config's own master/port entries are never overwritten, so restarting mid-transfer still has the original to fall back to. When the expiry passes the client restores that address, clears the key and reconnects. Malformed payloads and zero-day assignments are rejected outright. The way back depends on an expiry time, so honouring a permanent move would strand a host on an address it cannot leave. Give the POSIX connect() a timeout as well (non-blocking connect plus poll, 10 seconds). A blocking connect waiting for SYN retransmission froze the main loop for about two minutes when the port was filtered, delaying both heartbeats and the expiry restore. The transfer state is initialised after daemonize() for the same reason it is logged: logging before the double fork can leave the child deadlocked on the logger mutex. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
0b22d5e870
commit
3b3aed50e5
4 files changed
+346
-6
No files matched your search
+119
-3
@@ -10,6 +10,7 @@
|
||||
#include <thread>
|
||||
#include <fcntl.h>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <cerrno>
|
||||
#include <csignal>
|
||||
#include <sys/wait.h>
|
||||
@@ -39,6 +40,7 @@
|
||||
#include "common/client_auth_state.h"
|
||||
#include "common/posix_net_helpers.h"
|
||||
#include "common/sub_conn_thread.h"
|
||||
#include "common/host_transfer.h"
|
||||
#include "LinuxConfig.h"
|
||||
#include <openssl/evp.h>
|
||||
#include <cctype>
|
||||
@@ -58,6 +60,17 @@ static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重
|
||||
// 由主心跳循环择机 Disconnect 并重连。
|
||||
static std::atomic<bool> g_needReconnect(false);
|
||||
|
||||
// ============== 主机转移(COMMAND_ASSIGN_MASTER)==============
|
||||
// 服务端「转移主机」把目标写进 config.conf 的 transfer 键,之后每次重连都连新主控;
|
||||
// valid_to 到期后恢复本进程启动时的原主控。原主控只存在内存里(argv 或编译期默认),
|
||||
// 不能写回配置——恢复时读到的若还是转移目标,就成了原地打转。
|
||||
// 解析/编解码/地址应用在 common/host_transfer.h(macOS 客户端可直接复用)。
|
||||
static HostTransfer::Endpoint g_transferOrig; // 启动时的主控,过期恢复用
|
||||
static std::atomic<long long> g_transferValidTo(0); // >0 = 处于转移状态(到期时刻)
|
||||
static std::atomic<bool> g_transferPending(false); // 接收线程已写下新目标,待主循环应用
|
||||
static std::mutex g_transferMu; // 保护 g_transferPendingTarget
|
||||
static HostTransfer::Target g_transferPendingTarget;
|
||||
|
||||
// 自升级(COMMAND_UPDATE):fork+execv 重启自己时需要原始命令行,
|
||||
// 失败回报需要主连接(DataProcess 的 user 参数为 NULL,只能靠全局)。
|
||||
static int g_argc = 0;
|
||||
@@ -466,6 +479,65 @@ static void ApplyTlsAnchorChange(void* user)
|
||||
user, after ? "TLS" : "plaintext");
|
||||
}
|
||||
|
||||
// ============== 主机转移(COMMAND_ASSIGN_MASTER)==============
|
||||
|
||||
// 启动时读取转移记录:未过期就把连接地址改成转移目标(与 Windows
|
||||
// ClientDll.cpp StartClient 的启动处理一致)。必须在 daemonize 之后调用(见 main()
|
||||
// 里的说明),启动日志里打印的就是本次实际要连的地址。
|
||||
static void InitTransferState()
|
||||
{
|
||||
g_transferOrig = HostTransfer::CaptureEndpoint(g_SETTINGS);
|
||||
|
||||
LinuxConfig cfg;
|
||||
HostTransfer::Target t;
|
||||
long long now = (long long)time(nullptr);
|
||||
if (!HostTransfer::DecodeRecord(cfg.GetStr("transfer"), t))
|
||||
return;
|
||||
if (!t.Active(now)) {
|
||||
Mprintf("Transfer record already expired (%lld), ignored\n", t.validTo);
|
||||
return;
|
||||
}
|
||||
HostTransfer::ApplyTarget(g_SETTINGS, t);
|
||||
g_transferValidTo.store(t.validTo);
|
||||
Mprintf("Transfer active: %s:%d (transport=%d), %llds left\n",
|
||||
t.ep.ip.c_str(), t.ep.port, t.ep.transport, t.validTo - now);
|
||||
}
|
||||
|
||||
// 把接收线程记下的目标应用到全局连接参数。只在主线程调用:CONNECT_ADDRESS 没有
|
||||
// 跨线程同步,ConnectServer 读的就是它。只改地址、不主动断开——与 Windows 一致,
|
||||
// 下一次重连才生效。
|
||||
static void ApplyPendingTransfer()
|
||||
{
|
||||
if (!g_transferPending.load(std::memory_order_acquire))
|
||||
return;
|
||||
HostTransfer::Target t;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_transferMu);
|
||||
t = g_transferPendingTarget;
|
||||
g_transferPending.store(false, std::memory_order_release);
|
||||
}
|
||||
HostTransfer::ApplyTarget(g_SETTINGS, t);
|
||||
long long left = t.validTo - (long long)time(nullptr);
|
||||
Mprintf(">>> Transfer armed: next reconnect -> %s:%d (transport=%d), %llds left\n",
|
||||
t.ep.ip.c_str(), t.ep.port, t.ep.transport, left);
|
||||
}
|
||||
|
||||
// 转移到期:恢复原主控并重连。目标不可达时这是唯一的退路;days=0 的永久转移
|
||||
// 没有到期时间,也就没有这条退路——与 Windows 行为一致。
|
||||
static void CheckTransferExpiry()
|
||||
{
|
||||
long long validTo = g_transferValidTo.load(std::memory_order_relaxed);
|
||||
if (validTo <= 0 || (long long)time(nullptr) <= validTo)
|
||||
return;
|
||||
g_transferValidTo.store(0, std::memory_order_relaxed);
|
||||
HostTransfer::ApplyEndpoint(g_SETTINGS, g_transferOrig);
|
||||
LinuxConfig cfg;
|
||||
cfg.SetStr("transfer", ""); // 记录作废,重启后也不会再回到已过期的目标
|
||||
g_needReconnect.store(true, std::memory_order_relaxed);
|
||||
Mprintf(">>> Transfer expired: restoring %s:%d\n",
|
||||
g_transferOrig.ip.c_str(), g_transferOrig.port);
|
||||
}
|
||||
|
||||
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (szBuffer == nullptr || ulLength == 0)
|
||||
@@ -616,6 +688,35 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
} else {
|
||||
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
|
||||
}
|
||||
} else if (szBuffer[0] == COMMAND_ASSIGN_MASTER) {
|
||||
// 「转移主机」:host:port:days:shine[:transport],解析见 common/host_transfer.h。
|
||||
// 载荷非法时什么都不做——绝不能把脏数据当成有效转移,否则一台上线中的主机会
|
||||
// 被改到一个不存在的地址上去。
|
||||
HostTransfer::Target t;
|
||||
long long now = (long long)time(nullptr);
|
||||
if (!HostTransfer::ParseAssignCommand(szBuffer, ulLength, now, t)) {
|
||||
Mprintf("** [%p] ASSIGN: malformed payload, ignored ***\n", user);
|
||||
return TRUE;
|
||||
}
|
||||
// 有效期内重复下发忽略(与 Windows KernelManager 的 now <= valid_to 判断一致)。
|
||||
// 用原子变量而不是再读一次配置:状态以本进程为准,避免和主线程的写入交错。
|
||||
long long active = g_transferValidTo.load(std::memory_order_relaxed);
|
||||
if (now <= active) {
|
||||
Mprintf("** [%p] ASSIGN to %s:%d ignored: already assigned until %lld ***\n",
|
||||
user, t.ep.ip.c_str(), t.ep.port, active);
|
||||
return TRUE;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_transferMu);
|
||||
g_transferPendingTarget = t;
|
||||
g_transferPending.store(true, std::memory_order_release);
|
||||
}
|
||||
// 先挡住后续重复下发,再落盘:落盘失败也不至于被第二条命令覆盖。
|
||||
g_transferValidTo.store(t.validTo, std::memory_order_relaxed);
|
||||
LinuxConfig cfg;
|
||||
cfg.SetStr("transfer", HostTransfer::EncodeRecord(t));
|
||||
Mprintf("** [%p] ASSIGN to %s:%d for %llds, applying on next reconnect ***\n",
|
||||
user, t.ep.ip.c_str(), t.ep.port, t.validTo - now);
|
||||
} else if (szBuffer[0] == COMMAND_UPDATE) {
|
||||
// 服务端"升级程序"菜单下发新版本 ELF
|
||||
Mprintf("** [%p] Received 'UPDATE' command (%u bytes) ***\n", user, (unsigned)ulLength);
|
||||
@@ -1247,6 +1348,12 @@ int main(int argc, char* argv[])
|
||||
// 写 PID 文件(守护进程模式下 PID 已变为子进程的)
|
||||
writePidFile();
|
||||
|
||||
// 上次的「转移主机」还没到期就改连目标主控(原地址记在内存里,过期后恢复)。
|
||||
// 必须在 daemonize() 之后:它在有记录时会打日志,而 fork 时若日志线程正持有
|
||||
// 内部锁,子进程会永远卡在那把锁上(实测 -d 启动后只剩一行 fork 前的日志,
|
||||
// 父子进程都停在 futex)。fork 之前一律不碰 Logger。
|
||||
InitTransferState();
|
||||
|
||||
Mprintf("Server: %s:%d (PID: %d%s)\n",
|
||||
g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort(),
|
||||
getpid(), daemon_mode ? ", daemon" : "");
|
||||
@@ -1381,13 +1488,18 @@ int main(int argc, char* argv[])
|
||||
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
|
||||
// 不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议只能显式喂进去:否则哪怕
|
||||
// g_SETTINGS.protoType 配成 WS/WSS,也会静默按明文 TCP 直连(日志里一个字都没有)。
|
||||
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||||
// 喂动作在循环内(见下):转移/到期恢复都会改传输方式,只喂一次会按旧协议重连。
|
||||
if (g_SETTINGS.protoType == PROTO_WS || g_SETTINGS.protoType == PROTO_WSS) {
|
||||
Mprintf("[WS] 按配置的传输协议连接: proto=%d(WSS 需要 TLS 支持,不支持的平台会 fail-closed)\n",
|
||||
(int)(unsigned char)g_SETTINGS.protoType);
|
||||
}
|
||||
g_pMainClient = ClientObject.get(); // 自升级失败回报用
|
||||
while (!g_bExit) {
|
||||
// 转移目标要在用之前应用;上一次重连留下的「请断开」标志在此已无意义
|
||||
ApplyPendingTransfer();
|
||||
CheckTransferExpiry();
|
||||
g_needReconnect.store(false, std::memory_order_relaxed);
|
||||
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||||
clock_t c = clock();
|
||||
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {
|
||||
Sleep(5000);
|
||||
@@ -1427,15 +1539,19 @@ int main(int argc, char* argv[])
|
||||
// 等待心跳间隔(每秒检查一次退出条件,保证及时响应)
|
||||
int interval = g_heartbeatInterval > 0 ? g_heartbeatInterval : 30;
|
||||
for (int i = 0; i < interval; ++i) {
|
||||
// 转移生效只改地址(下次重连才用),到期则改回原主控并置重连标志
|
||||
ApplyPendingTransfer();
|
||||
CheckTransferExpiry();
|
||||
if (g_needReconnect.load(std::memory_order_relaxed))
|
||||
break;
|
||||
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
|
||||
break;
|
||||
Sleep(1000);
|
||||
}
|
||||
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE):断开后由外层循环用新传输方式重连。
|
||||
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE)与转移到期都会置这个标志:
|
||||
// 断开后由外层循环用新地址、新传输方式重连。
|
||||
if (g_needReconnect.exchange(false)) {
|
||||
Mprintf(">>> Reconnecting to apply the TLS transport change\n");
|
||||
Mprintf(">>> Reconnecting to apply the address/transport change\n");
|
||||
ClientObject->Disconnect();
|
||||
break;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user