mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
fix: 增加@所有人 完善mac发送清理与端口回退
This commit is contained in:
1 parent
c50f8861a4
commit
aca103cb96
9 files changed
+737
-173
No files matched your search
@@ -3524,6 +3524,7 @@ app.whenReady().then(async () => {
|
||||
targets.some(
|
||||
(target) =>
|
||||
target.targets.includes('host') ||
|
||||
target.targets.includes('frida_helper') ||
|
||||
(macWechatRuntimeManager.getPort() === 4290 &&
|
||||
target.targets.includes('port_4290'))
|
||||
)
|
||||
|
||||
@@ -14,13 +14,93 @@ export interface MacWechatResidualCleanupDependencies {
|
||||
platform: NodeJS.Platform
|
||||
listWechatPids: () => Promise<number[]>
|
||||
listHostPids: () => Promise<number[]>
|
||||
listFridaHelperPids: () => Promise<number[]>
|
||||
listPortPids: () => Promise<number[]>
|
||||
processName: (pid: number) => Promise<string>
|
||||
processCommand: (pid: number) => Promise<string>
|
||||
processCwd: (pid: number) => Promise<string>
|
||||
processState: (pid: number) => Promise<string>
|
||||
processIdentity: (pid: number) => Promise<string>
|
||||
signal: (pid: number, signal: NodeJS.Signals) => void
|
||||
wait: (milliseconds: number) => Promise<void>
|
||||
}
|
||||
|
||||
const SEND_HOST_PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
|
||||
|
||||
function isTraceMemoRuntimePath(value: string): boolean {
|
||||
const normalized = value.replace(/\\/g, '/').toLowerCase()
|
||||
return /\/tracememo(?:\.app\/contents)?\/resources\/runtime\/darwin-arm64(?:\/|$)/.test(
|
||||
normalized
|
||||
)
|
||||
}
|
||||
|
||||
export function isTraceMemoFridaHelper(command: string, cwd: string): boolean {
|
||||
return isTraceMemoRuntimePath(command) || isTraceMemoRuntimePath(cwd)
|
||||
}
|
||||
|
||||
/* 不要把进程信息不可读当作进程已退出:TCC 限制下仍可能有存活进程。 */
|
||||
function resolveProcessName(
|
||||
name: string,
|
||||
command: string,
|
||||
cwd: string,
|
||||
isFridaHelper: boolean
|
||||
): string {
|
||||
const trimmed = name.trim()
|
||||
if (/^frida-hel/.test(trimmed)) return 'frida-helper'
|
||||
if (/^tm-wechat/.test(trimmed)) return 'tm-wechat-host'
|
||||
if (trimmed && trimmed !== 'unknown') return trimmed
|
||||
if (/tm-wechat-host/.test(command)) return 'tm-wechat-host'
|
||||
if (/frida-helper/.test(command)) return 'frida-helper'
|
||||
if (isFridaHelper) return 'frida-helper'
|
||||
if (isTraceMemoRuntimePath(cwd)) return 'tm-wechat-host'
|
||||
return 'unknown'
|
||||
}
|
||||
|
||||
async function readShortProcessName(pid: number): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'/usr/sbin/lsof',
|
||||
['-a', '-p', String(pid), '-d', 'cwd'],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
/* lsof 可能忽略失效的 -p 参数,因此必须核对返回行的 PID。 */
|
||||
for (const line of stdout.split('\n')) {
|
||||
const columns = line.trim().split(/\s+/)
|
||||
if (columns[1] === String(pid)) return columns[0] || ''
|
||||
}
|
||||
return ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
async function readProcessField(pid: number, field: string): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', `${field}=`], {
|
||||
timeout: 2_000
|
||||
})
|
||||
return stdout.trim()
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
async function readProcessCwd(pid: number): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'/usr/sbin/lsof',
|
||||
['-a', '-p', String(pid), '-d', 'cwd', '-Fn'],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
const lines = stdout.split('\n')
|
||||
/* lsof 可能忽略失效的 -p 参数,因此必须核对记录的 PID。 */
|
||||
if (lines.find((line) => line.startsWith('p')) !== `p${pid}`) return ''
|
||||
return lines.find((line) => line.startsWith('n'))?.slice(1) || ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export async function readPids(
|
||||
executable: string,
|
||||
args: string[],
|
||||
@@ -49,26 +129,58 @@ const defaultDependencies: MacWechatResidualCleanupDependencies = {
|
||||
])
|
||||
return [...new Set(results.flat())]
|
||||
},
|
||||
listPortPids: () => readPids('/usr/sbin/lsof', ['-nP', '-t', '-iTCP:4290', '-sTCP:LISTEN']),
|
||||
listHostPids: () => readPids('/usr/bin/pgrep', ['-x', 'tm-wechat-host']),
|
||||
listPortPids: () =>
|
||||
readPids('/usr/sbin/lsof', [
|
||||
'-nP',
|
||||
'-t',
|
||||
`-iTCP:${SEND_HOST_PORT}`,
|
||||
'-sTCP:LISTEN'
|
||||
]),
|
||||
listHostPids: async () => {
|
||||
const pids = await readPids('/usr/bin/pgrep', ['-x', 'tm-wechat-host'])
|
||||
const [commands, directories] = await Promise.all([
|
||||
Promise.all(pids.map((pid) => readProcessField(pid, 'command'))),
|
||||
Promise.all(pids.map(readProcessCwd))
|
||||
])
|
||||
return pids.filter(
|
||||
(_, index) =>
|
||||
isTraceMemoRuntimePath(commands[index]) || isTraceMemoRuntimePath(directories[index])
|
||||
)
|
||||
},
|
||||
listFridaHelperPids: async () => {
|
||||
const pids = await readPids('/usr/bin/pgrep', ['-f', 'frida-helper'])
|
||||
const [commands, directories] = await Promise.all([
|
||||
Promise.all(pids.map((pid) => readProcessField(pid, 'command'))),
|
||||
Promise.all(pids.map(readProcessCwd))
|
||||
])
|
||||
return pids.filter((_, index) => isTraceMemoFridaHelper(commands[index], directories[index]))
|
||||
},
|
||||
processName: async (pid) => {
|
||||
try {
|
||||
const { stdout } = await execFileAsync('/bin/ps', ['-p', String(pid), '-o', 'comm='], {
|
||||
timeout: 2_000
|
||||
})
|
||||
return stdout.trim().split('/').pop() || 'unknown'
|
||||
const name = stdout.trim().split('/').pop() || ''
|
||||
if (name) return name
|
||||
} catch {
|
||||
return 'unknown'
|
||||
/* ps 对同用户外部进程可能整体不可用,落到 lsof。 */
|
||||
}
|
||||
return readShortProcessName(pid) || 'unknown'
|
||||
},
|
||||
processCommand: (pid) => readProcessField(pid, 'command'),
|
||||
processCwd: readProcessCwd,
|
||||
processState: (pid) => readProcessField(pid, 'state'),
|
||||
processIdentity: async (pid) => {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'/bin/ps',
|
||||
['-p', String(pid), '-o', 'lstart=', '-o', 'comm='],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
return createHash('sha256').update(stdout.trim()).digest('hex')
|
||||
const [startTime, command, cwd] = await Promise.all([
|
||||
readProcessField(pid, 'lstart'),
|
||||
readProcessField(pid, 'command'),
|
||||
readProcessCwd(pid)
|
||||
])
|
||||
/* 纳入 PID,避免进程退出后复用同一工作目录导致身份碰撞。 */
|
||||
return createHash('sha256')
|
||||
.update([String(pid), startTime, command, cwd].join('\0'))
|
||||
.digest('hex')
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
@@ -86,60 +198,129 @@ function mergeTargets(
|
||||
hostPids: number[],
|
||||
portPids: number[],
|
||||
processNames: Map<number, string>,
|
||||
processIdentities: Map<number, string>
|
||||
processIdentities: Map<number, string>,
|
||||
processStates: Map<number, string>,
|
||||
fridaHelperPids: number[]
|
||||
): ObservedTarget[] {
|
||||
const targets = new Map<number, Set<'wechat' | 'host' | 'port_4290'>>()
|
||||
const targets = new Map<number, Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>>()
|
||||
for (const pid of wechatPids) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) continue
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290'>()
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
|
||||
reasons.add('wechat')
|
||||
targets.set(pid, reasons)
|
||||
}
|
||||
for (const pid of hostPids) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) continue
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290'>()
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
|
||||
reasons.add('host')
|
||||
targets.set(pid, reasons)
|
||||
}
|
||||
for (const pid of portPids) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) continue
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290'>()
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
|
||||
reasons.add('port_4290')
|
||||
targets.set(pid, reasons)
|
||||
}
|
||||
for (const pid of fridaHelperPids) {
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) continue
|
||||
const reasons = targets.get(pid) || new Set<'wechat' | 'host' | 'port_4290' | 'frida_helper'>()
|
||||
reasons.add('frida_helper')
|
||||
targets.set(pid, reasons)
|
||||
}
|
||||
return [...targets.entries()]
|
||||
.sort(([first], [second]) => first - second)
|
||||
.map(([pid, reasons]) => ({
|
||||
pid,
|
||||
name: processNames.get(pid) || 'unknown',
|
||||
targets: [...reasons].sort(),
|
||||
confirmationToken: processIdentities.get(pid) || ''
|
||||
}))
|
||||
.map(([pid, reasons]) => {
|
||||
const state = processStates.get(pid) || ''
|
||||
return {
|
||||
pid,
|
||||
name: processNames.get(pid) || 'unknown',
|
||||
...(state ? { state } : {}),
|
||||
/* 只有明确的 U 状态才标记为不可中断;状态未知不做推断。 */
|
||||
...(/U/.test(state) ? { uninterruptible: true } : {}),
|
||||
targets: [...reasons].sort(),
|
||||
confirmationToken: processIdentities.get(pid) || ''
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function inspectObservedTargets(
|
||||
dependencies: MacWechatResidualCleanupDependencies
|
||||
): Promise<ObservedTarget[]> {
|
||||
if (dependencies.platform !== 'darwin') return []
|
||||
const [rawWechatPids, rawHostPids, rawPortPids] = await Promise.all([
|
||||
const [rawWechatPids, rawHostPids, rawPortPids, rawFridaHelperPids] = await Promise.all([
|
||||
dependencies.listWechatPids(),
|
||||
dependencies.listHostPids(),
|
||||
dependencies.listPortPids()
|
||||
dependencies.listPortPids(),
|
||||
dependencies.listFridaHelperPids()
|
||||
])
|
||||
const wechatPids = rawWechatPids.filter((pid) => pid !== process.pid)
|
||||
const hostPids = rawHostPids.filter((pid) => pid !== process.pid)
|
||||
const portPids = rawPortPids.filter((pid) => pid !== process.pid)
|
||||
const pids = [...new Set([...wechatPids, ...portPids])].filter(
|
||||
const fridaHelperPids = rawFridaHelperPids.filter((pid) => pid !== process.pid)
|
||||
const pids = [...new Set([...wechatPids, ...portPids, ...fridaHelperPids])].filter(
|
||||
(pid) => Number.isSafeInteger(pid) && pid > 0
|
||||
)
|
||||
for (const pid of hostPids) {
|
||||
if (Number.isSafeInteger(pid) && pid > 0 && !pids.includes(pid)) pids.push(pid)
|
||||
}
|
||||
const [names, identities] = await Promise.all([
|
||||
const [names, identities, states] = await Promise.all([
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processName(pid)] as const)),
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processIdentity(pid)] as const))
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processIdentity(pid)] as const)),
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processState(pid)] as const))
|
||||
])
|
||||
return mergeTargets(wechatPids, hostPids, portPids, new Map(names), new Map(identities))
|
||||
const [commands, directories] = await Promise.all([
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processCommand(pid)] as const)),
|
||||
Promise.all(pids.map(async (pid) => [pid, await dependencies.processCwd(pid)] as const))
|
||||
])
|
||||
const commandByPid = new Map(commands)
|
||||
const cwdByPid = new Map(directories)
|
||||
const nameByPid = new Map(names)
|
||||
const filteredFridaHelpers = fridaHelperPids.filter((pid) =>
|
||||
isTraceMemoFridaHelper(commandByPid.get(pid) || '', cwdByPid.get(pid) || '')
|
||||
)
|
||||
const fridaHelperSet = new Set(filteredFridaHelpers)
|
||||
const resolvedNames = new Map<number, string>()
|
||||
for (const pid of pids) {
|
||||
resolvedNames.set(
|
||||
pid,
|
||||
resolveProcessName(
|
||||
nameByPid.get(pid) || '',
|
||||
commandByPid.get(pid) || '',
|
||||
cwdByPid.get(pid) || '',
|
||||
fridaHelperSet.has(pid)
|
||||
)
|
||||
)
|
||||
}
|
||||
return mergeTargets(
|
||||
wechatPids,
|
||||
hostPids,
|
||||
portPids,
|
||||
resolvedNames,
|
||||
new Map(identities),
|
||||
new Map(states),
|
||||
filteredFridaHelpers
|
||||
)
|
||||
}
|
||||
|
||||
async function waitForConfirmedTargets(
|
||||
dependencies: MacWechatResidualCleanupDependencies,
|
||||
selected: ObservedTarget[],
|
||||
attempts: number,
|
||||
intervalMs: number
|
||||
): Promise<ObservedTarget[]> {
|
||||
const expected = new Map(selected.map((target) => [target.pid, target.confirmationToken]))
|
||||
let remaining = selected.filter((target) => !/U/.test(target.state || ''))
|
||||
if (remaining.length === 0) return selected
|
||||
for (let attempt = 0; attempt < attempts && remaining.length > 0; attempt++) {
|
||||
await dependencies.wait(intervalMs)
|
||||
const current = await inspectObservedTargets(dependencies)
|
||||
remaining = current.filter(
|
||||
(target) =>
|
||||
expected.get(target.pid) === target.confirmationToken && !/U/.test(target.state || '')
|
||||
)
|
||||
}
|
||||
const blocked = selected.filter((target) => /U/.test(target.state || ''))
|
||||
return [...remaining, ...blocked]
|
||||
}
|
||||
|
||||
export async function inspectMacWechatResidualProcesses(
|
||||
@@ -170,10 +351,11 @@ export async function cleanupMacWechatResidualProcesses(
|
||||
const selected = current.filter(
|
||||
(target) => confirmed.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
const selectedIdentities = new Map(selected.map((target) => [target.pid, target.confirmationToken]))
|
||||
if (selected.length === 0) {
|
||||
return {
|
||||
stopped: [],
|
||||
remaining: current.filter((target) => confirmed.has(target.pid))
|
||||
remaining: current
|
||||
}
|
||||
}
|
||||
let cleanupTargetsNotified = false
|
||||
@@ -185,7 +367,9 @@ export async function cleanupMacWechatResidualProcesses(
|
||||
const identity = await dependencies.processIdentity(target.pid)
|
||||
if (!expectedIdentity || identity !== expectedIdentity) return
|
||||
if (
|
||||
(target.targets.includes('host') || target.targets.includes('port_4290')) &&
|
||||
(target.targets.includes('host') ||
|
||||
target.targets.includes('port_4290') ||
|
||||
target.targets.includes('frida_helper')) &&
|
||||
!cleanupTargetsNotified
|
||||
) {
|
||||
cleanupTargetsNotified = true
|
||||
@@ -198,33 +382,73 @@ export async function cleanupMacWechatResidualProcesses(
|
||||
}
|
||||
}
|
||||
|
||||
for (const target of selected.filter((item) => item.targets.includes('wechat'))) {
|
||||
await signalMatchingTarget(target, confirmed.get(target.pid) || '', 'SIGTERM')
|
||||
}
|
||||
if (selected.some((item) => item.targets.includes('wechat'))) await dependencies.wait(1_000)
|
||||
|
||||
let remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid)
|
||||
let activeTargets = (await inspectObservedTargets(dependencies)).filter(
|
||||
(target) =>
|
||||
confirmed.has(target.pid) &&
|
||||
selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
for (const target of remaining) {
|
||||
const selectedTarget = selected.find((item) => item.pid === target.pid)
|
||||
if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue
|
||||
await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGTERM')
|
||||
const hostTargets = activeTargets.filter((target) => target.targets.includes('host'))
|
||||
for (const target of hostTargets) {
|
||||
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
|
||||
}
|
||||
if (hostTargets.some((target) => !/U/.test(target.state || ''))) {
|
||||
await dependencies.wait(1_000)
|
||||
await waitForConfirmedTargets(dependencies, hostTargets, 8, 250)
|
||||
}
|
||||
if (remaining.length > 0) await dependencies.wait(1_000)
|
||||
|
||||
remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid)
|
||||
activeTargets = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid) && selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
for (const target of remaining) {
|
||||
const helperTargets = activeTargets.filter(
|
||||
(target) =>
|
||||
!target.targets.includes('host') &&
|
||||
target.targets.includes('frida_helper') &&
|
||||
selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
const unrelatedPortTargets = activeTargets.filter(
|
||||
(target) =>
|
||||
!target.targets.includes('host') &&
|
||||
!target.targets.includes('frida_helper') &&
|
||||
selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
for (const target of helperTargets) {
|
||||
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
|
||||
}
|
||||
for (const target of unrelatedPortTargets) {
|
||||
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
|
||||
}
|
||||
await waitForConfirmedTargets(dependencies, helperTargets, 4, 250)
|
||||
await waitForConfirmedTargets(dependencies, unrelatedPortTargets, 4, 250)
|
||||
|
||||
activeTargets = (await inspectObservedTargets(dependencies)).filter(
|
||||
(target) =>
|
||||
confirmed.has(target.pid) &&
|
||||
selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
const wechatTargets = activeTargets.filter((target) => target.targets.includes('wechat'))
|
||||
for (const target of wechatTargets) {
|
||||
await signalMatchingTarget(target, target.confirmationToken, 'SIGTERM')
|
||||
}
|
||||
await waitForConfirmedTargets(dependencies, wechatTargets, 8, 250)
|
||||
const remainingTargets = activeTargets.filter(
|
||||
(target) =>
|
||||
!target.targets.includes('host') &&
|
||||
!target.targets.includes('frida_helper') &&
|
||||
!target.targets.includes('wechat') &&
|
||||
selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
await waitForConfirmedTargets(dependencies, remainingTargets, 10, 500)
|
||||
|
||||
activeTargets = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid) && selectedIdentities.get(target.pid) === target.confirmationToken
|
||||
)
|
||||
for (const target of activeTargets) {
|
||||
const selectedTarget = selected.find((item) => item.pid === target.pid)
|
||||
if (!selectedTarget || target.confirmationToken !== selectedTarget.confirmationToken) continue
|
||||
await signalMatchingTarget(target, selectedTarget.confirmationToken, 'SIGKILL')
|
||||
}
|
||||
if (remaining.length > 0) await dependencies.wait(250)
|
||||
remaining = (await inspectObservedTargets(dependencies)).filter((target) =>
|
||||
confirmed.has(target.pid)
|
||||
)
|
||||
await waitForConfirmedTargets(dependencies, activeTargets, 8, 250)
|
||||
const remaining = await inspectObservedTargets(dependencies)
|
||||
return {
|
||||
stopped: selected
|
||||
.filter((target) => !remaining.some((item) => item.pid === target.pid))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { execFileSync, spawn, type ChildProcess } from 'child_process'
|
||||
import { execFile, execFileSync, spawn, type ChildProcess } from 'child_process'
|
||||
import { promisify } from 'node:util'
|
||||
import { chmodSync, existsSync } from 'fs'
|
||||
import { get, request as httpRequest } from 'http'
|
||||
import { join } from 'path'
|
||||
@@ -30,6 +31,8 @@ import {
|
||||
MacWechatRuntimeManifestCache
|
||||
} from './mac-wechat-runtime-artifact'
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
/*
|
||||
* MacWechatRuntimeManager — lifecycle owner of the built-in macOS native
|
||||
* WeChat runtime (tm-wechat-host + libtmwechat.dylib).
|
||||
@@ -48,10 +51,10 @@ import {
|
||||
* auto-binding, that path dead-ends in a 20s attach timeout every time.
|
||||
*/
|
||||
|
||||
/* 默认 4290。进程会 fork 继承监听 fd(CLOEXEC 只挡 exec),
|
||||
* host 崩溃后孤儿进程仍扣着端口,新 host bind 失败会返回 1 无限重启。
|
||||
* 被占用时用 TM_WECHAT_HOST_PORT 指到备用端口。 */
|
||||
const PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
|
||||
/* Helper 会继承监听 fd,并在 Host 退出后继续持有;它卡在内核不可中断态时
|
||||
* SIGKILL 也不回收,重试同一端口永远失败,所以启动必须允许备用端口。 */
|
||||
const DEFAULT_PORT = Number(process.env.TM_WECHAT_HOST_PORT) || 4290
|
||||
const PORT_FALLBACK_SPAN = 3
|
||||
const HOST = '127.0.0.1'
|
||||
const START_TIMEOUT_MS = 15_000
|
||||
const REQUEST_TIMEOUT_MS = 30_000
|
||||
@@ -61,6 +64,36 @@ const CRASH_RESTART_DELAY_MS = 1_500
|
||||
const LICENSE_STATUS_TIMEOUT_MS = 8_000
|
||||
const LICENSE_REFRESH_TIMEOUT_MS = 20_000
|
||||
|
||||
/* 仅地址占用可以通过切换端口恢复。 */
|
||||
function isPortConflictDiagnostic(diagnostic: string): boolean {
|
||||
return /address already in use|EADDRINUSE|bind .*failed/i.test(diagnostic)
|
||||
}
|
||||
|
||||
async function describePortHolder(port: number): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(
|
||||
'/usr/sbin/lsof',
|
||||
['-nP', '-t', `-iTCP:${port}`, '-sTCP:LISTEN'],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
const pid = Number(stdout.trim().split(/\s+/)[0])
|
||||
if (!Number.isSafeInteger(pid) || pid <= 0) return ''
|
||||
try {
|
||||
const { stdout: command } = await execFileAsync(
|
||||
'/bin/ps',
|
||||
['-p', String(pid), '-o', 'comm='],
|
||||
{ timeout: 2_000 }
|
||||
)
|
||||
const name = command.trim().split('/').pop() || 'unknown'
|
||||
return `${name}(PID ${pid})`
|
||||
} catch {
|
||||
return `PID ${pid}(进程信息不可读,可能卡在退出中)`
|
||||
}
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
interface MacWechatSenderStatusInput {
|
||||
snapshot: MacWechatRuntimeSnapshot
|
||||
binding: MacWechatBindingStatus | null
|
||||
@@ -75,6 +108,15 @@ export function shouldClearWechatRestartRequired(
|
||||
return orphanWechatPid > 0 && currentWechatPid > 0 && orphanWechatPid !== currentWechatPid
|
||||
}
|
||||
|
||||
export function formatMacWechatHostStartupFailure(code: number | null, diagnostic: string): string {
|
||||
const lines = diagnostic.trim().split('\n').filter(Boolean)
|
||||
const detail = lines[lines.length - 1]
|
||||
if (detail) return `发送运行时启动失败(进程退出码 ${code ?? '未知'}):${detail}`
|
||||
return code === null
|
||||
? '发送运行时在启动过程中退出'
|
||||
: `发送运行时启动失败(进程退出码 ${code})`
|
||||
}
|
||||
|
||||
export function resolveMacWechatSendMechanism(
|
||||
binding: MacWechatBindingStatus | null,
|
||||
manifest: MacWechatRuntimeManifest | null
|
||||
@@ -226,17 +268,20 @@ export class MacWechatRuntimeManager {
|
||||
private lastError: string | null = null
|
||||
private restartTimer: NodeJS.Timeout | null = null
|
||||
private manuallyStopped = false
|
||||
private activePort = DEFAULT_PORT
|
||||
private portFallbackFrom: number | null = null
|
||||
|
||||
getPort(): number {
|
||||
return PORT
|
||||
return this.activePort
|
||||
}
|
||||
|
||||
getSnapshot(): MacWechatRuntimeSnapshot {
|
||||
return {
|
||||
lifecycle: this.lifecycle,
|
||||
wechatRestartRequired: this.wechatRestartRequired,
|
||||
endpoint: `http://${HOST}:${PORT}`,
|
||||
port: PORT,
|
||||
endpoint: `http://${HOST}:${this.activePort}`,
|
||||
port: this.activePort,
|
||||
...(this.portFallbackFrom === null ? {} : { portFallbackFrom: this.portFallbackFrom }),
|
||||
runtimeDir: this.resolveRuntimeDir() ?? undefined,
|
||||
error: this.lastError ?? undefined,
|
||||
binding: this.lastBinding ?? undefined
|
||||
@@ -394,7 +439,7 @@ export class MacWechatRuntimeManager {
|
||||
* frida session, so the app is immediately ready with NO re-bind, exactly
|
||||
* the "keep the send capability process" behaviour the user asked to carry over.
|
||||
*/
|
||||
if (await this.ping()) {
|
||||
if (await this.adoptRunningHost()) {
|
||||
this.lifecycle = 'online'
|
||||
this.child = null
|
||||
this.wechatRestartRequired = false
|
||||
@@ -458,46 +503,151 @@ export class MacWechatRuntimeManager {
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
this.lifecycle = 'starting'
|
||||
this.lastError = null
|
||||
const manifestPath = join(runtimeDir, 'runtime-manifest.json')
|
||||
/* stderr 保持管道以便启动失败时取诊断;运行日志走 hostLogFile。 */
|
||||
const hostLogFile = join(app.getPath('logs'), 'tm-wechat-host.log')
|
||||
const candidates = this.candidatePorts()
|
||||
const failures: Array<{ port: number; detail: string; portConflict: boolean }> = []
|
||||
|
||||
try {
|
||||
/* Host stderr goes to /dev/null (stdio ignored, see note above), so the
|
||||
* host writes its own log file via TM_WECHAT_LOG_FILE. Without this the
|
||||
* agent's stage beacons (send-enter / cdn-enter / …) are invisible and a
|
||||
* media/CDN stall is undiagnosable. info level so stage beacons show. */
|
||||
const hostLogFile = join(app.getPath('logs'), 'tm-wechat-host.log')
|
||||
this.child = spawn(
|
||||
hostPath,
|
||||
[
|
||||
'--port',
|
||||
String(PORT),
|
||||
'--manifest',
|
||||
join(runtimeDir, 'runtime-manifest.json'),
|
||||
'--log-level',
|
||||
'info'
|
||||
],
|
||||
{
|
||||
cwd: runtimeDir,
|
||||
stdio: 'ignore',
|
||||
detached: false,
|
||||
env: { ...process.env, TM_WECHAT_LOG_FILE: hostLogFile }
|
||||
for (const port of candidates) {
|
||||
this.activePort = port
|
||||
this.lifecycle = 'starting'
|
||||
this.lastError = null
|
||||
|
||||
let child: ChildProcess
|
||||
try {
|
||||
child = spawn(
|
||||
hostPath,
|
||||
['--port', String(port), '--manifest', manifestPath, '--log-level', 'info'],
|
||||
{
|
||||
cwd: runtimeDir,
|
||||
stdio: ['ignore', 'ignore', 'pipe'],
|
||||
detached: false,
|
||||
env: { ...process.env, TM_WECHAT_LOG_FILE: hostLogFile }
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
this.lifecycle = 'stopped'
|
||||
this.lastError = String(error)
|
||||
return this.getSnapshot()
|
||||
}
|
||||
this.child = child
|
||||
|
||||
let startupDiagnostic = ''
|
||||
let exitedDuringStartup = false
|
||||
child.stderr?.setEncoding('utf8')
|
||||
child.stderr?.on('data', (chunk: string) => {
|
||||
startupDiagnostic = (startupDiagnostic + chunk).slice(-2_000)
|
||||
})
|
||||
child.on('exit', () => {
|
||||
exitedDuringStartup = true
|
||||
if (this.child === child) this.child = null
|
||||
})
|
||||
child.on('error', (error) => {
|
||||
exitedDuringStartup = true
|
||||
startupDiagnostic += `\nspawn error: ${error.message}`
|
||||
if (this.child === child) this.child = null
|
||||
})
|
||||
|
||||
/* Host 退出就结束等待,不必耗满 healthz 超时。 */
|
||||
let reachable = false
|
||||
const deadline = Date.now() + START_TIMEOUT_MS
|
||||
while (Date.now() < deadline) {
|
||||
if (await this.ping()) {
|
||||
reachable = true
|
||||
break
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
this.lifecycle = 'stopped'
|
||||
this.lastError = String(error)
|
||||
return this.getSnapshot()
|
||||
if (exitedDuringStartup) break
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
}
|
||||
|
||||
if (reachable) {
|
||||
this.lifecycle = 'online'
|
||||
this.portFallbackFrom = port === DEFAULT_PORT ? null : DEFAULT_PORT
|
||||
this.attachChildLifecycleHandlers(child, startupDiagnostic)
|
||||
if (this.portFallbackFrom !== null) {
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'host_port_fallback',
|
||||
details: { preferredPort: DEFAULT_PORT, activePort: port }
|
||||
})
|
||||
}
|
||||
await this.refreshBinding().catch(() => undefined)
|
||||
if (
|
||||
!this.lastBinding ||
|
||||
!this.manifest ||
|
||||
!bindingMatchesRuntimeManifest(this.lastBinding, this.manifest)
|
||||
) {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = '运行中的 host 与 runtime manifest 不一致'
|
||||
return this.getSnapshot()
|
||||
}
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
const portConflict = isPortConflictDiagnostic(startupDiagnostic)
|
||||
failures.push({
|
||||
port,
|
||||
detail: exitedDuringStartup
|
||||
? formatMacWechatHostStartupFailure(child.exitCode, startupDiagnostic)
|
||||
: '发送运行时未在超时内响应 /healthz',
|
||||
portConflict
|
||||
})
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'host_port_attempt_failed',
|
||||
details: { port, portConflict }
|
||||
})
|
||||
/* 其他启动失败换端口也不会好,直接停。 */
|
||||
if (!portConflict) break
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
try {
|
||||
child.kill('SIGKILL')
|
||||
} catch {
|
||||
/* 进程可能已在状态检查后退出。 */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.child.on('exit', (code) => {
|
||||
const exitedDuringStartup = this.lifecycle === 'starting' && this.startInFlight !== null
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = await this.formatPortRotationFailure(failures)
|
||||
return this.getSnapshot()
|
||||
}
|
||||
|
||||
/* Always retry the preferred port first so it is reused once available. */
|
||||
private candidatePorts(): number[] {
|
||||
const ports = [DEFAULT_PORT, this.activePort]
|
||||
for (let offset = 1; offset <= PORT_FALLBACK_SPAN; offset++) ports.push(DEFAULT_PORT + offset)
|
||||
return ports.filter(
|
||||
(port, index) =>
|
||||
Number.isSafeInteger(port) && port > 0 && port < 65_536 && ports.indexOf(port) === index
|
||||
)
|
||||
}
|
||||
|
||||
/* Reuse an existing Host on any supported port before spawning another one. */
|
||||
private async adoptRunningHost(): Promise<boolean> {
|
||||
for (const port of this.candidatePorts()) {
|
||||
const previous = this.activePort
|
||||
this.activePort = port
|
||||
if (await this.ping()) {
|
||||
this.portFallbackFrom = port === DEFAULT_PORT ? null : DEFAULT_PORT
|
||||
return true
|
||||
}
|
||||
this.activePort = previous
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
private attachChildLifecycleHandlers(child: ChildProcess, startupDiagnostic: string): void {
|
||||
child.on('exit', (code) => {
|
||||
const wasBound =
|
||||
this.lastBinding?.bound === true ||
|
||||
this.lastBinding?.sessionAttached === true ||
|
||||
this.lastBinding?.bindingState === 'binding'
|
||||
const orphanPid = this.lastBinding?.boundWechatPid || this.lastBinding?.wechatPid || 0
|
||||
this.child = null
|
||||
if (this.child === child) this.child = null
|
||||
this.lastBinding = null
|
||||
if (this.lifecycle === 'stopped') return // deliberate shutdown
|
||||
|
||||
@@ -511,31 +661,24 @@ export class MacWechatRuntimeManager {
|
||||
message: 'host_died_while_bound',
|
||||
details: { code: code ?? null, orphanWechatPid: orphanPid }
|
||||
})
|
||||
} else {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
if (exitedDuringStartup) {
|
||||
this.lastError =
|
||||
code === null
|
||||
? '发送运行时在启动过程中退出'
|
||||
: `发送运行时启动失败(进程退出码 ${code})`
|
||||
}
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'host_died_while_unbound_auto_restart',
|
||||
details: { code: code ?? null }
|
||||
})
|
||||
if (!exitedDuringStartup) {
|
||||
if (this.restartTimer) clearTimeout(this.restartTimer)
|
||||
this.restartTimer = setTimeout(() => {
|
||||
void this.ensureStarted()
|
||||
}, CRASH_RESTART_DELAY_MS)
|
||||
}
|
||||
return
|
||||
}
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = formatMacWechatHostStartupFailure(code, startupDiagnostic)
|
||||
appLogger.write({
|
||||
level: 'warn',
|
||||
scope: 'mac-wechat-runtime',
|
||||
message: 'host_died_while_unbound_auto_restart',
|
||||
details: { code: code ?? null }
|
||||
})
|
||||
if (this.restartTimer) clearTimeout(this.restartTimer)
|
||||
this.restartTimer = setTimeout(() => {
|
||||
void this.ensureStarted()
|
||||
}, CRASH_RESTART_DELAY_MS)
|
||||
})
|
||||
this.child.on('error', (error) => {
|
||||
child.on('error', (error) => {
|
||||
if (this.lifecycle === 'stopped') return
|
||||
this.child = null
|
||||
if (this.child === child) this.child = null
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = '无法启动发送 Host:' + error.message
|
||||
appLogger.write({
|
||||
@@ -545,33 +688,18 @@ export class MacWechatRuntimeManager {
|
||||
details: { detail: error.message }
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Wait for /healthz
|
||||
const deadline = Date.now() + START_TIMEOUT_MS
|
||||
while (Date.now() < deadline) {
|
||||
if (await this.ping()) {
|
||||
this.lifecycle = 'online'
|
||||
await this.refreshBinding().catch(() => undefined)
|
||||
if (
|
||||
!this.lastBinding ||
|
||||
!this.manifest ||
|
||||
!bindingMatchesRuntimeManifest(this.lastBinding, this.manifest)
|
||||
) {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = '运行中的 host 与 runtime manifest 不一致'
|
||||
return this.getSnapshot()
|
||||
}
|
||||
return this.getSnapshot()
|
||||
}
|
||||
if (this.child === null) break // died during startup
|
||||
await new Promise((resolve) => setTimeout(resolve, 300))
|
||||
}
|
||||
|
||||
if (this.lifecycle === 'starting') {
|
||||
this.lifecycle = 'crashed_unbound'
|
||||
this.lastError = 'host did not answer /healthz in time'
|
||||
}
|
||||
return this.getSnapshot()
|
||||
private async formatPortRotationFailure(
|
||||
failures: Array<{ port: number; detail: string; portConflict: boolean }>
|
||||
): Promise<string> {
|
||||
const last = failures[failures.length - 1]
|
||||
if (!last) return '发送运行时启动失败'
|
||||
if (!failures.some((failure) => failure.portConflict)) return last.detail
|
||||
const holder = await describePortHolder(last.port)
|
||||
const holderText = holder ? `,占用者 ${holder}` : ''
|
||||
if (failures.length === 1) return `${last.detail}${holderText}`
|
||||
return `端口 ${failures.map((failure) => failure.port).join('、')} 均被占用${holderText}。请重启系统释放端口,或用 TM_WECHAT_HOST_PORT 指定其他端口。`
|
||||
}
|
||||
|
||||
private request(
|
||||
@@ -588,7 +716,7 @@ export class MacWechatRuntimeManager {
|
||||
const req = transport(
|
||||
{
|
||||
host: HOST,
|
||||
port: PORT,
|
||||
port: this.activePort,
|
||||
path,
|
||||
method,
|
||||
timeout: timeoutMs,
|
||||
@@ -836,7 +964,7 @@ export class MacWechatRuntimeManager {
|
||||
arch: process.arch,
|
||||
sipDisabled: true,
|
||||
wechatRunning: false,
|
||||
endpoint: `http://${HOST}:${PORT}`,
|
||||
endpoint: `http://${HOST}:${this.activePort}`,
|
||||
endpointReady: false,
|
||||
runtimeReady: false,
|
||||
attachReady: false,
|
||||
@@ -891,7 +1019,7 @@ export class MacWechatRuntimeManager {
|
||||
arch: process.arch,
|
||||
sipDisabled: true,
|
||||
wechatRunning: false,
|
||||
endpoint: `http://${HOST}:${PORT}`,
|
||||
endpoint: `http://${HOST}:${this.activePort}`,
|
||||
endpointReady: false,
|
||||
runtimeReady: false,
|
||||
attachReady: false,
|
||||
|
||||
Reference in new issue
Block a user