/// <summary> /// 设置绕行规则 /// </summary> public bool SetupBypass() { // 让服务器 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) { using (var sr = new StringReader(Encoding.UTF8.GetString(Properties.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); } } } // 处理全局绕过 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); } } if (SavedMode.Type == 2) // 处理仅规则内走直连 { // 将 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(); // 创建默认路由 if (!NativeMethods.CreateRoute("0.0.0.0", 0, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index, 10)) { State = Models.State.Stopped; foreach (var address in ServerAddresses) { NativeMethods.DeleteRoute(address.ToString(), 32, Global.Adapter.Gateway.ToString(), Global.Adapter.Index); } return(false); } 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) // 处理仅规则内走代理 { 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); } } } } return(true); }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否成功</returns> public bool Start(Models.Server server, Models.Mode mode) { if (!File.Exists("bin\\Redirector.exe")) { return(false); } // 生成驱动文件路径 var driver = String.Format("{0}\\drivers\\netfilter2.sys", Environment.SystemDirectory); // 检查驱动是否存在 if (!File.Exists(driver)) { // 生成系统版本 var version = $"{Environment.OSVersion.Version.Major.ToString()}.{Environment.OSVersion.Version.Minor.ToString()}"; // 检查系统版本并复制对应驱动 try { switch (version) { case "10.0": File.Copy("bin\\Win-10.sys", driver); Utils.Logging.Info("已复制 Win10 驱动"); break; case "6.3": case "6.2": File.Copy("bin\\Win-8.sys", driver); Utils.Logging.Info("已复制 Win8 驱动"); break; case "6.1": case "6.0": File.Copy("bin\\Win-7.sys", driver); Utils.Logging.Info("已复制 Win7 驱动"); break; default: Utils.Logging.Info($"不支持的系统版本:{version}"); return(false); } } catch (Exception e) { Utils.Logging.Info("复制驱动文件失败"); Utils.Logging.Info(e.ToString()); return(false); } // 注册驱动文件 var result = nfapinet.NFAPI.nf_registerDriver("netfilter2"); if (result != nfapinet.NF_STATUS.NF_STATUS_SUCCESS) { Utils.Logging.Info($"注册驱动失败,返回值:{result}"); return(false); } } try { var service = new ServiceController("netfilter2"); if (service.Status == ServiceControllerStatus.Stopped) { service.Start(); } } catch (Exception e) { Utils.Logging.Info(e.ToString()); var result = nfapinet.NFAPI.nf_registerDriver("netfilter2"); if (result != nfapinet.NF_STATUS.NF_STATUS_SUCCESS) { Utils.Logging.Info($"注册驱动失败,返回值:{result}"); return(false); } } var processes = ""; foreach (var proc in mode.Rule) { processes += proc; processes += ","; } processes = processes.Substring(0, processes.Length - 1); Instance = MainController.GetProcess(); Instance.StartInfo.FileName = "bin\\Redirector.exe"; var fallback = ""; if (server.Type != "Socks5") { fallback = $"-r 127.0.0.1:{Global.Settings.Socks5LocalPort} -p \"{processes}\""; } else { var result = Utils.DNS.Lookup(server.Hostname); if (result == null) { Utils.Logging.Info("无法解析服务器 IP 地址"); return(false); } fallback = $"-r {result.ToString()}:{server.Port} -p \"{processes}\""; if (!String.IsNullOrWhiteSpace(server.Username) && !String.IsNullOrWhiteSpace(server.Password)) { fallback += $" -username \"{server.Username}\" -password \"{server.Password}\""; } } Instance.StartInfo.Arguments = fallback + $" -t {Global.Settings.RedirectorTCPPort}"; Instance.OutputDataReceived += OnOutputDataReceived; Instance.ErrorDataReceived += OnOutputDataReceived; State = Models.State.Starting; Instance.Start(); Instance.BeginOutputReadLine(); Instance.BeginErrorReadLine(); var IsFallback = false; for (int i = 0; i < 1000; i++) { Thread.Sleep(10); if (State == Models.State.Started) { return(true); } if (State == Models.State.Stopped) { if (!IsFallback) { IsFallback = true; Stop(); Utils.Logging.Info($"尝试去除 \"-t {Global.Settings.RedirectorTCPPort}\" 参数后启动 \"bin\\Redirector.exe\""); Instance.StartInfo.Arguments = FallBackArg; Utils.Logging.Info($"当前 \"bin\\Redirector.exe\" 启动参数为 \"{Instance.StartInfo.Arguments}\""); Global.Settings.RedirectorTCPPort = 2800; Instance.CancelOutputRead(); Instance.CancelErrorRead(); Instance.OutputDataReceived += OnOutputDataReceived; Instance.ErrorDataReceived += OnOutputDataReceived; State = Models.State.Starting; Instance.Start(); Instance.BeginOutputReadLine(); Instance.BeginErrorReadLine(); } else { Utils.Logging.Info("NF 进程启动失败"); Stop(); return(false); } } } Utils.Logging.Info("NF 进程启动超时"); Stop(); return(false); }
private void ControlButton_Click(object sender, EventArgs e) { if (State == Models.State.Waiting || State == Models.State.Stopped) { // 当前 ServerComboBox 中至少有一项 if (ServerComboBox.SelectedIndex == -1) { MessageBox.Show(Utils.i18N.Translate("Please select a server first"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // 当前 ModeComboBox 中至少有一项 if (ModeComboBox.SelectedIndex == -1) { MessageBox.Show(Utils.i18N.Translate("Please select an mode first"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false; ControlButton.Text = "..."; StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Starting")}"; State = Models.State.Starting; Task.Run(() => { var server = ServerComboBox.SelectedItem as Models.Server; var mode = ModeComboBox.SelectedItem as Models.Mode; MainController = new MainController(); if (MainController.Start(server, mode)) { // UsedBandwidthLabel.Visible = UploadSpeedLabel.Visible = DownloadSpeedLabel.Visible = true; // MainController.pNFController.OnBandwidthUpdated += OnBandwidthUpdated; ControlButton.Enabled = true; ControlButton.Text = Utils.i18N.Translate("Stop"); if (mode.Type != 3 && mode.Type != 5) { if (server.Type != "Socks5") { if (Global.Settings.LocalAddress == "0.0.0.0") { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} ({Utils.i18N.Translate("Allow other Devices to connect")} Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort})"; } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} (Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort}{")"}"; } } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")}"; } } else { if (server.Type != "Socks5") { if (Global.Settings.LocalAddress == "0.0.0.0") { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} ({Utils.i18N.Translate("Allow other Devices to connect")} Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort} | HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort}{")"}"; } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} (Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort} | HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort})"; } } else { if (Global.Settings.LocalAddress == "0.0.0.0") { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} ({Utils.i18N.Translate("Allow other Devices to connect")} HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort}{")"}"; } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} (HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort})"; } } } State = Models.State.Started; } else { MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true; ControlButton.Text = Utils.i18N.Translate("Start"); StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Start failed")}"; State = Models.State.Stopped; } }); } else { ControlButton.Enabled = false; ControlButton.Text = "..."; StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Stopping")}"; State = Models.State.Stopping; MenuStrip.Enabled = ConfigurationGroupBox.Enabled = SettingsButton.Enabled = true; ProfileGroupBox.Enabled = false; Task.Run(() => { var server = ServerComboBox.SelectedItem as Models.Server; var mode = ModeComboBox.SelectedItem as Models.Mode; MainController.Stop(); // LastUploadBandwidth = 0; // LastDownloadBandwidth = 0; // UploadSpeedLabel.Text = "↑: 0 KB/s"; // DownloadSpeedLabel.Text = "↓: 0 KB/s"; // UsedBandwidthLabel.Text = $"{Utils.i18N.Translate("Used")}{Utils.i18N.Translate(": ")}0 KB"; // UsedBandwidthLabel.Visible = UploadSpeedLabel.Visible = DownloadSpeedLabel.Visible = false; ControlButton.Enabled = true; ProfileGroupBox.Enabled = true; ControlButton.Text = Utils.i18N.Translate("Start"); StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Stopped")}"; State = Models.State.Stopped; TestServer(); }); } }
/// <summary> /// 启动 /// </summary> /// <param name="server">配置</param> /// <returns>是否成功</returns> public bool Start(Models.Server server, Models.Mode mode) { 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; 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 { dns = "1.1.1.1,1.0.0.1"; } 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; State = Models.State.Starting; Instance.Start(); Instance.BeginErrorReadLine(); Instance.BeginOutputReadLine(); Instance.PriorityClass = ProcessPriorityClass.RealTime; for (var i = 0; i < 1000; i++) { Thread.Sleep(10); if (State == Models.State.Started) { return(true); } if (State == Models.State.Stopped) { Stop(); return(false); } } return(false); }
/// <summary> /// 设置绕行规则 /// </summary> public bool SetupBypass() { MainForm.Instance.StatusText($"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.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(Properties.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 = Models.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) { string 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); } } } } return(true); }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否启动成功</returns> public bool Start(Models.Server server, Models.Mode mode) { if (!File.Exists("bin\\v2ray.exe") || !File.Exists("bin\\v2ctl.exe")) { return(false); } File.WriteAllText("data\\last.json", Newtonsoft.Json.JsonConvert.SerializeObject(new Models.Information.VMess.Config() { inbounds = new List <Models.Information.VMess.Inbounds>() { new Models.Information.VMess.Inbounds() { settings = new Models.Information.VMess.InboundSettings(), port = Global.Settings.Socks5LocalPort, listen = Global.Settings.LocalAddress } }, outbounds = new List <Models.Information.VMess.Outbounds>() { new Models.Information.VMess.Outbounds() { settings = new Models.Information.VMess.OutboundSettings() { vnext = new List <Models.Information.VMess.VNext>() { new Models.Information.VMess.VNext() { address = server.Hostname, port = server.Port, users = new List <Models.Information.VMess.User> { new Models.Information.VMess.User() { id = server.UserID, alterId = server.AlterID, security = server.EncryptMethod } } } } }, streamSettings = new Models.Information.VMess.StreamSettings() { network = server.TransferProtocol, security = server.TLSSecure == true ? "tls" : "", wsSettings = server.TransferProtocol == "ws" ? new Models.Information.VMess.WebSocketSettings() { path = server.Path == "" ? "/" : server.Path, headers = new Models.Information.VMess.WSHeaders() { Host = server.Host == "" ? server.Hostname : server.Host } } : null, tcpSettings = server.FakeType == "http" ? new Models.Information.VMess.TCPSettings() { header = new Models.Information.VMess.TCPHeaders() { type = server.FakeType, request = new Models.Information.VMess.TCPRequest() { path = server.Path == "" ? "/" : server.Path, headers = new Models.Information.VMess.TCPRequestHeaders() { Host = server.Host == "" ? server.Hostname : server.Host } } } } : null, kcpSettings = server.TransferProtocol == "kcp" ? new Models.Information.VMess.KCPSettings() { header = new Models.Information.VMess.TCPHeaders() { type = server.FakeType } } : null, quicSettings = server.TransferProtocol == "quic" ? new Models.Information.VMess.QUICSettings() { security = server.QUICSecure, key = server.QUICSecret, header = new Models.Information.VMess.TCPHeaders() { type = server.FakeType } } : null, httpSettings = server.TransferProtocol == "h2" ? new Models.Information.VMess.HTTPSettings() { host = server.Host == "" ? server.Hostname : server.Host, path = server.Path == "" ? "/" : server.Path } : null, tlsSettings = new Models.Information.VMess.TLSSettings() }, mux = new Models.Information.VMess.OutboundMux() }, new Models.Information.VMess.Outbounds() { tag = "direct", protocol = "freedom", settings = null, streamSettings = null, mux = null } }, routing = new Models.Information.VMess.Routing() { rules = new List <Models.Information.VMess.RoutingRules>() { mode.BypassChina == true ? new Models.Information.VMess.RoutingRules() { type = "field", ip = new List <string> { "geoip:cn", "geoip:private" }, domain = new List <string> { "geosite:cn" }, outboundTag = "direct" } : new Models.Information.VMess.RoutingRules() { type = "field", ip = new List <string> { "geoip:private" }, outboundTag = "direct" } } } })); // 清理上一次的日志文件,防止淤积占用磁盘空间 if (Directory.Exists("logging")) { if (File.Exists("logging\\v2ray.log")) { File.Delete("logging\\v2ray.log"); } } Instance = MainController.GetProcess(); Instance.StartInfo.FileName = "bin\\v2ray.exe"; Instance.StartInfo.Arguments = "-config ..\\data\\last.json"; Instance.OutputDataReceived += OnOutputDataReceived; Instance.ErrorDataReceived += OnOutputDataReceived; State = Models.State.Starting; Instance.Start(); Instance.BeginOutputReadLine(); Instance.BeginErrorReadLine(); for (int i = 0; i < 1000; i++) { Thread.Sleep(10); if (State == Models.State.Started) { if (File.Exists("data\\last.json")) { File.Delete("data\\last.json"); } return(true); } if (State == Models.State.Stopped) { Utils.Logging.Info("V2Ray 进程启动失败"); Stop(); return(false); } } Utils.Logging.Info("V2Ray 进程启动超时"); Stop(); return(false); }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否启动成功</returns> public bool Start(Models.Server server, Models.Mode mode) { if (!File.Exists("bin\\ShadowsocksR.exe")) { return(false); } Instance = MainController.GetProcess(); Instance.StartInfo.FileName = "bin\\ShadowsocksR.exe"; Instance.StartInfo.Arguments = $"-s {server.Hostname} -p {server.Port} -k \"{server.Password}\" -m {server.EncryptMethod}"; if (!String.IsNullOrEmpty(server.Protocol)) { Instance.StartInfo.Arguments += $" -O {server.Protocol}"; if (!String.IsNullOrEmpty(server.ProtocolParam)) { Instance.StartInfo.Arguments += $" -G \"{server.ProtocolParam}\""; } } if (!String.IsNullOrEmpty(server.OBFS)) { Instance.StartInfo.Arguments += $" -o {server.OBFS}"; if (!String.IsNullOrEmpty(server.OBFSParam)) { Instance.StartInfo.Arguments += $" -g \"{server.OBFSParam}\""; } } Instance.StartInfo.Arguments += $" -b {Global.Settings.LocalAddress} -l {Global.Settings.Socks5LocalPort} -u"; if (mode.BypassChina) { Instance.StartInfo.Arguments += " --acl default.acl"; } Instance.OutputDataReceived += OnOutputDataReceived; Instance.ErrorDataReceived += OnOutputDataReceived; State = Models.State.Starting; Instance.Start(); Instance.BeginOutputReadLine(); Instance.BeginErrorReadLine(); for (int i = 0; i < 1000; i++) { Thread.Sleep(10); if (State == Models.State.Started) { return(true); } if (State == Models.State.Stopped) { Utils.Logging.Info("SSR 进程启动失败"); Stop(); return(false); } } Utils.Logging.Info("SSR 进程启动超时"); Stop(); return(false); }
private void ControlButton_Click(object sender, EventArgs e) { if (State == Models.State.Waiting || State == Models.State.Stopped) { // 当前 ServerComboBox 中至少有一项 if (ServerComboBox.SelectedIndex == -1) { MessageBox.Show(Utils.i18N.Translate("Please select a server first"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } // 当前 ModeComboBox 中至少有一项 if (ModeComboBox.SelectedIndex == -1) { MessageBox.Show(Utils.i18N.Translate("Please select an mode first"), Utils.i18N.Translate("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information); return; } MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false; ControlButton.Text = "..."; StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Starting")}"; State = Models.State.Starting; Task.Run(() => { var server = ServerComboBox.SelectedItem as Models.Server; var mode = ModeComboBox.SelectedItem as Models.Mode; MainController = new MainController(); var startResult = MainController.Start(server, mode);//item1是否启动成功,item2nat类型 if (startResult.Item2 != null) { NatTypeStatusLabel.Text = "NatType:" + startResult.Item2; } else { NatTypeStatusLabel.Text = ""; } if (startResult.Item1) { // UsedBandwidthLabel.Visible = UploadSpeedLabel.Visible = DownloadSpeedLabel.Visible = true; // MainController.pNFController.OnBandwidthUpdated += OnBandwidthUpdated; // 如果勾选启动后最小化 if (Global.Settings.MinimizeWhenStarted) { WindowState = FormWindowState.Minimized; NotifyIcon.Visible = true; if (IsFirstOpened) { // 显示提示语 NotifyIcon.ShowBalloonTip(5, UpdateChecker.Name, Utils.i18N.Translate("Netch is now minimized to the notification bar, double click this icon to restore."), ToolTipIcon.Info); IsFirstOpened = false; } Hide(); } ControlButton.Enabled = true; ControlButton.Text = Utils.i18N.Translate("Stop"); if (mode.Type != 3 && mode.Type != 5) { if (server.Type != "Socks5") { if (Global.Settings.LocalAddress == "0.0.0.0") { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} ({Utils.i18N.Translate("Allow other Devices to connect")} Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort})"; } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} (Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort}{")"}"; } } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")}"; } } else { if (server.Type != "Socks5") { if (Global.Settings.LocalAddress == "0.0.0.0") { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} ({Utils.i18N.Translate("Allow other Devices to connect")} Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort} | HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort}{")"}"; } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} (Socks5 {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.Socks5LocalPort} | HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort})"; } } else { if (Global.Settings.LocalAddress == "0.0.0.0") { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} ({Utils.i18N.Translate("Allow other Devices to connect")} HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort}{")"}"; } else { StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Started")} (HTTP {Utils.i18N.Translate("Local Port")}{Utils.i18N.Translate(": ")}{Global.Settings.HTTPLocalPort})"; } } } State = Models.State.Started; } else { MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true; ControlButton.Text = Utils.i18N.Translate("Start"); StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Start failed")}"; State = Models.State.Stopped; } }); } else { ControlButton.Enabled = false; ControlButton.Text = "..."; StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Stopping")}"; State = Models.State.Stopping; MenuStrip.Enabled = ConfigurationGroupBox.Enabled = SettingsButton.Enabled = true; ProfileGroupBox.Enabled = false; Task.Run(() => { var server = ServerComboBox.SelectedItem as Models.Server; var mode = ModeComboBox.SelectedItem as Models.Mode; MainController.Stop(); NatTypeStatusLabel.Text = ""; // LastUploadBandwidth = 0; // LastDownloadBandwidth = 0; // UploadSpeedLabel.Text = "↑: 0 KB/s"; // DownloadSpeedLabel.Text = "↓: 0 KB/s"; // UsedBandwidthLabel.Text = $"{Utils.i18N.Translate("Used")}{Utils.i18N.Translate(": ")}0 KB"; // UsedBandwidthLabel.Visible = UploadSpeedLabel.Visible = DownloadSpeedLabel.Visible = false; ControlButton.Enabled = true; ProfileGroupBox.Enabled = true; ControlButton.Text = Utils.i18N.Translate("Start"); StatusLabel.Text = $"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Stopped")}"; State = Models.State.Stopped; TestServer(); }); } }
public void DeleteState(Models.State state) { repoState.Delete(state); }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否启动成功</returns> public bool Start(Models.Server server, Models.Mode mode) { MainForm.Instance.StatusText($"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Starting Shadowsocks")}"); File.Delete("logging\\shadowsocks.log"); //从DLL启动Shaowsocks if (Global.Settings.BootShadowsocksFromDLL) { State = Models.State.Starting; var client = Encoding.UTF8.GetBytes($"0.0.0.0:{Global.Settings.Socks5LocalPort}"); var remote = Encoding.UTF8.GetBytes($"{server.Hostname}:{server.Port}"); var passwd = Encoding.UTF8.GetBytes($"{server.Password}"); var method = Encoding.UTF8.GetBytes($"{server.EncryptMethod}"); if (!NativeMethods.Shadowsocks.Info(client, remote, passwd, method)) { State = Models.State.Stopped; Logging.Info("DllSS_Info设置失败!"); return(false); } Logging.Info("DllSS_Info设置成功!"); if (!NativeMethods.Shadowsocks.Start()) { State = Models.State.Stopped; Logging.Info("DllSS_Start 启动失败!"); return(false); } Logging.Info("DllSS_Start 启动成功!"); State = Models.State.Started; return(true); } if (!File.Exists("bin\\Shadowsocks.exe")) { return(false); } Instance = MainController.GetProcess(); Instance.StartInfo.FileName = "bin\\Shadowsocks.exe"; if (!string.IsNullOrWhiteSpace(server.Plugin) && !string.IsNullOrWhiteSpace(server.PluginOption)) { Instance.StartInfo.Arguments = $"-s {server.Hostname} -p {server.Port} -b {Global.Settings.LocalAddress} -l {Global.Settings.Socks5LocalPort} -m {server.EncryptMethod} -k \"{server.Password}\" -u --plugin {server.Plugin} --plugin-opts \"{server.PluginOption}\""; } else { Instance.StartInfo.Arguments = $"-s {server.Hostname} -p {server.Port} -b {Global.Settings.LocalAddress} -l {Global.Settings.Socks5LocalPort} -m {server.EncryptMethod} -k \"{server.Password}\" -u"; } if (mode.BypassChina) { Instance.StartInfo.Arguments += " --acl default.acl"; } Instance.OutputDataReceived += OnOutputDataReceived; Instance.ErrorDataReceived += OnOutputDataReceived; State = Models.State.Starting; Instance.Start(); Instance.BeginOutputReadLine(); Instance.BeginErrorReadLine(); for (var i = 0; i < 1000; i++) { Thread.Sleep(10); if (State == Models.State.Started) { return(true); } if (State == Models.State.Stopped) { Utils.Logging.Info("SS 进程启动失败"); Stop(); return(false); } } Utils.Logging.Info("SS 进程启动超时"); Stop(); return(false); }
public void EditState(Models.State state) { repoState.Update(state); }
public void AddState(Models.State state) { repoState.Create(state); }
/// <summary> /// 设置绕行规则 /// </summary> public bool SetupBypass() { // 让服务器 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) { using (var sr = new StringReader(Encoding.UTF8.GetString(Properties.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); } } } // 处理全局绕过 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); } } if (SavedMode.Type == 2) // 处理仅规则内走直连 { // 创建默认路由 if (!NativeMethods.CreateRoute("0.0.0.0", 0, Global.Settings.TUNTAP.Gateway, Global.TUNTAP.Index, 10)) { State = Models.State.Stopped; foreach (var address in ServerAddresses) { NativeMethods.DeleteRoute(address.ToString(), 32, Global.Adapter.Gateway.ToString(), Global.Adapter.Index); } return(false); } 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) // 处理仅规则内走代理 { 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); } } } } return(true); }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否成功</returns> public bool Start(Models.Server server, Models.Mode mode) { MainForm.Instance.StatusText($"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Starting Redirector")}"); // 检查驱动是否存在 if (File.Exists(driverPath)) { //检查驱动版本号 FileVersionInfo fileVerInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(driverPath); if (new Version(fileVerInfo.FileVersion) < new Version(UpdateChecker.NFDriverVersion)) { //需要更新驱动 try { var service = new ServiceController("netfilter2"); if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } nfapinet.NFAPI.nf_unRegisterDriver("netfilter2"); //删除老驱动 File.Delete(driverPath); if (!InstallDriver()) { return(false); } } catch (Exception) { Utils.Logging.Info($"更新驱动出错"); } } } else { if (!InstallDriver()) { return(false); } } try { //启动驱动服务 var service = new ServiceController("netfilter2"); if (service.Status == ServiceControllerStatus.Running) { //防止其他程序占用 重置NF百万ID限制 待定 /*service.Stop(); * MainForm.Instance.StatusText($"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Starting netfilter2 Service")}"); * service.Start();*/ } else if (service.Status == ServiceControllerStatus.Stopped) { MainForm.Instance.StatusText($"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Starting netfilter2 Service")}"); service.Start(); } } catch (Exception e) { Utils.Logging.Info(e.ToString()); var result = nfapinet.NFAPI.nf_registerDriver("netfilter2"); if (result != nfapinet.NF_STATUS.NF_STATUS_SUCCESS) { Utils.Logging.Info($"注册驱动失败,返回值:{result}"); return(false); } } var processes = ""; //开启进程白名单模式 if (!Global.Settings.ProcessBypassMode) { processes += "NTT.exe,"; } foreach (var proc in mode.Rule) { processes += proc; processes += ","; } processes = processes.Substring(0, processes.Length - 1); Instance = MainController.GetProcess(); var fallback = ""; if (Global.Settings.UseRedirector2) { if (!File.Exists("bin\\Redirector2.exe")) { return(false); } Instance.StartInfo.FileName = "bin\\Redirector2.exe"; if (server.Type != "Socks5") { fallback += $" 127.0.0.1:{Global.Settings.Socks5LocalPort}"; fallback += $" \"{processes}\""; } else { var result = Utils.DNS.Lookup(server.Hostname); if (result == null) { Utils.Logging.Info("无法解析服务器 IP 地址"); return(false); } fallback += $" {result}:{server.Port}"; fallback += $" \"{processes}\""; if (!string.IsNullOrWhiteSpace(server.Username) && !string.IsNullOrWhiteSpace(server.Password)) { fallback += $" \"{server.Username}\""; fallback += $" \"{server.Password}\""; } } } else { if (!File.Exists("bin\\Redirector.exe")) { return(false); } Instance.StartInfo.FileName = "bin\\Redirector.exe"; //开启进程白名单模式 if (Global.Settings.ProcessBypassMode) { processes += ",Shadowsocks.exe"; processes += ",ShadowsocksR.exe"; processes += ",Privoxy.exe"; processes += ",simple-obfs.exe"; processes += ",v2ray.exe,v2ctl.exe,v2ray-plugin.exe"; fallback += " -bypass true "; } else { fallback += " -bypass false "; } if (server.Type != "Socks5") { fallback += $"-r 127.0.0.1:{Global.Settings.Socks5LocalPort} -p \"{processes}\""; } else { var result = Utils.DNS.Lookup(server.Hostname); if (result == null) { Utils.Logging.Info("无法解析服务器 IP 地址"); return(false); } fallback += $"-r {result}:{server.Port} -p \"{processes}\""; if (!string.IsNullOrWhiteSpace(server.Username) && !string.IsNullOrWhiteSpace(server.Password)) { fallback += $" -username \"{server.Username}\" -password \"{server.Password}\""; } } } if (File.Exists("logging\\redirector.log")) { File.Delete("logging\\redirector.log"); } Instance.StartInfo.Arguments = fallback + $" -tcport {Global.Settings.RedirectorTCPPort}"; Utils.Logging.Info(Instance.StartInfo.Arguments); Instance.OutputDataReceived += OnOutputDataReceived; Instance.ErrorDataReceived += OnOutputDataReceived; State = Models.State.Starting; Instance.Start(); Instance.BeginOutputReadLine(); Instance.BeginErrorReadLine(); for (var i = 0; i < 1000; i++) { Thread.Sleep(10); if (State == Models.State.Started) { return(true); } } Utils.Logging.Info("NF 进程启动超时"); Stop(); return(false); }
/// <summary> /// 启动 /// </summary> /// <param name="server">服务器</param> /// <param name="mode">模式</param> /// <returns>是否成功</returns> public bool Start(Models.Server server, Models.Mode mode) { MainForm.Instance.StatusText($"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Starting Redirector")}"); if (!File.Exists("bin\\Redirector.exe")) { return(false); } // 生成驱动文件路径 var driver = string.Format("{0}\\drivers\\netfilter2.sys", Environment.SystemDirectory); if (File.Exists(driver)) { //为了防止小白一直问如何卸载老驱动核心,每次启动时卸载删除一次驱动,保证系统使用最新驱动核心(简单粗暴 但有效:D。增加启动成功率,驱动在被其他加速器占用的情况下可能会导致启动失败 try { var service = new ServiceController("netfilter2"); if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } nfapinet.NFAPI.nf_unRegisterDriver("netfilter2"); File.Delete(driver); } catch (Exception) { // 跳过 } // 生成系统版本 var version = $"{Environment.OSVersion.Version.Major.ToString()}.{Environment.OSVersion.Version.Minor.ToString()}"; // 检查系统版本并复制对应驱动 try { switch (version) { case "10.0": File.Copy("bin\\Win-10.sys", driver); Utils.Logging.Info("已复制 Win10 驱动"); break; case "6.3": case "6.2": File.Copy("bin\\Win-8.sys", driver); Utils.Logging.Info("已复制 Win8 驱动"); break; case "6.1": case "6.0": File.Copy("bin\\Win-7.sys", driver); Utils.Logging.Info("已复制 Win7 驱动"); break; default: Utils.Logging.Info($"不支持的系统版本:{version}"); return(false); } } catch (Exception e) { Utils.Logging.Info("复制驱动文件失败"); Utils.Logging.Info(e.ToString()); return(false); } // 注册驱动文件 var result = nfapinet.NFAPI.nf_registerDriver("netfilter2"); if (result != nfapinet.NF_STATUS.NF_STATUS_SUCCESS) { Utils.Logging.Info($"注册驱动失败,返回值:{result}"); return(false); } } // 检查驱动是否存在 /*if (!File.Exists(driver)) * { * }*/ try { var service = new ServiceController("netfilter2"); if (service.Status == ServiceControllerStatus.Stopped) { MainForm.Instance.StatusText($"{Utils.i18N.Translate("Status")}{Utils.i18N.Translate(": ")}{Utils.i18N.Translate("Starting netfilter2 Service")}"); service.Start(); } } catch (Exception e) { Utils.Logging.Info(e.ToString()); var result = nfapinet.NFAPI.nf_registerDriver("netfilter2"); if (result != nfapinet.NF_STATUS.NF_STATUS_SUCCESS) { Utils.Logging.Info($"注册驱动失败,返回值:{result}"); return(false); } } var processes = "NTT.exe,"; foreach (var proc in mode.Rule) { processes += proc; processes += ","; } processes = processes.Substring(0, processes.Length - 1); Instance = MainController.GetProcess(); Instance.StartInfo.FileName = "bin\\Redirector.exe"; var fallback = ""; if (server.Type != "Socks5") { fallback = $"-r 127.0.0.1:{Global.Settings.Socks5LocalPort} -p \"{processes}\""; } else { var result = Utils.DNS.Lookup(server.Hostname); if (result == null) { Utils.Logging.Info("无法解析服务器 IP 地址"); return(false); } fallback = $"-r {result}:{server.Port} -p \"{processes}\""; if (!string.IsNullOrWhiteSpace(server.Username) && !string.IsNullOrWhiteSpace(server.Password)) { fallback += $" -username \"{server.Username}\" -password \"{server.Password}\""; } } Instance.StartInfo.Arguments = fallback; Instance.OutputDataReceived += OnOutputDataReceived; Instance.ErrorDataReceived += OnOutputDataReceived; State = Models.State.Starting; Instance.Start(); Instance.BeginOutputReadLine(); Instance.BeginErrorReadLine(); for (var i = 0; i < 1000; i++) { Thread.Sleep(10); if (State == Models.State.Started) { return(true); } } Utils.Logging.Info("NF 进程启动超时"); Stop(); return(false); }