diff --git a/client/ClientDll.cpp b/client/ClientDll.cpp index 5cbaa06..3f6ff29 100644 --- a/client/ClientDll.cpp +++ b/client/ClientDll.cpp @@ -851,12 +851,42 @@ void ConfirmProtoSwitch(iniFile& cfg) } // namespace -// 转移临时连接是否已过 valid_to。目标不可达时 StartClient 走的是外层重连循环, -// 进不到内层心跳循环,所以两处都要查。 -static bool TransferExpired(iniFile& cfg) +// 「被转移」的主控:注册表里有未过期的 valid_to 就把主连接改到 master:port, +// 并记下到期时刻。KernelManager 的 ASSIGN 分支只写配置 + 断开连接(CONNECT_ADDRESS +// 不参与跨线程同步,不能在收包线程里改),真正的应用在这里:进 StartClient 时一次, +// 之后每轮重连前再看一眼——所以会话中途下发的转移,下一轮就生效,不用等进程重启。 +// 返回 true 表示当前处于转移期(assigned)。 +static bool ApplyAssignedMaster(iniFile& cfg, CONNECT_ADDRESS& settings, double& valid_to) { - double validTo = atof(cfg.GetStr("settings", "valid_to").c_str()); - return validTo > 0 && time(0) > validTo; + auto now = time(0); + valid_to = atof(cfg.GetStr("settings", "valid_to").c_str()); + if (now > valid_to) + return false; + auto saved_ip = cfg.GetStr("settings", "master"); + auto saved_port = cfg.GetInt("settings", "port"); + if (saved_ip.empty() || saved_port <= 0) + return false; + settings.SetServer(saved_ip.c_str(), saved_port); + auto saved_proto = cfg.GetStr("settings", "master_proto"); + if (saved_proto == "0" || saved_proto == "1") + settings.iHeaderEnc = atoi(saved_proto.c_str()); + // 转移时一并下发的传输方式(新服务端才有;老记录没有这个键)。没有记录就 + // 沿用烘焙值——这里不能写死 PROTO_TCP,否则老转移记录会把原本 WSS 的 + // 客户端改回直连。 + auto saved_transport = cfg.GetStr("settings", "master_transport"); + if (saved_transport == "0" || saved_transport == "5" || saved_transport == "6") + settings.protoType = (char)atoi(saved_transport.c_str()); + // 每轮重连都会走到这里,目标没变就不再打日志——否则一个连不上的转移目标会把 + // 客户端日志刷成同一条重复行,排查时反而看不到别的。 + static std::string logged; + const std::string cur = saved_ip + ":" + std::to_string(saved_port) + "@" + + std::to_string((long long)valid_to); + if (cur != logged) { + logged = cur; + Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(), + saved_port, int(valid_to - now)); + } + return true; } DWORD WINAPI StartClient(LPVOID lParam) @@ -868,28 +898,14 @@ DWORD WINAPI StartClient(LPVOID lParam) double valid_to = 0; std::string ip = settings.ServerIP(); int port = settings.ServerPort(); + // 转移会把主连接改成目标主控的传输方式(master_transport),复原时要一并还原, + // 否则从 WSS 主控转出去的主机会按目标的传输方式去连原主控。 + const char linkProto = settings.protoType; + const int linkHeaderEnc = settings.iHeaderEnc; Mprintf("StartClient begin[%s:%d]\n", ip.c_str(), port); ActivityHistory::Instance().Start(); - if (!app.m_bShared) { - auto now = time(0); - valid_to = atof(cfg.GetStr("settings", "valid_to").c_str()); - if (assigned = now <= valid_to) { - auto saved_ip = cfg.GetStr("settings", "master"); - auto saved_port = cfg.GetInt("settings", "port"); - settings.SetServer(saved_ip.c_str(), saved_port); - auto saved_proto = cfg.GetStr("settings", "master_proto"); - if (saved_proto == "0" || saved_proto == "1") - settings.iHeaderEnc = atoi(saved_proto.c_str()); - // 转移时一并下发的传输方式(新服务端才有;老记录没有这个键)。没有记录就 - // 沿用烘焙值——这里不能写死 PROTO_TCP,否则老转移记录会把原本 WSS 的 - // 客户端改回直连。 - auto saved_transport = cfg.GetStr("settings", "master_transport"); - if (saved_transport == "0" || saved_transport == "5" || saved_transport == "6") - settings.protoType = (char)atoi(saved_transport.c_str()); - Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(), saved_port, - int(valid_to-now)); - } - } + if (!app.m_bShared) + assigned = ApplyAssignedMaster(cfg, settings, valid_to); auto list = app.GetSharedMasterList(); if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) { // 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient, @@ -973,12 +989,34 @@ DWORD WINAPI StartClient(LPVOID lParam) app.SetThreadRun(TRUE); ThreadInfo* kb = CreateKB(&settings, bExit, pubIP, isAuthKernel); static auto _ = RestoreMemDLL(&cfg, &settings, app.g_bExit); + // 转移到期复原。必须与连接状态解耦:旧实现只在心跳循环里判断,转移目标不可达时 + // 主连接一直重连失败,根本进不了那个循环,主机就会卡在一个已经过期的地址上, + // 只能等进程重启。复原后置 S_CLIENT_UPDATE:StartClientApp 复位状态并重新进入 + // 本函数,注册表里的 valid_to 已过期,不会再把地址改回转移目标。 + auto restoreExpiredAssignment = [&]() -> bool { + if (!assigned || time(0) <= valid_to) + return false; + // ip/port/proto 是进 StartClient 时记下的、被转移覆盖之前的链路。 + app.SetProcessState(S_CLIENT_UPDATE); + settings.SetServer(ip.c_str(), port); + settings.protoType = linkProto; + settings.iHeaderEnc = linkHeaderEnc; + Mprintf("[StartClient] Client is restored to %s:%d\n", ip.c_str(), port); + return true; + }; while (app.m_bIsRunning(&app)) { - if (app.m_sharedKind == SHARED_KIND_TRANSFER && TransferExpired(cfg)) { - Mprintf("[StartClient] Transfer expired; stopping transfer instance\n"); - app.SetProcessState(S_CLIENT_EXIT); + // 每轮都从注册表对齐一次转移目标:会话中途被转移时,KernelManager 的 ASSIGN + // 分支写的是注册表并断开连接(CONNECT_ADDRESS 不参与跨线程同步,收包线程改不了), + // 新地址只能在这里读出来再连。 + // 不能像以前那样「只在 assigned 为假时读一次」——到期复原后 assigned 已经是真, + // 原主控再次发起转移就会被整条漏掉(注册表改了、会话还连在老地址上)。 + // 没有有效记录(从未转移 / 已过期)时本函数一个键都不改,代价只是读几个注册表值。 + if (!app.m_bShared && ApplyAssignedMaster(cfg, settings, valid_to)) + assigned = TRUE; + // 到期判断放在建连之前:目标不可达时下面的 ConnectServer 会一直失败, + // 心跳循环根本进不去,复原不能只依赖那条路径。 + if (restoreExpiredAssignment()) break; - } ULONGLONG dwTickCount = GetTickCount64(); // 协议切换:按注册表里的入口覆盖建连(分享实例不受主控的切换影响,被分配/转移 // 过主控的入口优先)。 @@ -1008,14 +1046,6 @@ DWORD WINAPI StartClient(LPVOID lParam) WAIT_n(app.m_bIsRunning(&app)&& ClientObject->IsRunning() && ClientObject->IsConnected(), 10, 200); do { - // 转移临时连接自己按 valid_to 到期退出。主实例可能一直连着原主控 - // (assigned=false),永远走不到下面的到期恢复分支,只能由这条连接自查; - // 否则它会一直挂在转移目标上,直到客户端进程重启。 - if (app.m_sharedKind == SHARED_KIND_TRANSFER && TransferExpired(cfg)) { - Mprintf("[StartClient] Transfer expired; stopping transfer instance\n"); - app.SetProcessState(S_CLIENT_EXIT); - break; - } Manager->SendHeartbeat(); SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED); // 协议切换:新入口「登录被接受」后才撤销自动回退计时(ConfirmProtoSwitch 幂等)。 @@ -1026,14 +1056,8 @@ DWORD WINAPI StartClient(LPVOID lParam) // 不放在循环前一次判定:MasterSettings 可能比第一轮心跳晚到。 if (ClientObject->IsConnected() && ClientObject->IsLoginAcked()) ConfirmProtoSwitch(cfg); - if (assigned && time(0) > valid_to) { - // 转移到期:主连接回到原主控,同时收掉转移顺带起的那条临时连接, - // 否则它会一直连着转移目标(Linux 到期同样停 KIND_TRANSFER)。 - StopSharedInstances(SHARED_KIND_TRANSFER); - app.SetProcessState(S_CLIENT_UPDATE); - settings.SetServer(ip.c_str(), port); - Mprintf("[StartClient] Client is restored to %s:%d\n", ip.c_str(), port); - } + // 连接期间到期也要立刻复原;不可达的情况由外层循环开头兜底。 + restoreExpiredAssignment(); } while (ClientObject->IsRunning() && ClientObject->IsConnected() && app.m_bIsRunning(&app)); while (GetTickCount64() - dwTickCount < 5000 && app.m_bIsRunning(&app)) Sleep(200); diff --git a/client/ClientDll.h b/client/ClientDll.h index 228cc14..9f3fea7 100644 --- a/client/ClientDll.h +++ b/client/ClientDll.h @@ -142,12 +142,11 @@ public: // (主控经 nginx 走 WSS、分享目标直连设备端口时就得是 TCP),所以不能一律照抄主控。 ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE, int headerEnc = -1, int protoType = -1); -// 分享实例的种类。取消分享只停 SHARED_KIND_SHARE;「转移主机」末尾贯穿到分享分支 -// 顺带起的那条连接标成 SHARED_KIND_TRANSFER,取消分享不能动它(与 Linux 客户端的 -// KIND_SHARE / KIND_TRANSFER 语义一致)。 +// 分享实例的种类。「转移主机」不再起分享实例(它直接让主连接搬到新主控), +// 所以现在只有一种;保留枚举是为了让 StartSharedClient / StopSharedInstances +// 的签名在后续再引入实例种类时不用改调用点。 enum SharedInstanceKind { SHARED_KIND_SHARE = 1, - SHARED_KIND_TRANSFER = 2, }; // 启动一个分享实例线程并在进程内登记,targetKey 为目标地址 "ip:port"。 diff --git a/client/KernelManager.cpp b/client/KernelManager.cpp index b6fd964..44a2623 100644 --- a/client/KernelManager.cpp +++ b/client/KernelManager.cpp @@ -1368,7 +1368,21 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength) break; auto now = time(nullptr); auto valid_to = atoi(m_cfg->GetStr("settings", "valid_to").c_str()); - if (now <= valid_to) break; // Avoid assign again + if (now <= valid_to) { + // 转移期间不接受第二次转移:主机此刻只连着新主控,它无权再改归属, + // 否则到期按原主控复原时中间那一跳就成了谁也不认的孤儿。 + Mprintf("Assign ignored: already assigned until %lld\n", (long long)valid_to); + ClientMsg msg("转移主机", "Host is already transferred, ignored"); + SendData((LPBYTE)&msg, sizeof(msg)); + break; + } + // 先校验天数再落盘:天数非法时一个键都不改,避免留下「master 换了但 + // 没有 valid_to」的半截记录(重启后 assigned 为假,地址却已经变了)。 + float days = atof(v[2].c_str()); + if (days <= 0) { + Mprintf("Assign ignored: invalid days '%s'\n", v[2].c_str()); + break; + } m_cfg->SetStr("settings", "master", v[0]); m_cfg->SetStr("settings", "port", v[1]); if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL) @@ -1379,12 +1393,19 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength) m_cfg->SetStr("settings", "master_transport", std::to_string(shareTransport)); else m_cfg->SetStr("settings", "master_transport", ""); - float days = atof(v[2].c_str()); - if (days > 0) { - auto valid_to = time(0) + days*86400; - // overflow after 2038-01-19 - m_cfg->SetStr("settings", "valid_to", std::to_string(valid_to)); - } + auto valid_to_new = (long long)(time(0) + days*86400); + // overflow after 2038-01-19 + m_cfg->SetStr("settings", "valid_to", std::to_string(valid_to_new)); + // 真转移:断开当前主控,主连接立刻连到新主控(旧主控上这台主机随即 + // 离线)。不另起分享实例——那只是「分享」,新主控拿到的是一条不能 + // 升级、也不真正属于它的旁路连接。新地址由 StartClient 的重连循环 + // 在下一轮开头从注册表应用(CONNECT_ADDRESS 不参与跨线程同步, + // 不能在收包线程里改)。 + Mprintf("Assign to %s:%s for %llds, moving the main link now\n", + v[0].c_str(), v[1].c_str(), (long long)days*86400); + if (m_ClientObject) + m_ClientObject->Disconnect(); + break; } case SHARE_TYPE_YAMA: { // 目标键(host:port)只解析一次,share_list 归并与实例登记共用。 @@ -1397,6 +1418,15 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength) SendData((LPBYTE)&msg, sizeof(msg)); break; } + // 转移期间不接受分享:主机此刻只连着新主控,新主控无权再把它分出去。 + // 放行的话,到期按原主控复原后这条分享连接还挂在别处,等于凭空多出 + // 一条谁也不认的链路(Linux 客户端同样拒绝)。 + if (time(0) <= atoi(m_cfg->GetStr("settings", "valid_to").c_str())) { + Mprintf("Share ignored: host is transferred\n"); + ClientMsg msg("分享主机", "Host is transferred, sharing is not allowed"); + SendData((LPBYTE)&msg, sizeof(msg)); + break; + } if (targetKey.empty()) break; auto share = targetKey; @@ -1437,17 +1467,11 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength) break; } // 登记后起线程。同一目标只留一条连接(与 Linux 的 SpawnManagedChild - // 一致):分享要顶掉同目标上的旧分享,以及会被长期分享接管的转移临时 - // 连接;转移目标已有分享实例时不再多连一条,否则同一 clientID 互踢。 - const bool transfer = szBuffer[1] == SHARE_TYPE_YAMA_FOREVER; - if (transfer && HasSharedInstanceForTarget(targetKey, SHARED_KIND_SHARE)) { - Mprintf("Transfer target %s already reachable via a share instance; extra connection skipped\n", - targetKey.c_str()); - break; - } + // 一致):重复下发同一目标只替换记录,旧连接先停掉再起新的,否则同一 + // clientID 会有两条连接互相踢。 StopSharedInstancesForTarget(targetKey); auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE, shareProto, shareTransport); - StartSharedClient(a, transfer ? SHARED_KIND_TRANSFER : SHARED_KIND_SHARE, targetKey); + StartSharedClient(a, SHARED_KIND_SHARE, targetKey); break; } case SHARE_TYPE_HOLDINGHANDS: @@ -1460,8 +1484,8 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength) int stopped = 0; if (m_ClientApp->IsMainInstance()) { m_cfg->SetStr("settings", "share_list", ""); - // 分享实例是同进程里的线程,停掉后连接立即断开;转移顺带起的那条 - // (SHARED_KIND_TRANSFER) 不动,取消分享撤销不了转移。 + // 分享实例是同进程里的线程,停掉后连接立即断开。取消分享只停分享实例, + // 撤销不了转移(转移改的是主连接自己连的地址,不涉及分享线程)。 stopped = StopSharedInstances(SHARED_KIND_SHARE); Mprintf("Share cancel: stopping %d share instance(s)\n", stopped); } diff --git a/common/host_share.h b/common/host_share.h index bbdc0e9..0ef5461 100644 --- a/common/host_share.h +++ b/common/host_share.h @@ -10,7 +10,8 @@ // server/2015Remote/2015RemoteDlg.cpp ShareClient)。命令字节是 COMMAND_SHARE(59), // 不是「转移主机」用的 COMMAND_ASSIGN_MASTER(207);Windows 客户端的 case 把两者 // 并在一起、靠 buf[1] 的类型字节区分,这里同样两个都收。和「转移主机」的区别: -// 转移改的是本实例的主连接,分享另起一条通往目标主控的连接,主连接原样保留。 +// 转移改的是本实例的主连接(收包后立刻断开、重连到新主控,老主控那边随即离线), +// 分享另起一条通往目标主控的连接,主连接原样保留。 // Windows 侧是同一进程里再起一个 ClientApp 线程(client/KernelManager.cpp、 // client/ClientDll.cpp 的 m_bShared 分支);Linux 侧由主实例 fork+exec 出一个 // 分享子进程,复用同一份登录/心跳/命令处理代码。 diff --git a/linux/README.md b/linux/README.md index 7f75cbc..dcd2ad6 100644 --- a/linux/README.md +++ b/linux/README.md @@ -30,7 +30,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件 | 屏幕预览(缩略图) | `ScreenPreview.cpp` | `client/ScreenPreview.cpp` | ✅ 完整(X11 抓屏 → 缩放 → 原始 BGRA 上报,由服务端统一编码 JPEG;双击预览、列表缩略图、MCP `get_screenshot` 均可用。无 `DISPLAY` 时不声明能力位,服务端不会发请求) | | V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔Linux(含 MCP `upload_file`/`download_file`:发送完成包带流式 SHA-256,路径不存在/无权限回 `TOKEN_DOWNLOAD_ERROR`) | | C2C 文件接收 | `FileTransferV2.h` | `file_upload.h` | ✅ Windows/MCP → Linux(目标目录由服务端 `dst_dir` 指定,落盘后回执) | -| 主机转移 | `common/host_transfer.h` + main.cpp | `KernelManager.cpp` | ✅ 完整(`COMMAND_ASSIGN_MASTER`,下发后立即另起一条连接,主连接重连时生效;到期自动回原主控并收掉那条连接) | +| 主机转移 | `common/host_transfer.h` + main.cpp | `KernelManager.cpp` | ✅ 完整(`COMMAND_ASSIGN_MASTER`,**真的转移**:收包后立刻断开原主控、主连接连到新主控,旧主控上这台主机随即离线;新主控可正常远控/升级,但不能再转移或分享它;到期自动回原主控) | | 主机分享 | `common/host_share.h` + main.cpp | `KernelManager.cpp` / `ClientDll.cpp` | ✅ 完整(每条分享记录 fork 一个 `--share` 子进程,主连接不受影响;取消分享立即断开,重启自动恢复) | | 配置持久化 | `LinuxConfig` | INI 文件 | ✅ 完整 | | MCP 远程管理 | 复用 `SystemManager.h` / `PTYHandler.h` / `ScreenHandler.h` | 服务端 MCP | ✅ 档 1:`kill_process`、`exec_command`、`terminal_open/exec/close`、`remote_open/close/mouse/keyboard/clipboard`(服务端放开门禁,客户端协议本已实现) | @@ -219,21 +219,23 @@ Windows 客户端的同名命令没有摘要(走内存加载器/更新器) 服务端选中一台主机后点「转移主机」,选目标主控和有效天数,客户端会: 1. 把目标写进 `~/.config/ghost/config.conf` 的 `transfer` 键(`ip:port:transport:shine:valid_to`); -2. **立即另起一条通往新主控的连接**(与分享同一个 fork+exec 机制),新主控马上就能看到 - 这台主机上线;它与老主控之间的主连接原样保留,不会断开; -3. 下一次重连(断线重连、客户端重启)时主连接才搬到新主控,那条临时连接随之消失; +2. **立刻断开当前主控**,主连接改连新主控——转移是把这条主连接搬走,不是另开一条。 + 老主控上这台主机随即离线,`--share` 那种旁路连接在这里是不对的:新主控拿到的 + 会是一条不能升级、也不真正属于它的连接; +3. 新主控从此可以像自己的主机一样操作它:远控、文件、终端、**升级程序**都正常; 4. 过了有效天数自动回到转移前的原主控——原地址只记在内存里(启动参数或编译期默认), - 不写回配置,所以重启后仍然有效;到期时那条临时连接一并收掉。 + 不写回配置,所以重启后仍然有效;到期时按原地址重连。 -第 2 步与 Windows 客户端现有的实际行为一致(`KernelManager.cpp` 的转移分支会贯穿到分享 -分支、额外起一个 shared 实例);差别只在到期处理:Windows 那条连接要等进程重启才消失。 +转移期间(`now <= valid_to`)客户端会拒绝两件事:**再次转移**和**分享**。前者是为了防止 +主机被 B 转到 C、到期却按 A 复原,中间那一跳成为谁也不认的孤儿;后者是因为主机此刻只 +连着新主控,新主控无权再把它分出去。两条都会回一条消息进服务端消息栏,不会静默丢弃。 注意事项: - 目标是永久转移(天数填 0)时客户端会拒绝,避免把主机改到一个不可达的地址后无法回退; - 有效期内重复下发会被忽略(与 Windows 客户端一致); - 转移期间切换传输方式(明文 / WS / WSS)会跟随服务端下发的 `transport` 段; -- 「取消分享」不会影响转移建立的临时连接; +- 「取消分享」只收掉分享子进程,撤销不了转移; - 只想把主机要回来,直接把 `transfer` 键清空并重启客户端即可。 ## 主机分享 diff --git a/linux/main.cpp b/linux/main.cpp index 9fc173f..e7e26d1 100644 --- a/linux/main.cpp +++ b/linux/main.cpp @@ -53,15 +53,10 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength); static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength); -// 主机分享/转移的子进程管理(实现在进程辅助函数之后,DataProcess/main 里都要用) -// 分享子进程与转移子进程都走同一套 fork+exec 管理,只是归属不同: -// KIND_SHARE 「取消分享」只停这些 -// KIND_TRANSFER 转移到期时停这些(提前建立的那条连接) -// KIND_ALL 主实例退出时全停 -enum ManagedKind { KIND_SHARE, KIND_TRANSFER, KIND_ALL }; +// 主机分享的子进程管理(实现在进程辅助函数之后,DataProcess/main 里都要用)。 +// 转移不在这里:转移是主连接自己换地址(见下面的 g_needReconnect),不起子进程。 static bool StartShareInstance(const std::string& entry); -static bool StartTransferInstance(const std::string& entry); -static void StopChildren(ManagedKind kind); +static void StopChildren(); static void StartShareInstancesFromConfig(); // 远程地址:当前为写死状态,如需调试,请按实际情况修改 @@ -76,8 +71,9 @@ static std::atomic g_needResendLogin(false); // 分组变更后需要重 static std::atomic g_needReconnect(false); // ============== 主机转移(COMMAND_ASSIGN_MASTER)============== -// 服务端「转移主机」把目标写进 config.conf 的 transfer 键,之后每次重连都连新主控; -// valid_to 到期后恢复本进程启动时的原主控。原主控只存在内存里(argv 或编译期默认), +// 转移 = 主连接真的搬到新主控:收包后立刻断开当前主控、连到目标,旧主控上这台主机 +// 随即离线。目标写进 config.conf 的 transfer 键,之后每次重连都连新主控;valid_to +// 到期后恢复本进程启动时的原主控。原主控只存在内存里(argv 或编译期默认), // 不能写回配置——恢复时读到的若还是转移目标,就成了原地打转。 // 解析/编解码/地址应用在 common/host_transfer.h(macOS 客户端可直接复用)。 static HostTransfer::Endpoint g_transferOrig; // 启动时的主控,过期恢复用 @@ -96,14 +92,11 @@ static bool g_bShareInstance = false; // 本进程是分享子 static std::mutex g_shareMu; // 保护 g_shareProcs // 子进程 pid 和它启动时用的那条记录:判断「同一条分享」只能比这条记录,不能比配置 // 里的——命令处理是先写配置再起进程,配置里已经是新记录了。 -// transfer=true 表示这是「转移主机」立即建立的那条连接(见 StartTransferInstance), -// 它不进 share_list、不受「取消分享」影响。 struct ShareProc { pid_t pid; std::string entry; - bool transfer; }; -static std::map g_shareProcs; // "ip:port" / "transfer:ip:port" -> 子进程 +static std::map g_shareProcs; // "ip:port" -> 子进程 // 分享条目上限:每条都对应一个常驻子进程,服务端误发/恶意刷下发不能把进程表打爆。 static const size_t kMaxShareEntries = 16; static std::atomic g_shareReaperStop(false); @@ -574,8 +567,8 @@ static void InitTransferState() } // 把接收线程记下的目标应用到全局连接参数。只在主线程调用:CONNECT_ADDRESS 没有 -// 跨线程同步,ConnectServer 读的就是它。只改地址、不主动断开——与 Windows 一致, -// 下一次重连才生效。 +// 跨线程同步,ConnectServer 读的就是它。收包时已经置了 g_needReconnect,心跳循环 +// 会立刻断开重连,所以这里的地址在下一秒就生效——不是「等下次自然重连」。 static void ApplyPendingTransfer() { if (!g_transferPending.load(std::memory_order_acquire)) @@ -588,7 +581,7 @@ static void ApplyPendingTransfer() } 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", + Mprintf(">>> Transfer applied: -> %s:%d (transport=%d), %llds left\n", t.ep.ip.c_str(), t.ep.port, t.ep.transport, left); } @@ -606,8 +599,6 @@ static void CheckTransferExpiry() g_needReconnect.store(true, std::memory_order_relaxed); Mprintf(">>> Transfer expired: restoring %s:%d\n", g_transferOrig.ip.c_str(), g_transferOrig.port); - // 转移时提前建立的那条连接也要收掉,否则过期后主机仍挂在新主控上。 - StopChildren(KIND_TRANSFER); } // ============== 历史活动(COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY) ============== @@ -861,6 +852,14 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) Mprintf("** [%p] SHARE ignored: running as share instance ***\n", user); return TRUE; } + // 转移期间不接受分享:主机此刻只连着新主控,新主控无权再把它分出去。 + // 放行的话,到期按原主控复原后这条分享连接还挂在别处,等于凭空多出 + // 一条谁也不认的链路。 + if ((long long)time(nullptr) <= g_transferValidTo.load(std::memory_order_relaxed)) { + Mprintf("** [%p] SHARE ignored: host is transferred until %lld ***\n", + user, g_transferValidTo.load(std::memory_order_relaxed)); + return TRUE; + } HostShare::Endpoint ep; if (!HostShare::ParseCommand(szBuffer, ulLength, ep)) { Mprintf("** [%p] SHARE: malformed payload, ignored ***\n", user); @@ -898,10 +897,19 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) } // 有效期内重复下发忽略(与 Windows KernelManager 的 now <= valid_to 判断一致)。 // 用原子变量而不是再读一次配置:状态以本进程为准,避免和主线程的写入交错。 + // 这条同时挡住了「转移目标主控再转一手」:主机被转移到 B 之后只连着 B,B 发来的 + // 转移命令一律落在这里被丢掉——只有原主控(主机复原后才连回去的那一台)还有 + // 机会发起下一次转移。不这么挡的话,B 把主机转到 C,到期却按原主控复原, + // 中间那一跳就成了谁也不认的孤儿。 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); + // 主控那边点完看不到任何反馈会以为下发丢了,回一条消息进消息栏。 + if (g_pMainClient && g_pMainClient->IsConnected()) { + ClientMsg msg("Transfer host", "Host is already transferred, ignored"); + g_pMainClient->Send2Server((char*)&msg, sizeof(msg)); + } return TRUE; } { @@ -913,18 +921,18 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) g_transferValidTo.store(t.validTo, std::memory_order_relaxed); LinuxConfig cfg; cfg.SetStr("transfer", HostTransfer::EncodeRecord(t)); - // 立即再起一条通往新主控的连接,新主控马上就能看到这台主机上线;本实例与老主控 - // 的主连接原样保留,下次重连(含重启)才轮到主连接过去。这与 Windows 客户端 - // 现有语义一致:KernelManager 的转移分支末尾没有 break,会贯穿到分享分支, - // 额外起一个 shared 实例连到同一个目标地址。 - Mprintf("** [%p] ASSIGN to %s:%d for %llds, main link moves on next reconnect ***\n", + // 真转移:断掉当前主控,主连接立刻连到新主控,旧主控上这台主机随即离线。 + // 不能另起一条临时连接——那只是「分享」,新主控拿到的是一条不能升级、 + // 也不真正属于它的旁路连接(升级命令按设计只认主连接)。 + // 目标由主线程的 ApplyPendingTransfer 落到 g_SETTINGS,本标志让它马上重连。 + g_needReconnect.store(true, std::memory_order_relaxed); + Mprintf("** [%p] ASSIGN to %s:%d for %llds, moving the main link now ***\n", user, t.ep.ip.c_str(), t.ep.port, t.validTo - now); - StartTransferInstance(HostShare::EncodeEntry(t.ep)); // 新主控立即看到上线 } else if (szBuffer[0] == COMMAND_SHARE_CANCEL) { // 「取消分享」:清掉持久化列表并立刻收掉分享子进程。Windows 客户端在 // COMMAND_SHARE_CANCEL 里也改成停掉同进程的分享线程(StopSharedInstances), - // 两端都是立即断开;Linux 的分享实例是独立进程,直接 stop。转移顺带起的 - // 实例(KIND_TRANSFER / SHARED_KIND_TRANSFER)两端都不动。 + // 两端都是立即断开;Linux 的分享实例是独立进程,直接 stop。转移不涉及子进程, + // 取消分享自然也撤销不了转移。 if (g_bShareInstance) { Mprintf("** [%p] SHARE_CANCEL ignored: running as share instance ***\n", user); return TRUE; @@ -932,7 +940,7 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) LinuxConfig cfg; cfg.SetStr("share_list", ""); Mprintf("** [%p] SHARE_CANCEL: stopping all share instances ***\n", user); - StopChildren(KIND_SHARE); + StopChildren(); } else if (szBuffer[0] == COMMAND_UPDATE) { // 服务端"升级程序"菜单下发新版本 ELF。 // 分享实例不升级:二进制是主实例和所有分享实例共用的,好几个进程同时替换 @@ -1316,15 +1324,14 @@ static void ShareReaperLoop() int st = 0; pid_t r = waitpid(it->second.pid, &st, WNOHANG); if (r == it->second.pid) { - const char* kind = it->second.transfer ? "Transfer instance" : "Share instance"; if (WIFEXITED(st)) - Mprintf(">>> %s %s exited (code %d)\n", - kind, it->first.c_str(), WEXITSTATUS(st)); + Mprintf(">>> Share instance %s exited (code %d)\n", + it->first.c_str(), WEXITSTATUS(st)); else if (WIFSIGNALED(st)) - Mprintf(">>> %s %s exited by signal %d\n", - kind, it->first.c_str(), WTERMSIG(st)); + Mprintf(">>> Share instance %s exited by signal %d\n", + it->first.c_str(), WTERMSIG(st)); else - Mprintf(">>> %s %s exited\n", kind, it->first.c_str()); + Mprintf(">>> Share instance %s exited\n", it->first.c_str()); it = g_shareProcs.erase(it); } else if (r < 0 && errno == ECHILD) { it = g_shareProcs.erase(it); // 已被别处收走(防御) @@ -1421,9 +1428,8 @@ static void TerminateChildLocked(pid_t pid) Mprintf(">>> Child pid %d still alive after SIGKILL, giving up on it\n", (int)pid); } -// 起一个受管子进程并登记。key 在本进程内唯一:分享用 "ip:port",转移用 "transfer:ip:port", -// 这样转移目标与分享目标相同也不会互相顶掉。 -static bool SpawnManagedChild(const std::string& key, const std::string& entry, bool transfer) +// 起一个受管子进程并登记。key 是目标主控 "ip:port"。 +static bool SpawnManagedChild(const std::string& key, const std::string& entry) { EnsureShareReaper(); @@ -1448,9 +1454,8 @@ static bool SpawnManagedChild(const std::string& key, const std::string& entry, pid_t pid = SpawnShareProcess(entry); if (pid <= 0) return false; - g_shareProcs[key] = ShareProc{ pid, entry, transfer }; - Mprintf(">>> %s instance started: %s (pid %d)\n", - transfer ? "Transfer" : "Share", entry.c_str(), (int)pid); + g_shareProcs[key] = ShareProc{ pid, entry }; + Mprintf(">>> Share instance started: %s (pid %d)\n", entry.c_str(), (int)pid); return true; } @@ -1460,61 +1465,19 @@ static bool StartShareInstance(const std::string& entry) if (!HostShare::DecodeEntry(entry, ep)) return false; const std::string shareKey = HostShare::MasterKey(ep); - { - // 同一主控上已有一条「转移」临时连接:分享是长期连接,接管它的职责。 - // 不收掉的话,这个主控上会挂着同一 clientID 的两条连接,互踢。 - const std::string transferKey = "transfer:" + shareKey; - std::lock_guard lk(g_shareMu); - auto it = g_shareProcs.find(transferKey); - if (it != g_shareProcs.end()) { - Mprintf(">>> Share to %s replaces the transfer instance (pid %d)\n", - shareKey.c_str(), (int)it->second.pid); - TerminateChildLocked(it->second.pid); - g_shareProcs.erase(it); - } - } - return SpawnManagedChild(shareKey, entry, false); + return SpawnManagedChild(shareKey, entry); } -// 「转移主机」立即生效的那条连接:不进 share_list(重启后由主连接自己过去), -// 也不受「取消分享」影响;目标可以暂时不可达,子进程有自己的重连循环。 -static bool StartTransferInstance(const std::string& entry) -{ - HostShare::Endpoint ep; - if (!HostShare::DecodeEntry(entry, ep)) - return false; - const std::string shareKey = HostShare::MasterKey(ep); - { - // 同一个主控已经有分享连接时不必再起一条:目标那边已经能看到这台主机, - // 两条同 clientID 的连接只会互相踢。 - std::lock_guard lk(g_shareMu); - auto it = g_shareProcs.find(shareKey); - if (it != g_shareProcs.end() && !it->second.transfer - && ChildAliveLocked(it->second.pid)) { - Mprintf(">>> Transfer target %s already reachable via share instance " - "(pid %d), extra connection skipped\n", - shareKey.c_str(), (int)it->second.pid); - return true; - } - } - return SpawnManagedChild("transfer:" + shareKey, entry, true); -} - -// 停掉指定归属的子进程:SIGTERM 让子进程走自己的 signal handler 正常退出, -// 3 秒还不走就 SIGKILL(再等 1 秒)。 +// 停掉所有子进程(分享实例;转移已不产生子进程):SIGTERM 让子进程走自己的 +// signal handler 正常退出,3 秒还不走就 SIGKILL(再等 1 秒)。 // 等待阶段不持 g_shareMu:调用点就在接收线程上,持锁睡会把 reaper 和其它起停一起堵住。 -static void StopChildren(ManagedKind kind) +static void StopChildren() { - auto match = [kind](const ShareProc& p) { - return kind == KIND_ALL || p.transfer == (kind == KIND_TRANSFER); - }; - std::vector pids; { std::lock_guard lk(g_shareMu); for (auto& kv : g_shareProcs) - if (match(kv.second)) - pids.push_back(kv.second.pid); + pids.push_back(kv.second.pid); for (pid_t pid : pids) kill(pid, SIGTERM); // 只发信号,不等待 } @@ -2042,10 +2005,6 @@ int main(int argc, char* argv[]) Sleep(5000); continue; } - // 主连接已经搬到转移目标:那条「提前建立」的临时连接完成使命。留着就是同一 - // clientID 在这个主控上的第二条连接,服务端会互踢。 - if (g_transferValidTo.load(std::memory_order_relaxed) > 0) - StopChildren(KIND_TRANSFER); // 进入新连接,重置服务端身份校验状态 ClientAuth::OnNewConnection(); @@ -2174,7 +2133,7 @@ int main(int argc, char* argv[]) g_shareReaperStop.store(true, std::memory_order_relaxed); if (g_shareReaperThread.joinable()) g_shareReaperThread.join(); - StopChildren(KIND_ALL); + StopChildren(); } // 采样线程要在 main 的局部对象(historyChecker)析构前停掉 diff --git a/server/go/README.md b/server/go/README.md index d80fc4c..f319ae7 100644 --- a/server/go/README.md +++ b/server/go/README.md @@ -72,6 +72,7 @@ Web 应用能力 (Phase 3-7): - **鼠标 / 键盘输入**: Win32 消息映射 (`WM_*` / `VK_*` / `MK_*`),MSG64 48 字节布局直传客户端 - **Web 终端**: xterm.js + Windows ConPTY / 旧 cmd 管道双模式;二进制 "TRM1" 帧分流;尺寸自适应;单设备单 viewer - **用户与分组**: admin 可创建/删除 viewer 账号、配置 allowed_groups,users.json 原子写入 +- **转移主机**: 把主机临时交给另一台 master(通常是 MFC 服务端)做客户端升级,到期由客户端自动连回本机;转移状态持久化并在设备卡片上倒计时显示。仅 Go 服务端下发 `device_list.transfer`,MFC 共用同一份页面但不会出现该入口 ## 支持的命令 @@ -102,6 +103,7 @@ Web 应用能力 (Phase 3-7): | `COMMAND_SHELL` | 40 | 请求开启 shell 子连接 | | `CMD_TERMINAL_RESIZE` | 81 | PTY 尺寸 (cols / rows int16 LE) | | `COMMAND_BYE` | 204 | 优雅断开屏幕 / 终端 | +| `COMMAND_ASSIGN_MASTER` | 207 | 转移主机:`host:port:days::transport` + `SHARE_TYPE_YAMA_FOREVER`(transport:0=TCP / 5=WS / 6=WSS),客户端到期自动连回本机 | | `CMD_MASTERSETTING` | 215 | 主控配置 + HMAC 签名 (1000B) | | `CMD_HEARTBEAT_ACK` | 216 | 心跳响应(携带 Authorized 字段) | | `TOKEN_CONN_AUTH` | 246 | 子连接身份握手响应 (256B) | @@ -172,6 +174,9 @@ VSCode F5 调试时由 `sync-web-assets` preLaunchTask 自动同步。 | `YAMA_WEB_TRUST_PROXY` | Set to `1` only when running behind a reverse proxy you control (caddy / nginx / cloudflare). Switches client-IP extraction to use the last entry of `X-Forwarded-For` instead of `RemoteAddr`, so per-IP login rate limit sees the real client. Direct-exposure deployments MUST leave this unset — otherwise attackers can spoof the header to evade rate limits. | `1` | | `YAMA_AUDIT_LOG` | 安全审计日志路径(JSON lines)。默认 `logs/audit.log`;设为 `off` / `none` / `0` / `-` 关闭独立文件(审计记录仍会写入 `logs/server.log`)。审计记录带 `audit=true` 和稳定的 `event` 名,便于告警与检索。 | `/var/log/yama/audit.log` | | `YAMA_SSO_JWT_SECRET` | **[SSO]** Shared HS256 secret for bridging the parent portal's `auth_token` JWT into a YAMA web session via `/sso`. Must equal the upstream portal's signing key (FMS: `SERVER_PRIVATE_KEY`). **Only `admin` portal users are auto-logged-in**; other roles still need YAMA's own web login. Unset → SSO disabled, `/sso` returns 401. | `` | +| `YAMA_TRANSFER_TARGET` | **[转移主机]** 预填 Web UI「转移主机」弹窗的目标 `host:port`。仅作默认值,操作员仍可改填其它地址;留空则按钮照常可用、输入框为空。 | `mfc.example.com:6543` | +| `YAMA_TRANSFER_DAYS` | **[转移主机]** 预填的转移天数(到期后客户端自动连回本机),默认 `1`。取值 `(0, 365]`,弹窗输入框下限为 `0.5`;非正数或无法解析时忽略并沿用默认值。 | `2` | +| `YAMA_TRANSFER_TRANSPORT` | **[转移主机]** 转移后主机连接目标主控所用的传输方式:`0`=TCP(默认,MFC 主控直连端口)、`5`=WS、`6`=WSS。命令里始终携带该段——缺省时客户端会沿用当前链路的传输方式,WSS 主机转移到直连主控会一直连不上。 | `0` | ```bash # Linux/macOS @@ -347,6 +352,7 @@ Web 端与设备端的认证、授权、远程控制操作会额外写入**独 | `remote.clipboard.get` / `.set` | 剪贴板读取 / 写入(只记字节数,**不记内容**) | | `remote.rdp_reset` | 远程 RDP 会话归位操作 | | `admin.user.create` / `admin.user.delete` / `admin.device.delete` | 管理操作(`target` / `device_id` / `mode`) | +| `admin.device.transfer` | 转移主机(`device_id` / `target` / `days` / `until`);被拒时带 `ok:false` 与 `reason`(`invalid_target`、`already_transferred`、`offline`、`send_failed`),并以 `WARN` 级别记录 | | `admin.audit.query` | 管理员在网页查询审计日志(记录筛选条件与命中数) | | `device.online` / `device.offline` | 受控设备上线 / 下线 | | `device.auth.success` / `.failure` / `.throttled` / `.heartbeat.success` | 设备 TCP 授权结果(**只记 passcode 长度,不记 passcode**) | diff --git a/server/go/cmd/main.go b/server/go/cmd/main.go index 0b53ba3..6591ea2 100644 --- a/server/go/cmd/main.go +++ b/server/go/cmd/main.go @@ -1375,6 +1375,38 @@ func main() { } else { log.Info("SSO disabled (YAMA_SSO_JWT_SECRET not set) — web login only") } + // "Transfer host": the web UI hands a host over to another master (the MFC + // server) so that master can push a client upgrade to it; the host returns + // to this server on its own once the days run out. The target only + // pre-fills the dialog — the operator can still type another one, and an + // empty value keeps the feature available with an empty field. + transferTarget := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_TARGET")) + transferDays := 1.0 + if v := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_DAYS")); v != "" { + if d, err := strconv.ParseFloat(v, 64); err == nil && d > 0 { + transferDays = d + } else { + log.Info("Ignoring YAMA_TRANSFER_DAYS=%q (want a positive number)", v) + } + } + // The link the transferred host uses to reach the target. It is always in + // the command: clients keep their current link when it is missing, so a + // WSS-managed host would try WSS against a plain-TCP master. Default TCP + // matches what an MFC master listens on. + transferTransport := protocol.TransferTransportTCP + if v := strings.TrimSpace(os.Getenv("YAMA_TRANSFER_TRANSPORT")); v != "" { + switch v { + case "0", "5", "6": + transferTransport, _ = strconv.Atoi(v) + default: + log.Info("Ignoring YAMA_TRANSFER_TRANSPORT=%q (want 0=TCP, 5=WS, 6=WSS)", v) + } + } + if transferTarget != "" { + log.Info("Host transfer dialog pre-filled with %s (%.1f days, transport=%d)", + transferTarget, transferDays, transferTransport) + } + webCfg := web.Config{ AllowedOrigins: allowedOrigins, LoginIPLimit: wsauth.NewRateLimiter(10, time.Minute), @@ -1384,6 +1416,9 @@ func main() { BrandName: brandName, SSO: ssoDetector, DeviceACL: deviceACL, + TransferTarget: transferTarget, + TransferDays: transferDays, + TransferTransport: transferTransport, } // Start HTTP server for web UI. Hub gives it read-only access to the diff --git a/server/go/devicehistory/devicehistory.go b/server/go/devicehistory/devicehistory.go index 745103b..01286bb 100644 --- a/server/go/devicehistory/devicehistory.go +++ b/server/go/devicehistory/devicehistory.go @@ -58,6 +58,14 @@ type Record struct { FirstSeen int64 `json:"first_seen"` LastSeen int64 `json:"last_seen"` + + // TransferTo / TransferUntil mark a host that was handed over to another + // master (COMMAND_ASSIGN_MASTER): target is "host:port", until is the unix + // second the client goes back to its original master on its own. The store + // only remembers it for display — it never acts on the deadline, and a + // login here clears it because that means the host is back. + TransferTo string `json:"transfer_to,omitempty"` + TransferUntil int64 `json:"transfer_until,omitempty"` } type fileShape struct { @@ -165,6 +173,13 @@ func (s *Store) upsertAt(d hub.DeviceInfo, at time.Time) { rec.IP = d.IP rec.Screen = d.Screen rec.LastSeen = now + // A login on this server means the host is here, not at the master it was + // handed to: either it came back early (the upgrade finished, or the target + // was unreachable) or the deadline passed while this server was down. In + // both cases the marker would label an online card as "transferred" and + // keep the operator from transferring it again until the deadline. + rec.TransferTo = "" + rec.TransferUntil = 0 s.online[d.ID] = true s.pruneLocked() @@ -244,6 +259,59 @@ func (s *Store) Offline(online map[string]struct{}) []hub.DeviceInfo { return out } +// SetTransfer marks id as handed over to target ("host:port") until the given +// unix second. Reports false when the device has no history record — only a +// device that logged in at least once can be transferred, and the marker has +// nowhere to live otherwise. +func (s *Store) SetTransfer(id, target string, until int64) bool { + if id == "" || target == "" || until <= 0 { + return false + } + s.mu.Lock() + defer s.mu.Unlock() + rec, ok := s.devices[id] + if !ok { + return false + } + rec.TransferTo = target + rec.TransferUntil = until + s.markDirtyLocked() + return true +} + +// ClearTransfer forgets the handover marker and reports whether one was set. +func (s *Store) ClearTransfer(id string) bool { + s.mu.Lock() + defer s.mu.Unlock() + rec, ok := s.devices[id] + if !ok || rec.TransferUntil == 0 { + return false + } + rec.TransferTo = "" + rec.TransferUntil = 0 + s.markDirtyLocked() + return true +} + +// Transfer returns the current handover marker, dropping it once the deadline +// has passed: the client returns to its original master by itself, so an +// expired marker would only mislabel the card forever. +func (s *Store) Transfer(id string) (target string, until int64, ok bool) { + s.mu.Lock() + defer s.mu.Unlock() + rec, found := s.devices[id] + if !found || rec.TransferUntil == 0 { + return "", 0, false + } + if time.Now().Unix() >= rec.TransferUntil { + rec.TransferTo = "" + rec.TransferUntil = 0 + s.markDirtyLocked() + return "", 0, false + } + return rec.TransferTo, rec.TransferUntil, true +} + // Remove deletes the persisted record for id and reports whether one existed. // This is the web UI's explicit "delete" for an offline device: an offline // record has no live agent to uninstall, so forgetting it is all "delete" can diff --git a/server/go/devicehistory/devicehistory_test.go b/server/go/devicehistory/devicehistory_test.go index 87a4099..8aac697 100644 --- a/server/go/devicehistory/devicehistory_test.go +++ b/server/go/devicehistory/devicehistory_test.go @@ -261,3 +261,48 @@ func TestFlushLeavesNoTempFiles(t *testing.T) { } } } + +// A transfer marker is dropped once its deadline passes — the client is back on +// its original master by then, so keeping the label would be a lie — and also +// as soon as the device logs in here again, because that means it is back +// early (upgrade done, or the target was unreachable). +func TestTransferMarkerLifecycle(t *testing.T) { + path := filepath.Join(t.TempDir(), "devices.json") + s, err := Open(path, 1000, nil) + if err != nil { + t.Fatalf("Open: %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + + h := hub.New() + h.Subscribe(s) + h.Register(&hub.Device{ID: "dev-1", Name: "PC-1"}, &connection.Context{RemoteAddr: "198.51.100.9:5000"}) + + if _, _, ok := s.Transfer("dev-1"); ok { + t.Fatal("fresh device already reports a transfer") + } + if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(time.Hour).Unix()) { + t.Fatal("SetTransfer on a known device failed") + } + if target, _, ok := s.Transfer("dev-1"); !ok || target != "mfc.example:6544" { + t.Fatalf("marker not visible: %q/%v", target, ok) + } + + // Expired marker is dropped on read. + if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(-time.Second).Unix()) { + t.Fatal("SetTransfer with a past deadline failed") + } + if _, _, ok := s.Transfer("dev-1"); ok { + t.Fatal("expired transfer marker still reported") + } + + // A login on this server means the host is back, so the marker goes away. + if !s.SetTransfer("dev-1", "mfc.example:6544", time.Now().Add(time.Hour).Unix()) { + t.Fatal("SetTransfer after expiry failed") + } + h.Unregister("dev-1") + h.Register(&hub.Device{ID: "dev-1", Name: "PC-1"}, &connection.Context{RemoteAddr: "198.51.100.9:5001"}) + if target, until, ok := s.Transfer("dev-1"); ok { + t.Fatalf("marker survived a reconnect: %q/%d", target, until) + } +} diff --git a/server/go/protocol/commands.go b/server/go/protocol/commands.go index cf7576b..5ce5a72 100644 --- a/server/go/protocol/commands.go +++ b/server/go/protocol/commands.go @@ -155,6 +155,21 @@ const ( CommandBye byte = 204 // COMMAND_BYE - disconnect CommandHeartbeat byte = 216 // CMD_HEARTBEAT_ACK + // CommandAssignMaster moves a host to another master (COMMAND_ASSIGN_MASTER). + // Payload: [cmd][ShareTypeYamaForever]host:port:days[:shine[:transport]]\0 + // The client stores the target plus a deadline and goes back to the master it + // captured at startup when the deadline passes — the Go server does not take + // part in the restore. See common/host_transfer.h. + CommandAssignMaster byte = 207 + ShareTypeYamaForever byte = 100 // SHARE_TYPE_YAMA_FOREVER — "transfer", not "share" + + // TransferTransport* are the clients' CONNECT_ADDRESS.protoType values + // (common/commands.h): PROTO_TCP=0, PROTO_WS=5, PROTO_WSS=6. They travel in + // the assign-master payload's transport segment. + TransferTransportTCP int = 0 + TransferTransportWS int = 5 + TransferTransportWSS int = 6 + // Client -> Server tokens TokenAuth byte = 100 // TOKEN_AUTH - authorization required TokenHeartbeat byte = 101 // TOKEN_HEARTBEAT @@ -705,3 +720,29 @@ func BuildValidation(days float64, admin string, port int, maxDepth uint16) []by return data } + +// BuildAssignMasterPacket encodes a "transfer this host to another master" +// command, byte-compatible with the MFC server's assignFunction +// (server/2015Remote/2015RemoteDlg.cpp): +// +// [COMMAND_ASSIGN_MASTER][SHARE_TYPE_YAMA_FOREVER]host:port:days::transport\0 +// +// The shine segment stays empty: the header-encryption variant is not +// something this server can know better than the host, and clients rotate it +// when a login is rejected (client/IOCPClient.h). The transport segment is +// always sent, because an absent segment does **not** mean "plain TCP" to the +// clients — they keep the link they run today (client/ClientDll.cpp +// ApplyAssignedMaster, common/host_endpoint.h ApplyEndpoint). A host that +// talks WSS to this server would then try WSS against the MFC master's raw TCP +// port and never connect. The caller picks the transport; TCP (0) matches what +// an MFC master listens on. days is formatted without trailing zeros so "0.5" +// survives the round trip. +func BuildAssignMasterPacket(host string, port int, days float64, transport int) []byte { + payload := host + ":" + strconv.Itoa(port) + ":" + strconv.FormatFloat(days, 'f', -1, 64) + + "::" + strconv.Itoa(transport) + pkt := make([]byte, 0, 2+len(payload)+1) + pkt = append(pkt, CommandAssignMaster, ShareTypeYamaForever) + pkt = append(pkt, payload...) + pkt = append(pkt, 0) // clients parse the payload as a C string + return pkt +} diff --git a/server/go/protocol/commands_test.go b/server/go/protocol/commands_test.go index 54066c8..1add2d8 100644 --- a/server/go/protocol/commands_test.go +++ b/server/go/protocol/commands_test.go @@ -103,3 +103,35 @@ func isCommandTokenName(name string) bool { strings.HasPrefix(name, "Token") || strings.HasPrefix(name, "Cmd") } + +// The assign-master payload must stay byte-compatible with the MFC master's +// assignFunction, otherwise the client parses the wrong fields: days keeps +// fractions ("0.5" for a half-day handover) and the string is NUL-terminated +// because both clients read it as a C string. The shine segment is empty +// (clients then keep their header-encryption variant) while the transport +// segment is always present — without it the clients would keep the link they +// run today, which is exactly the WSS-vs-TCP mismatch that made the transfer +// unreachable. +func TestBuildAssignMasterPacket(t *testing.T) { + cases := []struct { + host string + port int + days float64 + transport int + want string + }{ + {"mfc.example", 6544, 1, TransferTransportTCP, "mfc.example:6544:1::0\x00"}, + {"10.0.0.5", 6543, 0.5, TransferTransportTCP, "10.0.0.5:6543:0.5::0\x00"}, + {"mfc.example", 6544, 2.25, TransferTransportWS, "mfc.example:6544:2.25::5\x00"}, + {"mfc.example", 6544, 1, TransferTransportWSS, "mfc.example:6544:1::6\x00"}, + } + for _, tc := range cases { + got := BuildAssignMasterPacket(tc.host, tc.port, tc.days, tc.transport) + if len(got) < 2 || got[0] != CommandAssignMaster || got[1] != ShareTypeYamaForever { + t.Fatalf("header = %v, want [%d %d]", got[:2], CommandAssignMaster, ShareTypeYamaForever) + } + if string(got[2:]) != tc.want { + t.Fatalf("payload = %q, want %q", got[2:], tc.want) + } + } +} diff --git a/server/go/web/audit.go b/server/go/web/audit.go index 2e4d931..a79e33c 100644 --- a/server/go/web/audit.go +++ b/server/go/web/audit.go @@ -32,12 +32,13 @@ const ( auditClipGet = "remote.clipboard.get" auditRdpReset = "remote.rdp_reset" - auditUserCreate = "admin.user.create" - auditUserDelete = "admin.user.delete" - auditDeviceAdmin = "admin.device.delete" - auditDeviceBind = "admin.device.bind" - auditDeviceUnbind = "admin.device.unbind" - auditQuery = "admin.audit.query" + auditUserCreate = "admin.user.create" + auditUserDelete = "admin.user.delete" + auditDeviceAdmin = "admin.device.delete" + auditDeviceTransfer = "admin.device.transfer" + auditDeviceBind = "admin.device.bind" + auditDeviceUnbind = "admin.device.unbind" + auditQuery = "admin.audit.query" ) // audit emits one audit record for a WebSocket client. Identity fields are diff --git a/server/go/web/server.go b/server/go/web/server.go index 06e04e9..f62a5a7 100644 --- a/server/go/web/server.go +++ b/server/go/web/server.go @@ -40,6 +40,9 @@ type Server struct { trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only) basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root brandName string // white-label title; "" = "SimpleRemoter" (official branding) + transferTarget string // pre-filled "transfer host" target, "host:port" + transferDays float64 // pre-filled "transfer host" days + transferTransport int // link to the target: protocol.TransferTransport* sso SSODetector // nil = SSO disabled mcp mcpEndpoint // nil = no /mcp route sweepDone chan struct{} // closes to stop the login-limiter sweeper @@ -93,6 +96,20 @@ type Config struct { // behaviour: every authenticated session sees every device). The shipped // server always wires one; tests may omit it. DeviceACL *DeviceACL + // TransferTarget ("host:port") and TransferDays pre-fill the web UI's + // "transfer host" dialog. Reporting them is also what tells the shared + // page that this backend implements COMMAND_ASSIGN_MASTER — the MFC server + // serves the same page but never reports it, so no transfer button appears + // where the command would be dropped. Empty target = the operator types + // the address; days <= 0 falls back to 1. + // + // TransferTransport is the link the transferred host must use to reach the + // target (protocol.TransferTransportTCP/WS/WSS; zero value = TCP, what an + // MFC master listens on). It is always sent to the client: leaving it out + // would make a host that currently talks WSS keep WSS against the target. + TransferTarget string + TransferDays float64 + TransferTransport int } // New creates an HTTP server bound to the given port. port=0 disables the server. @@ -121,6 +138,9 @@ func (s *Server) WithConfig(cfg Config) *Server { s.brandName = resolveBrandName(cfg.BrandName, s.basePath) s.sso = cfg.SSO s.deviceACL = cfg.DeviceACL + s.transferTarget = cfg.TransferTarget + s.transferDays = cfg.TransferDays + s.transferTransport = cfg.TransferTransport return s } @@ -145,7 +165,8 @@ func (s *Server) Start() error { withOriginAllowlist(s.allowedOrigins). withLoginRateLimiters(s.loginIPLimit, s.loginUserLimit). withTrustForwardedFor(s.trustForwardedFor). - withDeviceACL(s.deviceACL) + withDeviceACL(s.deviceACL). + withTransferDefaults(s.transferTarget, s.transferDays, s.transferTransport) mux := http.NewServeMux() mux.HandleFunc("/", s.handleIndex) diff --git a/server/go/web/transfer_device_test.go b/server/go/web/transfer_device_test.go new file mode 100644 index 0000000..c48a1d6 --- /dev/null +++ b/server/go/web/transfer_device_test.go @@ -0,0 +1,278 @@ +package web + +import ( + "encoding/json" + "testing" + + "github.com/yuanyuanxiang/SimpleRemoter/server/go/connection" + "github.com/yuanyuanxiang/SimpleRemoter/server/go/hub" + "github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol" +) + +// transferReply drains queued messages until the transfer result arrives. The +// handler also broadcasts devices_changed to every authenticated client, so +// the reply is not necessarily the first message on the channel. +func transferReply(t *testing.T, c *wsClient) map[string]any { + t.Helper() + for i := 0; i < 8; i++ { + select { + case m := <-c.send: + var out map[string]any + if err := json.Unmarshal(m.data, &out); err != nil { + t.Fatalf("decode reply: %v", err) + } + if out["cmd"] == "transfer_device_result" { + return out + } + default: + t.Fatal("no transfer_device_result reply") + } + } + t.Fatal("transfer_device_result not queued") + return nil +} + +func TestTransferDeviceSendsAssignMaster(t *testing.T) { + wh, h, hist := deleteTestHub(t) + var sent []byte + h.SetSender(func(_ *connection.Context, data []byte) error { + sent = append([]byte(nil), data...) + return nil + }) + h.Register(&hub.Device{ID: "live", Name: "Live"}, + &connection.Context{RemoteAddr: "10.0.0.9:1000"}) + + c, tok := deleteTestClient(wh, "admin") + raw, _ := json.Marshal(map[string]any{ + "token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 2, + }) + wh.handleTransferDevice(c, raw) + + rep := transferReply(t, c) + if rep["ok"] != true { + t.Fatalf("reply = %+v, want ok", rep) + } + if rep["target"] != "mfc.example:6544" { + t.Fatalf("target = %v, want mfc.example:6544", rep["target"]) + } + + // Wire format must match the MFC master byte for byte: command, transfer + // type, then host:port:days::transport as a NUL-terminated string. The + // empty shine segment keeps the host's header-encryption variant; the + // transport segment must always be present (TCP unless configured), or a + // host that currently talks WSS would keep WSS against the target. + want := string([]byte{protocol.CommandAssignMaster, protocol.ShareTypeYamaForever}) + + "mfc.example:6544:2::0\x00" + if string(sent) != want { + t.Fatalf("sent = %q, want %q", sent, want) + } + + // The marker is what the card renders as "transferred → …". + target, until, ok := hist.Transfer("live") + if !ok || target != "mfc.example:6544" || until <= 0 { + t.Fatalf("history marker = %q/%d/%v, want mfc.example:6544 with a deadline", target, until, ok) + } +} + +// The configured transport must reach the device: the clients keep their +// current link when the segment is missing, so a WSS-managed host handed to a +// plain-TCP master would retry WSS forever. +func TestTransferDeviceSendsConfiguredTransport(t *testing.T) { + wh, h, _ := deleteTestHub(t) + wh.withTransferDefaults("mfc.example:6544", 2, protocol.TransferTransportWSS) + var sent []byte + h.SetSender(func(_ *connection.Context, data []byte) error { + sent = append([]byte(nil), data...) + return nil + }) + h.Register(&hub.Device{ID: "live", Name: "Live"}, + &connection.Context{RemoteAddr: "10.0.0.14:1000"}) + + c, tok := deleteTestClient(wh, "admin") + raw, _ := json.Marshal(map[string]any{ + "token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 1, + }) + wh.handleTransferDevice(c, raw) + + if rep := transferReply(t, c); rep["ok"] != true { + t.Fatalf("reply = %+v, want ok", rep) + } + want := string([]byte{protocol.CommandAssignMaster, protocol.ShareTypeYamaForever}) + + "mfc.example:6544:1::6\x00" + if string(sent) != want { + t.Fatalf("sent = %q, want %q", sent, want) + } +} + +func TestTransferDeviceRequiresAdmin(t *testing.T) { + wh, h, hist := deleteTestHub(t) + sent := false + h.SetSender(func(_ *connection.Context, _ []byte) error { + sent = true + return nil + }) + h.Register(&hub.Device{ID: "live", Name: "Live"}, + &connection.Context{RemoteAddr: "10.0.0.10:1000"}) + + c, tok := deleteTestClient(wh, "viewer") + raw, _ := json.Marshal(map[string]any{ + "token": tok, "id": "live", "host": "mfc.example", "port": 6544, "days": 1, + }) + wh.handleTransferDevice(c, raw) + + if rep := transferReply(t, c); rep["ok"] != false { + t.Fatalf("reply = %+v, want ok:false", rep) + } + if sent { + t.Fatal("viewer's transfer command reached the device") + } + if _, _, ok := hist.Transfer("live"); ok { + t.Fatal("viewer's transfer left a marker") + } +} + +func TestTransferDeviceOffline(t *testing.T) { + wh, _, _ := deleteTestHub(t) + + c, tok := deleteTestClient(wh, "admin") + raw, _ := json.Marshal(map[string]any{ + "token": tok, "id": "never-seen", "host": "mfc.example", "port": 6544, "days": 1, + }) + wh.handleTransferDevice(c, raw) + + if rep := transferReply(t, c); rep["ok"] != false || rep["msg"] != "Host is offline" { + t.Fatalf("reply = %+v, want offline failure", rep) + } +} + +func TestTransferDeviceRejectsBadTarget(t *testing.T) { + cases := []struct { + name string + in map[string]any + }{ + {"empty host", map[string]any{"host": "", "port": 6544, "days": 1}}, + {"colon in host", map[string]any{"host": "mfc:6544", "port": 6544, "days": 1}}, + {"port zero", map[string]any{"host": "mfc.example", "port": 0, "days": 1}}, + {"port too big", map[string]any{"host": "mfc.example", "port": 70000, "days": 1}}, + {"zero days", map[string]any{"host": "mfc.example", "port": 6544, "days": 0}}, + {"too many days", map[string]any{"host": "mfc.example", "port": 6544, "days": 400}}, + {"no id", map[string]any{"id": "", "host": "mfc.example", "port": 6544, "days": 1}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + wh, h, _ := deleteTestHub(t) + sent := false + h.SetSender(func(_ *connection.Context, _ []byte) error { + sent = true + return nil + }) + h.Register(&hub.Device{ID: "live", Name: "Live"}, + &connection.Context{RemoteAddr: "10.0.0.11:1000"}) + + c, tok := deleteTestClient(wh, "admin") + args := map[string]any{"token": tok, "id": "live"} + for k, v := range tc.in { + args[k] = v + } + raw, _ := json.Marshal(args) + wh.handleTransferDevice(c, raw) + + if rep := transferReply(t, c); rep["ok"] != false { + t.Fatalf("reply = %+v, want ok:false", rep) + } + if sent { + t.Fatal("invalid target still reached the device") + } + }) + } +} + +// A second assignment while the first one is live would be ignored by the +// Windows client ("Avoid assign again"), so the server must not report success +// for it. +func TestTransferDeviceRefusesSecondTransfer(t *testing.T) { + wh, h, hist := deleteTestHub(t) + sends := 0 + h.SetSender(func(_ *connection.Context, _ []byte) error { + sends++ + return nil + }) + h.Register(&hub.Device{ID: "live", Name: "Live"}, + &connection.Context{RemoteAddr: "10.0.0.12:1000"}) + if !hist.SetTransfer("live", "mfc.example:6544", 1<<62) { + t.Fatal("SetTransfer on a live device failed") + } + + c, tok := deleteTestClient(wh, "admin") + raw, _ := json.Marshal(map[string]any{ + "token": tok, "id": "live", "host": "other.example", "port": 6544, "days": 1, + }) + wh.handleTransferDevice(c, raw) + + rep := transferReply(t, c) + if rep["ok"] != false { + t.Fatalf("reply = %+v, want ok:false", rep) + } + if sends != 0 { + t.Fatalf("device received %d commands, want 0", sends) + } + if target, _, _ := hist.Transfer("live"); target != "mfc.example:6544" { + t.Fatalf("marker overwritten to %q", target) + } +} + +// The shared page decides whether to show the transfer button by the presence +// of the "transfer" object in device_list, and reads the card marker from +// transferTo/transferUntil. Both are part of the contract with index.html. +func TestDeviceListReportsTransferContract(t *testing.T) { + wh, h, hist := deleteTestHub(t) + wh.withTransferDefaults("mfc.example:6544", 2, protocol.TransferTransportTCP) + + h.Register(&hub.Device{ID: "live", Name: "Live"}, + &connection.Context{RemoteAddr: "10.0.0.13:1000"}) + if !hist.SetTransfer("live", "mfc.example:6544", 4102444800) { // year 2100 + t.Fatal("SetTransfer failed") + } + + c, tok := deleteTestClient(wh, "admin") + raw, _ := json.Marshal(map[string]any{"token": tok}) + wh.handleGetDevices(c, raw) + + var out struct { + Cmd string `json:"cmd"` + Transfer *struct { + Target string `json:"target"` + Days float64 `json:"days"` + } `json:"transfer"` + Devices []struct { + ID string `json:"id"` + TransferTo string `json:"transferTo"` + TransferUntil int64 `json:"transferUntil"` + } `json:"devices"` + } + for i := 0; i < 8; i++ { + select { + case m := <-c.send: + if err := json.Unmarshal(m.data, &out); err != nil { + t.Fatalf("decode: %v", err) + } + default: + t.Fatal("no device_list reply") + } + if out.Cmd == "device_list" { + break + } + } + if out.Transfer == nil { + t.Fatal("device_list carries no transfer config — the page would hide the button") + } + if out.Transfer.Target != "mfc.example:6544" || out.Transfer.Days != 2 { + t.Fatalf("transfer config = %+v", *out.Transfer) + } + if len(out.Devices) != 1 { + t.Fatalf("devices = %d, want 1", len(out.Devices)) + } + if d := out.Devices[0]; d.TransferTo != "mfc.example:6544" || d.TransferUntil == 0 { + t.Fatalf("device marker = %+v, want mfc.example:6544 with a deadline", d) + } +} diff --git a/server/go/web/ws.go b/server/go/web/ws.go index bbf92a7..b4ae05e 100644 --- a/server/go/web/ws.go +++ b/server/go/web/ws.go @@ -181,6 +181,16 @@ type wsHub struct { loginIPLimit *wsauth.RateLimiter loginUserLimit *wsauth.RateLimiter trustForwardedFor bool // honor X-Forwarded-For (only when behind a trusted proxy) + + // transferTarget / transferDays pre-fill the "transfer host" dialog and, + // by being reported to the browser, tell the shared page that this backend + // implements COMMAND_ASSIGN_MASTER at all (see withTransferDefaults). + // transferTransport is the link the transferred host uses to reach the + // target (protocol.TransferTransport*); it is sent in the command because + // the clients keep their current link when it is missing. + transferTarget string + transferDays float64 + transferTransport int } func newWSHub(auth *wsauth.Authenticator, devices *hub.Hub, history *devicehistory.Store, log *logger.Logger) *wsHub { @@ -227,6 +237,22 @@ func (h *wsHub) withDeviceACL(acl *DeviceACL) *wsHub { return h } +// withTransferDefaults installs the pre-filled target/days and the link type +// (protocol.TransferTransport*) for the web UI's "transfer host" dialog. An +// empty target still enables the feature: the operator types the address in +// the dialog. The front-end keys the button's visibility off this being +// reported at all, so the shared page shows no transfer button on the MFC +// server (which never reports it). +func (h *wsHub) withTransferDefaults(target string, days float64, transport int) *wsHub { + h.transferTarget = target + if days <= 0 { + days = 1 // one day is enough for an upgrade round-trip + } + h.transferDays = days + h.transferTransport = transport + return h +} + // isSuperAdmin reports whether this session is the built-in admin account // (username "admin" + role admin). Other admin-role users — local accounts // created in the user panel or portal admins bridged by SSO — are device- diff --git a/server/go/web/ws_handlers.go b/server/go/web/ws_handlers.go index 8e7a167..5bd3a93 100644 --- a/server/go/web/ws_handlers.go +++ b/server/go/web/ws_handlers.go @@ -5,6 +5,7 @@ import ( "errors" "math" "sort" + "strconv" "strings" "time" @@ -90,6 +91,8 @@ func (h *wsHub) dispatch(c *wsClient, cmd string, raw []byte) { // Admin operations (Phase 7). case "delete_device": h.handleDeleteDevice(c, raw) + case "transfer_device": + h.handleTransferDevice(c, raw) case "create_user": h.handleCreateUser(c, raw) case "delete_user": @@ -790,6 +793,13 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) { "devices": h.listVisibleDevices(c), "username": c.user, "role": c.role, + // Presence of this object is what tells the shared page that this + // backend implements "transfer host" (the MFC server omits it), so the + // button never appears where the command would go nowhere. + "transfer": map[string]any{ + "target": h.transferTarget, + "days": h.transferDays, + }, })) } @@ -799,6 +809,11 @@ func (h *wsHub) handleGetDevices(c *wsClient, raw []byte) { type deviceListItem struct { hub.DeviceInfo Owner string `json:"owner,omitempty"` + // TransferTo / TransferUntil carry the "handed over to another master" + // marker so the card can say where the host went and how long it stays + // there. Absent for a host that was never transferred. + TransferTo string `json:"transferTo,omitempty"` + TransferUntil int64 `json:"transferUntil,omitempty"` } // listVisibleDevices applies the device ACL to the online + offline snapshot. @@ -815,7 +830,13 @@ func (h *wsHub) listVisibleDevices(c *wsClient) []deviceListItem { if h.acl != nil && c.isSuperAdmin() { owner = h.acl.Owner(d.ID) } - out = append(out, deviceListItem{DeviceInfo: d, Owner: owner}) + item := deviceListItem{DeviceInfo: d, Owner: owner} + if h.history != nil { + if target, until, ok := h.history.Transfer(d.ID); ok { + item.TransferTo, item.TransferUntil = target, until + } + } + out = append(out, item) } return out } @@ -1314,6 +1335,124 @@ func (h *wsHub) handleDeleteDevice(c *wsClient, raw []byte) { })) } +// maxTransferDays bounds the dialog input. A handover that outlives a year is +// indistinguishable from "lost the host": the client would sit on the other +// master long after whatever upgrade it was sent there for. +const maxTransferDays = 365 + +// handleTransferDevice hands one online host over to another master +// (COMMAND_ASSIGN_MASTER + SHARE_TYPE_YAMA_FOREVER) — the path that lets a Go +// server's host be upgraded by the MFC master: only a master the host is +// actually online on can push a new client build to it. +// +// The deadline is the client's business. It stored the master it booted +// against and reconnects there when the days run out, so nothing here +// schedules a restore; the server only keeps a marker so the card can read +// "transferred → host:port, N left" instead of silently going offline. +// +// Admin-only: this moves a host off this master. +func (h *wsHub) handleTransferDevice(c *wsClient, raw []byte) { + const replyCmd = "transfer_device_result" + if !h.requireAdmin(c, raw, replyCmd) { + return + } + var in struct { + ID string `json:"id"` + Host string `json:"host"` + Port int `json:"port"` + Days float64 `json:"days"` + } + if err := json.Unmarshal(raw, &in); err != nil { + h.audit(c, true, auditDeviceTransfer, map[string]any{ + "ok": false, + "reason": "bad_payload", + }) + c.queue(mustJSON(map[string]any{ + "cmd": replyCmd, "ok": false, "msg": "Invalid transfer payload", + })) + return + } + in.ID = strings.TrimSpace(in.ID) + in.Host = strings.TrimSpace(in.Host) + + // A ':' in the host would shift every following payload field, and the + // whole packet has to stay inside the 260-byte buffer both clients parse + // (MFC's assignFunction uses bToken[_MAX_PATH]). + if in.ID == "" || in.Host == "" || strings.Contains(in.Host, ":") || len(in.Host) > 200 || + in.Port <= 0 || in.Port > 65535 || in.Days <= 0 || in.Days > maxTransferDays { + h.audit(c, true, auditDeviceTransfer, map[string]any{ + "device_id": in.ID, + "host": in.Host, + "port": in.Port, + "days": in.Days, + "ok": false, + "reason": "invalid_target", + }) + c.queue(mustJSON(map[string]any{ + "cmd": replyCmd, "ok": false, + "msg": "Invalid target address or days (1-365)", + })) + return + } + + // The Windows client ignores a second assignment while the first one is + // still live ("Avoid assign again"), so accepting it here would report a + // success the host never acted on. + target := in.Host + ":" + strconv.Itoa(in.Port) + if h.history != nil { + if prev, until, active := h.history.Transfer(in.ID); active { + h.audit(c, true, auditDeviceTransfer, map[string]any{ + "device_id": in.ID, + "target": prev, + "ok": false, + "reason": "already_transferred", + }) + c.queue(mustJSON(map[string]any{ + "cmd": replyCmd, "ok": false, + "msg": "Host is already transferred to " + prev + " until it expires", + "target": prev, "until": until, + })) + return + } + } + + if err := h.devices.SendToDevice(in.ID, protocol.BuildAssignMasterPacket(in.Host, in.Port, in.Days, h.transferTransport)); err != nil { + reason := "send_failed" + if errors.Is(err, hub.ErrDeviceOffline) { + reason = "offline" + } + h.audit(c, true, auditDeviceTransfer, map[string]any{ + "device_id": in.ID, + "target": target, + "ok": false, + "reason": reason, + "error": err.Error(), + }) + c.queue(mustJSON(map[string]any{ + "cmd": replyCmd, "ok": false, "msg": "Host is offline", + })) + return + } + + until := time.Now().Add(time.Duration(in.Days * 24 * float64(time.Hour))).Unix() + if h.history != nil { + // Display-only: a device whose login event has not landed yet still got + // the command, so a missing record must not turn this into a failure. + h.history.SetTransfer(in.ID, target, until) + } + h.audit(c, false, auditDeviceTransfer, map[string]any{ + "device_id": in.ID, + "target": target, + "days": in.Days, + "until": until, + "ok": true, + }) + h.broadcastAuthenticated(`{"cmd":"devices_changed"}`) + c.queue(mustJSON(map[string]any{ + "cmd": replyCmd, "ok": true, "id": in.ID, "target": target, "until": until, + })) +} + // handleDeleteUser removes an account and revokes any of its live sessions. // Admin-only. The bootstrap "admin" account is rejected at the wsauth layer. func (h *wsHub) handleDeleteUser(c *wsClient, raw []byte) { diff --git a/server/web/index.html b/server/web/index.html index 514d94d..932a266 100644 --- a/server/web/index.html +++ b/server/web/index.html @@ -642,6 +642,21 @@ max-width: 200px; flex-shrink: 1; } + /* 「已转移」标记:主机被转移到另一台主控(MFC),到期自己回来。 + 只在 Go 后端出现——device_list 里没有 transfer 字段时整个功能都不渲染。 */ + .device-card .transfer-badge { + margin-top: 8px; + font-size: 12px; + color: #d68910; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + .device-grid.list-view .device-card .transfer-badge { + margin-top: 0; + max-width: 240px; + flex-shrink: 1; + } /* 卡片操作图标(终端 / 删除):右上角,独立于卡片本体点击事件 (onclick stopPropagation)。List 视图卡片是一行,改为垂直居中。 */ .device-card .card-actions { @@ -670,7 +685,12 @@ .device-card .card-term-btn:hover { background: rgba(76, 175, 80, 0.25); color: #4caf50; } .device-card .card-del-btn:hover { background: rgba(231, 76, 60, 0.25); color: #e74c3c; } .device-card .card-bind-btn:hover { background: rgba(230, 126, 34, 0.25); color: #e67e22; } + .device-card .card-transfer-btn:hover { background: rgba(214, 137, 16, 0.25); color: #d68910; } .device-card h3 { padding-right: 124px; } /* 给右上角操作图标让位 */ + /* 4 个操作图标(终端/绑定/转移/删除)= 4×32 + 3×6 + 右边距 12,比默认的 + 3 个宽 38px;不让位标题会钻到图标底下。list-view 的 h3 padding-right:0 + 选择器权重更高,不受影响。 */ + .device-card.many-actions h3 { padding-right: 162px; } .device-grid.list-view .device-card .card-actions { top: 50%; transform: translateY(-50%); @@ -2174,6 +2194,36 @@ + + +