refactor: TUNTAPController SearchTapAdapter

change: Reinstall TUN/TAP Adapter to Uninstall TUN/TAP Adapter
rename: ICS to Tap Network Sharing
This commit is contained in:
ChsBuffer
2020-10-04 22:05:08 +08:00
parent 4b4280c06b
commit 2dc4bb771e
10 changed files with 133 additions and 146 deletions

View File

@@ -169,7 +169,7 @@ namespace Netch.Controllers
/// <returns>是否成功卸载</returns>
public static bool UninstallDriver()
{
Global.MainForm.StatusText(i18N.Translate("Uninstalling NF Service"));
Global.MainForm.StatusText(i18N.TranslateFormat("Uninstalling {0}", "NF Service"));
Logging.Info("卸载 NF 驱动");
try
{

View File

@@ -28,12 +28,12 @@ namespace Netch.Controllers
/// <summary>
/// 服务器 IP 地址
/// </summary>
private IPAddress[] _serverAddresses = new IPAddress[0];
private IPAddress _serverAddresses;
/// <summary>
/// 本地 DNS 服务控制器
/// </summary>
public DNSController pDNSController = new DNSController();
public DNSController DNSController = new DNSController();
public TUNTAPController()
{
@@ -44,33 +44,84 @@ namespace Netch.Controllers
public override string Name { get; protected set; } = "tun2socks";
public override string MainFile { get; protected set; } = "tun2socks.exe";
/// <summary>
/// 配置 TUNTAP 适配器
/// </summary>
private bool Configure()
public bool Start(Server s, Mode mode)
{
// 查询服务器 IP 地址
var destination = Dns.GetHostAddressesAsync(_savedServer.Hostname);
if (destination.Wait(1000))
{
if (destination.Result.Length == 0) return false;
_savedMode = mode;
_savedServer = s;
_serverAddresses = destination.Result;
// 查询服务器 IP 地址
_serverAddresses = DNS.Lookup(_savedServer.Hostname);
if (_serverAddresses == null)
{
return false;
}
// 搜索出口
return SearchTapAdapter();
// 查找并安装 TAP 适配器
if (!SearchTapAdapter() && !AddTap())
{
Logging.Error("Tap 适配器安装失败");
return false;
}
SetupRouteTable();
string dns;
if (Global.Settings.TUNTAP.UseCustomDNS)
{
if (Global.Settings.TUNTAP.DNS.Any())
{
dns = Global.Settings.TUNTAP.DNS.Aggregate((current, ip) => $"{current},{ip}");
}
else
{
Global.Settings.TUNTAP.DNS.Add("1.1.1.1");
dns = "1.1.1.1";
}
}
else
{
var _ = DNSController.Start();
dns = "127.0.0.1";
}
var argument = new StringBuilder();
if (s.IsSocks5())
argument.Append($"-proxyServer {s.Hostname}:{s.Port} ");
else
argument.Append($"-proxyServer 127.0.0.1:{Global.Settings.Socks5LocalPort} ");
argument.Append(
$"-tunAddr {Global.Settings.TUNTAP.Address} -tunMask {Global.Settings.TUNTAP.Netmask} -tunGw {Global.Settings.TUNTAP.Gateway} -tunDns {dns} -tunName \"{TUNTAP.GetName(Global.TUNTAP.ComponentID)}\" ");
if (Global.Settings.TUNTAP.UseFakeDNS && Global.Flags.SupportFakeDns)
argument.Append("-fakeDns ");
return StartInstanceAuto(argument.ToString(), ProcessPriorityClass.RealTime);
}
/// <summary>
/// TUN/TAP停止
/// </summary>
public override void Stop()
{
var tasks = new[]
{
Task.Factory.StartNew(StopInstance),
Task.Factory.StartNew(ClearRouteTable),
Task.Factory.StartNew(DNSController.Stop)
};
Task.WaitAll(tasks);
}
private readonly List<IPNetwork> _directIPs = new List<IPNetwork>();
private readonly List<IPNetwork> _proxyIPs = new List<IPNetwork>();
private readonly List<IPNetwork> _proxyIPs = new List<IPNetwork>();
/// <summary>
/// 设置绕行规则
/// </summary>
/// <returns>是否设置成功</returns>
private bool SetupRouteTable()
private void SetupRouteTable()
{
Logging.Info("收集路由表规则");
Global.MainForm.StatusText(i18N.Translate("SetupBypass"));
@@ -79,8 +130,8 @@ namespace Netch.Controllers
_directIPs.AddRange(Global.Settings.BypassIPs.Select(IPNetwork.Parse));
Logging.Info("绕行 → 服务器 IP");
_directIPs.AddRange(_serverAddresses.Where(address => !IPAddress.IsLoopback(address))
.Select(address => IPNetwork.Parse(address.ToString(), 32)));
if (!IPAddress.IsLoopback(_serverAddresses))
_directIPs.Add(IPNetwork.Parse(_serverAddresses.ToString(), 32));
Logging.Info("绕行 → 局域网 IP");
_directIPs.AddRange(_bypassLanIPs.Select(IPNetwork.Parse));
@@ -113,22 +164,11 @@ namespace Netch.Controllers
Logging.Info("代理 → 自定义 DNS");
if (Global.Settings.TUNTAP.UseCustomDNS)
{
var dns = string.Empty;
foreach (var value in Global.Settings.TUNTAP.DNS)
{
dns += value;
dns += ',';
}
dns = dns.Trim();
dns = dns.Substring(0, dns.Length - 1);
RouteAction(Action.Create, dns, 32, RouteType.TUNTAP);
_proxyIPs.AddRange(Global.Settings.TUNTAP.DNS.Select(ip => IPNetwork.Parse(ip, 32)));
}
else
{
_proxyIPs.AddRange(
new[] {"1.1.1.1", "8.8.8.8", "9.9.9.9", "185.222.222.222"}.Select(ip =>
IPNetwork.Parse(ip, 32)));
_proxyIPs.AddRange(new[] {"1.1.1.1", "8.8.8.8", "9.9.9.9", "185.222.222.222"}.Select(ip => IPNetwork.Parse(ip, 32)));
}
}
@@ -167,7 +207,7 @@ namespace Netch.Controllers
if (!RouteAction(Action.Create, IPNetwork.Parse("0.0.0.0", 0), RouteType.TUNTAP))
{
State = State.Stopped;
return false;
return;
}
break;
@@ -176,8 +216,6 @@ namespace Netch.Controllers
Logging.Info("设置路由规则");
RouteAction(Action.Create, _directIPs, RouteType.Gateway);
RouteAction(Action.Create, _proxyIPs, RouteType.TUNTAP);
return true;
}
@@ -203,65 +241,6 @@ namespace Netch.Controllers
}
public bool Start(Server s, Mode mode)
{
_savedMode = mode;
_savedServer = s;
if (!Configure()) return false;
SetupRouteTable();
var adapterName = TUNTAP.GetName(Global.TUNTAP.ComponentID);
string dns;
if (Global.Settings.TUNTAP.UseCustomDNS)
{
if (Global.Settings.TUNTAP.DNS.Any())
{
dns = Global.Settings.TUNTAP.DNS.Aggregate((current, ip) => $"{current},{ip}");
}
else
{
Global.Settings.TUNTAP.DNS.Add("1.1.1.1");
dns = "1.1.1.1";
}
}
else
{
var _ = pDNSController.Start();
dns = "127.0.0.1";
}
var argument = new StringBuilder();
if (s.IsSocks5())
argument.Append($"-proxyServer {s.Hostname}:{s.Port} ");
else
argument.Append($"-proxyServer 127.0.0.1:{Global.Settings.Socks5LocalPort} ");
argument.Append(
$"-tunAddr {Global.Settings.TUNTAP.Address} -tunMask {Global.Settings.TUNTAP.Netmask} -tunGw {Global.Settings.TUNTAP.Gateway} -tunDns {dns} -tunName \"{adapterName}\" ");
if (Global.Settings.TUNTAP.UseFakeDNS && Global.Flags.SupportFakeDns)
argument.Append("-fakeDns ");
return StartInstanceAuto(argument.ToString(), ProcessPriorityClass.RealTime);
}
/// <summary>
/// TUN/TAP停止
/// </summary>
public override void Stop()
{
var tasks = new[]
{
Task.Factory.StartNew(StopInstance),
Task.Factory.StartNew(ClearRouteTable),
Task.Factory.StartNew(pDNSController.Stop)
};
Task.WaitAll(tasks);
}
public bool TestFakeDNS()
{
var exited = false;
@@ -303,27 +282,15 @@ namespace Netch.Controllers
/// </summary>
public static bool SearchTapAdapter()
{
Global.TUNTAP.Adapter = null;
Global.TUNTAP.Index = -1;
Global.TUNTAP.ComponentID = TUNTAP.GetComponentID();
// 搜索 TUN/TAP 适配器的索引
if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID))
{
Logging.Info("找不到 TAP 适配器");
if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"),
confirm: true) == DialogResult.OK)
{
TUNTAP.addtap();
// 给点时间不然立马安装完毕就查找适配器可能会导致找不到适配器ID
Thread.Sleep(1000);
if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
{
Logging.Error("找不到 TAP 适配器,驱动可能安装失败");
return false;
}
}
else
{
Logging.Info("取消安装 TAP 驱动 ");
return false;
}
Logging.Info("TAP 适配器未安装");
return false;
}
// 根据 ComponentID 寻找 Tap适配器
@@ -334,6 +301,7 @@ namespace Netch.Controllers
Global.TUNTAP.Index = adapter.GetIPProperties().GetIPv4Properties().Index;
Logging.Info(
$"TAP 适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
return true;
}
catch (Exception e)
{
@@ -346,6 +314,18 @@ namespace Netch.Controllers
Logging.Error(msg);
return false;
}
}
private static bool AddTap()
{
TUNTAP.addtap();
// 给点时间不然立马安装完毕就查找适配器可能会导致找不到适配器ID
Thread.Sleep(1000);
if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
{
Logging.Error("找不到 TAP 适配器,驱动可能安装失败");
return false;
}
return true;
}

View File

@@ -45,7 +45,7 @@
this.UpdateACLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.updateACLWithProxyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.UninstallServiceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.reinstallTapDriverToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.UninstallTapDriverToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.HelpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.CheckForUpdatesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.fAQToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
@@ -193,7 +193,7 @@
this.UpdateACLToolStripMenuItem,
this.updateACLWithProxyToolStripMenuItem,
this.UninstallServiceToolStripMenuItem,
this.reinstallTapDriverToolStripMenuItem});
this.UninstallTapDriverToolStripMenuItem});
this.OptionsToolStripMenuItem.Margin = new System.Windows.Forms.Padding(0, 0, 0, 1);
this.OptionsToolStripMenuItem.Name = "OptionsToolStripMenuItem";
this.OptionsToolStripMenuItem.Size = new System.Drawing.Size(66, 21);
@@ -234,12 +234,12 @@
this.UninstallServiceToolStripMenuItem.Text = "Uninstall NF Service";
this.UninstallServiceToolStripMenuItem.Click += new System.EventHandler(this.UninstallServiceToolStripMenuItem_Click);
//
// reinstallTapDriverToolStripMenuItem
// UninstallTapDriverToolStripMenuItem
//
this.reinstallTapDriverToolStripMenuItem.Name = "reinstallTapDriverToolStripMenuItem";
this.reinstallTapDriverToolStripMenuItem.Size = new System.Drawing.Size(219, 22);
this.reinstallTapDriverToolStripMenuItem.Text = "Reinstall TUN/TAP driver";
this.reinstallTapDriverToolStripMenuItem.Click += new System.EventHandler(this.reinstallTapDriverToolStripMenuItem_Click);
this.UninstallTapDriverToolStripMenuItem.Name = "UninstallTapDriverToolStripMenuItem";
this.UninstallTapDriverToolStripMenuItem.Size = new System.Drawing.Size(219, 22);
this.UninstallTapDriverToolStripMenuItem.Text = "Uninstall TUN/TAP driver";
this.UninstallTapDriverToolStripMenuItem.Click += new System.EventHandler(this.reinstallTapDriverToolStripMenuItem_Click);
//
// HelpToolStripMenuItem
//
@@ -735,7 +735,7 @@
private System.Windows.Forms.Label ProfileLabel;
private System.Windows.Forms.TextBox ProfileNameText;
private System.Windows.Forms.TableLayoutPanel ProfileTable;
private System.Windows.Forms.ToolStripMenuItem reinstallTapDriverToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem UninstallTapDriverToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem CheckForUpdatesToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem ReloadModesToolStripMenuItem;
private System.Windows.Forms.ComboBox ServerComboBox;

View File

@@ -315,14 +315,14 @@ namespace Netch.Forms
private async void UninstallServiceToolStripMenuItem_Click(object sender, EventArgs e)
{
Enabled = false;
StatusText(i18N.Translate("Uninstalling NF Service"));
StatusText(i18N.TranslateFormat("Uninstalling {0}", "NF Service"));
try
{
await Task.Run(() =>
{
if (NFController.UninstallDriver())
{
StatusText(i18N.Translate("Service has been uninstalled"));
StatusText(i18N.TranslateFormat("{0} has been uninstalled", "NF Service"));
}
});
}
@@ -334,20 +334,16 @@ namespace Netch.Forms
private async void reinstallTapDriverToolStripMenuItem_Click(object sender, EventArgs e)
{
StatusText(i18N.Translate("Reinstalling TUN/TAP driver"));
StatusText(i18N.TranslateFormat("Uninstalling {0}", "TUN/TAP driver"));
Enabled = false;
try
{
await Task.Run(() =>
{
TUNTAP.deltapall();
TUNTAP.addtap();
});
StatusText(i18N.Translate("Reinstall TUN/TAP driver successfully"));
await Task.Run(TUNTAP.deltapall);
StatusText(i18N.TranslateFormat("{0} has been uninstalled", "TUN/TAP driver"));
}
catch
catch (Exception exception)
{
NotifyTip(i18N.Translate("Reinstall TUN/TAP driver failed"), info: false);
Logging.Error($"卸载 TUN/TAP 适配器失败: {exception}");
}
finally
{

View File

@@ -37,7 +37,7 @@ namespace Netch.Forms
UninstallServiceToolStripMenuItem.Enabled =
updateACLWithProxyToolStripMenuItem.Enabled =
UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled =
reinstallTapDriverToolStripMenuItem.Enabled =
UninstallTapDriverToolStripMenuItem.Enabled =
ReloadModesToolStripMenuItem.Enabled = enabled;
}

View File

@@ -41,6 +41,13 @@ namespace Netch.Forms
{
AddAddServerToolStripMenuItems();
#region i18N Translations
_mainFormText.Add(UninstallServiceToolStripMenuItem.Name, new[] {"Uninstall {0}", "NF Service"});
_mainFormText.Add(UninstallTapDriverToolStripMenuItem.Name, new[] {"Uninstall {0}", "TUN/TAP driver"});
#endregion
OnlyInstance.Called += OnCalled;
// 计算 ComboBox绘制 目标宽度
_eWidth = ServerComboBox.Width / 10;

View File

@@ -206,7 +206,8 @@
this.ICSCheckBox.Name = "ICSCheckBox";
this.ICSCheckBox.Size = new System.Drawing.Size(46, 21);
this.ICSCheckBox.TabIndex = 5;
this.ICSCheckBox.Text = "ICS";
this.ICSCheckBox.Text = "Tap Network Sharing";
this.ICSCheckBox.Enabled = false;
this.ICSCheckBox.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.ICSCheckBox.UseVisualStyleBackColor = true;
this.ICSCheckBox.CheckedChanged += new System.EventHandler(this.ICSCheckBox_CheckedChanged);

View File

@@ -38,7 +38,12 @@ namespace Netch.Forms
TUNTAPUseCustomDNSCheckBox_CheckedChanged(null, null);
ProxyDNSCheckBox.Checked = Global.Settings.TUNTAP.ProxyDNS;
UseFakeDNSCheckBox.Checked = Global.Settings.TUNTAP.UseFakeDNS;
ICSCheckBox.Checked = ICSHelper.Enabled;
if (TUNTAPController.SearchTapAdapter())
{
ICSCheckBox.Enabled = true;
ICSCheckBox.Checked = ICSHelper.Enabled;
}
// Behavior
ExitWhenClosedCheckBox.Checked = Global.Settings.ExitWhenClosed;

View File

@@ -11,7 +11,7 @@
"Stop": "停止",
"Waiting for command": "等待命令中",
"Starting": "正在启动中",
"Start failed": "启动失败请打开软件目录logging文件夹查看日志",
"Start failed": "启动失败",
"Started": "已启动",
"Stopping": "正在停止中",
"Stopped": "已停止",
@@ -78,9 +78,11 @@
"Update servers error from {0}": "从 {0} 更新服务器失败",
"Options": "选项",
"Uninstall NF Service": "卸载 NF 服务",
"Uninstalling NF Service": "正在卸载 NF 服务中",
"Service has been uninstalled": "服务已卸载",
"NF Service": "NF 服务",
"TUN/TAP driver": "TUN/TAP 驱动",
"Uninstall {0}": "卸载 {0}",
"Uninstalling {0}": "正在卸载 {0} 中",
"{0} has been uninstalled": "{0} 已卸载",
"Reload Modes": "重载模式",
"Modes have been reload": "模式已重载",
"Clean DNS Cache": "清理 DNS 缓存",
@@ -89,10 +91,6 @@
"Update ACL with proxy": "使用代理更新 ACL 规则",
"ACL updated successfully": "ACL 更新成功",
"ACL update failed": "ACL 更新失败",
"Reinstall TUN/TAP driver": "重新安装 TUN/TAP 驱动",
"Reinstall TUN/TAP driver successfully": "重装 TUN/TAP 驱动成功",
"Reinstall TUN/TAP driver failed": "重装 TUN/TAP 驱动失败",
"Reinstalling TUN/TAP driver": "正在重装 TUN/TAP 驱动",
"Open Directory": "打开目录",
"About": "关于",

View File

@@ -51,7 +51,7 @@ namespace Netch.Utils
/// <returns>适配器名称</returns>
public static string GetName(string componentId)
{
var registry = Registry.LocalMachine.OpenSubKey(string.Format("{0}\\{1}\\Connection", NETWORK_KEY, componentId));
var registry = Registry.LocalMachine.OpenSubKey($"{NETWORK_KEY}\\{componentId}\\Connection");
return registry.GetValue("Name", "").ToString();
}
@@ -70,7 +70,7 @@ namespace Netch.Utils
/// </summary>
public static void deltapall()
{
Logging.Info("正在卸载 TUN/TAP 适配器");
Logging.Info("卸载 TUN/TAP 适配器");
var installProcess = new Process {StartInfo = {WindowStyle = ProcessWindowStyle.Hidden, FileName = Path.Combine("bin/tap-driver", "deltapall.bat")}};
installProcess.Start();
installProcess.WaitForExit();
@@ -82,7 +82,7 @@ namespace Netch.Utils
/// </summary>
public static void addtap()
{
Logging.Info("正在安装 TUN/TAP 适配器");
Logging.Info("安装 TUN/TAP 适配器");
//安装Tap Driver
var installProcess = new Process {StartInfo = {WindowStyle = ProcessWindowStyle.Hidden, FileName = Path.Combine("bin/tap-driver", "addtap.bat")}};
installProcess.Start();