import { spawn, execSync } from 'child_process'; import fs from 'fs'; import path from 'path'; import service from '../core/BaseService.js'; import configUtil from '../utils/config.js'; import { getProjectRoot, getResourcePath, getAppDataDir, isRecordingMode } from '../utils/runtime.js'; const FRPC_EXE = process.platform === 'win32' ? 'frpc.exe' : 'frpc'; // 文件日志:写 console + 写入文件(方便打包后排查问题) function _logFile(...args) { const msg = args.join(' '); console.log(msg); try { const logDir = getAppDataDir(); const logPath = path.join(logDir, 'frpc.log'); const ts = new Date().toISOString().replace('T', ' ').substring(0, 19); fs.appendFileSync(logPath, `[${ts}] ${msg}\n`, 'utf-8'); } catch (_) { /* 写日志失败不阻塞主流程 */ } } function _errFile(...args) { const msg = args.join(' '); console.error(msg); try { const logDir = getAppDataDir(); const logPath = path.join(logDir, 'frpc.log'); const ts = new Date().toISOString().replace('T', ' ').substring(0, 19); fs.appendFileSync(logPath, `[${ts}] [ERR] ${msg}\n`, 'utf-8'); } catch (_) { /* ignore */ } } class FrpcService extends service { constructor() { super(); this.process = null; this.status = 'stopped'; // stopped | starting | running | error this._watchTimer = null; this._startGen = 0; // 启动代际号:并发调用 _startFrpc 时只允许最后一次真正 spawn this.updateConfig = this.updateConfig.bind(this); this.getStatus = this.getStatus.bind(this); this.stop = this.stop.bind(this); // 启动时检查是否需要自动拉起 frpc _logFile('[Frpc] 服务初始化, 当前 frpc 配置:', JSON.stringify(this.config.frpc || null)); this._autoStart(); } /** * 应用启动时自动拉起(仅录制模式:enabled 或配置了 serverAddr 才启用; * 非录制服务器不自动穿透,即使历史配置残留 enabled=true) */ _autoStart() { const cfg = this.config.frpc || {}; const recording = isRecordingMode(this.config); const shouldAutoStart = recording && (!!cfg.enabled || !!cfg.serverAddr); if (shouldAutoStart) { _logFile('[Frpc] 自动启动 frpc (enabled=' + !!cfg.enabled + ', recording=' + recording + ')'); if (!cfg.enabled) { // 补写 enabled 标记,避免后续 updateConfig 判定混乱 cfg.enabled = true; this.config.frpc = cfg; } this._startFrpc(); } else { _logFile('[Frpc] 跳过自动启动 (enabled=' + !!cfg.enabled + ', recording=' + recording + ')'); } } /** * 服务端下发 frpc 配置(通过 WS 调用) */ async updateConfig(data) { if (!data || typeof data !== 'object') { return { ok: false, message: '配置数据无效' }; } const { config, app } = this; config.frpc = { enabled: !!data.enabled, serverAddr: data.serverAddr || '', serverPort: Number(data.serverPort) || 6005, authToken: data.authToken || '', token: data.token || '', proxies: Array.isArray(data.proxies) ? data.proxies : [] }; configUtil.write(config); app.config = config; _logFile('[Frpc] 配置已更新:', JSON.stringify(config.frpc)); // 根据 enabled 决定启动或停止 if (config.frpc.enabled && config.frpc.serverAddr) { this._startFrpc(); return { ok: true, message: 'frpc 配置已更新,正在启动' }; } else { this._stopFrpc(); return { ok: true, message: 'frpc 已停用' }; } } /** * 停止 frpc */ stop() { this._stopFrpc(); return { ok: true, message: 'frpc 已停止' }; } /** * 获取当前状态 */ getStatus() { return { status: this.status, enabled: !!(this.config.frpc && this.config.frpc.enabled) }; } // ─── frpc 进程管理 ─── _findFrpcExe() { const root = getProjectRoot(); const exeName = FRPC_EXE; if (process.platform === 'win32') { this._frpcSearchPaths = [ getResourcePath('frpc', exeName), getResourcePath(exeName), path.join(root, exeName), path.join(root, 'frpc', exeName), path.join(root, 'bin', exeName), path.join(process.cwd(), exeName), exeName ]; } else { // Linux: 优先查找系统 PATH,再查项目目录 this._frpcSearchPaths = [ '/usr/bin/frpc', '/usr/local/bin/frpc', '/www/server/frpc/frpc', '/opt/frp/frpc', path.join(root, 'frpc', exeName), path.join(root, exeName), path.join(process.cwd(), exeName), exeName ]; } for (const p of this._frpcSearchPaths) { if (fs.existsSync(p)) return p; } return null; } _generateFrpcIni() { const cfg = this.config.frpc || {}; const lines = ['[common]']; lines.push('server_addr = ' + (cfg.serverAddr || '127.0.0.1')); lines.push('server_port = ' + (cfg.serverPort || 6005)); if (cfg.authToken) { lines.push('token = ' + cfg.authToken); } // 代理配置 if (Array.isArray(cfg.proxies)) { for (const p of cfg.proxies) { if (!p.name) continue; lines.push(''); lines.push('[' + p.name + ']'); lines.push('type = ' + (p.type || 'http')); lines.push('local_ip = ' + (p.localIp || '127.0.0.1')); lines.push('local_port = ' + (p.localPort || 0)); // http/https 类型用 subdomain,不设 remote_port if (p.type === 'http' || p.type === 'https') { if (p.subdomain) { lines.push('subdomain = ' + p.subdomain); } if (p.customDomains) { lines.push('custom_domains = ' + p.customDomains); } } else { lines.push('remote_port = ' + (p.remotePort || 0)); } } } const root = getAppDataDir(); const iniPath = path.join(root, 'frpc.ini'); fs.writeFileSync(iniPath, lines.join('\n'), 'utf-8'); return iniPath; } _startFrpc() { const hadProcess = !!this.process; this._stopFrpc(); // 代际号:更新配置等场景会并发调用 _startFrpc,且清理遗留进程后会延迟 2 秒才 spawn, // 没有这个守卫会出现“两次调用各 spawn 一次” → 两个 frpc 抢同一代理名(第二个报 already exists) const gen = ++this._startGen; const doSpawn = (retried) => { if (gen !== this._startGen) { _logFile('[Frpc] 忽略过期的启动请求(已有更新的启动流程)'); return; } const exePath = this._findFrpcExe(); if (!exePath) { _errFile('[Frpc] frpc.exe 未找到,搜索路径:', JSON.stringify(this._frpcSearchPaths)); for (const p of this._frpcSearchPaths) { _errFile('[Frpc] 检查:', p, fs.existsSync(p) ? '(存在)' : '(不存在)'); } this._setStatus('error'); return; } const iniPath = this._generateFrpcIni(); // 启动前先清理「使用同一 ini」的遗留 frpc(含父进程已死的孤儿):它们占着同一个 frp 代理名, // 新实例会报 `proxy ... already exists` 而注册失败 → 平台经隧道进来的调用全部失败 // (2026-09-11 实测:frpc.log 自 2026-07-28 起累计 32724 条该错误)。 if (!retried) { const stale = this._killStaleFrpc(iniPath); if (stale > 0) { _logFile('[Frpc] 已终止 ' + stale + ' 个遗留 frpc 进程,2 秒后强制清理残留并重新启动'); setTimeout(() => { if (gen !== this._startGen) return; // 已被更新的启动请求取代 this._killStaleFrpc(iniPath, true); doSpawn(true); }, 2000); return; } } _logFile('[Frpc] 启动 frpc:', exePath, '-c', iniPath); _logFile('[Frpc] ini 内容:', fs.readFileSync(iniPath, 'utf-8')); try { const spawnOpts = { stdio: ['ignore', 'pipe', 'pipe'] }; if (process.platform === 'win32') { spawnOpts.windowsHide = true; } this.process = spawn(exePath, ['-c', iniPath], spawnOpts); this._setStatus('starting'); this.process.stdout.on('data', (data) => { const text = data.toString(); _logFile('[Frpc][stdout]', text.trim()); // frpc 输出中包含 "start proxy success" 表示连接成功 if (text.includes('start proxy success') || text.includes('run success')) { this._setStatus('running'); } }); this.process.stderr.on('data', (data) => { _errFile('[Frpc][stderr]', data.toString().trim()); }); this.process.on('error', (err) => { _errFile('[Frpc] 进程错误:', err.message); this._setStatus('error'); }); this.process.on('exit', (code) => { _logFile('[Frpc] 进程退出, code:', code); if (this.status !== 'stopped') { this._setStatus('error'); } this.process = null; }); // 超时检测:10 秒内没收到 running 则标记 error clearTimeout(this._watchTimer); this._watchTimer = setTimeout(() => { if (this.status === 'starting') { _errFile('[Frpc] 启动超时 (10s)'); this._setStatus('error'); } }, 10000); } catch (err) { _errFile('[Frpc] 启动失败:', err.message); this._setStatus('error'); } }; if (hadProcess) { // 延迟 3 秒让 frp 服务端释放旧代理名 setTimeout(doSpawn, 3000); } else { doSpawn(); } } /** * 清理「命令行里带本服务 ini 路径」的遗留 frpc 进程(不碰系统上其它 frpc,如宝塔的 /www/server/frpc/frpc)。 * 场景:node 进程被 kill/崩溃时,它 spawn 的 frpc 会变成孤儿(PPID=1)继续占着 frp 代理名, * 导致新 frpc 注册失败、平台无法经隧道访问本机(任务派发走 WS 出站通道不受影响,故不易察觉)。 * @param {string} iniPath 本服务生成的 frpc.ini 绝对路径 * @param {boolean} force true=直接 SIGKILL,false=SIGTERM 优雅退出 * @returns {number} 被终止的进程数 */ _killStaleFrpc(iniPath, force = false) { if (!iniPath) return 0; const selfPid = this.process ? this.process.pid : null; const rows = []; try { if (process.platform === 'win32') { // PowerShell 脚本用 -EncodedCommand(base64) 传递,彻底避开 cmd/PowerShell 的多层引号问题 const psScript = "Get-CimInstance Win32_Process -Filter \"Name='frpc.exe'\" | ForEach-Object { \"$($_.ProcessId)||$($_.CommandLine)\" }"; const b64 = Buffer.from(psScript, 'utf16le').toString('base64'); const out = execSync(`powershell -NoProfile -NonInteractive -EncodedCommand ${b64}`, { encoding: 'utf-8', timeout: 10000, windowsHide: true }); for (const line of out.split(/\r?\n/)) { const i = line.indexOf('||'); if (i <= 0) continue; const pid = Number(line.slice(0, i)); if (pid) rows.push({ pid, args: line.slice(i + 2) }); } } else { const out = execSync('ps -eo pid=,args=', { encoding: 'utf-8', timeout: 8000 }); for (const line of out.split('\n')) { const m = line.trim().match(/^(\d+)\s+(.*)$/); if (m) rows.push({ pid: Number(m[1]), args: m[2] }); } } } catch (e) { _errFile('[Frpc] 枚举 frpc 进程失败:', e.message); return 0; } let killed = 0; for (const r of rows) { if (!r.pid || r.pid === process.pid || r.pid === selfPid) continue; if (!r.args || !r.args.includes(iniPath)) continue; try { process.kill(r.pid, force ? 'SIGKILL' : 'SIGTERM'); killed++; _logFile('[Frpc] 已清理遗留 frpc pid=' + r.pid + (force ? '(SIGKILL)' : '(SIGTERM)')); } catch (_) { /* 进程可能已退出 */ } } return killed; } _stopFrpc() { clearTimeout(this._watchTimer); if (this.process) { // 移除旧进程的所有事件监听,避免退出事件在新进程启动后误设 error this.process.removeAllListeners(); try { this.process.kill(); } catch (e) { /* ignore */ } this.process = null; } this._setStatus('stopped'); } _setStatus(newStatus) { const prev = this.status; this.status = newStatus; if (prev !== newStatus) { _logFile('[Frpc] 状态变更: ' + prev + ' -> ' + newStatus); // 通知本地前端 this.app.emit('frpcStatusChange', { status: newStatus }); } } } export default FrpcService;