using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace FastGithub.Dns.DnscryptProxy
{
///
/// DnscryptProxy服务
///
sealed class DnscryptProxyService
{
private readonly FastGithubConfig fastGithubConfig;
///
/// 获取文件名
///
public string Name => "dnscrypt-proxy";
///
/// DnscryptProxy服务
///
///
public DnscryptProxyService(FastGithubConfig fastGithubConfig)
{
this.fastGithubConfig = fastGithubConfig;
}
///
/// 启动dnscrypt-proxy
///
///
///
public async Task StartAsync(CancellationToken cancellationToken)
{
var tomlPath = $"{this.Name}.toml";
await TomlUtil.SetListensAsync(tomlPath, this.fastGithubConfig.PureDns, cancellationToken);
foreach (var process in Process.GetProcessesByName(this.Name))
{
process.Kill();
}
if (OperatingSystem.IsWindows())
{
this.StartDnscryptProxy("-service install", waitForExit: true);
this.StartDnscryptProxy("-service start", waitForExit: true);
}
else
{
this.StartDnscryptProxy(string.Empty, waitForExit: false);
}
}
///
/// 停止dnscrypt-proxy
///
public void Stop()
{
if (OperatingSystem.IsWindows())
{
this.StartDnscryptProxy("-service stop", waitForExit: true);
this.StartDnscryptProxy("-service uninstall", waitForExit: true);
}
foreach (var process in Process.GetProcessesByName(this.Name))
{
process.Kill();
}
}
///
/// 等待退出
///
public void WaitForExit()
{
var process = Process.GetProcessesByName(this.Name).FirstOrDefault();
if (process != null)
{
process.WaitForExit();
}
}
///
/// 启动DnscryptProxy进程
///
///
///
private void StartDnscryptProxy(string arguments, bool waitForExit)
{
var process = Process.Start(new ProcessStartInfo
{
FileName = OperatingSystem.IsWindows() ? $"{this.Name}.exe" : this.Name,
Arguments = arguments,
UseShellExecute = true,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden
});
if (waitForExit && process != null)
{
process.WaitForExit();
}
}
///
/// 转换为字符串
///
///
public override string ToString()
{
return this.Name;
}
}
}