示例#1
0
        /// <summary>
        ///     搜索出口和TUNTAP适配器
        /// </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))
            {
                Logging.Info("TAP 适配器未安装");
                return(false);
            }

            // 根据 ComponentID 寻找 Tap适配器
            try
            {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
                Global.TUNTAP.Adapter = adapter;
                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)
            {
                var msg = e switch
                {
                    InvalidOperationException _ => $"找不到标识符为 {Global.TUNTAP.ComponentID} 的 TAP 适配器: {e.Message}",
                    NetworkInformationException _ => $"获取 Tap 适配器信息错误: {e.Message}",
                    _ => $"Tap 适配器其他异常: {e}"
                };
                Logging.Error(msg);
                return(false);
            }
        }
示例#2
0
        public TapAdapter()
        {
            Index       = -1;
            ComponentID = TUNTAP.GetComponentID() ?? throw new MessageException("TAP 适配器未安装");

            // 根据 ComponentID 寻找 Tap适配器
            NetworkInterface = NetworkInterface.GetAllNetworkInterfaces().First(i => i.Id == ComponentID);
            Index            = NetworkInterface.GetIPProperties().GetIPv4Properties().Index;
            Logging.Info($"TAP 适配器:{NetworkInterface.Name} {NetworkInterface.Id} {NetworkInterface.Description}, index: {Index}");
        }
示例#3
0
        public override bool Start(Server server, Mode mode)
        {
            _savedMode   = mode;
            _savedServer = server;

            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
            {
                pDNSController.Start();
                dns = "127.0.0.1";
            }

            var argument = new StringBuilder();

            if (server.Type == "Socks5")
            {
                argument.Append($"-proxyServer {server.Hostname}:{server.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.SupportFakeDns)
            {
                argument.Append("-fakeDns ");
            }

            return(StartInstanceAuto(argument.ToString(), ProcessPriorityClass.RealTime));
        }
示例#4
0
        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);
        }
示例#5
0
        public override bool Start(Server server, Mode mode)
        {
            _savedMode   = mode;
            _savedServer = server;

            if (!Configure())
            {
                return(false);
            }

            SetupRouteTable();

            var adapterName = TUNTAP.GetName(Global.TUNTAP.ComponentID);

            string dns;

            //V2ray使用Unbound本地DNS会导致查询异常缓慢故此V2ray不启动unbound而是使用自定义DNS
            //if (Global.Settings.TUNTAP.UseCustomDNS || server.Type.Equals("VMess"))
            if (Global.Settings.TUNTAP.UseCustomDNS)
            {
                dns = Global.Settings.TUNTAP.DNS.Aggregate(string.Empty, (current, value) => current + (value + ',')).Trim();
                dns = dns.Substring(0, dns.Length - 1);
            }
            else
            {
                pDNSController.Start();
                dns = "127.0.0.1";
            }

            if (Global.Settings.TUNTAP.UseFakeDNS)
            {
                dns += " -fakeDns";
            }

            var argument = new StringBuilder();

            if (server.Type == "Socks5")
            {
                argument.Append($"-proxyServer {server.Hostname}:{server.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}\"");

            State = State.Starting;
            return(StartInstanceAuto(argument.ToString(), ProcessPriorityClass.RealTime));
        }
示例#6
0
        public static void Main()
        {
            // 检查 TUN/TAP 适配器
            if (TUNTAP.GetComponentId() == "" && !TUNTAP.Create())
            {
                MessageBox.Show("尝试安装 TUN/TAP 适配器时失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                Application.Exit();
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(Global.Views.MainForm = new MainForm());
        }
示例#7
0
        /// <summary>
        ///     搜索出口和TUNTAP适配器
        /// </summary>
        public static bool SearchTapAdapter()
        {
            // 搜索 TUN/TAP 适配器的索引
            if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
            {
                Logging.Info("找不到 TAP 适配器");
                if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"),
                                     confirm: true) == DialogResult.OK)
                {
                    Configuration.addtap();
                    // 给点时间,不然立马安装完毕就查找适配器可能会导致找不到适配器ID
                    Thread.Sleep(1000);
                    if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
                    {
                        Logging.Error("找不到 TAP 适配器,驱动可能安装失败");
                        return(false);
                    }
                }
                else
                {
                    Logging.Info("取消安装 TAP 驱动 ");
                    return(false);
                }
            }

            // 根据 ComponentID 寻找 Tap适配器
            try
            {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
                Global.TUNTAP.Adapter = adapter;
                Global.TUNTAP.Index   = adapter.GetIPProperties().GetIPv4Properties().Index;
                Logging.Info(
                    $"TAP 适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
            }
            catch (Exception e)
            {
                var msg = e switch
                {
                    InvalidOperationException _ => $"找不到标识符为 {Global.TUNTAP.ComponentID} 的 TAP 适配器: {e.Message}",
                    NetworkInformationException _ => $"获取 Tap 适配器信息错误: {e.Message}",
                    _ => $"Tap 适配器其他异常: {e}"
                };
                Logging.Error(msg);
                return(false);
            }

            return(true);
        }
示例#8
0
        /// <summary>
        ///     搜索出口和TUNTAP适配器
        /// </summary>
        private static bool SearchAdapters()
        {
            NetworkInterface adapter;

            Logging.Info("搜索适配器");
            if (Win32Native.GetBestRoute(BitConverter.ToUInt32(IPAddress.Parse("114.114.114.114").GetAddressBytes(), 0), 0, out var pRoute) == 0)
            {
                Global.Adapter.Index = pRoute.dwForwardIfIndex;
                adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.GetIPProperties().GetIPv4Properties().Index == Global.Adapter.Index);
                Global.Adapter.Address = adapter.GetIPProperties().UnicastAddresses.First(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork).Address;
                Global.Adapter.Gateway = new IPAddress(pRoute.dwForwardNextHop);
                Logging.Info($"出口 IPv4 地址:{Global.Adapter.Address}");
                Logging.Info($"出口 网关 地址:{Global.Adapter.Gateway}");
                Logging.Info($"出口适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.Adapter.Index}");
            }
            else
            {
                Logging.Error("GetBestRoute 搜索失败(找不到出口适配器)");
                return(false);
            }

            // 搜索 TUN/TAP 适配器的索引
            Global.TUNTAP.ComponentID = TUNTAP.GetComponentID();
            if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID))
            {
                Logging.Error("未找到可用 TAP 适配器");
                if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"), confirm: true) == DialogResult.OK)
                {
                    Configuration.addtap();
                    // 给点时间,不然立马安装完毕就查找适配器可能会导致找不到适配器ID
                    Thread.Sleep(1000);
                    Global.TUNTAP.ComponentID = TUNTAP.GetComponentID();
                }
                else
                {
                    return(false);
                }
            }

            adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
            Global.TUNTAP.Adapter = adapter;
            Global.TUNTAP.Index   = adapter.GetIPProperties().GetIPv4Properties().Index;
            Logging.Info($"TAP 适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
            return(true);
        }
示例#9
0
        /// <summary>
        ///     搜索出口和TUNTAP适配器
        /// </summary>
        public static bool SearchTapAdapter()
        {
            // 搜索 TUN/TAP 适配器的索引
            if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
            {
                Logging.Info("TAP adapter not found");
                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 adapter not found, The driver may fail to install");
                        return(false);
                    }
                }
                else
                {
                    Logging.Info("TAP driver installation cancelled");
                    return(false);
                }
            }

            // 根据 ComponentID 寻找 Tap适配器
            try {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
                Global.TUNTAP.Adapter = adapter;
                Global.TUNTAP.Index   = adapter.GetIPProperties().GetIPv4Properties().Index;
                Logging.Info(
                    $"TAP adapter: {adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
            } catch (Exception e) {
                var msg = e switch
                {
                    InvalidOperationException _ => $"Could not find tap adapter with identifier {Global.TUNTAP.ComponentID}: {e.Message}",
                    NetworkInformationException _ => $"Error getting tap adapter information: {e.Message}",
                    _ => $"Tap adapter other exceptions: {e}"
                };
                Logging.Error(msg);
                return(false);
            }

            return(true);
        }
示例#10
0
        public static void Main()
        {
#if !DEBUG
            var filenames = new string[]
            {
                "driver\\OemVista.inf",
                "driver\\tap0901.cat",
                "driver\\tap0901.sys",
                "tapinstall.exe",
                "tun2socks.exe",
                "geoip.dat",
                "geosite.dat",
                "v2ctl.exe",
                "v2ray.exe",
                "wv2ray.exe"
            };

            // 依赖文件检查
            foreach (var filename in filenames)
            {
                if (!File.Exists(filename))
                {
                    MessageBox.Show(string.Format("缺失重要文件:{0}", filename), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    Application.Exit();
                    return;
                }
            }

            // 检查 TUN/TAP 适配器
            if (TUNTAP.GetComponentId() == "" && !TUNTAP.Create())
            {
                MessageBox.Show("尝试安装 TUN/TAP 适配器时失败!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                Application.Exit();
                return;
            }
#endif

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(Global.Views.MainForm = new MainForm());
        }
示例#11
0
        private async void reinstallTapDriverToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StatusText(i18N.Translate("Reinstalling TUN/TAP driver"));
            Enabled = false;
            try
            {
                await Task.Run(() =>
                {
                    TUNTAP.deltapall();
                    TUNTAP.addtap();
                });

                StatusText(i18N.Translate("Reinstall TUN/TAP driver successfully"));
            }
            catch
            {
                NotifyTip(i18N.Translate("Reinstall TUN/TAP driver failed"), info: false);
            }
            finally
            {
                State   = State.Waiting;
                Enabled = true;
            }
        }
示例#12
0
        /// <summary>
        ///		启动
        /// </summary>
        /// <param name="server">配置</param>
        /// <returns>是否成功</returns>
        public bool Start(Server server, Mode mode)
        {
            MainForm.Instance.StatusText(i18N.Translate("Starting Tap"));
            foreach (var proc in Process.GetProcessesByName("tun2socks"))
            {
                try
                {
                    proc.Kill();
                }
                catch (Exception)
                {
                    // 跳过
                }
            }

            if (!File.Exists("bin\\tun2socks.exe"))
            {
                return(false);
            }

            if (File.Exists("logging\\tun2socks.log"))
            {
                File.Delete("logging\\tun2socks.log");
            }

            SavedMode   = mode;
            SavedServer = server;

            if (!Configure())
            {
                return(false);
            }

            Logging.Info("设置绕行规则");
            SetupBypass();
            Logging.Info("设置绕行规则完毕");

            Instance = new Process();
            Instance.StartInfo.WorkingDirectory = string.Format("{0}\\bin", Directory.GetCurrentDirectory());
            Instance.StartInfo.FileName         = string.Format("{0}\\bin\\tun2socks.exe", Directory.GetCurrentDirectory());
            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.StartInfo.CreateNoWindow         = true;
            Instance.StartInfo.RedirectStandardError  = true;
            Instance.StartInfo.RedirectStandardInput  = true;
            Instance.StartInfo.RedirectStandardOutput = true;
            Instance.StartInfo.UseShellExecute        = false;
            Instance.EnableRaisingEvents = true;
            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);
        }
示例#13
0
        /// <summary>
        ///     搜索出口和TUNTAP适配器
        /// </summary>
        private static bool SearchAdapters()
        {
            // 寻找出口适配器
            if (Win32Native.GetBestRoute(BitConverter.ToUInt32(IPAddress.Parse("114.114.114.114").GetAddressBytes(), 0), 0, out var pRoute) != 0)
            {
                Logging.Error("GetBestRoute 搜索失败(找不到出口适配器)");
                return(false);
            }

            Global.Adapter.Index = pRoute.dwForwardIfIndex;

            // 搜索 TUN/TAP 适配器的索引
            if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
            {
                Logging.Info("找不到 TAP 适配器");
                if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"), confirm: true) == DialogResult.OK)
                {
                    Configuration.addtap();
                    // 给点时间,不然立马安装完毕就查找适配器可能会导致找不到适配器ID
                    Thread.Sleep(1000);
                    if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
                    {
                        Logging.Error("找不到 TAP 适配器,驱动可能安装失败");
                        return(false);
                    }
                }
                else
                {
                    Logging.Info("取消安装 TAP 驱动 ");
                    return(false);
                }
            }

            // 根据 IP Index 寻找 出口适配器
            var errorAdaptersId = new List <string>();

            try
            {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ =>
                {
                    try
                    {
                        return(_.GetIPProperties().GetIPv4Properties().Index == Global.Adapter.Index);
                    }
                    catch (NetworkInformationException)
                    {
                        errorAdaptersId.Add(_.Id);
                        return(false);
                    }
                });
                Global.Adapter.Address = adapter.GetIPProperties().UnicastAddresses.First(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork).Address;
                Global.Adapter.Gateway = new IPAddress(pRoute.dwForwardNextHop);
                Logging.Info($"出口 IPv4 地址:{Global.Adapter.Address}");
                Logging.Info($"出口 网关 地址:{Global.Adapter.Gateway}");
                Logging.Info($"出口适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.Adapter.Index}");
            }
            catch (Exception e)
            {
                Logging.Error($"找不到 IP Index 为 {Global.Adapter.Index} 的出口适配器: {e.Message}");
                PrintAdapters();
                return(false);
            }

            // 根据 ComponentID 寻找 Tap适配器
            try
            {
                var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
                Global.TUNTAP.Adapter = adapter;
                Global.TUNTAP.Index   = adapter.GetIPProperties().GetIPv4Properties().Index;
                Logging.Info($"TAP 适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
            }
            catch (Exception e)
            {
                var msg = e switch
                {
                    InvalidOperationException _ => $"找不到标识符为 {Global.TUNTAP.ComponentID} 的 TAP 适配器: {e.Message}",
                    NetworkInformationException _ => $"获取 Tap 适配器信息错误: {e.Message}",
                    _ => $"Tap 适配器其他异常: {e}"
                };
                Logging.Error(msg);
                PrintAdapters();
                return(false);
            }

            return(true);

            void PrintAdapters()
            {
                Logging.Info("所有适配器:\n" +
                             NetworkInterface.GetAllNetworkInterfaces().Aggregate(string.Empty, (current, adapter)
                                                                                  => current + $"{ /*如果加了 ’*‘ 代表遍历中出现异常的适配器  */(errorAdaptersId.Contains(adapter.Id) ? "*" : "")}{adapter.Name} {adapter.Id} {adapter.Description}{Global.EOF}"));
            }
        }
示例#14
0
文件: MainForm.cs 项目: Ryandan/x2tap
        private void ControlButton_Click(object sender, EventArgs e)
        {
            if (!Started)
            {
                if (ProxyComboBox.SelectedIndex != -1)
                {
                    if (TUNTAP.GetComponentId() != "")
                    {
                        Status = "执行中";
                        Reset(false);
                        ControlButton.Text = "执行中";

                        Task.Run(() =>
                        {
                            try
                            {
                                Thread.Sleep(1000);
                                Status = "正在生成配置文件中";
                                if (ModeComboBox.SelectedIndex == 0)
                                {
                                    File.WriteAllText("v2ray.txt", ProxyComboBox.Text.StartsWith("[v2ray]") ? Config.v2rayGet(Global.v2rayProxies[ProxyComboBox.SelectedIndex]) : Config.ShadowsocksGet(Global.ShadowsocksProxies[ProxyComboBox.SelectedIndex - Global.v2rayProxies.Count]));
                                }
                                else
                                {
                                    File.WriteAllText("v2ray.txt", ProxyComboBox.Text.StartsWith("[v2ray]") ? Config.v2rayGet(Global.v2rayProxies[ProxyComboBox.SelectedIndex], false) : Config.ShadowsocksGet(Global.ShadowsocksProxies[ProxyComboBox.SelectedIndex - Global.v2rayProxies.Count], false));
                                }

                                Thread.Sleep(1000);
                                Status = "正在启动 v2ray 中";
                                Shell.ExecuteCommandNoWait("start", "wv2ray.exe", "-config", "v2ray.txt");

                                Thread.Sleep(2000);
                                try
                                {
                                    using (var client = new TcpClient())
                                    {
                                        var task = client.BeginConnect("127.0.0.1", 2810, null, null);
                                        if (!task.AsyncWaitHandle.WaitOne(1000))
                                        {
                                            throw new TimeoutException();
                                        }

                                        client.EndConnect(task);
                                    }
                                }
                                catch (Exception)
                                {
                                    Status = "检测到 v2ray 启动失败";
                                    Reset();
                                    Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "wv2ray.exe");
                                    MessageBox.Show("检测到 v2ray 启动失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }

                                Thread.Sleep(1000);
                                Status = "正在启动 tun2socks 中";
                                Shell.ExecuteCommandNoWait("start", "RunHiddenConsole.exe", "tun2socks.exe", "-enable-dns-cache", "-local-socks-addr", "127.0.0.1:2810", "-tun-address", "10.0.236.10", "-tun-mask", "255.255.255.0", "-tun-gw", "10.0.236.1", "-tun-dns", "127.0.0.1");

                                Thread.Sleep(2000);
                                if (Process.GetProcessesByName("tun2socks").Length == 0)
                                {
                                    Status = "检测到 tun2socks 启动失败";
                                    Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "tun2socks.exe");
                                    MessageBox.Show("检测到 tun2socks 启动失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }

                                Thread.Sleep(1000);
                                Status = "正在配置 路由表 中";
                                if (ModeComboBox.SelectedIndex == 0 || ModeComboBox.SelectedIndex == 1)
                                {
                                    if (!Route.Add("0.0.0.0", "0.0.0.0", "10.0.236.1"))
                                    {
                                        Route.Delete("0.0.0.0", "0.0.0.0", "10.0.236.1");
                                        Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "wv2ray.exe");
                                        Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "tun2socks.exe");
                                        Status = "在操作路由表时发生错误!";
                                        Reset();
                                        MessageBox.Show("在操作路由表时发生错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        return;
                                    }

                                    if (!Route.Add("0.0.0.0", "128.0.0.0", "10.0.236.1"))
                                    {
                                        Route.Delete("0.0.0.0", "0.0.0.0", "10.0.236.1");
                                        Route.Delete("0.0.0.0", "128.0.0.0", "10.0.236.1");
                                        Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "wv2ray.exe");
                                        Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "tun2socks.exe");
                                        Status = "在操作路由表时发生错误!";
                                        Reset();
                                        MessageBox.Show("在操作路由表时发生错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        return;
                                    }
                                }
                                else
                                {
                                    var mode = Global.Modes[ModeComboBox.SelectedIndex - 2];
                                    if (mode.Type == 1)
                                    {
                                        if (!Route.Add("0.0.0.0", "0.0.0.0", "10.0.236.1"))
                                        {
                                            Route.Delete("0.0.0.0", "0.0.0.0", "10.0.236.1");
                                            Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "wv2ray.exe");
                                            Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "tun2socks.exe");
                                            Status = "在操作路由表时发生错误!";
                                            Reset();
                                            MessageBox.Show("在操作路由表时发生错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            return;
                                        }

                                        if (!Route.Add("0.0.0.0", "128.0.0.0", "10.0.236.1"))
                                        {
                                            Route.Delete("0.0.0.0", "0.0.0.0", "10.0.236.1");
                                            Route.Delete("0.0.0.0", "128.0.0.0", "10.0.236.1");
                                            Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "wv2ray.exe");
                                            Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "tun2socks.exe");
                                            Status = "在操作路由表时发生错误!";
                                            Reset();
                                            MessageBox.Show("在操作路由表时发生错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            return;
                                        }
                                    }

                                    foreach (var rule in mode.Rule)
                                    {
                                        var splited = rule.Split('/');
                                        if (splited.Length == 2)
                                        {
                                            if (mode.Type == 0)
                                            {
                                                Route.Add(splited[0], Route.TranslateCIDR(splited[1]), "10.0.236.1");
                                            }
                                            else
                                            {
                                                Route.Add(splited[0], Route.TranslateCIDR(splited[1]), Global.Config.adapterGateway);
                                            }
                                        }
                                    }
                                }

                                Thread.Sleep(1000);
                                Status = "正在清理 DNS 缓存中";
                                Shell.ExecuteCommandNoWait("ipconfig", "/flushdns");

                                Thread.Sleep(1000);
                                Status                = "已启动,请自行检查网络是否正常";
                                Bandwidth             = 0;
                                Started               = true;
                                ControlButton.Text    = "停止";
                                ControlButton.Enabled = true;
                            }
                            catch (Exception ex)
                            {
                                Reset(true);

                                MessageBox.Show(ex.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        });
                    }
                    else
                    {
                        MessageBox.Show("未检测到 TUN/TAP 适配器,请检查 TAP-Windows 驱动是否正确安装!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    MessageBox.Show("请选择一个代理", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                ControlButton.Text    = "执行中";
                ControlButton.Enabled = false;

                Task.Run(() =>
                {
                    Thread.Sleep(1000);
                    Status = "正在重置 路由表 中";
                    Route.Delete("0.0.0.0", "0.0.0.0", "10.0.236.1");
                    Route.Delete("0.0.0.0", "128.0.0.0", "10.0.236.1");
                    if (ModeComboBox.SelectedIndex != 0 && ModeComboBox.SelectedIndex != 1)
                    {
                        foreach (var rule in Global.Modes[ModeComboBox.SelectedIndex - 2].Rule)
                        {
                            var splited = rule.Split('/');
                            if (splited.Length == 2)
                            {
                                Route.Delete(splited[0]);
                            }
                        }
                    }

                    Thread.Sleep(1000);
                    Status = "正在停止 tun2socks 中";
                    Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "wv2ray.exe");

                    Thread.Sleep(1000);
                    Status = "正在停止 v2ray 中";
                    Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "tun2socks.exe");

                    Status  = "已停止";
                    Started = false;
                    Reset();
                });
            }
        }
示例#15
0
        private void ControlButton_Click(object sender, EventArgs e)
        {
            if (!Started)
            {
                if (ProxyComboBox.SelectedIndex != -1)
                {
                    if (TUNTAP.GetComponentId() != "")
                    {
                        Status = "执行中";
                        ProxyComboBox.Enabled              = false;
                        ModeComboBox.Enabled               = false;
                        Addv2rayServerButton.Enabled       = false;
                        AddShadowsocksServerButton.Enabled = false;
                        DeleteButton.Enabled               = false;
                        EditButton.Enabled      = false;
                        SubscribeButton.Enabled = false;
                        AdvancedButton.Enabled  = false;
                        ControlButton.Text      = "执行中";
                        ControlButton.Enabled   = false;

                        Task.Run(() =>
                        {
                            Thread.Sleep(1000);
                            Status = "正在生成配置文件中";
                            Invoke(new MethodInvoker(() =>
                            {
                                if (ModeComboBox.SelectedIndex == 0)
                                {
                                    File.WriteAllText("v2ray.txt", ProxyComboBox.Text.StartsWith("[v2ray]") ? v2rayConfig(Encoding.UTF8.GetString(Resources.v2rayWithBypassChina)) : ShadowsocksConfig(Encoding.UTF8.GetString(Resources.ShadowsocksWithBypassChina)));
                                }
                                else
                                {
                                    File.WriteAllText("v2ray.txt", ProxyComboBox.Text.StartsWith("[v2ray]") ? v2rayConfig(Encoding.UTF8.GetString(Resources.v2rayWithoutBypassChina)) : ShadowsocksConfig(Encoding.UTF8.GetString(Resources.ShadowsocksWithoutBypassChina)));
                                }
                            }));

                            Thread.Sleep(1000);
                            Status = "正在启动 v2ray 中";
                            Shell.ExecuteCommandNoWait("start", "wv2ray.exe", "-config", "v2ray.txt");

                            Thread.Sleep(2000);
                            try
                            {
                                using (var client = new TcpClient())
                                {
                                    var task = client.BeginConnect("127.0.0.1", 2810, null, null);
                                    if (!task.AsyncWaitHandle.WaitOne(1000))
                                    {
                                        throw new TimeoutException();
                                    }

                                    client.EndConnect(task);
                                }
                            }
                            catch (Exception)
                            {
                                Status = "检测到 v2ray 启动失败";
                                Invoke(new MethodInvoker(() =>
                                {
                                    ProxyComboBox.Enabled              = true;
                                    ModeComboBox.Enabled               = true;
                                    Addv2rayServerButton.Enabled       = true;
                                    AddShadowsocksServerButton.Enabled = true;
                                    DeleteButton.Enabled               = true;
                                    EditButton.Enabled      = true;
                                    SubscribeButton.Enabled = true;
                                    AdvancedButton.Enabled  = true;
                                    ControlButton.Text      = "启动";
                                    ControlButton.Enabled   = true;
                                }));
                                Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "wv2ray.exe");
                                MessageBox.Show("检测到 v2ray 启动失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                            Thread.Sleep(1000);
                            Status = "正在启动 tun2socks 中";
                            Shell.ExecuteCommandNoWait("start", "RunHiddenConsole.exe", "tun2socks.exe", "-enable-dns-cache", "-local-socks-addr", "127.0.0.1:2810", "-public-only", "-tun-address", "10.0.236.10", "-tun-mask", "255.255.255.0", "-tun-gw", "10.0.236.1", "-tun-dns", "114.114.114.114,114.114.115.115");

                            Thread.Sleep(2000);
                            if (Process.GetProcessesByName("tun2socks").Length == 0)
                            {
                                Status = "检测到 tun2socks 启动失败";
                                Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "tun2socks.exe");
                                MessageBox.Show("检测到 tun2socks 启动失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                            Thread.Sleep(1000);
                            Status = "正在配置 路由表 中";
                            if (!Route.Add("0.0.0.0", "0.0.0.0", "10.0.236.1"))
                            {
                                Route.Delete("0.0.0.0", "0.0.0.0", "10.0.236.1");
                                Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "wv2ray.exe");
                                Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "tun2socks.exe");
                                Status = "在操作路由表时发生错误!";
                                Invoke(new MethodInvoker(() =>
                                {
                                    ProxyComboBox.Enabled              = true;
                                    ModeComboBox.Enabled               = true;
                                    Addv2rayServerButton.Enabled       = true;
                                    AddShadowsocksServerButton.Enabled = true;
                                    DeleteButton.Enabled               = true;
                                    EditButton.Enabled      = true;
                                    SubscribeButton.Enabled = true;
                                    AdvancedButton.Enabled  = true;
                                    ControlButton.Text      = "启动";
                                    ControlButton.Enabled   = true;
                                }));
                                MessageBox.Show("在操作路由表时发生错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                            if (!Route.Add("0.0.0.0", "128.0.0.0", "10.0.236.1"))
                            {
                                Route.Delete("0.0.0.0", "128.0.0.0", "10.0.236.1");
                                Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "wv2ray.exe");
                                Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "tun2socks.exe");
                                Status = "在操作路由表时发生错误!";
                                Invoke(new MethodInvoker(() =>
                                {
                                    ProxyComboBox.Enabled              = true;
                                    ModeComboBox.Enabled               = true;
                                    Addv2rayServerButton.Enabled       = true;
                                    AddShadowsocksServerButton.Enabled = true;
                                    DeleteButton.Enabled               = true;
                                    EditButton.Enabled      = true;
                                    SubscribeButton.Enabled = true;
                                    AdvancedButton.Enabled  = true;
                                    ControlButton.Text      = "启动";
                                    ControlButton.Enabled   = true;
                                }));
                                MessageBox.Show("在操作路由表时发生错误!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                            Thread.Sleep(1000);
                            Status    = "已启动,请自行检查网络是否正常";
                            Bandwidth = 0;
                            Started   = true;
                            Invoke(new MethodInvoker(() =>
                            {
                                ControlButton.Text    = "停止";
                                ControlButton.Enabled = true;
                            }));
                        });
                    }
                    else
                    {
                        MessageBox.Show("未检测到 TUN/TAP 适配器,请检查 TAP-Windows 驱动是否正确安装!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    MessageBox.Show("请选择一个代理", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                ControlButton.Text    = "执行中";
                ControlButton.Enabled = false;

                Task.Run(() =>
                {
                    Thread.Sleep(1000);
                    Status = "正在重置 路由表 中";
                    Route.Delete("0.0.0.0", "128.0.0.0", "10.0.236.1");

                    Thread.Sleep(1000);
                    Status = "正在停止 tun2socks 中";
                    Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "wv2ray.exe");

                    Thread.Sleep(1000);
                    Status = "正在停止 v2ray 中";
                    Shell.ExecuteCommandNoWait("taskkill", "/f", "/t", "/im", "tun2socks.exe");

                    Status  = "已停止";
                    Started = false;
                    Invoke(new MethodInvoker(() =>
                    {
                        ProxyComboBox.Enabled              = true;
                        ModeComboBox.Enabled               = true;
                        Addv2rayServerButton.Enabled       = true;
                        AddShadowsocksServerButton.Enabled = true;
                        DeleteButton.Enabled               = true;
                        EditButton.Enabled      = true;
                        SubscribeButton.Enabled = true;
                        AdvancedButton.Enabled  = true;
                        ControlButton.Text      = "启动";
                        ControlButton.Enabled   = true;
                    }));
                });
            }
        }
        public bool Start()
        {
            string TUNTAPaddress = "10.0.0.2";
            string TUNTAPgw      = "10.0.0.1";
            string hostName      = "127.0.0.1";
            string port          = "2801";

            // 查找并安装 TAP 适配器
            if (string.IsNullOrEmpty(TUNTAP.GetComponentID()))
            {
                //CCWin.MessageBoxEx.Show("未检测到虚拟网卡驱动,驱动即将自动安装,请在弹出的窗口内点击'始终安装此驱动程序软件',并重新加速!", "提示:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                TUNTAP.addtap();
            }
            string path = System.Environment.CurrentDirectory;

            if (!Directory.Exists(path + @"\bin"))//如果不存在就创建bin文件夹
            {
                Directory.CreateDirectory(path + @"\bin");
            }
            if (!File.Exists(path + @"\bin\Accelerator.exe"))//tun2socks.exe不存在就从资源导出
            {
                CCWin.MessageBoxEx.Show("驱动文件丢失,请重新安装本软件!", "提示:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return(false);
            }
            string url       = EncryptsHelper.Decrypt(ConfigurationManager.ConnectionStrings["GamesURL"].ToString());
            string tempParh  = Path.GetTempPath();
            string routepath = tempParh + "routetmp.txt";

            if (File.Exists(tempParh + "routetmp.txt"))
            {
                File.Delete(tempParh + "routetmp.txt");
            }
            NetWorkHelper.RoutetxtSave(url + MainFrm.CurrentGame.SerialCode + ".txt", routepath);
            if (!File.Exists(tempParh + "routetmp.txt"))
            {
                CCWin.MessageBoxEx.Show("获取路由表文件失败,请联系开发者!", "提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            Task.Run(() =>
            {
                //修改路由表文件
                string routeif = TUNTAPController.GetIF().ToString();
                //防止文本字符中有特殊字符。必须用Encoding.Default
                StreamReader reader = new StreamReader(tempParh + "routetmp.txt", Encoding.Default);
                String a            = reader.ReadToEnd();
                a = a.Replace("IFZ", $"{routeif}");//替换IF值
                StreamWriter readTxt = new StreamWriter(tempParh + "routetmp1.txt", false, Encoding.Default);
                readTxt.Write(a);
                readTxt.Flush();
                readTxt.Close();
                reader.Close();
                File.Copy(tempParh + "routetmp1.txt", tempParh + "routetmp.txt", true);
                File.Delete(tempParh + "routetmp1.txt");
            });
            var argument = new StringBuilder();

            //argument.Append(
            //    $"-tunAddr {TUNTAPaddress} -tunGw {TUNTAPgw} -dnsServer 8.8.8.8,8.8.4.4 -proxyType shadowsocks -proxyServer {hostName}:{port} " +
            //    $"-proxyCipher {method} -proxyPassword {pwd}");
            argument.Append(
                $"-tunAddr {TUNTAPaddress} -tunGw {TUNTAPgw} -dnsServer 8.8.8.8,8.8.4.4 -proxyServer {hostName}:{port} ");

            NoBoundaries = new Process();
            NoBoundaries.StartInfo.FileName               = path + @"\bin\Accelerator.exe";
            NoBoundaries.StartInfo.Arguments              = argument.ToString();
            NoBoundaries.StartInfo.UseShellExecute        = false; //是否使用操作系统shell启动
            NoBoundaries.StartInfo.RedirectStandardInput  = true;  //接受来自调用程序的输入信息
            NoBoundaries.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
            NoBoundaries.StartInfo.CreateNoWindow         = true;  //不显示程序窗口
            NoBoundaries.Start();
            return(true);
        }
示例#17
0
        public override bool Start(Server server, Mode mode)
        {
            Global.MainForm.StatusText(i18N.Translate("Starting Tap"));

            _savedMode   = mode;
            _savedServer = server;

            if (!Configure())
            {
                return(false);
            }

            SetupRouteTable();

            Instance = GetProcess();

            var adapterName = TUNTAP.GetName(Global.TUNTAP.ComponentID);

            string dns;

            //V2ray使用Unbound本地DNS会导致查询异常缓慢故此V2ray不启动unbound而是使用自定义DNS
            //if (Global.Settings.TUNTAP.UseCustomDNS || server.Type.Equals("VMess"))
            if (Global.Settings.TUNTAP.UseCustomDNS)
            {
                dns = string.Empty;
                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 = $"-proxyServer {server.Hostname}:{server.Port} -tunAddr {Global.Settings.TUNTAP.Address} -tunMask {Global.Settings.TUNTAP.Netmask} -tunGw {Global.Settings.TUNTAP.Gateway} -tunDns {dns} -tunName \"{adapterName}\"";
            }
            else
            {
                Instance.StartInfo.Arguments = $"-proxyServer 127.0.0.1:{Global.Settings.Socks5LocalPort} -tunAddr {Global.Settings.TUNTAP.Address} -tunMask {Global.Settings.TUNTAP.Netmask} -tunGw {Global.Settings.TUNTAP.Gateway} -tunDns {dns} -tunName \"{adapterName}\"";
            }

            Instance.ErrorDataReceived  += OnOutputDataReceived;
            Instance.OutputDataReceived += OnOutputDataReceived;

            State = State.Starting;
            Instance.Start();
            Instance.BeginErrorReadLine();
            Instance.BeginOutputReadLine();
            Instance.PriorityClass = ProcessPriorityClass.RealTime;

            for (var i = 0; i < 1000; i++)
            {
                Thread.Sleep(10);

                switch (State)
                {
                case State.Started:
                    return(true);

                case State.Stopped:
                    Stop();
                    return(false);
                }
            }

            return(false);
        }
示例#18
0
        public bool Start(Server s, Mode mode)
        {
            _savedMode   = mode;
            _savedServer = s;

            // 查询服务器 IP 地址
            _serverAddresses = DNS.Lookup(_savedServer.Hostname);

            // 查找出口适配器
            if (!Utils.Utils.SearchOutboundAdapter())
            {
                return(false);
            }

            // 查找并安装 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 {_serverAddresses}:{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));
        }
        public static int GetIF()
        {
            var list = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == TUNTAP.GetComponentID());

            return(list.GetIPProperties().GetIPv4Properties().Index);
        }
示例#20
0
        /// <summary>
        ///     搜索出口和TUNTAP适配器
        /// </summary>
        private static bool SearchAdapters()
        {
            // 寻找出口适配器
            if (Win32Native.GetBestRoute(BitConverter.ToUInt32(IPAddress.Parse("114.114.114.114").GetAddressBytes(), 0), 0, out var pRoute) != 0)
            {
                Logging.Error("GetBestRoute 搜索失败(找不到出口适配器)");
                return(false);
            }

            Global.Adapter.Index = pRoute.dwForwardIfIndex;

            // 搜索 TUN/TAP 适配器的索引
            if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
            {
                Logging.Info("找不到 TAP 适配器");
                if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"), confirm: true) == DialogResult.OK)
                {
                    Configuration.addtap();
                    // 给点时间,不然立马安装完毕就查找适配器可能会导致找不到适配器ID
                    Thread.Sleep(1000);
                    if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID = TUNTAP.GetComponentID()))
                    {
                        Logging.Error("找不到 TAP 适配器,驱动可能安装失败");
                        return(false);
                    }
                }
                else
                {
                    Logging.Info("取消安装 TAP 驱动 ");
                    return(false);
                }
            }

            try
            {
                try
                {
                    var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.GetIPProperties().GetIPv4Properties().Index == Global.Adapter.Index);
                    Global.Adapter.Address = adapter.GetIPProperties().UnicastAddresses.First(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork).Address;
                    Global.Adapter.Gateway = new IPAddress(pRoute.dwForwardNextHop);
                    Logging.Info($"出口 IPv4 地址:{Global.Adapter.Address}");
                    Logging.Info($"出口 网关 地址:{Global.Adapter.Gateway}");
                    Logging.Info($"出口适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.Adapter.Index}");
                    // Ex NetworkInformationException: 此接口不支持 IPv4 协议。

                    // Ex NetworkInformationException: Windows 系统函数调用失败。
                    // Ex System.ArgumentNullException: source 或 predicate 为 null。
                }
                catch (Exception e)
                {
                    if (e is InvalidOperationException)
                    {
                        Logging.Error($"找不到网络接口索引为 {Global.Adapter.Index} 的出口适配器");
                    }
                    throw;
                }

                try
                {
                    var adapter = NetworkInterface.GetAllNetworkInterfaces().First(_ => _.Id == Global.TUNTAP.ComponentID);
                    Global.TUNTAP.Adapter = adapter;
                    Global.TUNTAP.Index   = adapter.GetIPProperties().GetIPv4Properties().Index;
                    Logging.Info($"TAP 适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}");
                }
                catch (Exception e)
                {
                    if (e is InvalidOperationException)
                    {
                        Logging.Error($"找不到标识符为 {Global.TUNTAP.ComponentID} 的 TAP 适配器");
                    }
                    throw;
                }

                return(true);
            }
            catch (InvalidOperationException)
            {
                // 理论上如果得到了网络接口的索引/网络适配器的标识符不会找不到网卡
                // 只是异常处理
                Logging.Info("所有适配器:\n" +
                             NetworkInterface.GetAllNetworkInterfaces().Aggregate(string.Empty, (current, adapter)
                                                                                  => current + $"{adapter.Name} {adapter.Id} {adapter.Description}, index: {Global.TUNTAP.Index}{Global.EOF}"));
                return(false);
            }
            catch (NetworkInformationException e)
            {
                if (e.ErrorCode == 10043)
                {
                    MessageBoxX.Show("适配器未开启IPv4协议", LogLevel.ERROR, owner: Global.MainForm);
                }
                return(false);
            }
        }
示例#21
0
        /// <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);
        }
示例#22
0
        /// <summary>
        ///     搜索出口
        /// </summary>
        public static bool SearchOutbounds()
        {
            Logging.Info("正在搜索出口中");

            if (Win32Native.GetBestRoute(BitConverter.ToUInt32(IPAddress.Parse("114.114.114.114").GetAddressBytes(), 0), 0, out var pRoute) == 0)
            {
                Global.Adapter.Index   = pRoute.dwForwardIfIndex;
                Global.Adapter.Gateway = new IPAddress(pRoute.dwForwardNextHop);
                Logging.Info($"当前 网关 地址:{Global.Adapter.Gateway}");
            }
            else
            {
                Logging.Error("GetBestRoute 搜索失败");
                return(false);
            }

            Logging.Info($"搜索适配器index:{Global.Adapter.Index}");
            var AddressGot = false;

            foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
            {
                try
                {
                    var adapterProperties = adapter.GetIPProperties();
                    var p = adapterProperties.GetIPv4Properties();
                    Logging.Info($"检测适配器:{adapter.Name} {adapter.Id} {adapter.Description}, index: {p.Index}");

                    // 通过索引查找对应适配器的 IPv4 地址
                    if (p.Index == Global.Adapter.Index)
                    {
                        var AdapterIPs = string.Empty;

                        foreach (var ip in adapterProperties.UnicastAddresses)
                        {
                            if (ip.Address.AddressFamily == AddressFamily.InterNetwork)
                            {
                                AddressGot             = true;
                                Global.Adapter.Address = ip.Address;
                                Logging.Info($"当前出口 IPv4 地址:{Global.Adapter.Address}");
                                break;
                            }

                            AdapterIPs = $"{ip.Address} | ";
                        }

                        if (!AddressGot)
                        {
                            if (AdapterIPs.Length > 3)
                            {
                                AdapterIPs = AdapterIPs.Substring(0, AdapterIPs.Length - 3);
                                Logging.Info($"所有出口地址:{AdapterIPs}");
                            }

                            Logging.Error("出口无 IPv4 地址,当前只支持 IPv4 地址");
                            return(false);
                        }

                        break;
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
            }

            if (!AddressGot)
            {
                Logging.Error("无法找到当前使用适配器");
                return(false);
            }

            // 搜索 TUN/TAP 适配器的索引
            Global.TUNTAP.ComponentID = TUNTAP.GetComponentID();
            if (string.IsNullOrEmpty(Global.TUNTAP.ComponentID))
            {
                Logging.Error("未找到可用 TUN/TAP 适配器");
                if (MessageBoxX.Show(i18N.Translate("TUN/TAP driver is not detected. Is it installed now?"), confirm: true) == DialogResult.OK)
                {
                    Configuration.addtap();
                    //给点时间,不然立马安装完毕就查找适配器可能会导致找不到适配器ID
                    Thread.Sleep(1000);
                    Global.TUNTAP.ComponentID = TUNTAP.GetComponentID();
                }
                else
                {
                    return(false);
                }

                //MessageBoxX.Show(i18N.Translate("Please install TAP-Windows and create an TUN/TAP adapter manually"));
                // return false;
            }

            foreach (var adapter in NetworkInterface.GetAllNetworkInterfaces())
            {
                if (adapter.Id == Global.TUNTAP.ComponentID)
                {
                    Global.TUNTAP.Adapter = adapter;
                    Global.TUNTAP.Index   = adapter.GetIPProperties().GetIPv4Properties().Index;

                    Logging.Info($"找到适配器TUN/TAP:{adapter.Id}");

                    return(true);
                }
            }

            Logging.Error("无法找到出口");
            return(false);
        }