4 Commits
Author SHA1 Message Date
yuanyuanxiang 7eebd3bd6c Feature: fold device-card actions into a "..." menu
Every card now shows a single ellipsis button no matter how many actions
apply; the same terminal/bind/transfer/delete actions live in a popup menu,
each with a one-line description of what it does.

The menu is attached to body and fixed-positioned because the card clips its
own overflow. It right-aligns to the button, flips above when the button sits
near the bottom of the viewport, and closes on outside click, Esc, scroll,
resize or list re-render. Entries are built per click from the live device,
so permission and online/transfer state cannot go stale. Grid and list views
share the flow; the list view centers the button vertically and both views
only need 56px of clearance for it.

Verified in a browser with a copy of the card markup: open/close paths, item
callbacks, bottom-edge flip and both view modes.
2026-11-20 13:51:32 +01:00
yuanyuanxiang 63c7cdf588 Feature: transfer a Go-managed host to the MFC master from the web console
A Go-managed host cannot receive the client upgrade that only the MFC master
can push. Transfer moves its main link there and brings it back after N days;
MFC has no reason to return it.

Transfer is not share: ASSIGN writes the target and drops the current
connection, so the old master sees the host go offline and the new master gets
a normal main link it can remote control and upgrade. While a transfer is live
the client refuses a second transfer and any share, so no host is handed to a
third master that expiry would orphan.

Server: admin-only `transfer_device` WS command, COMMAND_ASSIGN_MASTER +
SHARE_TYPE_YAMA_FOREVER as `host:port:days::transport\0`, byte-compatible with
the MFC dialog. The transport segment is always present (YAMA_TRANSFER_TRANSPORT,
default 0/TCP) because clients keep their current link when it is missing: a
WSS-managed host would otherwise retry WSS against the MFC master's raw TCP
port and never connect. The empty shine segment keeps the host's header
encryption. The button only renders when `device_list.transfer` is present,
which MFC never sends, so no MFC change is needed. devicehistory keeps
transfer_to/transfer_until for the card badge and drops the marker on expiry or
on a fresh login here.

Client: KernelManager.cpp writes the registry and disconnects; ClientDll.cpp
re-reads the registry at the top of every reconnect, so a mid-session transfer
lands on the next round. Expiry is checked before every connect attempt as well
as inside the heartbeat loop, so an unreachable target cannot pin the host to
an expired address until a restart; restoring rebuilds the link captured on
entry (address, header encryption, transport). linux/main.cpp applies the
transfer on the main loop and restores the captured endpoint at expiry; Android
does the same; macOS has neither share nor transfer.
2026-11-20 12:23:08 +01:00
yuanyuanxiang b466f568ab Fix(client): refresh RES_UPTIME on every login so host popup shows the real runtime
双击 Linux 主机浮窗显示「启动信息 2026-11-14 13:33:52 + 1.3h」:日期是对的(进程确实从
11-14 06:33 起一直在跑,期间只有 TCP 重连),错的是时长——真实 6.2d,而 1.3h 正好等于当天
09:05:53 那次重连到双击时刻的间隔。

2cbed0d 加的 RES_UPTIME(登录时刻进程已运行秒数)在 Linux/macOS/Android 里跟着 LOGIN_INFOR
一起在重连循环外只构造一次、重连时原样重发,于是永远停在进程启动那一瞬的 0;服务端做
RES_UPTIME + GetAliveTime(),加出来就只剩「本次连接时长」。Windows 没有这个问题,它的
GetLoginInfo 在连接循环里每次重建。老客户端(build Oct 31 及更早)根本不发这个字段,服务端
退回 szStartTime 字符串、LNX 按北京时间比,反而正确——这就是「老版本显示正常」的原因。

改法:LOGIN_INFOR::SetReserved(index, v) 按 '|' 位置改写单个字段(末尾空槽原样保留、超长
整体放弃、越界拒绝),三个客户端把各自复制粘贴的「拆字段改 [19]」换成一行调用,并新增
RefreshLoginUptime 在每次 SendLoginInfo 前重算 [20](含 Linux 的分组变更重发路径)。

影响:只动登录包的第 21 个字段,结构体布局、字段顺序与协议不变,老主控忽略它。
已部署的旧 build 需重新下发才会恢复正常显示。

验证:SetReserved 用 MSVC 单测(21 字段位置不变、连改两次、空槽保留、补槽、超长与越界
拒绝)。三个客户端本体未编译:本机 WSL 被安全策略拦住、Docker 引擎未启动。
2026-11-20 10:43:17 +01:00
yuanyuanxiangandClaude Code d6ea5fddea Fix(server): require left-button drag for desktop control of Android
桌面端(非触摸)控制 Android TV/盒子时,鼠标悬停会被客户端翻译成焦点移动,
鼠标划过画面就改变焦点。改为只在按住左键拖动时控制;触摸浏览器行为不变。

- MFC 主控:按 clientID 在主连接上解析并缓存客户端类型(新增线程安全的
  GetHostClientType,类型值在 m_cs 内读取);APK 主机的 WM_MOUSEMOVE 仅在
  MK_LBUTTON 按下时转发,不再每次移动都查主连接。
- Web 控制台:桌面 mousemove 对 Android 主机(优先使用服务端 isAndroidRemote,
  设备 os/clientType 只作兜底)只在左键按下时发 move;检查放在发送节流之后。
  touchstart/touchmove/touchend 未改动,触摸屏的单指移动、点按、拖拽、滚动
  和边缘手势保持原状。
- 安卓客户端未修改:TV 模式仍把带按键的 move 翻译成焦点导航,触摸浏览器
  发出的不带按键 move 继续可用。

验证:MFC Debug 服务端、Go 服务端构建通过;内联 JS 通过 node --check。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 21:57:38 +01:00
25 changed files with 1313 additions and 290 deletions

No files matched your search

+13 -20
View File
@@ -1993,26 +1993,7 @@ static void ApplyTlsAnchorChange()
// 重连会重新登录,登录前刷新该字段,否则列里一直显示旧值。只在主线程调用(同 SendLoginInfo)。
static void RefreshLoginTls(LOGIN_INFOR& info)
{
std::vector<std::string> fields;
std::string s(info.szReserved);
size_t pos = 0;
for (;;) {
size_t bar = s.find('|', pos);
if (bar == std::string::npos) { fields.push_back(s.substr(pos)); break; }
fields.push_back(s.substr(pos, bar - pos));
pos = bar + 1;
}
while (fields.size() <= (size_t)RES_TLS)
fields.push_back("");
fields[RES_TLS] = TlsEnabled() ? "1" : "0";
std::string joined;
for (size_t i = 0; i < fields.size(); ++i) {
if (i) joined += '|';
joined += fields[i];
}
strncpy(info.szReserved, joined.c_str(), sizeof(info.szReserved) - 1);
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
info.SetReserved(RES_TLS, TlsEnabled() ? "1" : "0");
}
#endif // YAMA_TLS_CHANNEL
@@ -2558,6 +2539,17 @@ static const auto g_processStartMono = std::chrono::steady_clock::now();
// 的状态清掉(服务重启 CaptureService 时真会撞上)。
static std::atomic<uint64_t> g_connGeneration{0};
// 登录 szReserved[20](RES_UPTIME)是「登录这一刻进程已经运行了多少秒」,服务端再加本次
// 上线时长才是当前运行时长。logInfo 在重连循环外只构造一次,不刷新的话重连上报的仍是
// 进程启动那一瞬的 0,服务端算出来就只剩「本次连接时长」(Linux 上实测:进程跑了 6 天,
// 浮窗只显示 1.3h)。只在主线程调用(同 SendLoginInfo)。
static void RefreshLoginUptime(LOGIN_INFOR& info)
{
long long up = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::steady_clock::now() - g_processStartMono).count();
info.SetReserved(RES_UPTIME, std::to_string(up > 0 ? up : 0).c_str());
}
static void ConnectionThread(uint64_t gen)
{
{
@@ -2689,6 +2681,7 @@ static void ConnectionThread(uint64_t gen)
#ifdef YAMA_TLS_CHANNEL
RefreshLoginTls(logInfo); // 传输方式可能已热切换,登录前刷新 RES_TLS
#endif
RefreshLoginUptime(logInfo); // 同一条连接可能是几小时前断掉后重连的,按「现在」重算
// 屏幕预览能力位按运行时状态刷新:无障碍服务在跑才声明(API 30+ 的 takeScreenshot),
// 服务端据此放行 get_screenshot;无障碍被关掉后重连会撤回,避免服务端白等抓屏。
// 锁屏同理:无障碍服务在跑且 API 28+ 才声明。
+69 -45
View File
@@ -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);
+3 -4
View File
@@ -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"。
+42 -18
View File
@@ -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);
}
+30
View File
@@ -1414,6 +1414,36 @@ typedef struct LOGIN_INFOR {
{
return StringToVector(szReserved, '|', n);
}
// 按位置改写第 index 个字段(服务端用 LOGIN_RES 下标取值)。AddReserved 只能往后追加,
// 改不了已写好的字段;重连重发登录前刷新某个「当前状态」字段(RES_TLS / RES_UPTIME)
// 就得靠这个。
// 字段数按分隔符数 + 1 数,末尾空槽也算一个字段,拼回去时原样保留——否则少写一个 '|'
// 会让后面的字段整体前移,服务端把用户名读成类型。整体放不下 szReserved 时返回 false
// 且保持原值,绝不写半截。
bool SetReserved(int index, const char* v)
{
if (index < 0 || index >= (int)RES_MAX) return false;
std::vector<std::string> fields;
const char* p = szReserved;
for (;;) {
const char* bar = strchr(p, '|');
if (bar == nullptr) {
fields.push_back(p);
break;
}
fields.push_back(std::string(p, bar - p));
p = bar + 1;
}
if (fields.size() < (size_t)index + 1)
fields.resize((size_t)index + 1); // 补空槽,std::string 默认空串
fields[index] = v ? v : "";
const std::string joined = VectorJoin(fields, '|');
if (joined.size() >= sizeof(szReserved)) return false;
memcpy(szReserved, joined.c_str(), joined.size() + 1);
return true;
}
private:
// 追加一个保留字段。szReserved 是「按位置」解析的(服务端用 LOGIN_RES 下标取值),
+2 -1
View File
@@ -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 出一个
// 分享子进程,复用同一份登录/心跳/命令处理代码。
+10 -8
View File
@@ -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` 键清空并重启客户端即可。
## 主机分享
+67 -115
View File
@@ -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<bool> g_needResendLogin(false); // 分组变更后需要重
static std::atomic<bool> 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<std::string, ShareProc> g_shareProcs; // "ip:port" / "transfer:ip:port" -> 子进程
static std::map<std::string, ShareProc> g_shareProcs; // "ip:port" -> 子进程
// 分享条目上限:每条都对应一个常驻子进程,服务端误发/恶意刷下发不能把进程表打爆。
static const size_t kMaxShareEntries = 16;
static std::atomic<bool> 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<std::mutex> 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<std::mutex> 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<pid_t> pids;
{
std::lock_guard<std::mutex> 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); // 只发信号,不等待
}
@@ -1778,30 +1741,17 @@ static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength)
// 只在主线程调用(与 SendLoginInfo 同一线程),避免和接收线程抢同一个结构体。
static void RefreshLoginTls(LOGIN_INFOR& info)
{
std::vector<std::string> fields;
std::string s(info.szReserved);
size_t pos = 0;
for (;;) {
size_t bar = s.find('|', pos);
if (bar == std::string::npos) {
fields.push_back(s.substr(pos));
break;
}
fields.push_back(s.substr(pos, bar - pos));
pos = bar + 1;
}
while (fields.size() <= (size_t)RES_TLS)
fields.push_back("");
fields[RES_TLS] = TlsEnabled() ? "1" : "0";
info.SetReserved(RES_TLS, TlsEnabled() ? "1" : "0");
}
std::string joined;
for (size_t i = 0; i < fields.size(); ++i) {
if (i)
joined += '|';
joined += fields[i];
}
strncpy(info.szReserved, joined.c_str(), sizeof(info.szReserved) - 1);
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
// 登录信息 szReserved 里的 [20] RES_UPTIME 是「登录这一刻进程已经运行了多少秒」,服务端
// 再加本次上线时长才是当前运行时长。logInfo 在重连循环外只构造一次(见 main 里的注释),
// 不刷新的话每次重连上报的仍是进程启动那一瞬的 0,服务端算出来就只剩「本次连接时长」——
// vps 实测:进程从 11-14 06:33 一直跑着,浮窗却只显示 1.3h(正好是当天 09:05 那次重连到
// 双击时刻的间隔),而启动时间本身是对的。与 RefreshLoginTls 同样只在主线程登录前调用。
static void RefreshLoginUptime(LOGIN_INFOR& info)
{
info.SetReserved(RES_UPTIME, std::to_string(getProcessUptimeSeconds()).c_str());
}
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
@@ -1891,6 +1841,9 @@ int main(int argc, char* argv[])
char hostname[256] = {};
gethostname(hostname, sizeof(hostname));
// 只构造一次,每次连接复用它发登录。因此凡是「随连接变化」的字段都必须在发送前
// 用 RefreshLoginTls / RefreshLoginUptime / RefreshLoginCaps 刷新;反过来,属于
// 「进程启动时的事实」(szStartTime、clientID、安装时间…)就靠复用保持不变。
LOGIN_INFOR logInfo;
// 读取分组名称(从配置文件或 g_SETTINGS)
@@ -2052,15 +2005,13 @@ int main(int argc, char* argv[])
Sleep(5000);
continue;
}
// 主连接已经搬到转移目标:那条「提前建立」的临时连接完成使命。留着就是同一
// clientID 在这个主控上的第二条连接,服务端会互踢。
if (g_transferValidTo.load(std::memory_order_relaxed) > 0)
StopChildren(KIND_TRANSFER);
// 进入新连接,重置服务端身份校验状态
ClientAuth::OnNewConnection();
// 传输方式可能已被热切换(TLS 启/停),登录上报的 RES_TLS 必须反映本次连接。
RefreshLoginTls(logInfo);
// 同一条连接可能是几小时前断掉后重连的,RES_UPTIME 必须按「现在」重算
RefreshLoginUptime(logInfo);
// 屏幕预览能力取决于本机当前是否有可用桌面(daemon 启动时可能还没有 DISPLAY)
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
@@ -2082,6 +2033,7 @@ int main(int argc, char* argv[])
}
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
RefreshLoginTls(logInfo);
RefreshLoginUptime(logInfo);
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo);
Mprintf(">> Resent login info after group change\n");
@@ -2181,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)析构前停掉
+11 -25
View File
@@ -662,35 +662,19 @@ static void fillLoginInfo(LOGIN_INFOR& info)
// [[19] RES_TLS] 是「当前」传输状态的快照,服务端在线列表的 TLS 列就取这个值。
// logInfo 只在启动时填一次、之后每条连接复用,因此热切换后重连时必须刷新它,
// 否则列里会一直显示切换前的状态。szReserved 是按 '|' 位置解析的,这里逐字段
// 拆开、只改第 [19] 项再拼回去(不能用 AddReserved,它只会往后追加)。
// 否则列里会一直显示切换前的状态(按位置改写见 LOGIN_INFOR::SetReserved)。
// 只在主线程调用(与 SendLoginInfo 同一线程),避免和接收线程抢同一个结构体。
static void RefreshLoginTls(LOGIN_INFOR& info)
{
std::vector<std::string> fields;
std::string s(info.szReserved);
size_t pos = 0;
for (;;) {
size_t bar = s.find('|', pos);
if (bar == std::string::npos) {
fields.push_back(s.substr(pos));
break;
}
fields.push_back(s.substr(pos, bar - pos));
pos = bar + 1;
}
while (fields.size() <= (size_t)RES_TLS)
fields.push_back("");
fields[RES_TLS] = TlsEnabled() ? "1" : "0";
info.SetReserved(RES_TLS, TlsEnabled() ? "1" : "0");
}
std::string joined;
for (size_t i = 0; i < fields.size(); ++i) {
if (i)
joined += '|';
joined += fields[i];
}
strncpy(info.szReserved, joined.c_str(), sizeof(info.szReserved) - 1);
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
// [20] RES_UPTIME 是「登录这一刻进程已经运行了多少秒」,服务端再加本次上线时长才是当前
// 运行时长。logInfo 在重连循环外只构造一次,不刷新的话重连上报的仍是进程启动那一瞬的
// 0,服务端算出来就只剩「本次连接时长」(Linux 上实测:进程跑了 6 天,浮窗只显示 1.3h)。
static void RefreshLoginUptime(LOGIN_INFOR& info)
{
info.SetReserved(RES_UPTIME, std::to_string(getProcessUptimeSeconds()).c_str());
}
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
@@ -1469,6 +1453,8 @@ int main(int argc, const char* argv[])
ClientAuth::OnNewConnection();
// 本条连接可能是热切换信任锚后重建的:TLS 标志按当前状态重算,再发登录。
RefreshLoginTls(logInfo);
// 同一条连接可能是几小时前断掉后重连的,RES_UPTIME 必须按「现在」重算
RefreshLoginUptime(logInfo);
// 录屏授权可能刚补齐(看守线程会重启进程,但这一次登录也要报对能力位)
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
+16
View File
@@ -13580,6 +13580,22 @@ context* CMy2015RemoteDlg::FindHostByClientID(uint64_t clientID)
return ctx;
}
bool CMy2015RemoteDlg::GetHostClientType(uint64_t clientID, CString& clientType)
{
clientType.Empty();
bool found = false;
EnterCriticalSection(&m_cs);
auto it = m_ClientIndex.find(clientID);
if (it != m_ClientIndex.end() && it->second < m_HostList.size()) {
if (context* ctx = m_HostList[it->second]) {
clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
found = true;
}
}
LeaveCriticalSection(&m_cs);
return found;
}
uint64_t CMy2015RemoteDlg::FindClientIDByIP(const std::string& ip)
{
CString clientIP(ip.c_str());
+3
View File
@@ -485,6 +485,9 @@ public:
std::vector<DllInfo*> m_DllList;
context* FindHostByIP(const std::string& ip);
context* FindHostByClientID(uint64_t clientID); // 线程安全:通过 clientID 精确查主连接
// 线程安全:在 m_cs 内读取并返回值,避免调用方拿到裸指针后再访问附加数据;
// 找不到主连接时返回 false。
bool GetHostClientType(uint64_t clientID, CString& clientType);
uint64_t FindClientIDByIP(const std::string& ip); // 线程安全:在锁内获取ID
void InjectTinyRunDll(const std::string& ip, int pid);
NOTIFYICONDATA m_Nid;
+14
View File
@@ -3442,7 +3442,21 @@ BOOL CScreenSpyDlg::PreTranslateMessage(MSG* pMsg)
case WM_MBUTTONDBLCLK:
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
SendScaledMouseMessage(pMsg, true);
break;
case WM_MOUSEMOVE:
// Android(含 TV/盒子)把悬停的 mousemove 翻译成焦点移动;MFC 控制端只在
// 按住左键拖动时转发,避免鼠标划过画面时远程焦点乱跳。触摸屏浏览器的输入
// 走 Web 前端的 touch 处理器,不经过这里。
if (m_bIsCtrl) {
if (m_androidHost < 0 && m_ClientID != 0 && g_2015RemoteDlg) {
CString clientType;
if (g_2015RemoteDlg->GetHostClientType(m_ClientID, clientType))
m_androidHost = clientType.CompareNoCase(_T("APK")) == 0 ? 1 : 0;
}
if (m_androidHost == 1 && !(pMsg->wParam & MK_LBUTTON))
break;
}
SendScaledMouseMessage(pMsg, true);
break;
case WM_MOUSEWHEEL: {
+3
View File
@@ -208,6 +208,9 @@ class CScreenSpyDlg : public DialogBase
DECLARE_DYNAMIC(CScreenSpyDlg)
CToolbarDlg* m_pToolbar = nullptr;
CMy2015RemoteDlg* m_pParent = nullptr;
// -1=尚未解析, 0=非 Android, 1=Android(APK)。只在 UI 线程读写:PreTranslateMessage
// 首次用到时解析并缓存,避免每次 mousemove 都查主连接。
int m_androidHost = -1;
public:
CStatusInfoWnd* m_pStatusInfoWnd = nullptr;
+6
View File
@@ -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. | `<shared-secret>` |
| `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**) |
+35
View File
@@ -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
+68
View File
@@ -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
@@ -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)
}
}
+41
View File
@@ -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
}
+32
View File
@@ -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)
}
}
}
+7 -6
View File
@@ -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
+22 -1
View File
@@ -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)
+278
View File
@@ -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)
}
}
+26
View File
@@ -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-
+140 -1
View File
@@ -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) {
+330 -46
View File
@@ -642,14 +642,28 @@
max-width: 200px;
flex-shrink: 1;
}
/* 卡片操作图标(终端 / 删除):右上角,独立于卡片本体点击事件
(onclick stopPropagation)。List 视图卡片是一行,改为垂直居中。 */
/* 「已转移」标记:主机被转移到另一台主控(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 {
position: absolute;
top: 12px;
right: 12px;
display: flex;
gap: 6px;
z-index: 1;
}
.device-card .card-icon-btn {
@@ -667,14 +681,57 @@
}
.device-card .card-icon-btn:hover { background: rgba(255,255,255,0.14); color: #fff; }
.device-card .card-icon-btn:active { transform: scale(0.92); }
.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 h3 { padding-right: 124px; } /* 给右上角操作图标让位 */
.device-card .card-more-btn[aria-expanded="true"] { background: rgba(255,255,255,0.14); color: #fff; }
.device-card h3 { padding-right: 56px; } /* 给右上角「…」按钮让位 */
.device-grid.list-view .device-card .card-actions {
top: 50%;
transform: translateY(-50%);
}
/* 「…」的弹出菜单:fixed 挂 body(卡片 overflow:hidden 会裁掉菜单),
JS 按按钮位置定位并做视口翻转/夹取。 */
.card-menu {
position: fixed;
z-index: 80;
width: 264px;
max-width: calc(100vw - 16px);
padding: 6px;
border: 1px solid #0f3460;
border-radius: 8px;
background: #16213e;
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.5);
}
.card-menu-item {
display: flex;
align-items: flex-start;
gap: 10px;
width: 100%;
padding: 8px;
border: none;
border-radius: 6px;
background: transparent;
color: #ddd;
text-align: left;
cursor: pointer;
}
.card-menu-item:hover, .card-menu-item:focus-visible { background: rgba(255,255,255,0.07); }
.card-menu-item:active { background: rgba(255,255,255,0.12); }
.card-menu-icon {
flex: 0 0 auto;
display: flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
margin-top: 1px;
}
.card-menu-item.term .card-menu-icon { color: #4caf50; }
.card-menu-item.bind .card-menu-icon { color: #e67e22; }
.card-menu-item.transfer .card-menu-icon { color: #d68910; }
.card-menu-item.del .card-menu-icon { color: #e74c3c; }
.card-menu-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.card-menu-label { font-size: 13px; font-weight: 500; color: #eee; }
.card-menu-item.del .card-menu-label { color: #e74c3c; }
.card-menu-desc { font-size: 11px; color: #8a93a8; line-height: 1.35; }
/* ====== 终端页面 ====== */
#term-page {
@@ -804,7 +861,7 @@
display: flex;
align-items: center;
padding: 12px 16px;
padding-right: 100px; /* 给垂直居中的操作图标列让位 */
padding-right: 56px; /* 给垂直居中的「…」按钮让位 */
gap: 20px;
}
.device-grid.list-view .device-card::before { display: none; }
@@ -2174,6 +2231,36 @@
</div>
</div>
<!-- Transfer Host Modal(仅 Go 后端:device_list 带 transfer 字段时才有入口) -->
<div class="modal-overlay" id="transfer-device-modal" onclick="if(event.target===this)cancelTransferDevice()">
<div class="modal-content" style="max-width:460px;">
<div class="modal-header">
<h3>Transfer Host</h3>
<button class="modal-close" onclick="cancelTransferDevice()">&times;</button>
</div>
<div class="user-form">
<div id="transfer-device-name" style="font-size:13px;color:#aaa;margin-bottom:10px;"></div>
<label style="font-size:13px;color:#aaa;display:block;margin:8px 0 4px;">
Target master (host:port)
</label>
<input type="text" id="transfer-target" placeholder="192.0.2.10:6543" autocomplete="off">
<label style="font-size:13px;color:#aaa;display:block;margin:12px 0 4px;">
Days until it comes back
</label>
<input type="number" id="transfer-days" min="0.5" max="365" step="0.5" value="1">
<div style="font-size:12px;color:#888;margin-top:8px;">
The host logs in on the target master and returns here by itself when the days
run out. While it is away it shows as offline on this server. Use this to hand a
host to the MFC master for a client upgrade.
</div>
<div style="display:flex;gap:8px;margin-top:14px;">
<button onclick="confirmTransferDevice()">Transfer</button>
<button class="cancel-btn" onclick="cancelTransferDevice()">Cancel</button>
</div>
</div>
</div>
</div>
<!-- Device Binding Modal(仅内置 admin 超级管理员可见) -->
<div class="modal-overlay" id="bind-device-modal" onclick="if(event.target===this)closeBindModal()">
<div class="modal-content" style="max-width:440px;">
@@ -2930,6 +3017,9 @@
}
updateAdminButtons();
devices = msg.devices || [];
// 只有实现了「转移主机」的后端(Go)才会带这个字段;
// MFC 复用同一份页面但不下发它,按钮因此不会出现。
transferCfg = msg.transfer || null;
// Keep current page (renderDeviceList adjusts if out of range)
renderDeviceList();
renderWallSidebar();
@@ -3212,6 +3302,14 @@
appAlert(msg.msg || 'Failed to delete device', 'Unable to Delete Device');
}
break;
case 'transfer_device_result':
if (msg.ok) {
// 设备会转到新主控上线;刷新一次,卡片带上「已转移」标记。
getDevices();
} else {
appAlert(msg.msg || 'Failed to transfer host', 'Unable to Transfer Host');
}
break;
case 'list_users_result':
if (msg.ok) {
// The built-in admin is the superadmin, never a bind target.
@@ -5010,7 +5108,130 @@
}
}
// ---- 卡片「…」操作菜单 ----
// 无论有几个操作,卡片上只显示一个「…」;点开弹出的菜单里才是终端/绑定/
// 转移/删除,每项带一句功能说明。菜单项在点击时按设备实时生成,权限和
// 在线状态不会因为列表渲染后变化而过期。
let cardMenuEl = null;
let cardMenuBtn = null;
const cardMenuSvg = {
term: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/></svg>',
bind: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>',
transfer: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/><polyline points="10 17 15 12 10 7"/><line x1="15" y1="12" x2="3" y2="12"/></svg>',
del: '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>' +
'<path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/></svg>'
};
function hasCardActions(d) {
if (d.online !== false) return true; // 在线设备至少有终端
return canBindDevices() || canDeleteDevices();
}
function cardMenuEntries(d) {
const offline = d.online === false;
const out = [];
if (!offline) {
out.push({ kind: 'term', label: 'Terminal', desc: 'Open a remote shell',
run: () => openTerminal(d.id) });
}
if (canBindDevices()) {
out.push({ kind: 'bind', label: 'Bind owner', desc: 'Assign this host to a user',
run: () => openBindModal(d.id) });
}
if (canTransferDevices() && !offline && !d.transferTo) {
out.push({ kind: 'transfer', label: 'Transfer host', desc: 'Move the host to another master',
run: () => openTransferModal(d.id) });
}
if (canDeleteDevices()) {
out.push({
kind: 'del',
label: offline ? 'Delete record' : 'Uninstall host',
desc: offline ? 'Remove this offline record' : 'Remove the client from this host',
run: () => askDeleteDevice(d.id)
});
}
return out;
}
function closeCardMenu() {
if (cardMenuEl) {
cardMenuEl.remove();
cardMenuEl = null;
}
if (cardMenuBtn) {
cardMenuBtn.setAttribute('aria-expanded', 'false');
cardMenuBtn = null;
}
}
function toggleCardMenu(btn, id) {
if (cardMenuBtn === btn) { // 再点一次同一个按钮 = 收起
closeCardMenu();
return;
}
const d = devices.find(x => String(x.id) === String(id));
const entries = d ? cardMenuEntries(d) : [];
closeCardMenu();
if (!entries.length) return;
const menu = document.createElement('div');
menu.className = 'card-menu';
menu.setAttribute('role', 'menu');
entries.forEach(en => {
const item = document.createElement('button');
item.type = 'button';
item.className = 'card-menu-item ' + en.kind;
item.setAttribute('role', 'menuitem');
item.innerHTML =
'<span class="card-menu-icon">' + cardMenuSvg[en.kind] + '</span>' +
'<span class="card-menu-text">' +
'<span class="card-menu-label">' + escapeHtml(en.label) + '</span>' +
'<span class="card-menu-desc">' + escapeHtml(en.desc) + '</span>' +
'</span>';
item.addEventListener('click', (e) => {
e.stopPropagation();
closeCardMenu();
en.run();
});
menu.appendChild(item);
});
document.body.appendChild(menu);
// 右对齐按钮,菜单默认向下;贴底时向上翻,左右夹在视口内。
const r = btn.getBoundingClientRect();
const mw = menu.offsetWidth;
const mh = menu.offsetHeight;
let left = r.right - mw;
let top = r.bottom + 6;
if (top + mh > window.innerHeight - 8) top = r.top - mh - 6;
if (top < 8) top = 8;
left = Math.max(8, Math.min(left, window.innerWidth - mw - 8));
menu.style.left = left + 'px';
menu.style.top = top + 'px';
cardMenuEl = menu;
cardMenuBtn = btn;
btn.setAttribute('aria-expanded', 'true');
}
document.addEventListener('click', (e) => {
if (!cardMenuEl) return;
if (cardMenuEl.contains(e.target)) return;
if (e.target.closest && e.target.closest('.card-more-btn')) return; // 切换由按钮自己处理
closeCardMenu();
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') closeCardMenu();
});
window.addEventListener('scroll', closeCardMenu, true); // 滚动后 fixed 菜单会跟丢锚点
window.addEventListener('resize', closeCardMenu);
function renderDeviceList() {
closeCardMenu();
renderGroupFilter();
const filtered = getFilteredDevices();
const ps = getPageSize();
@@ -5039,43 +5260,19 @@
const rtt = d.rtt || '-';
const ver = d.version || '-';
const activeWin = d.activeWindow || '';
// 操作图标:在线卡片有终端;删除对所有卡片开放(离线=删记录,
// 在线=卸载主机),仅管理员可用。Wall 模式不提供删除。
const actions = [];
if (!offline) {
actions.push(
'<button class="card-icon-btn card-term-btn" title="Open Terminal" aria-label="Terminal" ' +
'onclick="event.stopPropagation();openTerminal(\'' + jsAttr(d.id) + '\')">' +
'<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>' +
'</svg>' +
'</button>');
}
if (canBindDevices()) {
actions.push(
'<button class="card-icon-btn card-bind-btn" title="Bind owner" aria-label="Bind owner" ' +
'onclick="event.stopPropagation();openBindModal(\'' + jsAttr(d.id) + '\')">' +
'<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<rect x="3" y="11" width="18" height="11" rx="2"/>' +
'<path d="M7 11V7a5 5 0 0 1 10 0v4"/>' +
'</svg>' +
'</button>');
}
if (canDeleteDevices()) {
actions.push(
'<button class="card-icon-btn card-del-btn" title="' +
(offline ? 'Delete record' : 'Uninstall host') + '" aria-label="Delete" ' +
'onclick="event.stopPropagation();askDeleteDevice(\'' + jsAttr(d.id) + '\')">' +
'<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' +
'<polyline points="3 6 5 6 21 6"/>' +
'<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>' +
'<path d="M10 11v6"/><path d="M14 11v6"/>' +
'<path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"/>' +
'</svg>' +
'</button>');
}
const actionsHtml = actions.length
? '<div class="card-actions">' + actions.join('') + '</div>' : '';
// 操作全部收进右上角的「…」菜单(终端 / 绑定 / 转移 / 删除),
// 具体条目见 cardMenuEntries。这里只决定按钮是否出现。
const actionsHtml = hasCardActions(d)
? '<div class="card-actions">' +
'<button class="card-icon-btn card-more-btn" title="Actions" aria-label="More actions" ' +
'aria-haspopup="menu" aria-expanded="false" ' +
'onclick="event.stopPropagation();toggleCardMenu(this, \'' + jsAttr(d.id) + '\')">' +
'<svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">' +
'<circle cx="5" cy="12" r="1.7"/><circle cx="12" cy="12" r="1.7"/><circle cx="19" cy="12" r="1.7"/>' +
'</svg>' +
'</button>' +
'</div>'
: '';
return '<div class="device-card' + (offline ? ' offline' : '') + '"' +
(offline ? '' : ' onclick="connectDevice(\'' + jsAttr(d.id) + '\')"') + '>' +
actionsHtml +
@@ -5096,6 +5293,11 @@
'<span class="meta-item">' + screenInfo + '</span>' +
'</div>' +
(offline ? '<div class="last-seen">Last seen: ' + escapeHtml(formatLastSeen(d.last_seen)) + '</div>' : '') +
(d.transferTo
? '<div class="transfer-badge" title="Transferred to ' + escapeHtml(d.transferTo) + '">' +
'Transferred → ' + escapeHtml(d.transferTo) + ' · ' +
escapeHtml(formatTransferLeft(d.transferUntil)) + '</div>'
: '') +
(!offline && activeWin ? '<div class="active-window' + (isWindowBusy(activeWin) ? ' busy' : '') + '" title="' + escapeHtml(activeWin) + '">' + escapeHtml(activeWin) + '</div>' : '') +
'</div>';
}).join('');
@@ -5427,6 +5629,74 @@
ws.send(JSON.stringify({ cmd: 'delete_device', token, id }));
}
// ===== 转移主机(仅 Go 后端) =====
// 把一台主机临时交给另一台主控(MFC),让那台主控能给它下发客户端升级;
// 到期后主机自己回到本主控(客户端记着启动时捕获的地址),服务端不参与还原。
//
// 入口的可见性完全取决于 device_list 里有没有 transfer 字段:Go 与 MFC 共用
// 这一份页面,MFC 不下发该字段,于是没有按钮、也不会发出这条消息。
let transferCfg = null; // {target, days} | null
let pendingTransferDeviceId = null;
function canTransferDevices() {
return !!transferCfg && currentUserRole === 'admin';
}
// 卡片上的「剩余」只精确到分钟,够判断什么时候回来。
function formatTransferLeft(until) {
const left = (Number(until) || 0) * 1000 - Date.now();
if (left <= 0) return 'returning now';
const mins = Math.floor(left / 60000);
if (mins < 60) return mins + 'm left';
const hours = Math.floor(mins / 60);
if (hours < 48) return hours + 'h ' + (mins % 60) + 'm left';
return Math.floor(hours / 24) + 'd ' + (hours % 24) + 'h left';
}
function openTransferModal(id) {
if (!canTransferDevices()) return;
const d = devices.find(x => String(x.id) === String(id));
if (!d) { appAlert('Device not found.', 'Device Not Found'); return; }
if (d.online === false) { appAlert('Device is offline.', 'Device Offline'); return; }
pendingTransferDeviceId = String(id);
document.getElementById('transfer-device-name').textContent =
displayName(d) + ' (' + String(id) + ')';
document.getElementById('transfer-target').value = transferCfg.target || '';
document.getElementById('transfer-days').value = transferCfg.days || 1;
document.getElementById('transfer-device-modal').classList.add('active');
}
function cancelTransferDevice() {
pendingTransferDeviceId = null;
document.getElementById('transfer-device-modal').classList.remove('active');
}
function confirmTransferDevice() {
const id = pendingTransferDeviceId;
const targetRaw = document.getElementById('transfer-target').value.trim();
const days = parseFloat(document.getElementById('transfer-days').value);
if (!id) return;
// 拆 host:port:最后一个冒号之后是端口,host 里不允许再出现冒号——
// 服务端按 ':' 切字段,多一个冒号会把 days 读成端口。
const cut = targetRaw.lastIndexOf(':');
const host = cut > 0 ? targetRaw.slice(0, cut).trim() : '';
const port = cut > 0 ? parseInt(targetRaw.slice(cut + 1), 10) : NaN;
if (!host || host.indexOf(':') >= 0 || !(port >= 1 && port <= 65535)) {
appAlert('Enter the target as host:port, e.g. 192.0.2.10:6543.', 'Invalid Target');
return;
}
if (!(days > 0 && days <= 365)) {
appAlert('Days must be between 0.5 and 365.', 'Invalid Duration');
return;
}
document.getElementById('transfer-device-modal').classList.remove('active');
pendingTransferDeviceId = null;
if (!ws || ws.readyState !== WebSocket.OPEN) return;
ws.send(JSON.stringify({ cmd: 'transfer_device', token, id, host, port, days }));
}
// User Management Functions
let currentUserRole = 'viewer';
// Username of the current session. Only the built-in "admin" account is
@@ -7558,6 +7828,18 @@
sendMouse('up', x, y, 2);
}
// Android 主机(含 TV/盒子)会把悬停的 move 翻译成焦点移动;桌面鼠标
// 只在按住左键拖动时发送 move。优先用服务端下发的 isAndroidRemote
// (client_type === "APK"),设备列表字段只作兜底,保证与导航栏/直触
// 模式使用同一个判断。触摸路径走下面的 touch 处理器,不受影响。
function isAndroidHost() {
if (isAndroidRemote) return true;
if (!currentDevice) return false;
const os = String(currentDevice.os || '').toLowerCase();
const type = String(currentDevice.clientType || '').toLowerCase();
return os.includes('android') || type === 'apk';
}
// Desktop mouse handling
let lastMouseMove = 0;
let lastMouseX = 0, lastMouseY = 0;
@@ -7601,6 +7883,8 @@
lastMouseMove = now;
lastMouseX = pos.x;
lastMouseY = pos.y;
// Android(TV): 不按键的悬停不控制远程,只更新本地光标;按住左键拖动才发 move。
if (isAndroidHost() && !(e.buttons & 1)) return;
sendMouse('move', pos.x, pos.y, 0);
});