diff --git a/macos/Permissions.h b/macos/Permissions.h index 13294be..bd46c79 100644 --- a/macos/Permissions.h +++ b/macos/Permissions.h @@ -10,6 +10,12 @@ public: // Returns true if granted, false otherwise static bool checkScreenCapture(); + // 只查授权状态、不真的抓屏(macOS 10.15+,更早的版本恒为 true)。 + // 授权看守线程用它轮询:checkScreenCapture() 每调一次就抓一整帧(视网膜屏 + // 20+ MB),而这里只需要「用户刚在设置里勾上了」这个状态位。它在二进制重签名 + // 后可能报假阴性 —— 正因如此,启动时的那次检查仍用 checkScreenCapture()。 + static bool checkScreenCapturePreflight(); + // Request screen recording permission (shows system dialog, macOS 10.15+) static void requestScreenCapture(); diff --git a/macos/Permissions.mm b/macos/Permissions.mm index d27782d..8810e34 100644 --- a/macos/Permissions.mm +++ b/macos/Permissions.mm @@ -34,6 +34,13 @@ bool Permissions::checkScreenCapture() { return true; } +bool Permissions::checkScreenCapturePreflight() { + if (@available(macOS 10.15, *)) { + return CGPreflightScreenCaptureAccess(); + } + return true; +} + void Permissions::requestScreenCapture() { if (@available(macOS 10.15, *)) { // Trigger system permission dialog diff --git a/macos/README.txt b/macos/README.txt index 8fa607e..8133bb0 100644 --- a/macos/README.txt +++ b/macos/README.txt @@ -76,6 +76,30 @@ Permissions Required: 1. Screen Recording - System Settings > Privacy & Security > Screen Recording 2. Accessibility - System Settings > Privacy & Security > Accessibility + Both are TCC grants, and macOS applies them per process: a grant made while + the app is running only takes effect after it restarts. install.sh also resets + both (tccutil reset) and re-signs the bundle ad-hoc on every install, and a + rebuilt binary has a new cdhash, so the old records would not match anyway -- + expect to re-grant after each update. + + When a permission is missing at startup the client requests both, and starts + a watcher that polls CGPreflightScreenCaptureAccess / AXIsProcessTrusted -- + only for the permission that was actually missing; one that already passed + the real capture check is not re-judged by preflight (it can report false + negatives after re-signing). Once everything reads granted, the main loop + disconnects and launches a fresh process ("Auto-restart: launching a fresh + process ..."), so the new process starts with the grants in place: the old + "grant one, kill, reopen" round trip twice becomes "tick both boxes and let + it restart". The new process logs "(started by the auto-restart after + permissions were granted)" at startup, and that line is what the 运行日志 + dialog shows, because the in-memory ring dies with the old process; the + Auto-restart line itself stays in /tmp/ghost.log only. The watcher gives up + after 15 minutes, and the auto-restart happens at most once per launch + (guarded by GHOST_AUTO_RELAUNCHED), so if something still reports missing, + restart manually as before. The restart disconnects first, so the controller + sees a clean disconnect and reconnect, but any remote session in progress + (screen, terminal, file transfer) is dropped when it happens. + Features: [x] Screen capture (CGDisplayCreateImage) [x] H264 video encoding (VideoToolbox) diff --git a/macos/install.sh b/macos/install.sh index 654ee34..73dede4 100644 --- a/macos/install.sh +++ b/macos/install.sh @@ -110,7 +110,8 @@ echo "2. 授权以下权限 (在系统设置中勾选 GhostClient):" echo " - 屏幕录制: 允许捕获屏幕画面" echo " - 辅助功能: 允许控制鼠标键盘" echo "" -echo "3. 授权后重启应用:" +echo "3. 两个都授权后应用会自己重启一次(日志里是 Auto-restart: launching ...)," +echo " 一般不用手动操作。若 15 分钟内没等到,手动重启:" echo "" echo " pkill -f GhostClient && open /Applications/GhostClient.app" echo "" diff --git a/macos/main.mm b/macos/main.mm index 863609c..4ae6b8c 100644 --- a/macos/main.mm +++ b/macos/main.mm @@ -7,6 +7,10 @@ #import #import #import +#import +#import +#import +#import #import #import #import @@ -50,6 +54,9 @@ static std::atomic g_needResendLogin(false); // 分组变更后需要重 // DataProcess 跑在接收线程上,直接关 socket 会和主线程的发送竞争,所以只置标志, // 由主心跳循环择机 Disconnect 并重连(与 linux/main.cpp 的 g_needReconnect 同语义)。 static std::atomic g_needReconnect(false); +// 权限补齐后要求重启进程(见文件下方的「授权后自动重启」)。只看守线程置位,主循环 +// 见到它先断开主连接再重启,避免新进程起来时旧连接还挂在服务端。 +static std::atomic g_autoRestartPending(false); // Client ID (calculated from system info, used by ScreenHandler) uint64_t g_myClientID = 0; @@ -750,6 +757,163 @@ static void daemonize() } } +// ============== 授权后自动重启 ============== +// +// 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 @@ -1001,6 +1165,9 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) // -d 后台守护进程模式 int main(int argc, const char* argv[]) { + // 自动重启要按原样重放命令行(比如带 -d),argv 在进程生命周期内一直有效 + g_relaunchArgv = const_cast(argv); + // 解析 -d 参数 bool daemon_mode = (argc > 1 && strcmp(argv[1], "-d") == 0); @@ -1024,6 +1191,12 @@ int main(int argc, const char* argv[]) @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 @@ -1092,6 +1265,23 @@ int main(int argc, const char* argv[]) 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"); @@ -1118,6 +1308,13 @@ int main(int argc, const char* argv[]) 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); @@ -1148,10 +1345,18 @@ int main(int argc, const char* argv[]) 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)) {