mirror of
https://github.com/netchx/netch.git
synced 2026-03-18 18:13:21 +08:00
408 lines
16 KiB
C#
408 lines
16 KiB
C#
using System.Collections.Generic;
|
||
using System.Diagnostics;
|
||
using System.IO;
|
||
using System.Net;
|
||
using System.Text;
|
||
using System.Threading;
|
||
using Netch.Forms;
|
||
using Netch.Models;
|
||
using Netch.Properties;
|
||
using Netch.Utils;
|
||
|
||
namespace Netch.Controllers
|
||
{
|
||
public class TUNTAPController : Controller
|
||
{
|
||
// ByPassLan IP
|
||
private readonly List<string> BypassLanIPs = new List<string> {"10.0.0.0/8", "172.16.0.0/16", "192.168.0.0/16"};
|
||
|
||
/// <summary>
|
||
/// 本地 DNS 服务控制器
|
||
/// </summary>
|
||
public DNSController pDNSController = new DNSController();
|
||
|
||
public Mode SavedMode = new Mode();
|
||
|
||
/// <summary>
|
||
/// 保存传入的规则
|
||
/// </summary>
|
||
public Server SavedServer = new Server();
|
||
|
||
/// <summary>
|
||
/// 服务器 IP 地址
|
||
/// </summary>
|
||
public IPAddress[] ServerAddresses = new IPAddress[0];
|
||
|
||
public TUNTAPController()
|
||
{
|
||
MainName = "tun2socks";
|
||
ready = BeforeStartProgress();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 配置 TUNTAP 适配器
|
||
/// </summary>
|
||
public bool Configure()
|
||
{
|
||
// 查询服务器 IP 地址
|
||
var destination = Dns.GetHostAddressesAsync(SavedServer.Hostname);
|
||
if (destination.Wait(1000))
|
||
{
|
||
if (destination.Result.Length == 0) return false;
|
||
|
||
ServerAddresses = destination.Result;
|
||
}
|
||
|
||
// 搜索出口
|
||
return Configuration.SearchOutbounds();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 设置绕行规则
|
||
/// </summary>
|
||
public bool SetupBypass()
|
||
{
|
||
MainForm.Instance.StatusText(i18N.Translate("SetupBypass"));
|
||
Logging.Info("设置绕行规则 → 设置让服务器 IP 走直连");
|
||
// 让服务器 IP 走直连
|
||
foreach (var address in ServerAddresses)
|
||
if (!IPAddress.IsLoopback(address))
|
||
NativeMethods.CreateRoute(address.ToString(), 32, Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
|
||
// 处理模式的绕过中国
|
||
if (SavedMode.BypassChina)
|
||
{
|
||
Logging.Info("设置绕行规则 → 处理模式的绕过中国");
|
||
using (var sr = new StringReader(Encoding.UTF8.GetString(Resources.CNIP)))
|
||
{
|
||
string text;
|
||
|
||
while ((text = sr.ReadLine()) != null)
|
||
{
|
||
var info = text.Split('/');
|
||
|
||
NativeMethods.CreateRoute(info[0], int.Parse(info[1]), Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
}
|
||
}
|
||
}
|
||
|
||
Logging.Info("设置绕行规则 → 处理全局绕过 IP");
|
||
// 处理全局绕过 IP
|
||
foreach (var ip in Global.Settings.BypassIPs)
|
||
{
|
||
var info = ip.Split('/');
|
||
var address = IPAddress.Parse(info[0]);
|
||
|
||
if (!IPAddress.IsLoopback(address)) NativeMethods.CreateRoute(address.ToString(), int.Parse(info[1]), Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
}
|
||
|
||
Logging.Info("设置绕行规则 → 处理绕过局域网 IP");
|
||
// 处理绕过局域网 IP
|
||
foreach (var ip in BypassLanIPs)
|
||
{
|
||
var info = ip.Split('/');
|
||
var address = IPAddress.Parse(info[0]);
|
||
|
||
if (!IPAddress.IsLoopback(address)) NativeMethods.CreateRoute(address.ToString(), int.Parse(info[1]), Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
}
|
||
|
||
if (SavedMode.Type == 2) // 处理仅规则内走直连
|
||
{
|
||
Logging.Info("设置绕行规则 → 处理仅规则内走直连");
|
||
// 将 TUN/TAP 网卡权重放到最高
|
||
var instance = new Process
|
||
{
|
||
StartInfo =
|
||
{
|
||
FileName = "netsh",
|
||
Arguments = string.Format("interface ip set interface {0} metric=0", Global.TUNTAP.Index),
|
||
WindowStyle = ProcessWindowStyle.Hidden,
|
||
UseShellExecute = true,
|
||
CreateNoWindow = true
|
||
}
|
||
};
|
||
instance.Start();
|
||
|
||
Logging.Info("设置绕行规则 → 创建默认路由");
|
||
// 创建默认路由
|
||
if (!NativeMethods.CreateRoute("0.0.0.0", 0, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index, 10))
|
||
{
|
||
State = State.Stopped;
|
||
|
||
foreach (var address in ServerAddresses) NativeMethods.DeleteRoute(address.ToString(), 32, Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
|
||
return false;
|
||
}
|
||
|
||
Logging.Info("设置绕行规则 → 创建规则路由");
|
||
// 创建规则路由
|
||
foreach (var ip in SavedMode.Rule)
|
||
{
|
||
var info = ip.Split('/');
|
||
|
||
if (info.Length == 2)
|
||
if (int.TryParse(info[1], out var prefix))
|
||
NativeMethods.CreateRoute(info[0], prefix, Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
}
|
||
}
|
||
else if (SavedMode.Type == 1) // 处理仅规则内走代理
|
||
{
|
||
Logging.Info("设置绕行规则->处理仅规则内走代理");
|
||
foreach (var ip in SavedMode.Rule)
|
||
{
|
||
var info = ip.Split('/');
|
||
|
||
if (info.Length == 2)
|
||
if (int.TryParse(info[1], out var prefix))
|
||
NativeMethods.CreateRoute(info[0], prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
}
|
||
|
||
//处理 NAT 类型检测,由于协议的原因,无法仅通过域名确定需要代理的 IP,自己记录解析了返回的 IP,仅支持默认检测服务器
|
||
if (Global.Settings.STUN_Server == "stun.stunprotocol.org")
|
||
try
|
||
{
|
||
var nttAddress = Dns.GetHostAddresses(Global.Settings.STUN_Server)[0];
|
||
if (int.TryParse("32", out var prefix)) NativeMethods.CreateRoute(nttAddress.ToString(), prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
|
||
var nttrAddress = Dns.GetHostAddresses("stunresponse.coldthunder11.com")[0];
|
||
if (int.TryParse("32", out var prefixr)) NativeMethods.CreateRoute(nttrAddress.ToString(), prefixr, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
}
|
||
catch
|
||
{
|
||
Logging.Info("NAT 类型测试域名解析失败,将不会被添加到代理列表");
|
||
}
|
||
|
||
//处理DNS代理
|
||
if (Global.Settings.TUNTAP.ProxyDNS)
|
||
{
|
||
Logging.Info("设置绕行规则 → 处理自定义 DNS 代理");
|
||
if (Global.Settings.TUNTAP.UseCustomDNS)
|
||
{
|
||
var dns = "";
|
||
foreach (var value in Global.Settings.TUNTAP.DNS)
|
||
{
|
||
dns += value;
|
||
dns += ',';
|
||
}
|
||
|
||
dns = dns.Trim();
|
||
dns = dns.Substring(0, dns.Length - 1);
|
||
if (int.TryParse("32", out var prefix)) NativeMethods.CreateRoute(dns, prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
}
|
||
else
|
||
{
|
||
if (int.TryParse("32", out var prefix))
|
||
{
|
||
NativeMethods.CreateRoute("1.1.1.1", prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
NativeMethods.CreateRoute("8.8.8.8", prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
NativeMethods.CreateRoute("9.9.9.9", prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
NativeMethods.CreateRoute("185.222.222.222", prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
return true;
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 清除绕行规则
|
||
/// </summary>
|
||
public bool ClearBypass()
|
||
{
|
||
if (SavedMode.Type == 2)
|
||
{
|
||
NativeMethods.DeleteRoute("0.0.0.0", 0, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index, 10);
|
||
|
||
foreach (var ip in SavedMode.Rule)
|
||
{
|
||
var info = ip.Split('/');
|
||
|
||
if (info.Length == 2)
|
||
if (int.TryParse(info[1], out var prefix))
|
||
NativeMethods.DeleteRoute(info[0], prefix, Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
}
|
||
}
|
||
else if (SavedMode.Type == 1)
|
||
{
|
||
foreach (var ip in SavedMode.Rule)
|
||
{
|
||
var info = ip.Split('/');
|
||
|
||
if (info.Length == 2)
|
||
if (int.TryParse(info[1], out var prefix))
|
||
NativeMethods.DeleteRoute(info[0], prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
}
|
||
|
||
if (Global.Settings.STUN_Server == "stun.stunprotocol.org")
|
||
try
|
||
{
|
||
var nttAddress = Dns.GetHostAddresses(Global.Settings.STUN_Server)[0];
|
||
if (int.TryParse("32", out var prefix)) NativeMethods.DeleteRoute(nttAddress.ToString(), prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
|
||
var nttrAddress = Dns.GetHostAddresses("stunresponse.coldthunder11.com")[0];
|
||
if (int.TryParse("32", out var prefixr)) NativeMethods.DeleteRoute(nttrAddress.ToString(), prefixr, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
}
|
||
catch
|
||
{
|
||
}
|
||
|
||
if (Global.Settings.TUNTAP.ProxyDNS)
|
||
{
|
||
if (Global.Settings.TUNTAP.UseCustomDNS)
|
||
{
|
||
var dns = "";
|
||
foreach (var value in Global.Settings.TUNTAP.DNS)
|
||
{
|
||
dns += value;
|
||
dns += ',';
|
||
}
|
||
|
||
dns = dns.Trim();
|
||
dns = dns.Substring(0, dns.Length - 1);
|
||
if (int.TryParse("32", out var prefix)) NativeMethods.DeleteRoute(dns, prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
}
|
||
else
|
||
{
|
||
if (int.TryParse("32", out var prefix)) NativeMethods.DeleteRoute("1.1.1.1", prefix, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index);
|
||
}
|
||
}
|
||
}
|
||
|
||
foreach (var ip in Global.Settings.BypassIPs)
|
||
{
|
||
var info = ip.Split('/');
|
||
var address = IPAddress.Parse(info[0]);
|
||
|
||
if (!IPAddress.IsLoopback(address)) NativeMethods.DeleteRoute(address.ToString(), int.Parse(info[1]), Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
}
|
||
|
||
foreach (var ip in BypassLanIPs)
|
||
{
|
||
var info = ip.Split('/');
|
||
var address = IPAddress.Parse(info[0]);
|
||
|
||
if (!IPAddress.IsLoopback(address)) NativeMethods.DeleteRoute(address.ToString(), int.Parse(info[1]), Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
}
|
||
|
||
if (SavedMode.BypassChina)
|
||
using (var sr = new StringReader(Encoding.UTF8.GetString(Resources.CNIP)))
|
||
{
|
||
string text;
|
||
|
||
while ((text = sr.ReadLine()) != null)
|
||
{
|
||
var info = text.Split('/');
|
||
|
||
NativeMethods.DeleteRoute(info[0], int.Parse(info[1]), Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
}
|
||
}
|
||
|
||
foreach (var address in ServerAddresses)
|
||
if (!IPAddress.IsLoopback(address))
|
||
NativeMethods.DeleteRoute(address.ToString(), 32, Global.Adapter.Gateway.ToString(), Global.Adapter.Index);
|
||
|
||
return true;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 启动
|
||
/// </summary>
|
||
/// <param name="server">配置</param>
|
||
/// <returns>是否成功</returns>
|
||
public bool Start(Server server, Mode mode)
|
||
{
|
||
MainForm.Instance.StatusText(i18N.Translate("Starting Tap"));
|
||
|
||
SavedMode = mode;
|
||
SavedServer = server;
|
||
|
||
if (!Configure()) return false;
|
||
|
||
Logging.Info("设置绕行规则");
|
||
SetupBypass();
|
||
Logging.Info("设置绕行规则完毕");
|
||
|
||
Instance = MainController.GetProcess("bin\\tun2socks.exe");
|
||
|
||
var adapterName = TUNTAP.GetName(Global.TUNTAP.ComponentID);
|
||
Logging.Info($"tun2sock使用适配器:{adapterName}");
|
||
|
||
string dns;
|
||
//V2ray使用Unbound本地DNS会导致查询异常缓慢故此V2ray不启动unbound而是使用自定义DNS
|
||
//if (Global.Settings.TUNTAP.UseCustomDNS || server.Type.Equals("VMess"))
|
||
if (Global.Settings.TUNTAP.UseCustomDNS)
|
||
{
|
||
dns = "";
|
||
foreach (var value in Global.Settings.TUNTAP.DNS)
|
||
{
|
||
dns += value;
|
||
dns += ',';
|
||
}
|
||
|
||
dns = dns.Trim();
|
||
dns = dns.Substring(0, dns.Length - 1);
|
||
}
|
||
else
|
||
{
|
||
pDNSController.Start();
|
||
dns = "127.0.0.1";
|
||
}
|
||
|
||
if (Global.Settings.TUNTAP.UseFakeDNS) dns += " -fakeDns";
|
||
|
||
if (server.Type == "Socks5")
|
||
Instance.StartInfo.Arguments = string.Format("-proxyServer {0}:{1} -tunAddr {2} -tunMask {3} -tunGw {4} -tunDns {5} -tunName \"{6}\"", server.Hostname, server.Port, Global.Settings.TUNTAP.Address, Global.Settings.TUNTAP.Netmask, Global.Settings.TUNTAP.Gateway, dns, adapterName);
|
||
else
|
||
Instance.StartInfo.Arguments = string.Format("-proxyServer 127.0.0.1:{0} -tunAddr {1} -tunMask {2} -tunGw {3} -tunDns {4} -tunName \"{5}\"", Global.Settings.Socks5LocalPort, Global.Settings.TUNTAP.Address, Global.Settings.TUNTAP.Netmask, Global.Settings.TUNTAP.Gateway, dns, adapterName);
|
||
|
||
Instance.ErrorDataReceived += OnOutputDataReceived;
|
||
Instance.OutputDataReceived += OnOutputDataReceived;
|
||
|
||
Logging.Info(Instance.StartInfo.Arguments);
|
||
|
||
State = State.Starting;
|
||
Instance.Start();
|
||
Instance.BeginErrorReadLine();
|
||
Instance.BeginOutputReadLine();
|
||
Instance.PriorityClass = ProcessPriorityClass.RealTime;
|
||
|
||
for (var i = 0; i < 1000; i++)
|
||
{
|
||
Thread.Sleep(10);
|
||
|
||
if (State == State.Started) return true;
|
||
|
||
if (State == State.Stopped)
|
||
{
|
||
Stop();
|
||
return false;
|
||
}
|
||
}
|
||
|
||
return false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// TUN/TAP停止
|
||
/// </summary>
|
||
public new void Stop()
|
||
{
|
||
base.Stop();
|
||
ClearBypass();
|
||
pDNSController.Stop();
|
||
}
|
||
|
||
public void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
|
||
{
|
||
if (!WriteLog(e)) return;
|
||
if (State == State.Starting)
|
||
{
|
||
if (e.Data.Contains("Running"))
|
||
State = State.Started;
|
||
else if (e.Data.Contains("failed") || e.Data.Contains("invalid vconfig file")) State = State.Stopped;
|
||
}
|
||
}
|
||
}
|
||
} |