- 单进程:托盘常驻 + 原生设置窗口(internal/settings),移除 Wails 前端与 IPC - 触发器(鼠标角落 / 边缘滚轮 / 热键)+ 规则引擎 + 动作注册表 - 调节提示条:截屏 + glass.Blur 三层毛玻璃、背景跟随屏幕变化、悬停光感与拖动 - 音量 Core Audio COM、亮度 DDC/CI(gamma 兜底)、多显示器求平均 - 配置热重载 + 版本迁移 v1→v5、便携模式、崩溃取证三件套 - updater/native 插件 + 托盘「检查更新…」,watchdog 识别更新重启 - 自建 Gitea 发布:scripts/publish-gitea.ps1(updates.url 指向 latest Release)
419 lines
14 KiB
Go
419 lines
14 KiB
Go
// watchdog — ZerOriginTool 进程看门狗。
|
||
//
|
||
// 两种模式:
|
||
//
|
||
// 1. 被动监视(默认):每 2 秒检查 ZerOriginTool.exe 是否存活。一旦从
|
||
// "存在"变为"消失",立即记录:消失时刻 + 当前全部进程快照(重点标记
|
||
// 管家/清理类软件),追加写入 %LOCALAPPDATA%\ZerOriginTool\logs\watchdog.log。
|
||
// 常驻运行,不随目标进程退出而退出。
|
||
//
|
||
// 2. 监督模式(-supervise):以父进程身份拉起 ZerOriginTool.exe,捕获其
|
||
// stderr 与退出码;异常退出(无 clean-quit 标记)时自动重启(常驻保障),
|
||
// 正常退出(用户从托盘退出)时监督进程自行退出。单实例互斥,重复启动
|
||
// 静默丢弃。
|
||
package main
|
||
|
||
import (
|
||
"flag"
|
||
"fmt"
|
||
"os"
|
||
"os/exec"
|
||
"path/filepath"
|
||
"syscall"
|
||
"time"
|
||
"unsafe"
|
||
)
|
||
|
||
const (
|
||
targetName = "ZerOriginTool.exe"
|
||
checkEvery = 2 * time.Second
|
||
snapshotLog = "watchdog.log"
|
||
// relaunchGap 是子进程退出后等待新实例出现的时间窗口。mygo 更新器装完更新
|
||
// 用 Relaunch 启动新版本:新进程不写 clean-quit 标记,也不是本进程 cmd.Wait
|
||
// 捕获的那个 pid,只能靠"同名进程是否又出现"来识别,避免把更新重启当崩溃。
|
||
relaunchGap = 1500 * time.Millisecond
|
||
)
|
||
|
||
var (
|
||
kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||
procSnap = kernel32.NewProc("CreateToolhelp32Snapshot")
|
||
procFirst = kernel32.NewProc("Process32FirstW")
|
||
procNext = kernel32.NewProc("Process32NextW")
|
||
procClose = kernel32.NewProc("CloseHandle")
|
||
procOpen = kernel32.NewProc("OpenProcess")
|
||
procTimes = kernel32.NewProc("GetProcessTimes")
|
||
|
||
// 监督模式用
|
||
procCreateMutexW = kernel32.NewProc("CreateMutexW")
|
||
)
|
||
|
||
type processEntry32W struct {
|
||
size uint32
|
||
usage uint32
|
||
processID uint32
|
||
defaultHeapID uintptr
|
||
moduleID uint32
|
||
threads uint32
|
||
parentProcessID uint32
|
||
priClassBase int32
|
||
flags uint32
|
||
exeFile [260]uint16
|
||
}
|
||
|
||
type filetime struct {
|
||
low uint32
|
||
high uint32
|
||
}
|
||
|
||
const (
|
||
th32csSnapProcess = 0x00000002
|
||
processQueryInfo = 0x1000 // PROCESS_QUERY_LIMITED_INFORMATION
|
||
epochDelta = 116444736000000000
|
||
errorAlreadyExists = 183
|
||
createNoWindow = 0x08000000 // CREATE_NO_WINDOW
|
||
)
|
||
|
||
// procInfo 为进程快照条目(含启动时间)。
|
||
type procInfo struct {
|
||
pid uint32
|
||
ppid uint32
|
||
name string
|
||
startEpoch float64 // 启动时间(UNIX 秒),读取失败为 0
|
||
}
|
||
|
||
// listProcesses 返回进程快照(名称、PID、PPID、启动时间)。
|
||
func listProcesses() map[string][]procInfo {
|
||
out := map[string][]procInfo{}
|
||
snap, _, _ := procSnap.Call(th32csSnapProcess, 0)
|
||
if snap == 0 || snap == ^uintptr(0) {
|
||
return out
|
||
}
|
||
defer procClose.Call(snap)
|
||
|
||
var pe processEntry32W
|
||
pe.size = uint32(unsafe.Sizeof(pe))
|
||
r, _, _ := procFirst.Call(snap, uintptr(unsafe.Pointer(&pe)))
|
||
for r != 0 {
|
||
info := procInfo{
|
||
pid: pe.processID,
|
||
ppid: pe.parentProcessID,
|
||
name: syscall.UTF16ToString(pe.exeFile[:]),
|
||
startEpoch: getStartTime(pe.processID),
|
||
}
|
||
out[info.name] = append(out[info.name], info)
|
||
r, _, _ = procNext.Call(snap, uintptr(unsafe.Pointer(&pe)))
|
||
}
|
||
return out
|
||
}
|
||
|
||
// getStartTime 读取进程启动时间(UNIX 秒)。无权限读取时返回 0。
|
||
func getStartTime(pid uint32) float64 {
|
||
h, _, _ := procOpen.Call(processQueryInfo, 0, uintptr(pid))
|
||
if h == 0 {
|
||
return 0
|
||
}
|
||
defer procClose.Call(h)
|
||
var creation, exit, kernel, user filetime
|
||
r, _, _ := procTimes.Call(h,
|
||
uintptr(unsafe.Pointer(&creation)), uintptr(unsafe.Pointer(&exit)),
|
||
uintptr(unsafe.Pointer(&kernel)), uintptr(unsafe.Pointer(&user)))
|
||
if r == 0 {
|
||
return 0
|
||
}
|
||
total := uint64(creation.high)<<32 | uint64(creation.low)
|
||
return float64(total-epochDelta) / 10000000.0
|
||
}
|
||
|
||
// watcherLog 追加写入日志(原子 append)。
|
||
func watcherLog(path, line string) {
|
||
f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||
if err != nil {
|
||
return
|
||
}
|
||
defer f.Close()
|
||
_, _ = f.WriteString(line)
|
||
}
|
||
|
||
func nowStamp() string {
|
||
return time.Now().Format("2006-01-02T15:04:05.000-07:00")
|
||
}
|
||
|
||
func main() {
|
||
supervise := flag.Bool("supervise", false, "监督模式:拉起并监督 ZerOriginTool.exe,异常退出自动重启")
|
||
appFlag := flag.String("app", "", "监督模式下被监督的 exe 路径(默认:watchdog 同目录的 ZerOriginTool.exe)")
|
||
flag.Parse()
|
||
|
||
logDir := filepath.Join(os.Getenv("LOCALAPPDATA"), "ZerOriginTool", "logs")
|
||
if err := os.MkdirAll(logDir, 0o755); err != nil {
|
||
logDir = "."
|
||
}
|
||
logPath := filepath.Join(logDir, snapshotLog)
|
||
|
||
if *supervise {
|
||
runSupervisor(logDir, logPath, *appFlag)
|
||
return
|
||
}
|
||
|
||
watcherLog(logPath, fmt.Sprintf("=== watchdog started %s ===\n", nowStamp()))
|
||
|
||
alive := false
|
||
for {
|
||
procs := listProcesses()
|
||
running := len(procs[targetName]) > 0
|
||
|
||
now := nowStamp()
|
||
if running && !alive {
|
||
pids := ""
|
||
for _, p := range procs[targetName] {
|
||
pids += fmt.Sprintf("%d ", p.pid)
|
||
}
|
||
watcherLog(logPath, fmt.Sprintf("[%s] %s 出现 (PID=[%s])\n", now, targetName, pids))
|
||
}
|
||
if !running && alive {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] *** %s 消失!立即抓取进程快照 ***\n", now, targetName))
|
||
logSuspectSnapshot(logPath, now)
|
||
}
|
||
alive = running
|
||
time.Sleep(checkEvery)
|
||
}
|
||
}
|
||
|
||
// logSuspectSnapshot 抓取并记录可疑进程快照(管家/清理类,含启动时间)。
|
||
func logSuspectSnapshot(logPath, now string) {
|
||
snap := listProcesses()
|
||
watcherLog(logPath, fmt.Sprintf("[%s] 进程总数=%d\n", now, len(snap)))
|
||
// 重点标记管家/清理类(含启动时间——杀手若是临时拉起会当场暴露)
|
||
for name, infos := range snap {
|
||
if isSuspicious(name) {
|
||
for _, p := range infos {
|
||
st := "?"
|
||
if p.startEpoch > 0 {
|
||
st = time.Unix(int64(p.startEpoch), 0).Format("15:04:05")
|
||
}
|
||
watcherLog(logPath, fmt.Sprintf("[%s] SUSPECT %-40s pid=%d ppid=%d 启动=%s\n", now, name, p.pid, p.ppid, st))
|
||
}
|
||
}
|
||
}
|
||
watcherLog(logPath, fmt.Sprintf("[%s] === 快照结束 ===\n\n", now))
|
||
}
|
||
|
||
// ———————— 监督模式 ————————
|
||
|
||
// supervisorMutexName 监督进程单实例互斥名(与主进程单实例互斥区分)。
|
||
const supervisorMutexName = "Local\\ZerOriginToolSupervisor"
|
||
|
||
// supervisorMutex 保存互斥句柄,防止 GC 回收。
|
||
var supervisorMutex uintptr
|
||
|
||
// acquireSupervisorMutex 获取监督进程单实例互斥。已存在时返回 false(静默退出)。
|
||
func acquireSupervisorMutex() bool {
|
||
namePtr, err := syscall.UTF16PtrFromString(supervisorMutexName)
|
||
if err != nil {
|
||
return true // 失败时放行,避免监督完全失效
|
||
}
|
||
h, _, e := procCreateMutexW.Call(0, 0, uintptr(unsafe.Pointer(namePtr)))
|
||
if h == 0 {
|
||
return true
|
||
}
|
||
supervisorMutex = h
|
||
return e != syscall.Errno(errorAlreadyExists)
|
||
}
|
||
|
||
// cleanQuitFlagPath 返回主进程"正常退出"标记路径(与主进程写入路径一致)。
|
||
func cleanQuitFlagPath(logDir string) string {
|
||
return filepath.Join(logDir, "clean-quit.flag")
|
||
}
|
||
|
||
// runSupervisor 监督模式主循环。
|
||
// - 目标已在运行(如开机自启/用户手动启动):先被动监视,消失后接管拉起;
|
||
// - 目标未运行:以子进程拉起,stderr 重定向到 supervised-stderr.log;
|
||
// - 子进程退出:记录退出码/运行时长;有 clean-quit 标记 → 正常退出,监督进程退出;
|
||
// 无标记 → 视为异常死亡,抓快照后自动重启(崩溃循环时退避到 10s)。
|
||
func runSupervisor(logDir, logPath, appFlag string) {
|
||
watcherLog(logPath, fmt.Sprintf("=== supervisor started %s ===\n", nowStamp()))
|
||
if !acquireSupervisorMutex() {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor 已在运行,本实例退出\n", nowStamp()))
|
||
return
|
||
}
|
||
|
||
// 被监督 exe 路径:-app 优先,否则取 watchdog 同目录的 ZerOriginTool.exe。
|
||
appPath := appFlag
|
||
if appPath == "" {
|
||
exe, err := os.Executable()
|
||
if err != nil {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: resolve own exe failed: %v\n", nowStamp(), err))
|
||
return
|
||
}
|
||
appPath = filepath.Join(filepath.Dir(exe), targetName)
|
||
}
|
||
if _, err := os.Stat(appPath); err != nil {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: app not found: %s\n", nowStamp(), appPath))
|
||
return
|
||
}
|
||
appBase := filepath.Base(appPath)
|
||
flagPath := cleanQuitFlagPath(logDir)
|
||
stderrPath := filepath.Join(logDir, "supervised-stderr.log")
|
||
|
||
// 启动前清除旧标记:标记只反映"本次运行"的退出性质。
|
||
_ = os.Remove(flagPath)
|
||
|
||
for {
|
||
// 1) 目标已在运行 → 被动等待其消失。
|
||
if len(listProcesses()[appBase]) > 0 {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: %s 已在运行,转为被动监视\n", nowStamp(), appBase))
|
||
for {
|
||
time.Sleep(checkEvery)
|
||
if len(listProcesses()[appBase]) == 0 {
|
||
break
|
||
}
|
||
}
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: %s 消失,检查退出性质\n", nowStamp(), appBase))
|
||
if flagExists(flagPath) {
|
||
_ = os.Remove(flagPath)
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: 检测到正常退出标记,监督进程退出\n", nowStamp()))
|
||
return
|
||
}
|
||
// 更新重启:装配完更新后新实例往往在几百毫秒内就起来了,
|
||
// 这时再拉起一个只会被单实例锁挡回来,还留下无用的崩溃快照。
|
||
if waitForRelaunch(appBase, relaunchGap) {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: 检测到 %s 新实例(更新重启),继续被动监视\n", nowStamp(), appBase))
|
||
continue
|
||
}
|
||
logSuspectSnapshot(logPath, nowStamp())
|
||
}
|
||
|
||
// 2) 拉起目标(stderr 重定向,捕获 panic 等不可见输出)。
|
||
_ = os.Remove(flagPath)
|
||
sf, err := os.OpenFile(stderrPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||
if err != nil {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: open stderr log failed: %v\n", nowStamp(), err))
|
||
sf = nil
|
||
}
|
||
cmd := exec.Command(appPath)
|
||
cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: createNoWindow}
|
||
if sf != nil {
|
||
cmd.Stdout = sf
|
||
cmd.Stderr = sf
|
||
}
|
||
start := time.Now()
|
||
if err := cmd.Start(); err != nil {
|
||
if sf != nil {
|
||
_ = sf.Close()
|
||
}
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: 拉起 %s 失败: %v(10 秒后重试)\n", nowStamp(), appBase, err))
|
||
time.Sleep(10 * time.Second)
|
||
continue
|
||
}
|
||
if sf != nil {
|
||
_ = sf.Close()
|
||
}
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: 已拉起 %s pid=%d\n", nowStamp(), appBase, cmd.Process.Pid))
|
||
|
||
// 3) 等待退出,记录退出码与运行时长。
|
||
waitErr := cmd.Wait()
|
||
uptime := time.Since(start).Round(time.Second)
|
||
code := 0
|
||
if cmd.ProcessState != nil {
|
||
code = cmd.ProcessState.ExitCode()
|
||
}
|
||
if waitErr != nil {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: %s 退出 waitErr=%v code=%d uptime=%s\n",
|
||
nowStamp(), appBase, waitErr, code, uptime))
|
||
} else {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: %s 退出 code=%d uptime=%s\n",
|
||
nowStamp(), appBase, code, uptime))
|
||
}
|
||
|
||
// 4) 判定退出性质:有 clean-quit 标记 = 用户主动退出 → 监督进程退出。
|
||
if flagExists(flagPath) {
|
||
_ = os.Remove(flagPath)
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: 正常退出(用户从托盘退出),监督进程退出\n", nowStamp()))
|
||
return
|
||
}
|
||
|
||
// 4.5) 更新重启:mygo 更新器装完更新会用 Relaunch 启动新版本,
|
||
// 新进程既不写 clean-quit 标记,也不是本进程捕获的 pid。
|
||
// 同名进程已经起来 → 不是崩溃,别抓快照也别重复拉起。
|
||
if waitForRelaunch(appBase, relaunchGap) {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: 检测到 %s 新实例(更新重启),转为被动监视\n", nowStamp(), appBase))
|
||
continue
|
||
}
|
||
|
||
// 5) 异常死亡:抓快照后自动重启。短命崩溃(<30s)退避到 10s,防重启风暴。
|
||
logSuspectSnapshot(logPath, nowStamp())
|
||
delay := 3 * time.Second
|
||
if uptime < 30*time.Second {
|
||
delay = 10 * time.Second
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: 运行过短(%s),疑似崩溃循环,%s 后重启\n", nowStamp(), uptime, delay))
|
||
}
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: %s 秒后重启 %s\n", nowStamp(), delay, appBase))
|
||
time.Sleep(delay)
|
||
|
||
// 重启前若发现已有实例(用户手动启动了),转回被动监视,避免重复拉起。
|
||
if len(listProcesses()[appBase]) > 0 {
|
||
watcherLog(logPath, fmt.Sprintf("[%s] supervisor: 重启前发现 %s 已在运行,转被动监视\n", nowStamp(), appBase))
|
||
}
|
||
}
|
||
}
|
||
|
||
// waitForRelaunch 在目标进程退出后短暂等待同名进程重新出现,
|
||
// 用于区分"更新安装后的自动重启"与"崩溃退出"。
|
||
func waitForRelaunch(appBase string, gap time.Duration) bool {
|
||
deadline := time.Now().Add(gap)
|
||
for {
|
||
if len(listProcesses()[appBase]) > 0 {
|
||
return true
|
||
}
|
||
if !time.Now().Before(deadline) {
|
||
return false
|
||
}
|
||
time.Sleep(100 * time.Millisecond)
|
||
}
|
||
}
|
||
|
||
func flagExists(path string) bool {
|
||
_, err := os.Stat(path)
|
||
return err == nil
|
||
}
|
||
|
||
// isSuspicious 判断是否为可能清理后台进程的软件。
|
||
func isSuspicious(name string) bool {
|
||
n := name
|
||
kw := []string{
|
||
"hips", "huorong", "pcmanage", "pcmgr", "pcmanager", "pcoptim",
|
||
"mspcmanager", "hwmdccenter", "matebook", "quick", "everything",
|
||
"tencent", "360", "baidu", "sysdiag", "popblock", "cleaner",
|
||
"optimization", "trafficmonitor", "hiview", "hmscore",
|
||
}
|
||
for _, k := range kw {
|
||
if len(k) <= len(n) && containsFold(n, k) {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
func containsFold(s, sub string) bool {
|
||
if len(sub) == 0 {
|
||
return true
|
||
}
|
||
s = lower(s)
|
||
sub = lower(sub)
|
||
for i := 0; i+len(sub) <= len(s); i++ {
|
||
if s[i:i+len(sub)] == sub {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
func lower(s string) string {
|
||
b := []byte(s)
|
||
for i := range b {
|
||
if b[i] >= 'A' && b[i] <= 'Z' {
|
||
b[i] += 32
|
||
}
|
||
}
|
||
return string(b)
|
||
}
|