v2rayN/v2rayN/ServiceLib/Handler/CoreHandler.cs

314 lines
10 KiB
C#
Raw Normal View History

using System.Diagnostics;
2019-12-11 02:25:28 +00:00
using System.Text;
2019-10-11 06:15:20 +00:00
namespace ServiceLib.Handler;
/// <summary>
/// Core process processing class
/// </summary>
public class CoreHandler
2019-10-11 06:15:20 +00:00
{
private static readonly Lazy<CoreHandler> _instance = new(() => new());
public static CoreHandler Instance => _instance.Value;
private Config _config;
private Process? _process;
private Process? _processPre;
2025-04-26 01:50:31 +00:00
private bool _linuxSudo = false;
private Action<bool, string>? _updateFunc;
private const string _tag = "CoreHandler";
public async Task Init(Config config, Action<bool, string> updateFunc)
2019-10-11 06:15:20 +00:00
{
_config = config;
_updateFunc = updateFunc;
2023-02-10 03:22:03 +00:00
Environment.SetEnvironmentVariable(Global.V2RayLocalAsset, Utils.GetBinPath(""), EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable(Global.XrayLocalAsset, Utils.GetBinPath(""), EnvironmentVariableTarget.Process);
Environment.SetEnvironmentVariable(Global.XrayLocalCert, Utils.GetBinPath(""), EnvironmentVariableTarget.Process);
// TODO Temporary addition to support proper use of sing-box v1.12
Environment.SetEnvironmentVariable("ENABLE_DEPRECATED_SPECIAL_OUTBOUNDS", "true", EnvironmentVariableTarget.Process);
//Copy the bin folder to the storage location (for init)
if (Environment.GetEnvironmentVariable(Global.LocalAppData) == "1")
{
var fromPath = Utils.GetBaseDirectory("bin");
var toPath = Utils.GetBinPath("");
if (fromPath != toPath)
{
FileManager.CopyDirectory(fromPath, toPath, true, false);
}
}
if (Utils.IsNonWindows())
{
var coreInfo = CoreInfoHandler.Instance.GetCoreInfo();
foreach (var it in coreInfo)
{
if (it.CoreType == ECoreType.v2rayN)
{
if (Utils.UpgradeAppExists(out var upgradeFileName))
{
await Utils.SetLinuxChmod(upgradeFileName);
}
continue;
}
foreach (var name in it.CoreExes)
{
var exe = Utils.GetBinPath(Utils.GetExeName(name), it.CoreType.ToString());
if (File.Exists(exe))
{
await Utils.SetLinuxChmod(exe);
}
}
}
2019-10-11 06:15:20 +00:00
}
}
public async Task LoadCore(ProfileItem? node)
{
if (node == null)
{
UpdateFunc(false, ResUI.CheckServerSettings);
return;
}
2019-10-11 06:15:20 +00:00
var fileName = Utils.GetBinConfigPath(Global.CoreConfigFileName);
var result = await CoreConfigHandler.GenerateClientConfig(node, fileName);
if (result.Success != true)
2024-07-21 03:37:11 +00:00
{
UpdateFunc(true, result.Msg);
return;
}
2022-03-19 11:26:51 +00:00
UpdateFunc(false, $"{node.GetSummary()}");
UpdateFunc(false, $"{Utils.GetRuntimeInfo()}");
UpdateFunc(false, string.Format(ResUI.StartService, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
await CoreStop();
await Task.Delay(100);
2024-11-27 03:05:41 +00:00
if (Utils.IsWindows() && _config.TunModeItem.EnableTun)
{
2024-11-27 03:05:41 +00:00
await Task.Delay(100);
await WindowsUtils.RemoveTunDevice();
}
await CoreStart(node);
await CoreStartPreService(node);
if (_process != null)
{
UpdateFunc(true, $"{node.GetSummary()}");
}
}
public async Task<int> LoadCoreConfigSpeedtest(List<ServerTestItem> selecteds)
{
var coreType = selecteds.Exists(t => t.ConfigType is EConfigType.Hysteria2 or EConfigType.TUIC) ? ECoreType.sing_box : ECoreType.Xray;
var fileName = string.Format(Global.CoreSpeedtestConfigFileName, Utils.GetGuid(false));
var configPath = Utils.GetBinConfigPath(fileName);
var result = await CoreConfigHandler.GenerateClientSpeedtestConfig(_config, configPath, selecteds, coreType);
UpdateFunc(false, result.Msg);
if (result.Success != true)
{
return -1;
2019-10-11 06:15:20 +00:00
}
UpdateFunc(false, string.Format(ResUI.StartService, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
UpdateFunc(false, configPath);
var coreInfo = CoreInfoHandler.Instance.GetCoreInfo(coreType);
var proc = await RunProcess(coreInfo, fileName, true, false);
if (proc is null)
2019-10-21 02:35:54 +00:00
{
return -1;
}
2024-11-27 03:05:41 +00:00
return proc.Id;
}
2025-01-04 07:06:30 +00:00
public async Task<int> LoadCoreConfigSpeedtest(ServerTestItem testItem)
{
var node = await AppHandler.Instance.GetProfileItem(testItem.IndexId);
if (node is null)
{
return -1;
}
var fileName = string.Format(Global.CoreSpeedtestConfigFileName, Utils.GetGuid(false));
var configPath = Utils.GetBinConfigPath(fileName);
var result = await CoreConfigHandler.GenerateClientSpeedtestConfig(_config, node, testItem, configPath);
if (result.Success != true)
{
return -1;
}
var coreType = AppHandler.Instance.GetCoreType(node, node.ConfigType);
var coreInfo = CoreInfoHandler.Instance.GetCoreInfo(coreType);
var proc = await RunProcess(coreInfo, fileName, true, false);
if (proc is null)
{
return -1;
}
return proc.Id;
}
public async Task CoreStop()
{
try
{
2025-04-26 01:50:31 +00:00
if (_linuxSudo)
2025-04-25 08:36:28 +00:00
{
2025-04-26 01:50:31 +00:00
await CoreAdminHandler.Instance.KillProcessAsLinuxSudo();
_linuxSudo = false;
2025-04-25 08:36:28 +00:00
}
if (_process != null)
{
2025-04-26 01:50:31 +00:00
await ProcUtils.ProcessKill(_process, Utils.IsWindows());
_process = null;
}
if (_processPre != null)
{
2025-04-26 01:50:31 +00:00
await ProcUtils.ProcessKill(_processPre, Utils.IsWindows());
_processPre = null;
}
2019-10-21 02:35:54 +00:00
}
catch (Exception ex)
2019-10-11 06:15:20 +00:00
{
Logging.SaveLog(_tag, ex);
2019-10-11 06:15:20 +00:00
}
}
2023-01-01 11:42:01 +00:00
#region Private
2024-02-12 13:12:57 +00:00
private async Task CoreStart(ProfileItem node)
{
var coreType = _config.RunningCoreType = AppHandler.Instance.GetCoreType(node, node.ConfigType);
var coreInfo = CoreInfoHandler.Instance.GetCoreInfo(coreType);
2023-05-04 03:44:51 +00:00
var displayLog = node.ConfigType != EConfigType.Custom || node.DisplayLog;
var proc = await RunProcess(coreInfo, Global.CoreConfigFileName, displayLog, true);
if (proc is null)
{
return;
2024-11-27 03:05:41 +00:00
}
_process = proc;
}
private async Task CoreStartPreService(ProfileItem node)
{
if (_process != null && !_process.HasExited)
2024-11-27 03:05:41 +00:00
{
var coreType = AppHandler.Instance.GetCoreType(node, node.ConfigType);
var itemSocks = await ConfigHandler.GetPreSocksItem(_config, node, coreType);
if (itemSocks != null)
{
var preCoreType = itemSocks.CoreType ?? ECoreType.sing_box;
var fileName = Utils.GetBinConfigPath(Global.CorePreConfigFileName);
var result = await CoreConfigHandler.GenerateClientConfig(itemSocks, fileName);
if (result.Success)
{
var coreInfo = CoreInfoHandler.Instance.GetCoreInfo(preCoreType);
var proc = await RunProcess(coreInfo, Global.CorePreConfigFileName, true, true);
if (proc is null)
2023-04-21 06:49:33 +00:00
{
return;
}
_processPre = proc;
}
2019-10-11 06:15:20 +00:00
}
}
}
2023-01-01 11:42:01 +00:00
private void UpdateFunc(bool notify, string msg)
{
_updateFunc?.Invoke(notify, msg);
}
2019-12-24 01:01:13 +00:00
#endregion Private
#region Process
private async Task<Process?> RunProcess(CoreInfo? coreInfo, string configPath, bool displayLog, bool mayNeedSudo)
{
var fileName = CoreInfoHandler.Instance.GetCoreExecFile(coreInfo, out var msg);
if (fileName.IsNullOrEmpty())
2019-12-24 01:01:13 +00:00
{
UpdateFunc(false, msg);
return null;
}
2025-04-28 07:16:58 +00:00
try
{
if (mayNeedSudo
&& _config.TunModeItem.EnableTun
&& coreInfo.CoreType == ECoreType.sing_box
&& Utils.IsNonWindows())
{
_linuxSudo = true;
await CoreAdminHandler.Instance.Init(_config, _updateFunc);
return await CoreAdminHandler.Instance.RunProcessAsLinuxSudo(fileName, coreInfo, configPath);
}
return await RunProcessNormal(fileName, coreInfo, configPath, displayLog);
}
catch (Exception ex)
2025-04-26 01:50:31 +00:00
{
2025-04-28 07:16:58 +00:00
Logging.SaveLog(_tag, ex);
UpdateFunc(mayNeedSudo, ex.Message);
return null;
2025-04-26 01:50:31 +00:00
}
2025-04-28 07:16:58 +00:00
}
2025-04-26 01:50:31 +00:00
2025-04-28 07:16:58 +00:00
private async Task<Process?> RunProcessNormal(string fileName, CoreInfo? coreInfo, string configPath, bool displayLog)
{
Process proc = new()
{
StartInfo = new()
{
FileName = fileName,
Arguments = string.Format(coreInfo.Arguments, coreInfo.AbsolutePath ? Utils.GetBinConfigPath(configPath).AppendQuotes() : configPath),
WorkingDirectory = Utils.GetBinConfigPath(),
UseShellExecute = false,
RedirectStandardOutput = displayLog,
RedirectStandardError = displayLog,
CreateNoWindow = true,
StandardOutputEncoding = displayLog ? Encoding.UTF8 : null,
StandardErrorEncoding = displayLog ? Encoding.UTF8 : null,
}
};
if (displayLog)
{
void dataHandler(object sender, DataReceivedEventArgs e)
{
2025-04-28 07:16:58 +00:00
if (e.Data.IsNotEmpty())
{
2025-04-28 07:16:58 +00:00
UpdateFunc(false, e.Data + Environment.NewLine);
}
}
proc.OutputDataReceived += dataHandler;
proc.ErrorDataReceived += dataHandler;
2025-04-28 07:16:58 +00:00
}
proc.Start();
2024-11-27 08:52:25 +00:00
2025-04-28 07:16:58 +00:00
if (displayLog)
{
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
2024-11-27 08:52:25 +00:00
}
2025-04-28 07:16:58 +00:00
await Task.Delay(100);
AppHandler.Instance.AddProcess(proc.Handle);
if (proc is null or { HasExited: true })
2024-11-27 08:52:25 +00:00
{
2025-04-28 07:16:58 +00:00
throw new Exception(ResUI.FailedToRunCore);
}
2025-04-28 07:16:58 +00:00
return proc;
}
2024-11-27 08:52:25 +00:00
#endregion Process
}