From a25e89b2209d14dfa827dd6a4e1129e53072c8e1 Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Sat, 14 Nov 2026 12:08:52 +0100 Subject: [PATCH] Feat(client): report macOS runtime logs to the controller MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit macOS already handled COMMAND_QUERY_LOG and opened the sub-connection that sends TOKEN_REPORT_LOG, but the snapshot was always empty: macOS Mprintf went to NSLog/fprintf(stderr) and never through Logger, so the ring it dumps stayed empty and both the 运行日志 dialog and MCP get_client_log got nothing. macOS now writes Logger like Linux does, with enable=false so no second log file appears under ~/.config/ghost, and Logger mirrors each line to stderr, which main.mm already redirects to /tmp/ghost.log in daemon and App bundle mode. Prefix and timestamp match on both sides, so dialog and file can be compared line for line. main.mm logged its own lifecycle through NSLog, which never reaches the ring, so the lines people open the dialog for were missing; those calls now use Mprintf. The ObjC helpers (ScreenHandler/H264Encoder/InputHandler/Permissions) keep NSLog and stay file-only. POSIX reports one snapshot per connection, so reopening 运行日志 takes a fresh one; Windows keeps pushing every 3s. Verified with a WSL probe built with -D__APPLE__ (ring, incremental dump, stderr mirror), a MinGW probe for the _WIN32 branch, and a green Linux client rebuild. Not built or run on a real Mac. Co-Authored-By: deepseek-flash --- common/logger.h | 41 ++++++++++++++++++++++-------- docs/Mcp_Design.md | 11 ++++++++ macos/README.txt | 25 ++++++++++++++++++ macos/main.mm | 63 ++++++++++++++++++++++++++-------------------- 4 files changed, 102 insertions(+), 38 deletions(-) diff --git a/common/logger.h b/common/logger.h index 408547f..ebbb788 100644 --- a/common/logger.h +++ b/common/logger.h @@ -17,7 +17,8 @@ #endif #include -#include // fprintf:macOS 非 ObjC 翻译单元的 Mprintf 走 stderr +#include // fputs/fflush/stderr:macOS 的 mirrorStderr 把每行日志同步写 stderr +#include // strrchr:getFileName 不依赖调用方先包含 #include #include #include @@ -78,6 +79,20 @@ public: snprintf(buf, sizeof(buf), "%d", (int)getpid()); instance.pid = buf; instance.enable = false; +#elif defined(__APPLE__) + // macOS:只保留内存 ring + stderr,不另建日志文件。 + // - ring 是服务端「运行日志」菜单的数据源:COMMAND_QUERY_LOG → + // TOKEN_REPORT_LOG,见 common/ClientLogHandler.h; + // - stderr 已被 macos/main.mm 重定向到 /tmp/ghost.log(daemon 与 App + // bundle 两种启动方式都做),那是现场唯一日志文件,再往 + // ~/.config/ghost 写一份只会让两边对不上。 + // 此前 macOS 的 Mprintf 是 NSLog/fprintf,从不经过 Logger,ring 永远是 + // 空的 —— 服务端点「运行日志」打开后一个字都没有,就是这个原因。 + char buf[16] = {}; + snprintf(buf, sizeof(buf), "%d", (int)getpid()); + instance.pid = buf; + instance.enable = false; + instance.mirrorStderr = true; #else // Linux char buf[16] = {}; snprintf(buf, sizeof(buf), "%d", (int)getpid()); @@ -167,6 +182,14 @@ public: logEntry.pop_back(); logEntry += '\n'; + // macOS:把同一行镜像到 stderr,也就是 /tmp/ghost.log。ring 只留最近 + // kMemLogMax 条,而现场排查往往要往前翻,两边保持完全相同的文本(含前缀和 + // 时间戳),对照时不必换算。 + if (mirrorStderr) { + fputs(logEntry.c_str(), stderr); + fflush(stderr); + } + // Always record to in-memory ring buffer regardless of enable flag. { std::lock_guard lock(m_memMutex); @@ -263,6 +286,7 @@ private: } std::string logFileName; // 日志文件名 bool enable; // 是否启用 + bool mirrorStderr = false; // macOS:每行同时镜像到 stderr(/tmp/ghost.log) bool threadRun; // 日志线程状态 std::queue logQueue; // 日志队列 std::mutex queueMutex; // 队列互斥锁 @@ -384,19 +408,14 @@ inline const char* getFileName(const char* path) #elif defined(_WIN32) #define Mprintf(format, ...) Logger::getInstance().log(getFileName((__FILE__)), __LINE__, (format), __VA_ARGS__) #elif defined(__APPLE__) -// macOS: 使用 NSLog 输出到系统日志(可通过 Console.app 查看) +// macOS:与 Linux 一样写 Logger —— 内存 ring 供服务端「运行日志」菜单取回 +// (COMMAND_QUERY_LOG → TOKEN_REPORT_LOG),Logger 初始化时置 mirrorStderr, +// 同一行再落到 stderr,也就是 /tmp/ghost.log。不要改回 NSLog/fprintf:那样 +// ring 永远为空,菜单打开后没有任何内容。 #ifdef Mprintf #undef Mprintf #endif -#ifdef __OBJC__ -#define Mprintf(format, ...) NSLog(@"%@", [NSString stringWithFormat:@(format), ##__VA_ARGS__]) -#else -// 非 ObjC 翻译单元(IOCPClient/FileManager/TlsChannel 等)没有 NSLog,只能写流。 -// 必须写 stderr:macos/main.mm 把 stderr 重定向到 /tmp/ghost.log(daemon 与 App bundle -// 两种启动方式都做,App bundle 还设了 CFLOG_FORCE_STDERR 让 NSLog 也落到同一文件); -// stdout 在 App bundle / login item 启动时没人接收,写过去的日志会直接丢掉。 -#define Mprintf(format, ...) fprintf(stderr, format, ##__VA_ARGS__) -#endif +#define Mprintf(format, ...) Logger::getInstance().log(getFileName(__FILE__), __LINE__, format, ##__VA_ARGS__) #elif defined(__ANDROID__) #include #include diff --git a/docs/Mcp_Design.md b/docs/Mcp_Design.md index c4a618b..d5e4fb7 100644 --- a/docs/Mcp_Design.md +++ b/docs/Mcp_Design.md @@ -951,6 +951,17 @@ schema 里写明这一点;同时根键分支补上 `path: ""`,让两个分 `MessageHandle` 的 `TOKEN_REPORT_LOG` 分支取走首包后会 `CancelIO` 关掉这条连接,回在 主连接上就是把主连接关掉(客户端当场掉线)。 +macOS 还有第二层问题,只影响日志内容,2026-11-14 修:处理器虽然接上了,但 `Logger` 的 +ring 只能被 `Mprintf` 写入,而 macOS 的 `Mprintf` 当时直接走 `NSLog`/`fprintf(stderr)`, +从不经过 `Logger`——ring 恒为空,菜单和 `get_client_log` 拿到的都是空快照。现在 macOS 的 +`Mprintf`(由 `common/logger.h` 定义)与 Linux 一样写 `Logger`(ring;`enable=false` 不另 +建日志文件),再由 `Logger` 把同一行镜像到 stderr(即 `/tmp/ghost.log`),同一条 Mprintf +在文件与菜单里的文本、前缀、时间戳完全一致;ring 只留最近 1000 行,更早的内容只在文件 +里。`macos/main.mm` 里原先用 `NSLog` 的启动/配置/权限等生命周期行也一并改成 `Mprintf`, +否则菜单里看不到现场最常翻的那几行;`ScreenHandler`/`H264Encoder`/`InputHandler` 等 ObjC +模块的 `NSLog` 不动,它们和两条直接 `write(2)` 的启动横幅仍只出现在 `/tmp/ghost.log`。 +MFC 的「运行日志」对话框与 MCP 的 `get_client_log` 走同一条链路,两端同时可用。 + ### 18.4 验证与未覆盖 - 服务端 21:17:21 构建 + 两端客户端重编后实测:`ids` 批量(`get_host_detail` / diff --git a/macos/README.txt b/macos/README.txt index f6e5987..8fa607e 100644 --- a/macos/README.txt +++ b/macos/README.txt @@ -47,6 +47,31 @@ TLS Transport: If the log says "trust anchor exists but failed to load", the client refuses to connect (fail-closed) until the anchor is fixed or removed. +Client Log: + The controller's host right-click menu ("运行日志") sends COMMAND_QUERY_LOG; + the client opens a sub-connection and reports its in-memory log ring + (Logger, last 1000 lines) as TOKEN_REPORT_LOG. On macOS Mprintf (as defined + by common/logger.h) writes that ring, and Logger mirrors the same line to + stderr, so one Mprintf line reads identically in the dialog and in + /tmp/ghost.log (same prefix and timestamp); content older than the + 1000-entry ring exists only in the file. main.mm logs startup, config, + permissions, TLS, WS, connection and exit through Mprintf, so those lines + are all visible in the dialog. The ObjC helper modules (ScreenHandler / + H264Encoder / InputHandler / Permissions) still use NSLog, and the two + "=== ghost ... started ===" banners are raw write(2) calls; all of those + appear only in /tmp/ghost.log. Mprintf lines also no longer go to Apple's + Unified Logging (NSLog in the helpers still does). The MCP tool + get_client_log reads that same ring. + + Verify: open "运行日志" for the Mac host; the dialog should show startup + lines such as "=== macOS Ghost Client ===", "Config loaded from ...", + the permission results, "[TLS] transport on first connect: ...", plus + command and heartbeat entries. + + Note: the POSIX client reports a snapshot once per connection (the Windows + client keeps pushing increments every 3s). Closing and reopening "运行日志" + takes a fresh snapshot. + Permissions Required: 1. Screen Recording - System Settings > Privacy & Security > Screen Recording 2. Accessibility - System Settings > Privacy & Security > Accessibility diff --git a/macos/main.mm b/macos/main.mm index 7d52190..863609c 100644 --- a/macos/main.mm +++ b/macos/main.mm @@ -38,6 +38,11 @@ #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 g_running(true); static std::atomic g_needResendLogin(false); // 分组变更后需要重发登录信息 @@ -116,14 +121,14 @@ static void saveConfig() std::ofstream file(g_configPath, std::ios::trunc); if (!file.is_open()) { - NSLog(@"Failed to save config to %s", g_configPath.c_str()); + 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"; } - NSLog(@"Config saved to %s", g_configPath.c_str()); + Mprintf("Config saved to %s\n", g_configPath.c_str()); } // Get config string value @@ -144,7 +149,7 @@ static void setConfigStr(const std::string& key, const std::string& value) static void saveGroupName(const std::string& groupName) { setConfigStr("group_name", groupName); - NSLog(@"Group name saved: %s", groupName.c_str()); + Mprintf("Group name saved: %s\n", groupName.c_str()); } // Load group name from config file @@ -489,7 +494,7 @@ static std::string getInstallTime() installTime = [NSString stringWithUTF8String:currentTime.c_str()]; [defaults setObject:installTime forKey:@"ghost_install_time"]; [defaults synchronize]; - NSLog(@"First run - recorded install time: %@", installTime); + Mprintf("First run - recorded install time: %s\n", [installTime UTF8String]); } return std::string([installTime UTF8String]); @@ -608,8 +613,8 @@ static void fillLoginInfo(LOGIN_INFOR& info) std::string normPath = normalizeExePathLower(exePath); std::string idInput = machineId + "|" + normPath; g_myClientID = XXH64(idInput.c_str(), idInput.length(), 0); - NSLog(@"ClientID(v2): %llu (machineId=%s, path=%s)", - g_myClientID, machineId.c_str(), normPath.c_str()); + Mprintf("ClientID(v2): %llu (machineId=%s, path=%s)\n", + g_myClientID, machineId.c_str(), normPath.c_str()); } else { // 老算法兜底 char cpuStr[32]; @@ -620,7 +625,7 @@ static void fillLoginInfo(LOGIN_INFOR& info) cpuStr + "|" + exePath; g_myClientID = XXH64(idInput.c_str(), idInput.length(), 0); - NSLog(@"ClientID(v1 fallback): %llu (IOPlatformUUID 读取失败)", g_myClientID); + Mprintf("ClientID(v1 fallback): %llu (IOPlatformUUID 读取失败)\n", g_myClientID); } info.AddReserved(std::to_string(g_myClientID).c_str()); @@ -637,8 +642,8 @@ static void fillLoginInfo(LOGIN_INFOR& info) // 服务端签名输入:与服务端 AddList 处签名格式一致(startTime + "|" + clientID) ClientAuth::g_loginMsg = std::string(info.szStartTime) + "|" + std::to_string(g_myClientID); - NSLog(@"LOGIN_INFOR filled: OS=%s, Host=%s, CPU=%dMHz, PubIP=%s, ClientID=%llu", - osVer.c_str(), hostname.c_str(), info.dwCPUMHz, pubIP.c_str(), 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 列就取这个值。 @@ -696,6 +701,10 @@ static void setupSignals() } // 经典 Unix 双 fork 守护进程 +// +// 必须早于任何 Mprintf:Logger 单例在首次 Mprintf 时创建并启动刷盘线程,fork 之后 +// 子进程里那条线程并不存在(这里 enable=false 不刷盘,ring 与 stderr 镜像照常, +// 但别把第一条 Mprintf 挪到本函数之前)。 static void daemonize() { // macOS 10.12+ NSLog 默认只写 os_log(Unified Logging),非 TTY 时不写 stderr。 @@ -1014,14 +1023,14 @@ int main(int argc, const char* argv[]) } @autoreleasepool { - NSLog(@"=== macOS Ghost Client%s ===", daemon_mode ? " (daemon)" : ""); + Mprintf("=== macOS Ghost Client%s ===\n", daemon_mode ? " (daemon)" : ""); // ============== Power Management: Keep System Awake ============== // 1. Disable App Nap - prevent macOS from suspending this process id powerActivity = [[NSProcessInfo processInfo] beginActivityWithOptions:(NSActivityUserInitiated | NSActivityIdleSystemSleepDisabled) reason:@"Remote control client must maintain persistent connection"]; - NSLog(@"App Nap disabled, activity token acquired"); + Mprintf("App Nap disabled, activity token acquired\n"); // 2. Prevent system idle sleep using IOKit power assertion IOPMAssertionID sleepAssertionID = 0; @@ -1032,9 +1041,9 @@ int main(int argc, const char* argv[]) &sleepAssertionID ); if (result == kIOReturnSuccess) { - NSLog(@"Power assertion created: system idle sleep disabled (ID: %u)", sleepAssertionID); + Mprintf("Power assertion created: system idle sleep disabled (ID: %u)\n", sleepAssertionID); } else { - NSLog(@"Warning: Failed to create power assertion (error: 0x%x)", result); + Mprintf("Warning: Failed to create power assertion (error: 0x%x)\n", result); } // 3. Display sleep: managed by ScreenHandler - only prevents display sleep @@ -1045,7 +1054,7 @@ int main(int argc, const char* argv[]) // Load configuration file (~/.config/ghost/config.conf) loadConfig(); - NSLog(@"Config loaded from %s", g_configPath.c_str()); + Mprintf("Config loaded from %s\n", g_configPath.c_str()); // 传输方式由信任锚文件决定(服务端右键「TLS 传输」才会写入 ~/.config/ghost/yama-ca.pem)。 // 启动时打一行,排查「首次连接为什么/为什么不加密」不用去猜。 @@ -1057,14 +1066,14 @@ int main(int argc, const char* argv[]) } // Check permissions - NSLog(@"Checking permissions..."); + Mprintf("Checking permissions...\n"); bool hasScreenCapture = Permissions::checkScreenCapture(); if (hasScreenCapture) { - NSLog(@"Screen capture permission: OK"); + Mprintf("Screen capture permission: OK\n"); } else { - NSLog(@"Screen capture permission not granted."); - NSLog(@"Please grant permission in System Preferences > Privacy & Security > Screen Recording"); + 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 @@ -1076,20 +1085,20 @@ int main(int argc, const char* argv[]) bool hasAccessibility = Permissions::checkAccessibility(); if (hasAccessibility) { - NSLog(@"Accessibility permission: OK"); + Mprintf("Accessibility permission: OK\n"); } else { - NSLog(@"Accessibility permission not granted."); - NSLog(@"Please grant permission in System Preferences > Privacy & Security > Accessibility"); + Mprintf("Accessibility permission not granted.\n"); + Mprintf("Please grant permission in System Preferences > Privacy & Security > Accessibility\n"); Permissions::requestAccessibility(); } // FDA check is unreliable (no official API), just log a warning if (!Permissions::checkFullDiskAccess()) { - NSLog(@"Full Disk Access: not detected (may be false negative)."); - NSLog(@"If file access issues occur, grant FDA in System Preferences > Privacy & Security > Full Disk Access"); + 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 { - NSLog(@"Full Disk Access: OK"); + Mprintf("Full Disk Access: OK\n"); } // Create client @@ -1104,7 +1113,7 @@ int main(int argc, const char* argv[]) } // Main event loop - NSLog(@"Starting main loop..."); + Mprintf("Starting main loop...\n"); LOGIN_INFOR logInfo; fillLoginInfo(logInfo); @@ -1183,12 +1192,12 @@ int main(int argc, const char* argv[]) Mprintf(">>> Exit normally (g_bExit=%d)\n", (int)g_bExit); } - NSLog(@"Shutting down..."); + Mprintf("Shutting down...\n"); // Release power assertions if (sleepAssertionID) { IOPMAssertionRelease(sleepAssertionID); - NSLog(@"Released sleep assertion"); + Mprintf("Released sleep assertion\n"); } // Display assertion is managed by ScreenHandler (released in stop()) // powerActivity is automatically released when exiting @autoreleasepool