298 lines
8.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { spawn } 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.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();
}
/**
* 应用启动时自动拉起(如果 config.frpc.enabled 为 true,或录制模式下自动启用)
*/
_autoStart() {
const cfg = this.config.frpc || {};
// 录制模式 + 有 serverAddr 配置 → 自动启用(无论 enabled 字段)
const shouldAutoStart = cfg.enabled || (isRecordingMode(this.config) && cfg.serverAddr);
if (shouldAutoStart) {
_logFile('[Frpc] 自动启动 frpc (enabled=%s, recording=%s)',
!!cfg.enabled, isRecordingMode(this.config));
if (!cfg.enabled) {
// 补写 enabled 标记,避免后续 updateConfig 判定混乱
cfg.enabled = true;
this.config.frpc = cfg;
}
this._startFrpc();
}
}
/**
* 服务端下发 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',
'/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();
const doSpawn = () => {
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();
_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();
}
}
_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] 状态变更: %s -> %s', prev, newStatus);
// 通知本地前端
this.app.emit('frpcStatusChange', { status: newStatus });
}
}
}
export default FrpcService;