Files
SimpleRemoter/macos/main.mm
T
yuanyuanxianganddeepseek-flash 06b93f7bdb Feat(client): complete the macOS feature set (phase 0 and 1)
Phase 0 makes implementations that already existed reachable. macOS now
declares TERMINAL, SCREEN_CLIPBOARD, PROCESS and C2C_RECV_ACK; PROCESS is a
new bit and Linux declares it too. SystemManager was dead code -- its
constructor took a second argument and it did not derive IOCPManager, so the
sub-connection skeleton could never instantiate it -- and now matches the
createHandler/OnReceive contract, so COMMAND_SYSTEM really spawns a
sub-connection (proc_listpids, SIGKILL). DataProcess always gets a NULL user,
so main.mm keeps a g_pMainClient handle and the V2 C2C receiver finally
answers TOKEN_C2C_RECV_RESULT. The server asks for SupportsTerminal() on MAC
for exec_command / terminal_* and for SupportsProcess() for kill_process, so
an old build gets "client is too old" instead of a command nobody answers;
kToolPlatforms and mcp/tools.json follow. http_probe stays win/lnx: the
terminal works on macOS, but the probe uses GNU-only base64 -w.

Phase 1 is POSIX parity. ScreenPreview captures through CGDisplayCreateImage,
scales and ships BGRX for the server to encode, and the capability is only
declared when preflight or a real capture says the display is readable.
ActivityHistory samples the frontmost layer-0 window once a second and prints
the same records as Windows and Linux. COMMAND_SCREEN_KEYFRAME_REQ is now
consumed by Linux (x264 IDR) and macOS (VideoToolbox force keyframe): the
receive thread raises a flag, the capture thread -- which owns the encoder --
consumes it and puts it back if the frame never went out. The macOS quality
level persists in NSUserDefaults because main.mm rewrites config.conf.

Linux client and Debug x64 server rebuild green; check_platform_table PASS.
Not built or run on a Mac.

Co-Authored-By: deepseek-flash
2026-11-14 13:30:50 +01:00

1570 lines
66 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#import <Cocoa/Cocoa.h>
#import <sys/sysctl.h>
#import <sys/stat.h>
#import <mach/mach.h>
#import <mach-o/dyld.h>
#import <pwd.h>
#import <signal.h>
#import <unistd.h>
#import <fcntl.h>
#import <errno.h>
#import <limits.h>
#import <pthread.h>
#import <sys/wait.h>
#import <IOKit/IOKitLib.h>
#import <IOKit/pwr_mgt/IOPMLib.h>
#import <fstream>
#import <thread>
#import <atomic>
#import <memory>
#import <string>
#import <map>
#import <vector>
#import <cstring> // strncpy(RefreshLoginTls 改写 szReserved)
#import <system_error>
#import "../client/IOCPClient.h"
#include "../client/TlsChannel.h" // TLS 传输(信任锚保存/热重载),随 IOCPClient 一起定义 YAMA_TLS_CHANNEL
#define XXH_INLINE_ALL
#include "../common/xxhash.h"
#include "../common/rtt_estimator.h"
#include "../common/client_auth_state.h"
#include "../common/posix_net_helpers.h"
#include "../common/sub_conn_thread.h"
#include "../common/ClientLogHandler.h"
#import "Permissions.h"
#import "ScreenHandler.h"
#import "InputHandler.h"
#import "SystemManager.h"
#import "ScreenPreview.h"
#import "ActivityHistory.h"
#import "../common/PTYHandler.h"
#import "../common/FileManager.h"
#import "../common/FileTransferV2.h"
#import "../common/logger.h"
#import "ClipboardHandler.h"
// 本文件的运行期日志一律用 Mprintf:它既进内存 ring —— 服务端「运行日志」菜单与
// MCP 的 get_client_log 就取这一份 —— 又由 Logger 镜像到 stderr(/tmp/ghost.log)。
// NSLog 只会落在文件里、不进 ring,所以启动/配置/权限这些现场最常翻的行不要用
// NSLog。(ScreenHandler/H264/InputHandler 等 ObjC 模块里的 NSLog 保持原样。)
// Global state
static std::atomic<bool> g_running(true);
static std::atomic<bool> g_needResendLogin(false); // 分组变更后需要重发登录信息
// 传输方式热切换(服务端 COMMAND_TLS_ENABLE/DISABLE 改了信任锚)后需要重建连接。
// DataProcess 跑在接收线程上,直接关 socket 会和主线程的发送竞争,所以只置标志,
// 由主心跳循环择机 Disconnect 并重连(与 linux/main.cpp 的 g_needReconnect 同语义)。
static std::atomic<bool> g_needReconnect(false);
// 权限补齐后要求重启进程(见文件下方的「授权后自动重启」)。只看守线程置位,主循环
// 见到它先断开主连接再重启,避免新进程起来时旧连接还挂在服务端。
static std::atomic<bool> g_autoRestartPending(false);
// Client ID (calculated from system info, used by ScreenHandler)
uint64_t g_myClientID = 0;
// 主连接句柄。DataProcess 的 user 参数恒为 NULL,而 V2 C2C 落盘回执
// (TOKEN_C2C_RECV_RESULT)要发在主连接上,所以留一个全局指针(同 linux/main.cpp)。
// Send2Server 内部持锁,可在工作线程调用;用之前一律先判 IsConnected()。
static IOCPClient* g_pMainClient = nullptr;
// 服务端身份校验全局状态已抽到 common/client_auth_state.h(namespace ClientAuth)
// 远程地址:当前为写死状态,如需调试,请按实际情况修改
CONNECT_ADDRESS g_SETTINGS = { FLAG_GHOST, "91.99.165.207", "443", CLIENT_TYPE_MACOS };
State g_bExit = S_CLIENT_NORMAL;
// ============== Configuration File Functions ==============
// Config path: ~/.config/ghost/config.conf (same as Linux)
// Format: key=value (one per line)
static std::string g_configDir;
static std::string g_configPath;
static std::map<std::string, std::string> g_configData;
// Initialize config paths
static void initConfigPaths()
{
if (!g_configDir.empty()) return; // Already initialized
const char* home = getenv("HOME");
if (!home) {
struct passwd* pw = getpwuid(getuid());
if (pw) home = pw->pw_dir;
}
if (!home) home = "/tmp";
g_configDir = std::string(home) + "/.config/ghost";
g_configPath = g_configDir + "/config.conf";
}
// Recursively create directory
static void mkdirRecursive(const std::string& path)
{
size_t pos = 0;
while ((pos = path.find('/', pos + 1)) != std::string::npos) {
mkdir(path.substr(0, pos).c_str(), 0755);
}
mkdir(path.c_str(), 0755);
}
// Load all config from file
static void loadConfig()
{
initConfigPaths();
g_configData.clear();
std::ifstream file(g_configPath);
if (!file.is_open()) return;
std::string line;
while (std::getline(file, line)) {
size_t eq = line.find('=');
if (eq != std::string::npos) {
g_configData[line.substr(0, eq)] = line.substr(eq + 1);
}
}
}
// Save all config to file
static void saveConfig()
{
initConfigPaths();
mkdirRecursive(g_configDir);
std::ofstream file(g_configPath, std::ios::trunc);
if (!file.is_open()) {
Mprintf("Failed to save config to %s\n", g_configPath.c_str());
return;
}
for (const auto& kv : g_configData) {
file << kv.first << "=" << kv.second << "\n";
}
Mprintf("Config saved to %s\n", g_configPath.c_str());
}
// Get config string value
static std::string getConfigStr(const std::string& key, const std::string& def = "")
{
auto it = g_configData.find(key);
return it != g_configData.end() ? it->second : def;
}
// Set config string value
static void setConfigStr(const std::string& key, const std::string& value)
{
g_configData[key] = value;
saveConfig();
}
// Save group name to config file
static void saveGroupName(const std::string& groupName)
{
setConfigStr("group_name", groupName);
Mprintf("Group name saved: %s\n", groupName.c_str());
}
// Load group name from config file
static std::string loadGroupName()
{
return getConfigStr("group_name");
}
// ============== System Information Functions ==============
// Get macOS version string (e.g., "macOS 14.0 Sonoma")
static std::string getMacOSVersion()
{
NSOperatingSystemVersion version = [[NSProcessInfo processInfo] operatingSystemVersion];
NSString* versionString = [NSString stringWithFormat:@"macOS %ld.%ld.%ld",
(long)version.majorVersion,
(long)version.minorVersion,
(long)version.patchVersion];
return std::string([versionString UTF8String]);
}
// Get hostname
static std::string getHostname()
{
char hostname[256] = {};
gethostname(hostname, sizeof(hostname));
return std::string(hostname);
}
// Get CPU model and frequency
static std::string getCPUInfo()
{
char buf[256] = {};
size_t size = sizeof(buf);
if (sysctlbyname("machdep.cpu.brand_string", buf, &size, NULL, 0) == 0) {
return std::string(buf);
}
return "Unknown CPU";
}
// Get CPU frequency in MHz
static int getCPUFrequencyMHz()
{
uint64_t freq = 0;
size_t size = sizeof(freq);
if (sysctlbyname("hw.cpufrequency_max", &freq, &size, NULL, 0) == 0) {
return (int)(freq / 1000000);
}
return 0;
}
// Get number of CPU cores
static int getCPUCores()
{
int cores = 0;
size_t size = sizeof(cores);
if (sysctlbyname("hw.ncpu", &cores, &size, NULL, 0) == 0) {
return cores;
}
return 1;
}
// Get total physical memory in GB
static double getMemoryGB()
{
int64_t memSize = 0;
size_t size = sizeof(memSize);
if (sysctlbyname("hw.memsize", &memSize, &size, NULL, 0) == 0) {
return (double)memSize / (1024.0 * 1024.0 * 1024.0);
}
return 0;
}
// Get current username
static std::string getUsername()
{
struct passwd* pw = getpwuid(getuid());
if (pw && pw->pw_name) {
return std::string(pw->pw_name);
}
const char* user = getenv("USER");
return user ? std::string(user) : "unknown";
}
// 读取 IOKit 维护的 IOPlatformUUID(与 Windows MachineGuid 等价)
// 这是主板/系统级 UUID,由 IOPlatformExpertDevice 服务提供,重装系统通常不变。
// 对应:Windows HKLM\Software\Microsoft\Cryptography\MachineGuid
// Linux /etc/machine-id
static std::string getMachineId()
{
std::string result;
io_service_t platformExpert = IOServiceGetMatchingService(
kIOMasterPortDefault,
IOServiceMatching("IOPlatformExpertDevice"));
if (platformExpert != IO_OBJECT_NULL) {
CFTypeRef uuidProperty = IORegistryEntryCreateCFProperty(
platformExpert, CFSTR(kIOPlatformUUIDKey),
kCFAllocatorDefault, 0);
if (uuidProperty != nullptr) {
if (CFGetTypeID(uuidProperty) == CFStringGetTypeID()) {
CFStringRef uuidStr = (CFStringRef)uuidProperty;
char buf[64] = {};
if (CFStringGetCString(uuidStr, buf, sizeof(buf), kCFStringEncodingUTF8)) {
result = buf;
}
}
CFRelease(uuidProperty);
}
IOObjectRelease(platformExpert);
}
return result;
}
// 路径归一化(macOS 版):解析符号链接 + 转小写
// realpath 把 /Applications/foo/../bar 之类折回规范形式;
// 小写化保持与 Windows/Linux 跨端一致。macOS HFS+/APFS 默认大小写不敏感,
// 转小写不改变文件标识、但避免路径串大小写差异引起 ID 不同。
static std::string normalizeExePathLower(const std::string& path)
{
char resolved[PATH_MAX] = {};
std::string out;
if (realpath(path.c_str(), resolved) != nullptr) {
out = resolved;
} else {
out = path; // 解析失败:用原值
}
for (auto& c : out) {
if (c >= 'A' && c <= 'Z') c = c - 'A' + 'a';
}
return out;
}
// Get screen resolution
static std::string getScreenResolution()
{
// 用主显示器的全局显示坐标(points),与 CGEvent 注入坐标同一空间,也和
// ScreenHandler 抓屏所用的 CGMainDisplayID 保持一致。
// [NSScreen mainScreen] 在合盖接外置显示器时仍可能返回内置屏(如 1470x956),
// 上报后会让服务端以为主机分辨率是内置屏尺寸。
CGRect bounds = CGDisplayBounds(CGMainDisplayID());
if (bounds.size.width > 0 && bounds.size.height > 0) {
return [NSString stringWithFormat:@"1:%dx%d",
(int)(bounds.size.width + 0.5), (int)(bounds.size.height + 0.5)].UTF8String;
}
return "0:0x0";
}
// Get executable path
static std::string getExecutablePath()
{
char path[PATH_MAX];
uint32_t size = sizeof(path);
if (_NSGetExecutablePath(path, &size) == 0) {
return std::string(path);
}
return "";
}
// 进程已运行秒数(RES_UPTIME)的基准:本文件随进程启动即加载,取加载时刻为起点。
// 与同一块本机墙钟的当前时刻相减,时区不影响结果(下面 getTimeString 固定按 UTC+8
// 格式化,服务端无法据此还原出运行时长)。
static const std::time_t g_processStartTime = std::time(nullptr);
static long long getProcessUptimeSeconds()
{
long long up = static_cast<long long>(std::time(nullptr)) -
static_cast<long long>(g_processStartTime);
return up > 0 ? up : 0;
}
// Get current time string (Beijing time, UTC+8)
static std::string getTimeString()
{
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8*3600]];
NSString* dateString = [formatter stringFromDate:[NSDate date]];
return std::string([dateString UTF8String]);
}
// Get user idle time in seconds (time since last keyboard/mouse input)
static double getUserIdleTime()
{
// CGEventSourceSecondsSinceLastEventType returns seconds since last event
// kCGEventSourceStateCombinedSessionState includes all input sources
CFTimeInterval idleTime = CGEventSourceSecondsSinceLastEventType(
kCGEventSourceStateCombinedSessionState,
kCGAnyInputEventType
);
// Defensive: ensure non-negative (edge case protection)
return idleTime > 0 ? idleTime : 0;
}
// Check if screen is locked
static bool isScreenLocked()
{
// Method 1: Check CGSession dictionary for screen lock status
CFDictionaryRef sessionDict = CGSessionCopyCurrentDictionary();
if (sessionDict) {
// Check for "CGSSessionScreenIsLocked" key
CFBooleanRef screenLocked = (CFBooleanRef)CFDictionaryGetValue(
sessionDict, CFSTR("CGSSessionScreenIsLocked"));
if (screenLocked && CFBooleanGetValue(screenLocked)) {
CFRelease(sessionDict);
return true;
}
CFRelease(sessionDict);
}
// Method 2: Check if loginwindow is frontmost (screen saver / lock screen)
NSRunningApplication* frontApp = [[NSWorkspace sharedWorkspace] frontmostApplication];
if (frontApp) {
NSString* bundleId = [frontApp bundleIdentifier];
if ([bundleId isEqualToString:@"com.apple.loginwindow"] ||
[bundleId isEqualToString:@"com.apple.ScreenSaver.Engine"]) {
return true;
}
}
return false;
}
// Format time as HH:MM:SS with prefix
static std::string formatStatusTime(const char* prefix, double seconds)
{
int totalSecs = (int)seconds;
int hours = totalSecs / 3600;
int mins = (totalSecs % 3600) / 60;
int secs = totalSecs % 60;
char buffer[64];
snprintf(buffer, sizeof(buffer), "%s: %02d:%02d:%02d", prefix, hours, mins, secs);
return std::string(buffer);
}
// Get active application name or idle/locked status (works for background processes)
static std::string getActiveApp()
{
double idleTime = getUserIdleTime();
// Check if screen is locked first
if (isScreenLocked()) {
return formatStatusTime("Locked", idleTime);
}
// Check user idle time (matches Windows/Linux: 6 seconds threshold)
// If idle for more than 6 seconds, report inactive status
if (idleTime >= 6.0) {
return formatStatusTime("Inactive", idleTime);
}
// Use CGWindowListCopyWindowInfo to get the frontmost window
// This works reliably even when running as a background/nohup process
CFArrayRef windowList = CGWindowListCopyWindowInfo(
kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
kCGNullWindowID
);
if (windowList) {
CFIndex count = CFArrayGetCount(windowList);
for (CFIndex i = 0; i < count; i++) {
CFDictionaryRef window = (CFDictionaryRef)CFArrayGetValueAtIndex(windowList, i);
// Get window layer - layer 0 is normal windows
CFNumberRef layerRef = (CFNumberRef)CFDictionaryGetValue(window, kCGWindowLayer);
int layer = 0;
if (layerRef) {
CFNumberGetValue(layerRef, kCFNumberIntType, &layer);
}
// Skip non-normal windows (menu bar, dock, etc.)
if (layer != 0) continue;
// Get owner name (application name)
CFStringRef ownerName = (CFStringRef)CFDictionaryGetValue(window, kCGWindowOwnerName);
if (ownerName) {
char buffer[256] = {};
if (CFStringGetCString(ownerName, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
CFRelease(windowList);
return std::string(buffer);
}
}
}
CFRelease(windowList);
}
// Fallback to NSWorkspace (may not work for background processes)
NSRunningApplication* app = [[NSWorkspace sharedWorkspace] frontmostApplication];
if (app) {
NSString* name = [app localizedName];
if (name) {
return std::string([name UTF8String]);
}
}
return "";
}
// ============== Check if camera exists ==============
static bool hasCameraDevice()
{
// Most MacBooks have built-in FaceTime camera
// Check model identifier to determine if it's a MacBook
char model[256] = {};
size_t size = sizeof(model);
if (sysctlbyname("hw.model", model, &size, NULL, 0) == 0) {
std::string modelStr(model);
// MacBooks (Air/Pro) always have cameras
if (modelStr.find("MacBook") != std::string::npos) {
return true;
}
// iMac also has camera
if (modelStr.find("iMac") != std::string::npos) {
return true;
}
}
// Mac Mini and Mac Pro typically don't have built-in cameras
return false;
}
// ============== Public IP ==============
// Execute command and return output
// execCmd / httpGet / getPublicIP 已抽到 common/posix_net_helpers.h(namespace PosixNet)。
// 这里保留同名 wrapper 避免改动调用点。Linux 端额外的 jsonExtract / getGeoLocation
// macOS 暂未使用,需要时直接用 PosixNet:: 命名空间访问。
static inline std::string execCmd(const std::string& cmd) { return PosixNet::execCmd(cmd); }
static inline std::string httpGet(const std::string& url, int timeoutSec = 5) { return PosixNet::httpGet(url, timeoutSec); }
static inline std::string getPublicIP() { return PosixNet::getPublicIP(); }
// ============== Install Time (persistent storage) ==============
static std::string getInstallTime()
{
@autoreleasepool {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* installTime = [defaults stringForKey:@"ghost_install_time"];
if (installTime == nil || [installTime length] == 0) {
// First run - record current time as install time
std::string currentTime = getTimeString();
installTime = [NSString stringWithUTF8String:currentTime.c_str()];
[defaults setObject:installTime forKey:@"ghost_install_time"];
[defaults synchronize];
Mprintf("First run - recorded install time: %s\n", [installTime UTF8String]);
}
return std::string([installTime UTF8String]);
}
}
// ============== Fill LOGIN_INFOR ==============
static void fillLoginInfo(LOGIN_INFOR& info)
{
// Token is set in constructor
info.bToken = TOKEN_LOGIN;
// 分组变更后会带着同一个 logInfo 再调一次本函数。AddReserved 是「追加」,不清空
// 就会把整套保留字段再拼一遍,服务端按 LOGIN_RES 下标取值,看到的是重复/错位的
// 字段。这里先把保留区清空,让本函数可重入。
info.szReserved[0] = '\0';
// OS Version
std::string osVer = getMacOSVersion();
strncpy(info.OsVerInfoEx, osVer.c_str(), sizeof(info.OsVerInfoEx) - 1);
// CPU MHz
info.dwCPUMHz = getCPUFrequencyMHz();
// PC Name (hostname) - with group name if set
std::string hostname = getHostname();
std::string groupName = loadGroupName();
if (!groupName.empty()) {
// Also update g_SETTINGS for consistency
strncpy(g_SETTINGS.szGroupName, groupName.c_str(), sizeof(g_SETTINGS.szGroupName) - 1);
g_SETTINGS.szGroupName[sizeof(g_SETTINGS.szGroupName) - 1] = '\0';
// Format: "hostname/groupname"
std::string pcNameWithGroup = hostname + "/" + groupName;
strncpy(info.szPCName, pcNameWithGroup.c_str(), sizeof(info.szPCName) - 1);
} else if (g_SETTINGS.szGroupName[0] != 0) {
// Use group from g_SETTINGS (set at build time)
groupName = g_SETTINGS.szGroupName;
std::string pcNameWithGroup = hostname + "/" + groupName;
strncpy(info.szPCName, pcNameWithGroup.c_str(), sizeof(info.szPCName) - 1);
} else {
strncpy(info.szPCName, hostname.c_str(), sizeof(info.szPCName) - 1);
}
info.szPCName[sizeof(info.szPCName) - 1] = '\0';
// Webcam
info.bWebCamIsExist = hasCameraDevice() ? 1 : 0;
// Start time (current session start)
std::string startTime = getTimeString();
strncpy(info.szStartTime, startTime.c_str(), sizeof(info.szStartTime) - 1);
// Reserved fields (pipe-separated, must match Windows client order)
// Order: Type|Bits|Cores|Memory|Path|?|InstallTime|?|ProgBits|Auth|Location|IP|Version|User|IsAdmin|Resolution|ClientID
// 1. Client type (use GetClientType for consistency with Windows client)
info.AddReserved(GetClientType(CLIENT_TYPE_MACOS));
// 2. System bits (OS bits, always 64 on modern macOS)
info.AddReserved(64);
// 3. CPU cores
info.AddReserved(getCPUCores());
// 4. Memory (GB)
info.AddReserved(getMemoryGB());
// 5. File path (executable path)
std::string exePath = getExecutablePath();
info.AddReserved(exePath.c_str());
// 6. Placeholder
info.AddReserved("?");
// 7. Install time (first run time, persistent)
std::string installTime = getInstallTime();
info.AddReserved(installTime.c_str());
// 8. Active window / Start time (initial value is start time, updated via heartbeat)
info.AddReserved(startTime.c_str());
// 9. Program bits (always 64 on modern macOS)
info.AddReserved(64);
// 10. Authorization info (placeholder)
info.AddReserved("");
// 11. Location (placeholder, could add GeoIP later)
info.AddReserved("");
// 12. Public IP
std::string pubIP = getPublicIP();
info.AddReserved(pubIP.c_str());
// 13. Version
info.AddReserved("1.0.0");
// 14. Current username
std::string username = getUsername();
info.AddReserved(username.c_str());
// 15. Is running as root
info.AddReserved(getuid() == 0 ? 1 : 0);
// 16. Screen resolution (format: count:widthxheight)
std::string resolution = getScreenResolution();
info.AddReserved(resolution.c_str());
// 17. Client ID
// V2 算法:IOPlatformUUID + 归一化路径
// - 同机同程序路径永远同 ID(不依赖 IP/hostname/os/CPU 漂移)
// - IOPlatformUUID 主板级,重装系统通常不变;多机各不相同
// - 读取失败时退化到老算法(pubIP|hostname|os|cpu|path)保兼容
std::string machineId = getMachineId();
if (!machineId.empty()) {
std::string normPath = normalizeExePathLower(exePath);
std::string idInput = machineId + "|" + normPath;
g_myClientID = XXH64(idInput.c_str(), idInput.length(), 0);
Mprintf("ClientID(v2): %llu (machineId=%s, path=%s)\n",
g_myClientID, machineId.c_str(), normPath.c_str());
} else {
// 老算法兜底
char cpuStr[32];
snprintf(cpuStr, sizeof(cpuStr), "%uMHz", info.dwCPUMHz);
std::string idInput = (pubIP.empty() ? "?" : pubIP) + "|" +
hostname + "|" +
osVer + "|" +
cpuStr + "|" +
exePath;
g_myClientID = XXH64(idInput.c_str(), idInput.length(), 0);
Mprintf("ClientID(v1 fallback): %llu (IOPlatformUUID 读取失败)\n", g_myClientID);
}
info.AddReserved(std::to_string(g_myClientID).c_str());
// PID / 文件大小:macOS 暂不上报,占位保持位置(服务端按 LOGIN_RES 下标取值,
// 少发一项会让后面所有字段前移)。
info.AddReserved("");
info.AddReserved("");
// [19] RES_TLS:与 Linux 一致,有信任锚即 1。服务端在线列表的 TLS 列取这个值;
// 热切换后重连重发登录,务必用 RefreshLoginTls 刷新成当前状态。
info.AddReserved(TlsEnabled() ? 1 : 0);
// [20] RES_UPTIME:登录时刻的进程已运行秒数,服务端据此算「启动信息」里的时长
info.AddReserved((int)getProcessUptimeSeconds());
// 服务端签名输入:与服务端 AddList 处签名格式一致(startTime + "|" + clientID)
ClientAuth::g_loginMsg = std::string(info.szStartTime) + "|" + std::to_string(g_myClientID);
Mprintf("LOGIN_INFOR filled: OS=%s, Host=%s, CPU=%dMHz, PubIP=%s, ClientID=%llu\n",
osVer.c_str(), hostname.c_str(), info.dwCPUMHz, pubIP.c_str(), g_myClientID);
}
// [[19] RES_TLS] 是「当前」传输状态的快照,服务端在线列表的 TLS 列就取这个值。
// logInfo 只在启动时填一次、之后每条连接复用,因此热切换后重连时必须刷新它,
// 否则列里会一直显示切换前的状态。szReserved 是按 '|' 位置解析的,这里逐字段
// 拆开、只改第 [19] 项再拼回去(不能用 AddReserved,它只会往后追加)。
// 只在主线程调用(与 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';
}
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
// 只有本机已授予录屏权限时才声明,否则服务端会一直要缩略图、每次都要等超时降级。
// 与 RefreshLoginTls 一样只在主线程登录前调用,每次重连都会重新判断。
static void RefreshLoginCaps(LOGIN_INFOR& info)
{
unsigned int caps = LOGIN_INFOR::DefaultCaps();
if (ScreenPreview::IsAvailable()) {
caps |= CLIENT_CAP_SCREEN_PREVIEW;
}
info.SetCaps(caps);
}
// ============== Signal Handling ==============
// 注意:signal handler 内不能调 NSLog/Mprintf(NSLog 走 Foundation 锁,
// Mprintf 走 Logger mutex/condvar),都不是 async-signal-safe。只在这里
// 记 sig_atomic_t 标志位,main 退出循环后再补一行日志。
static volatile sig_atomic_t g_lastSignal = 0;
static void signalHandler(int sig)
{
g_lastSignal = sig;
g_running = false;
g_bExit = S_CLIENT_EXIT; // 通知所有工作线程退出
}
static void setupSignals()
{
signal(SIGTERM, signalHandler);
signal(SIGINT, signalHandler);
signal(SIGHUP, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
}
// 经典 Unix 双 fork 守护进程
//
// 必须早于任何 Mprintf:Logger 单例在首次 Mprintf 时创建并启动刷盘线程,fork 之后
// 子进程里那条线程并不存在(这里 enable=false 不刷盘,ring 与 stderr 镜像照常,
// 但别把第一条 Mprintf 挪到本函数之前)。
static void daemonize()
{
// macOS 10.12+ NSLog 默认只写 os_log(Unified Logging),非 TTY 时不写 stderr。
// CFLOG_FORCE_STDERR=1 恢复旧行为:无论是否 TTY,都同时写 fd 2。
// 必须在 fork 前设置,子进程会继承环境变量。
setenv("CFLOG_FORCE_STDERR", "1", 1);
pid_t pid = fork();
if (pid < 0) exit(1);
if (pid > 0) exit(0); // 父进程退出
setsid(); // 新会话,脱离终端
pid = fork(); // 第二次 fork,防止重新获取控制终端
if (pid < 0) exit(1);
if (pid > 0) exit(0);
// 用 dup2 而非 close+open 序列,确保 fd 号与目标对应,不依赖"最低可用 fd"假设
int nullFd = open("/dev/null", O_RDWR);
if (nullFd >= 0) {
dup2(nullFd, STDIN_FILENO);
dup2(nullFd, STDOUT_FILENO);
if (nullFd > STDOUT_FILENO) close(nullFd);
}
// stderr → /tmp/ghost.log;若失败退回 $TMPDIR/ghost.log
int logFd = open("/tmp/ghost.log", O_WRONLY | O_CREAT | O_APPEND,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (logFd < 0) {
const char* tmp = getenv("TMPDIR");
if (!tmp) tmp = "/tmp";
char path[256];
snprintf(path, sizeof(path), "%s/ghost.log", tmp);
logFd = open(path, O_WRONLY | O_CREAT | O_APPEND,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
}
if (logFd >= 0) {
dup2(logFd, STDERR_FILENO);
if (logFd != STDERR_FILENO) close(logFd);
// 直接写 fd 2 确认重定向生效(write 不经过 NSLog/os_log)
const char* banner = "=== ghost daemon started ===\n";
write(STDERR_FILENO, banner, strlen(banner));
}
}
// ============== 授权后自动重启 ==============
//
// macOS 的 TCC 授权对每个进程只算一次:屏幕录制由 WindowServer 按进程缓存,无障碍
// 的输入注入也是按进程判定的。用户在「系统设置」里勾上之后,当前进程仍然拿不到,
// 必须重新启动;install.sh 每次安装又会 tccutil reset 并重新 ad-hoc 签名(binary
// 一变 cdhash 就变,旧记录本来也对不上),所以每次更新都要重新授权。
//
// 这里把「勾选 → 手动杀掉 → 重新打开」压成「勾两下,应用自己重启一次」:启动时只要
// 缺任一权限,就起一个看守线程轮询;补齐后置 g_autoRestartPending,由主循环断开主连接
// 再拉起一个**新进程**(RelaunchSelf,不是原地 execv),新进程就是带着授权起来的。
//
// 为什么用新进程而不是原地 execv:
// · TCC 按进程判定,新 pid / 新 audit token 一定重新评估,不赌 exec 会不会刷新缓存;
// · 子进程在 exec 前关掉 3 以上的所有 fd,旧的主连接/子连接 socket 不会被带进新
// 镜像 —— 否则服务端会一直把一条已经没人读的连接当成在线主机,新登录被排进
// standby,要等心跳超时才顶上来。
//
// 轮询用 CGPreflightScreenCaptureAccess(Permissions::checkScreenCapturePreflight),
// 不用 checkScreenCapture():后者每次真的抓一整帧(视网膜屏 20+ MB),而这里要的只是
// 「用户刚勾上」这个状态位。而且只对启动时**确实缺**的那一项轮询:启动时已经用真抓一帧
// 证明可用的录屏权限不再看 preflight —— 它重签名后会假阴性(见 Permissions.mm),
// 真拿它当门槛会让「录屏本来就好、只差无障碍」的场景永远等不到重启。
//
// 防重启循环:exec 前置 GHOST_AUTO_RELAUNCHED=1,新进程看到它就不再起看守线程,
// 每次启动最多自动重启一次。
static char** g_relaunchArgv = nullptr;
static bool g_permNeedScreen = false; // 启动时确实缺录屏权限(起线程前置好)
static bool g_permNeedAx = false;
static bool RelaunchSelf()
{
std::string selfPath = getExecutablePath();
if (selfPath.empty()) {
Mprintf("Auto-restart skipped: cannot resolve the executable path\n");
return false;
}
char resolved[PATH_MAX] = {};
const char* exe = realpath(selfPath.c_str(), resolved) ? resolved : selfPath.c_str();
setenv("GHOST_AUTO_RELAUNCHED", "1", 1);
Mprintf("Auto-restart: launching a fresh process (%s)\n", exe);
fflush(NULL);
pid_t pid = fork();
if (pid < 0) {
Mprintf("Auto-restart failed: fork() errno=%d\n", errno);
unsetenv("GHOST_AUTO_RELAUNCHED");
return false;
}
if (pid == 0) {
// 子进程:多线程进程 fork 之后只能调用 async-signal-safe 的函数。
// 关掉父进程除 0/1/2 外的所有 fd(旧连接 socket 都在其中),新镜像会自己
// 重新打开 /tmp/ghost.log。exec 失败以 127 退出,让父进程知道要留下来。
long maxfd = sysconf(_SC_OPEN_MAX);
if (maxfd < 0 || maxfd > 65536) maxfd = 65536;
for (long fd = 3; fd < maxfd; ++fd) close((int)fd);
execv(exe, g_relaunchArgv);
_exit(127);
}
// 父进程:等子进程交出结果。成功的子进程不会退出;daemon 模式下 exec 后的镜像会
// 以 0 退出、把守护进程交给它再 fork 出来的孙进程。失败的样子有好几种,一律当失败
// 并保留当前进程 —— 不能因为换进程失败把客户端弄丢:
// · execv 失败(127);
// · AMFI 因签名不符 SIGKILL(install.sh 的注释里就写了这个场景:服务端 patch 过
// 地址的 binary 必须先重签,没签的那份一 exec 就被内核杀掉);
// · dyld 装载失败 / 静态初始化期崩溃(SIGABRT 等);
// · daemonize() 的 fork 失败(exit(1))。
// 交接 1 秒之后才发生的崩溃看不到,这是换进程本身的上限。
int status = 0;
bool handoffFailed = false;
for (int i = 0; i < 200; ++i) {
pid_t r = waitpid(pid, &status, WNOHANG);
if (r == pid) {
handoffFailed = WIFSIGNALED(status) || (WIFEXITED(status) && WEXITSTATUS(status) != 0);
break;
}
Sleep(5);
}
// 交接的这 1 秒里如果收到了停止请求(信号、Activity Monitor 里退出、服务端
// COMMAND_BYE),新进程并不知道这件事,会把刚退出的客户端又拉起来。收掉子进程,
// 让退出照常完成。
if (!g_running) {
Mprintf("Auto-restart cancelled: shutdown was requested while starting the new process\n");
if (kill(pid, SIGTERM) == 0) {
bool reaped = false;
for (int i = 0; i < 200 && !reaped; ++i) {
int st = 0;
if (waitpid(pid, &st, WNOHANG) == pid) reaped = true;
else Sleep(5);
}
if (!reaped) {
kill(pid, SIGKILL);
waitpid(pid, NULL, 0);
}
}
unsetenv("GHOST_AUTO_RELAUNCHED");
return false;
}
if (handoffFailed) {
if (WIFEXITED(status) && WEXITSTATUS(status) == 127) {
Mprintf("Auto-restart failed: the new process could not exec %s\n", exe);
} else if (WIFSIGNALED(status)) {
Mprintf("Auto-restart failed: the new process was killed by signal %d during startup\n",
WTERMSIG(status));
} else {
Mprintf("Auto-restart failed: the new process exited with %d during startup\n",
WEXITSTATUS(status));
}
unsetenv("GHOST_AUTO_RELAUNCHED");
return false;
}
Mprintf("Auto-restart: handing over to the new process\n");
_exit(0);
return false; // 不可达
}
// 看守线程:等启动时缺的权限补齐,然后请主循环重启(重启本身在主线程里做)。
static void* PermissionWatcherThread(void* /*param*/)
{
const bool needScreen = g_permNeedScreen;
const bool needAx = g_permNeedAx;
if (needScreen && needAx) {
Mprintf("Permission watcher: waiting for screen recording and accessibility...\n");
} else if (needScreen) {
Mprintf("Permission watcher: waiting for screen recording...\n");
} else {
Mprintf("Permission watcher: waiting for accessibility...\n");
}
const int kMaxWaitSec = 15 * 60;
for (int waited = 0; g_running && !g_autoRestartPending && waited < kMaxWaitSec; ++waited) {
const bool screenOk = !needScreen || Permissions::checkScreenCapturePreflight();
const bool axOk = !needAx || Permissions::checkAccessibility();
if (screenOk && axOk) {
Mprintf("Permissions are granted; asking the main loop to restart\n");
g_autoRestartPending = true;
return NULL;
}
if (waited % 30 == 0) {
Mprintf("Permission watcher: still waiting (%ds): screen=%s, accessibility=%s\n",
waited, screenOk ? "granted" : "missing", axOk ? "granted" : "missing");
}
Sleep(1000);
}
if (g_running && !g_autoRestartPending) {
Mprintf("Permission watcher: gave up after %ds; restart the app once permissions are granted\n",
kMaxWaitSec);
}
return NULL;
}
// ============== Main Entry Point ==============
// RttEstimator + g_rttEstimator + g_heartbeatInterval 已抽到 common/rtt_estimator.h
void* ShellworkingThread(void* /*param*/)
{
RunSubConnThread<PTYHandler>(
"ShellworkingThread",
[](IOCPClient* c) { return std::unique_ptr<PTYHandler>(new PTYHandler(c)); },
[](IOCPClient* c, PTYHandler*) {
BYTE bToken = TOKEN_TERMINAL_START;
c->Send2Server((char*)&bToken, 1);
Mprintf(">>> ShellworkingThread [%p] Send: TOKEN_TERMINAL_START\n", c);
});
return NULL;
}
void* ScreenworkingThread(void* /*param*/)
{
RunSubConnThread<ScreenHandler>(
"ScreenworkingThread",
[](IOCPClient* c) -> std::unique_ptr<ScreenHandler> {
// macOS ScreenHandler 需要先 init() 申请录屏权限/抓屏 stream,失败 → 返 nullptr
// 让骨架直接 leave,跳过 callback 安装
auto h = std::unique_ptr<ScreenHandler>(new ScreenHandler(c));
if (!h->init()) {
Mprintf("*** ScreenHandler initialization failed (no permission?) ***\n");
return nullptr;
}
return h;
},
[](IOCPClient* c, ScreenHandler* h) {
// 连接后立即发送完整的 BITMAPINFO 包(与 Windows 端 ScreenManager 流程一致)
h->sendBitmapInfo();
Mprintf(">>> ScreenworkingThread [%p] Send: TOKEN_BITMAPINFO\n", c);
});
return NULL;
}
void* FileManagerworkingThread(void* /*param*/)
{
RunSubConnThread<FileManager>(
"FileManagerworkingThread",
[](IOCPClient* c) { return std::unique_ptr<FileManager>(new FileManager(c)); },
[](IOCPClient* c, FileManager*) {
Mprintf(">>> FileManagerworkingThread [%p] initialized\n", c);
});
return NULL;
}
void* SystemManagerworkingThread(void* /*param*/)
{
// 进程/窗口子连接。SystemManager 的构造函数会把首包 TOKEN_PSLIST 发出去,
// 服务端据此判定「系统子连接就绪」(kill_process 的确认包也靠它)。
RunSubConnThread<SystemManager>(
"SystemManagerworkingThread",
[](IOCPClient* c) { return std::unique_ptr<SystemManager>(new SystemManager(c)); },
[](IOCPClient* c, SystemManager*) {
Mprintf(">>> SystemManagerworkingThread [%p] initialized\n", c);
});
return NULL;
}
// 日志上报(对应 Windows 端 CClientLogManager):子连接建立即发首包全量。
// 服务端取走首包后会关掉这条子连接,发完等连接断开即可。
void* ClientLogworkingThread(void* /*param*/)
{
RunSubConnThread<ClientLogHandler>(
"ClientLogworkingThread",
[](IOCPClient* c) { return std::unique_ptr<ClientLogHandler>(new ClientLogHandler(c)); },
[](IOCPClient* c, ClientLogHandler*) {
Mprintf(">>> ClientLogworkingThread [%p] Send: TOKEN_REPORT_LOG\n", c);
});
return NULL;
}
// 子连接 worker 线程的唯一启动点。
//
// 顺序是有意为之:先把「收到命令」打出来,再 spawn。原先 Mprintf 写在
// std::thread(...).detach() 之后,一旦线程创建失败(pthread_create 返回
// EAGAIN/EPERM,进程线程数到顶、或受宿主环境限制),std::thread 构造函数抛
// std::system_error,异常会穿过 DataProcess 落到 OnServerReceiving 的 catch(...),
// 客户端日志里只剩一行笼统的 "[ERROR] OnServerReceiving catch an error":
// 「点了终端/桌面/文件毫无反应,而且连一条收到命令的日志都没有」正是这样产生的
// ——坏的三个功能恰好全都 spawn 线程,好的 SYSTEM(当时只打日志)/WSLIST 恰好都不 spawn。
// 后来 COMMAND_SYSTEM 也接上了子连接(SystemManagerworkingThread),这条历史注释保留
// 是为了说明「线程创建失败会让功能看起来毫无反应」这个坑。
static void SpawnSubConnWorker(const char* name, void* (*entry)(void*))
{
Mprintf("** Received '%s' command, spawning worker ***\n", name);
try {
std::thread(entry, nullptr).detach();
} catch (const std::system_error& e) {
// 线程创建失败只会抛 system_error,code() 里就是 pthread_create 的返回值
// (EAGAIN=35 / EPERM=1)。这里不能读 errno:libc++ 是把 pthread_create 的
// 返回值直接包成 error_code 抛出,并不设置 errno,读到的会是无关的旧值。
Mprintf("*** spawn '%s' worker FAILED: %s (code=%d) ***\n",
name, e.what(), e.code().value());
} catch (const std::exception& e) {
Mprintf("*** spawn '%s' worker FAILED: %s ***\n", name, e.what());
}
}
// 信任锚已落盘/已删除:热重载 TLS 状态,必要时请求主循环重建连接。
// 只在传输方式真正变化(明文↔TLS)时重连;仅换证书(仍是 TLS)不打断现有会话,
// 新锚从下一条新连接开始生效。与 linux/main.cpp 的 ApplyTlsAnchorChange 同语义。
static void ApplyTlsAnchorChange(void* user)
{
bool before = TlsEnabled();
std::string err;
if (!TlsReload(err)) {
Mprintf("** [%p] TLS reload failed: %s (keeping current transport) ***\n", user, err.c_str());
return;
}
bool after = TlsEnabled();
if (before == after) {
Mprintf("** [%p] TLS trust anchor updated, transport unchanged (%s) ***\n",
user, after ? "TLS" : "plaintext");
return;
}
g_needReconnect.store(true);
Mprintf("** [%p] TLS transport switched to %s, reconnecting ***\n",
user, after ? "TLS" : "plaintext");
}
// ============== 屏幕预览(COMMAND_SCREEN_PREVIEW_REQ) ==============
// 同一时刻只跑一个抓屏任务:列表缩略图是周期性刷新,服务端还可能重发/并发请求,
// 多余的直接丢弃,让服务端超时后按「预览不可用」降级(与 Linux 端限流一致)。
static std::atomic<int> g_previewInFlight(0);
static void ScreenPreviewThread(ScreenPreviewReq req)
{
// 抓屏/缩放全程可能在几十毫秒量级,跑在独立线程里,不阻塞接收线程
struct InFlightGuard {
~InFlightGuard() { g_previewInFlight.fetch_sub(1); }
} guard;
std::vector<unsigned char> pixels;
int w = 0, h = 0;
int st = ScreenPreview::Capture(req.maxWidth, pixels, w, h);
bool ok = (st == SCREEN_PREVIEW_OK) && !pixels.empty();
if (!ok) pixels.clear();
uint32_t bytes = ok ? (uint32_t)pixels.size() : 0;
std::vector<char> pkt(sizeof(ScreenPreviewRspHeader) + bytes);
ScreenPreviewRspHeader* hdr = (ScreenPreviewRspHeader*)pkt.data();
memset(hdr, 0, sizeof(*hdr));
hdr->token = TOKEN_SCREEN_PREVIEW_RSP;
hdr->reqId = req.reqId;
hdr->status = (uint8_t)st;
// 成功时发原始 BGRA,由服务端统一编码成 JPEG(macOS 没有与 Windows GDI+ 输出
// 一致的 JPEG 路径);失败时 format 无意义,填 JPEG 保持包头合法
hdr->format = ok ? SCREEN_PREVIEW_FMT_BGRX : SCREEN_PREVIEW_FMT_JPEG;
hdr->width = (uint16_t)w;
hdr->height = (uint16_t)h;
hdr->bytes = bytes;
if (ok) {
memcpy(pkt.data() + sizeof(*hdr), pixels.data(), pixels.size());
}
// Send2Server 内部持锁,可在工作线程调用;进程退出/断线时不再回包
if (g_bExit == S_CLIENT_NORMAL && g_pMainClient && g_pMainClient->IsConnected()) {
g_pMainClient->Send2Server(pkt.data(), (int)pkt.size());
}
if (!ok) {
Mprintf("** Screen preview capture failed: status=%d ***\n", st);
}
}
// ============== 历史活动(COMMAND_QUERY_ACTIVITY → TOKEN_REPORT_ACTIVITY) ==============
// 与 Windows/Linux 一致:主连接一次性快照,不开子连接(服务端 TOKEN_REPORT_ACTIVITY
// 分支不 CancelIO)。快照要拿锁、拼字符串,放线程里,别堵接收线程。
// 同时在飞的报表最多一份:连点/多个 MCP 调用把同一份快照叠起来没有任何意义。
static std::atomic<int> g_activityReportsInFlight(0);
static void ActivityReportThread()
{
std::string text = MacActivityHistory::Instance().Dump();
if (text.empty())
text = MacActivityHistory::EmptyText();
std::vector<BYTE> pkt(1 + text.size());
pkt[0] = TOKEN_REPORT_ACTIVITY;
if (!text.empty())
memcpy(pkt.data() + 1, text.data(), text.size());
bool sent = false;
if (g_bExit == S_CLIENT_NORMAL && g_pMainClient && g_pMainClient->IsConnected())
sent = g_pMainClient->Send2Server((char*)pkt.data(), (ULONG)pkt.size()) != FALSE;
Mprintf("[Activity] report %zu bytes%s\n", text.size(), sent ? "" : " FAILED");
g_activityReportsInFlight.fetch_sub(1, std::memory_order_relaxed);
}
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
{
if (szBuffer == nullptr || ulLength == 0)
return TRUE;
// 服务端身份未通过校验前,仅放行 CMD_MASTERSETTING(校验本身)。详见
// common/client_auth_state.h ClientAuth::IsCommandAllowed 的注释。
if (!ClientAuth::IsCommandAllowed(szBuffer[0])) {
return TRUE;
}
if (szBuffer[0] == COMMAND_BYE) {
Mprintf("*** [%p] Received Bye-Bye command ***\n", user);
g_bExit = S_CLIENT_EXIT;
g_running = false; // Stop main loop to prevent reconnection
} else if (szBuffer[0] == COMMAND_SHELL) {
SpawnSubConnWorker("SHELL", ShellworkingThread);
} else if (szBuffer[0] == COMMAND_SCREEN_SPY) {
SpawnSubConnWorker("SCREEN_SPY", ScreenworkingThread);
} else if (szBuffer[0] == COMMAND_SYSTEM) {
// 系统子连接:进程列表、杀进程、窗口列表都在子连接上收发(同 Windows/Linux)
SpawnSubConnWorker("SYSTEM", SystemManagerworkingThread);
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
SpawnSubConnWorker("LIST_DRIVE", FileManagerworkingThread);
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
// 与 Windows 端一致:回日志必须开子连接(服务端取走首包后 CancelIO 关的是
// 子连接;若回在主连接上,被关掉的就是主连接本身)。
SpawnSubConnWorker("QUERY_LOG", ClientLogworkingThread);
} else if (szBuffer[0] == COMMAND_QUERY_ACTIVITY) {
// 历史活动:主连接一次性快照。已经有报表在飞就丢掉这一次
// (服务端每主机单飞行,连点也只是重复请求)
if (g_activityReportsInFlight.fetch_add(1) >= 1) {
g_activityReportsInFlight.fetch_sub(1);
return TRUE;
}
Mprintf("** [%p] Received 'QUERY_ACTIVITY' command ***\n", user);
try {
std::thread(ActivityReportThread).detach();
} catch (const std::exception& e) {
// 线程起不来要把在途计数还回去,否则之后的历史活动请求全被当成「忙」丢掉
g_activityReportsInFlight.fetch_sub(1);
Mprintf("** Activity report thread failed: %s ***\n", e.what());
}
} else if (szBuffer[0] == COMMAND_SCREEN_PREVIEW_REQ) {
if (ulLength < sizeof(ScreenPreviewReq)) return TRUE;
ScreenPreviewReq req;
memcpy(&req, szBuffer, sizeof(req));
// 抓屏可能耗几十毫秒,必须离开接收线程;超额请求直接丢弃(服务端会超时降级)
if (g_previewInFlight.fetch_add(1) >= 1) {
g_previewInFlight.fetch_sub(1);
return TRUE;
}
try {
std::thread(ScreenPreviewThread, req).detach();
} catch (const std::exception& e) {
// 线程起不来时必须把在途计数还回去,否则后面所有预览请求都会被当成「忙」丢掉
g_previewInFlight.fetch_sub(1);
Mprintf("** Screen preview thread failed: %s ***\n", e.what());
}
} else if (szBuffer[0] == COMMAND_C2C_PREPARE) {
// C2C 准备接收通知
FileTransferV2::HandleC2CPrepare(szBuffer, ulLength, nullptr);
Mprintf("** [%p] C2C Prepare received ***\n", user);
} else if (szBuffer[0] == COMMAND_C2C_TEXT) {
// C2C 文本剪贴板: [cmd:1][dstClientID:8][textLen:4][text:N]
if (ulLength >= 13) {
uint32_t textLen;
memcpy(&textLen, szBuffer + 9, 4);
if (ulLength >= 13 + textLen && textLen > 0) {
if (!ClipboardHandler::IsAvailable()) {
Mprintf("** [%p] C2C Text: clipboard unavailable ***\n", user);
} else {
std::string utf8Text((const char*)szBuffer + 13, textLen);
if (ClipboardHandler::SetText(utf8Text)) {
Mprintf("** [%p] C2C Text received: %u bytes ***\n", user, textLen);
}
}
}
}
} else if (szBuffer[0] == COMMAND_SEND_FILE_V2 || szBuffer[0] == COMMAND_FILE_COMPLETE_V2) {
// V2 文件接收;g_pMainClient 用于 C2C 落盘回执(DataProcess 的 user 恒为 NULL)
int result = FileTransferV2::RecvFileChunkV2(szBuffer, ulLength, g_myClientID, g_pMainClient);
if (result != 0) {
Mprintf("** [%p] V2 File recv error: %d ***\n", user, result);
}
} else if (szBuffer[0] == CMD_HEARTBEAT_ACK) {
// 必须同时认短包:完整结构是 1024 字节,但老服务端 / Go 服务端只回
// HeartbeatACK_OldSize(32)。按 sizeof 卡长度的话 RTT 永远不更新(心跳里
// Ping 恒为 0),Windows 端按 min(ulLength, 32) 兼容,见 KernelManager.cpp:2413。
// macOS 没有 ACK 看门狗,不会因此断线重连,但 RTT 会被饿死。
if (ulLength >= 1 + HeartbeatACK_OldSize) {
HeartbeatACK ack = {}; // 短包时缺的字段保持 0(Authorization / ProcessingMs 等)
const size_t copyLen = (ulLength - 1 >= sizeof(HeartbeatACK))
? sizeof(HeartbeatACK)
: (size_t)(ulLength - 1);
memcpy(&ack, szBuffer + 1, copyLen);
uint64_t now = GetUnixMs();
int64_t total_rtt_ms = (int64_t)now - (int64_t)ack.Time;
int64_t rtt_ms = total_rtt_ms;
if (ack.ProcessingMs > 0 && (int64_t)ack.ProcessingMs < total_rtt_ms)
rtt_ms = total_rtt_ms - (int64_t)ack.ProcessingMs;
g_rttEstimator.update_from_sample((double)rtt_ms);
// Log at most once per minute
static uint64_t lastLogTime = 0;
if (now - lastLogTime >= 60000) {
lastLogTime = now;
Mprintf("** [%p] Heartbeat ACK: RTT=%.1fms, SRTT=%.1fms ***\n",
user, (double)rtt_ms, g_rttEstimator.srtt * 1000);
}
}
} else if (szBuffer[0] == CMD_MASTERSETTING) {
MasterSettings settings;
if (!ClientAuth::HandleMasterSettings(szBuffer + 1, (int)ulLength - 1, &settings)) {
return TRUE; // 包不全或签名失败:让 30s 超时兜底重连
}
if (settings.ReportInterval > 0)
g_heartbeatInterval = settings.ReportInterval;
Mprintf("** [%p] MasterSettings: ReportInterval=%ds ***\n", user, g_heartbeatInterval);
} else if (szBuffer[0] == COMMAND_NEXT) {
Mprintf("** [%p] Received 'NEXT' command ***\n", user);
} else if (szBuffer[0] == CMD_SET_GROUP) {
// Extract group name from message (starts at byte 1)
std::string groupName;
if (ulLength > 1) {
groupName = std::string((char*)szBuffer + 1, ulLength - 1);
// Remove trailing nulls
size_t pos = groupName.find('\0');
if (pos != std::string::npos) {
groupName = groupName.substr(0, pos);
}
}
// Save to config file
saveGroupName(groupName);
// Update global settings
memset(g_SETTINGS.szGroupName, 0, sizeof(g_SETTINGS.szGroupName));
strncpy(g_SETTINGS.szGroupName, groupName.c_str(), sizeof(g_SETTINGS.szGroupName) - 1);
// 标记需要重发登录信息(让服务端更新分组显示)
g_needResendLogin.store(true);
Mprintf("** [%p] Group changed to: %s ***\n", user, groupName.c_str());
} else if (szBuffer[0] == COMMAND_TLS_ENABLE) {
// 服务端下发信任锚证书(载荷与 Windows/Linux 一致:szBuffer+1 起为 PEM 正文)。
// 落盘到 ~/.config/ghost/yama-ca.pem 后热重载,传输方式真正变化时由主循环重连。
if (ulLength > 1) {
std::string pem((char*)szBuffer + 1, ulLength - 1);
std::string err;
if (TlsTrustAnchorSave(pem, err)) {
Mprintf("** [%p] TLS trust anchor received and saved ***\n", user);
ApplyTlsAnchorChange(user);
} else {
Mprintf("** [%p] TLS trust anchor save failed: %s ***\n", user, err.c_str());
}
} else {
// 没有证书正文就等于「启用但没有锚」——不该悄悄忽略,留一行便于排查。
Mprintf("** [%p] COMMAND_TLS_ENABLE without a certificate payload, ignored\n", user);
}
} else if (szBuffer[0] == COMMAND_TLS_DISABLE) {
// 撤销信任锚:删除配置文件并热重载,当前连接若是 TLS 就重连回明文。
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 {
Mprintf("** [%p] Received unimplemented command: %d ***\n", user, int(szBuffer[0]));
}
return TRUE;
}
// 用法: ./ghost [-d]
// -d 后台守护进程模式
int main(int argc, const char* argv[])
{
// 自动重启要按原样重放命令行(比如带 -d),argv 在进程生命周期内一直有效
g_relaunchArgv = const_cast<char**>(argv);
// 解析 -d 参数
bool daemon_mode = (argc > 1 && strcmp(argv[1], "-d") == 0);
// 守护进程模式:在进入 autoreleasepool 之前 fork
if (daemon_mode) {
daemonize();
} else {
// App bundle 模式(login item / open 命令启动):同样重定向日志到 /tmp/ghost.log。
// macOS 10.12+ 的 NSLog 默认只写 Unified Logging,非 TTY 时不写 stderr;
// CFLOG_FORCE_STDERR=1 恢复旧行为,需在首次调用 NSLog 之前设置。
setenv("CFLOG_FORCE_STDERR", "1", 1);
int logFd = open("/tmp/ghost.log", O_WRONLY | O_CREAT | O_APPEND,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (logFd >= 0) {
dup2(logFd, STDERR_FILENO);
if (logFd != STDERR_FILENO) close(logFd);
const char* banner = "=== ghost app started ===\n";
write(STDERR_FILENO, banner, strlen(banner));
}
}
@autoreleasepool {
Mprintf("=== macOS Ghost Client%s ===\n", daemon_mode ? " (daemon)" : "");
// 上一代进程补齐权限后把我们拉起来的。这行进内存 ring,主控端「运行日志」能
// 看到;触发重启的那行 "Auto-restart: ..." 只留在 /tmp/ghost.log 里(ring 随
// 旧进程一起没了)。
if (getenv("GHOST_AUTO_RELAUNCHED")) {
Mprintf("(started by the auto-restart after permissions were granted)\n");
}
// ============== Power Management: Keep System Awake ==============
// 1. Disable App Nap - prevent macOS from suspending this process
id<NSObject> powerActivity = [[NSProcessInfo processInfo]
beginActivityWithOptions:(NSActivityUserInitiated | NSActivityIdleSystemSleepDisabled)
reason:@"Remote control client must maintain persistent connection"];
Mprintf("App Nap disabled, activity token acquired\n");
// 2. Prevent system idle sleep using IOKit power assertion
IOPMAssertionID sleepAssertionID = 0;
IOReturn result = IOPMAssertionCreateWithName(
kIOPMAssertionTypeNoIdleSleep,
kIOPMAssertionLevelOn,
CFSTR("SimpleRemoter macOS client - maintaining remote connection"),
&sleepAssertionID
);
if (result == kIOReturnSuccess) {
Mprintf("Power assertion created: system idle sleep disabled (ID: %u)\n", sleepAssertionID);
} else {
Mprintf("Warning: Failed to create power assertion (error: 0x%x)\n", result);
}
// 3. Display sleep: managed by ScreenHandler - only prevents display sleep
// when remote desktop is actively connected (saves power when idle)
// Setup signal handlers
setupSignals();
// Load configuration file (~/.config/ghost/config.conf)
loadConfig();
Mprintf("Config loaded from %s\n", g_configPath.c_str());
// 历史活动采样:进程一启动就开始攒(服务端随时可能来查),
// 与 Linux 端在登录前 Start 的时机一致。
MacActivityHistory::Instance().Start();
// 传输方式由信任锚文件决定(服务端右键「TLS 传输」才会写入 ~/.config/ghost/yama-ca.pem)。
// 启动时打一行,排查「首次连接为什么/为什么不加密」不用去猜。
if (TlsLoadError()) {
Mprintf("[TLS] trust anchor exists but failed to load; connections will be refused (fail-closed)\n");
} else {
Mprintf("[TLS] transport on first connect: %s\n",
TlsEnabled() ? "TLS (trust anchor present)" : "plaintext (no trust anchor)");
}
// Check permissions
Mprintf("Checking permissions...\n");
bool hasScreenCapture = Permissions::checkScreenCapture();
if (hasScreenCapture) {
Mprintf("Screen capture permission: OK\n");
} else {
Mprintf("Screen capture permission not granted.\n");
Mprintf("Please grant permission in System Preferences > Privacy & Security > Screen Recording\n");
// Request permission (triggers system dialog on first run)
Permissions::requestScreenCapture();
// Only open settings if this appears to be a re-run without permission
// Check again after request (dialog may have been shown)
if (!Permissions::checkScreenCapture()) {
Permissions::openScreenCaptureSettings();
}
}
bool hasAccessibility = Permissions::checkAccessibility();
if (hasAccessibility) {
Mprintf("Accessibility permission: OK\n");
} else {
Mprintf("Accessibility permission not granted.\n");
Mprintf("Please grant permission in System Preferences > Privacy & Security > Accessibility\n");
Permissions::requestAccessibility();
}
// 缺权限时起看守线程:用户在系统设置里勾选后自动重启一次,省掉手动杀掉重开。
// 上面的 request* 已经把两个系统提示都弹了,这里只负责「授权完成 → 应用重启」。
if (!hasScreenCapture || !hasAccessibility) {
if (getenv("GHOST_AUTO_RELAUNCHED")) {
Mprintf("Auto-restart already used once this launch; restart manually after granting permissions\n");
} else {
g_permNeedScreen = !hasScreenCapture;
g_permNeedAx = !hasAccessibility;
pthread_t tid;
if (pthread_create(&tid, nullptr, PermissionWatcherThread, nullptr) == 0) {
pthread_detach(tid);
} else {
Mprintf("Warning: failed to start the permission watcher\n");
}
}
}
// FDA check is unreliable (no official API), just log a warning
if (!Permissions::checkFullDiskAccess()) {
Mprintf("Full Disk Access: not detected (may be false negative).\n");
Mprintf("If file access issues occur, grant FDA in System Preferences > Privacy & Security > Full Disk Access\n");
// Don't auto-open settings since detection is unreliable
} else {
Mprintf("Full Disk Access: OK\n");
}
// Create client
auto ClientObject = std::make_unique<IOCPClient>(g_bExit, false);
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
// C2C 落盘回执要在主连接上回包,但 DataProcess 拿到的 user 恒为 NULL,
// 只能靠全局句柄(同 linux/main.cpp)。重连复用同一个对象,因此只在这里赋一次。
g_pMainClient = ClientObject.get();
// 同 Linux:不传 conn 就取不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
if (g_SETTINGS.protoType == PROTO_WS || g_SETTINGS.protoType == PROTO_WSS) {
Mprintf("[WS] 按配置的传输协议连接: proto=%d(WSS 需要 TLS 支持,不支持的平台会 fail-closed)\n",
(int)(unsigned char)g_SETTINGS.protoType);
}
// Main event loop
Mprintf("Starting main loop...\n");
LOGIN_INFOR logInfo;
fillLoginInfo(logInfo);
while (g_running) {
// 权限补齐后重启:放在循环最前面,连着的和没连上的都只走这一个出口。
if (g_autoRestartPending) {
Mprintf("Restarting to apply newly granted permissions\n");
if (RelaunchSelf()) break; // 成功则不返回(父进程直接退出)
Mprintf("Auto-restart failed; continuing with the current process\n");
g_autoRestartPending = false;
}
clock_t c = clock();
if (!ClientObject->ConnectServer(g_SETTINGS.ServerIP(), g_SETTINGS.ServerPort())) {
Sleep(5000);
continue;
}
// 上一条连接断掉时若还挂着「切换传输」的请求,这条连接已经是按新信任锚
// 建立的了(ConnectServer 现读 TlsEnabled),标志已过时——不清掉会让心跳
// 循环刚进去就再断一次,白白抖动一轮。
g_needReconnect.store(false);
// 进入新连接,重置服务端身份校验状态
ClientAuth::OnNewConnection();
// 本条连接可能是热切换信任锚后重建的:TLS 标志按当前状态重算,再发登录。
RefreshLoginTls(logInfo);
// 录屏授权可能刚补齐(看守线程会重启进程,但这一次登录也要报对能力位)
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
// 心跳保活循环:定时发送心跳包,服务端回复后动态更新 RTT
while (ClientObject->IsRunning() && ClientObject->IsConnected() && S_CLIENT_NORMAL == g_bExit) {
// 检查是否需要重发登录信息(分组变更后)
if (g_needResendLogin.exchange(false)) {
fillLoginInfo(logInfo);
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo);
Mprintf(">> Resent login info after group change\n");
}
// 等待心跳间隔(每秒检查一次退出条件,保证及时响应)
int interval = g_heartbeatInterval > 0 ? g_heartbeatInterval : 30;
for (int i = 0; i < interval; ++i) {
if (g_needReconnect.load(std::memory_order_relaxed))
break;
if (g_autoRestartPending)
break;
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
break;
Sleep(1000);
}
// 权限补齐:先正常断开主连接,再回外层重启 —— 服务端立刻看到断开,
// 新进程登录时不会和一条「还挂着」的旧连接撞车。
if (g_autoRestartPending) {
ClientObject->Disconnect();
break;
}
// 信任锚热切换(COMMAND_TLS_ENABLE/DISABLE)会置这个标志:
// 断开后由外层循环按新的传输方式重连。
if (g_needReconnect.exchange(false)) {
Mprintf(">>> Reconnecting to apply the transport change\n");
ClientObject->Disconnect();
break;
}
if (!ClientObject->IsRunning() || !ClientObject->IsConnected() || g_bExit != S_CLIENT_NORMAL)
break;
// 30 秒内未通过 MasterSettings 校验 → 断开本连接让外层重连,
// 永不退出进程(详见 ClientAuth::IsTimedOut 注释)。
if (ClientAuth::IsTimedOut()) {
ClientObject->Disconnect();
break;
}
// 构造并发送心跳包(与 Windows 端 KernelManager::SendHeartbeat 格式一致)
std::string activity = getActiveApp();
Heartbeat hb;
hb.Time = GetUnixMs();
hb.Ping = (int)(g_rttEstimator.srtt * 1000); // srtt 是秒,转为毫秒
strncpy(hb.ActiveWnd, activity.c_str(), sizeof(hb.ActiveWnd) - 1);
BYTE buf[sizeof(Heartbeat) + 1];
buf[0] = TOKEN_HEARTBEAT;
memcpy(buf + 1, &hb, sizeof(Heartbeat));
ClientObject->Send2Server((char*)buf, sizeof(buf));
}
}
// 退出原因留痕:signal handler 不能直接打日志,在这里补一行。
if (g_lastSignal != 0) {
Mprintf(">>> Exit by signal %d (g_bExit=%d)\n",
(int)g_lastSignal, (int)g_bExit);
} else {
Mprintf(">>> Exit normally (g_bExit=%d)\n", (int)g_bExit);
}
Mprintf("Shutting down...\n");
// 先断开在飞线程对主连接的引用:抓屏/历史活动线程是 detach 出来的,
// ClientObject 出作用域时它们可能还在跑。g_bExit 已置位能挡住绝大多数,
// 清空指针是最后一道保险(先判 g_bExit 再解引用)。
g_pMainClient = nullptr;
// 先收采样线程再关日志:采样循环本身不写日志,但停在静态析构里
// 会撞上正在拆除的 CoreFoundation 对象,不如走正常退出路径收干净。
MacActivityHistory::Instance().Stop();
// Release power assertions
if (sleepAssertionID) {
IOPMAssertionRelease(sleepAssertionID);
Mprintf("Released sleep assertion\n");
}
// Display assertion is managed by ScreenHandler (released in stop())
// powerActivity is automatically released when exiting @autoreleasepool
(void)powerActivity; // Suppress unused variable warning
// 显式停止日志,确保上面 Mprintf 的退出原因落盘。
// 不依赖 ~Logger() 的静态析构次序,避免后续新增日志相关静态对象时踩坑。
Logger::getInstance().stop();
}
return 0;
}