diff --git a/Netch/Controllers/DNSController.cs b/Netch/Controllers/DNSController.cs index 29a573ed..b58cd538 100644 --- a/Netch/Controllers/DNSController.cs +++ b/Netch/Controllers/DNSController.cs @@ -8,7 +8,7 @@ namespace Netch.Controllers { public DNSController() { - AkaName = "dns Service"; + Name = "dns Service"; MainFile = "unbound"; ExtFiles = new[] {"unbound-service.conf", "forward-zone.conf"}; InitCheck(); @@ -44,7 +44,7 @@ namespace Netch.Controllers private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { - WriteLog(e); + Write(e.Data); } public override void Stop() diff --git a/Netch/Controllers/EncryptedProxy/SSController.cs b/Netch/Controllers/EncryptedProxy/SSController.cs index 00bea7d7..4780c2ce 100644 --- a/Netch/Controllers/EncryptedProxy/SSController.cs +++ b/Netch/Controllers/EncryptedProxy/SSController.cs @@ -92,7 +92,7 @@ namespace Netch.Controllers public override void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { - if (!WriteLog(e)) return; + if (!Write(e.Data)) return; if (State == State.Starting) { if (Instance.HasExited) diff --git a/Netch/Controllers/EncryptedProxy/SSRController.cs b/Netch/Controllers/EncryptedProxy/SSRController.cs index d11975e0..6ef77874 100644 --- a/Netch/Controllers/EncryptedProxy/SSRController.cs +++ b/Netch/Controllers/EncryptedProxy/SSRController.cs @@ -18,7 +18,6 @@ namespace Netch.Controllers if (!Ready) return false; Instance = GetProcess("bin\\ShadowsocksR.exe"); - Instance.StartInfo.FileName = "bin\\ShadowsocksR.exe"; Instance.OutputDataReceived += OnOutputDataReceived; Instance.ErrorDataReceived += OnOutputDataReceived; @@ -69,7 +68,7 @@ namespace Netch.Controllers public override void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { - if (!WriteLog(e)) return; + if (!Write(e.Data)) return; if (State == State.Starting) { if (Instance.HasExited) diff --git a/Netch/Controllers/EncryptedProxy/TrojanController.cs b/Netch/Controllers/EncryptedProxy/TrojanController.cs index 090609b1..5b75b0ff 100644 --- a/Netch/Controllers/EncryptedProxy/TrojanController.cs +++ b/Netch/Controllers/EncryptedProxy/TrojanController.cs @@ -63,7 +63,7 @@ namespace Netch.Controllers public override void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { - if (!WriteLog(e)) return; + if (!Write(e.Data)) return; if (State == State.Starting) { if (Instance.HasExited) diff --git a/Netch/Controllers/EncryptedProxy/VMessController.cs b/Netch/Controllers/EncryptedProxy/VMessController.cs index 944ad063..19365fab 100644 --- a/Netch/Controllers/EncryptedProxy/VMessController.cs +++ b/Netch/Controllers/EncryptedProxy/VMessController.cs @@ -205,7 +205,7 @@ namespace Netch.Controllers public override void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { - if (!WriteLog(e)) return; + if (!Write(e.Data)) return; if (State == State.Starting) { if (Instance.HasExited) diff --git a/Netch/Controllers/Interface/Controller.cs b/Netch/Controllers/Interface/Controller.cs index 76ca45e9..f551094d 100644 --- a/Netch/Controllers/Interface/Controller.cs +++ b/Netch/Controllers/Interface/Controller.cs @@ -13,7 +13,7 @@ namespace Netch.Controllers /// /// 未赋值会在 赋值为 /// - public string AkaName; + public string Name; /// /// 其他需要文件 @@ -66,7 +66,7 @@ namespace Netch.Controllers /// protected void InitCheck() { - if (string.IsNullOrEmpty(AkaName)) AkaName = MainFile; + if (string.IsNullOrEmpty(Name)) Name = MainFile; var result = false; // 杀残留 @@ -74,7 +74,7 @@ namespace Netch.Controllers // 清日志 try { - if (File.Exists($"logging\\{AkaName}.log")) File.Delete($"logging\\{AkaName}.log"); + if (File.Exists($"logging\\{Name}.log")) File.Delete($"logging\\{Name}.log"); } catch (Exception) { @@ -90,38 +90,37 @@ namespace Netch.Controllers Logging.Error($"主程序 bin\\{MainFile}.exe 不存在"); } - if (ExtFiles == null) - extResult = true; - else - foreach (var f in ExtFiles) - if (!File.Exists($"bin\\{f}")) + if (ExtFiles != null) + { + foreach (var file in ExtFiles) + if (!File.Exists($"bin\\{file}")) { extResult = false; - Logging.Error($"附加文件 bin\\{f} 不存在"); + Logging.Error($"附加文件 bin\\{file} 不存在"); } + } result = extResult && mainResult; if (!result) - Logging.Error(AkaName + " 未就绪"); + Logging.Error(Name + " 未就绪"); Ready = result; } /// /// 写日志 /// - /// - /// 是否为空 - protected bool WriteLog(DataReceivedEventArgs std) + /// + /// 是否为空 + protected bool Write(string s) { - if (string.IsNullOrWhiteSpace(std.Data)) return false; + if (string.IsNullOrWhiteSpace(s)) return false; try - { - File.AppendAllText($"logging\\{AkaName}.log", $@"{std.Data}{Global.EOF}"); + File.AppendAllText($"logging\\{Name}.log", s + Global.EOF); } catch (Exception e) { - Logging.Error($"写入{AkaName}日志错误:\n" + e); + Logging.Error($"写入{Name}日志错误:\n" + e); } return true; diff --git a/Netch/Controllers/MainController.cs b/Netch/Controllers/MainController.cs index 93b3d66d..ae144998 100644 --- a/Netch/Controllers/MainController.cs +++ b/Netch/Controllers/MainController.cs @@ -18,7 +18,7 @@ namespace Netch.Controllers /// /// NTT 控制器 /// - public NTTController pNTTController; + public NTTController pNTTController = new NTTController(); [DllImport("dnsapi", EntryPoint = "DnsFlushResolverCache")] public static extern uint FlushDNSResolverCache(); @@ -31,7 +31,6 @@ namespace Netch.Controllers /// 是否启动成功 public bool Start(Server server, Mode mode) { - pNTTController ??= new NTTController(); FlushDNSResolverCache(); var result = false; @@ -57,12 +56,13 @@ namespace Netch.Controllers break; } - MainForm.Instance.StatusText(i18N.Translate("Starting ", pEncryptedProxyController.AkaName)); + Global.MainForm.StatusText(i18N.Translate("Starting ", pEncryptedProxyController.Name)); if (pEncryptedProxyController.Ready) result = pEncryptedProxyController.Start(server, mode); } if (result) { + Logging.Info("加密代理已启动"); // 加密代理已启动 switch (mode.Type) { @@ -84,26 +84,29 @@ namespace Netch.Controllers if (pModeController != null && pModeController.Ready) { - MainForm.Instance.StatusText(i18N.Translate("Starting ", pModeController.AkaName)); + Global.MainForm.StatusText(i18N.Translate("Starting ", pModeController.Name)); result = pModeController.Start(server, mode); } - switch (mode.Type) + if (result) { - case 0: - case 1: - case 2: - if (result) + Logging.Info("模式已启动"); + switch (mode.Type) + { + case 0: + case 1: + case 2: Task.Run(() => { - MainForm.Instance.NatTypeStatusText(i18N.Translate("Starting NatTester")); + Global.MainForm.NatTypeStatusText(i18N.Translate("Starting NatTester")); // Thread.Sleep(1000); var (nttResult, natType, localEnd, publicEnd) = pNTTController.Start(); var country = Utils.Utils.GetCityCode(publicEnd); - if (nttResult) MainForm.Instance.NatTypeStatusText(natType, country); + if (nttResult) Global.MainForm.NatTypeStatusText(natType, country); }); - break; + break; + } } } diff --git a/Netch/Controllers/Mode/HTTPController.cs b/Netch/Controllers/Mode/HTTPController.cs index df320b9b..99565bc0 100644 --- a/Netch/Controllers/Mode/HTTPController.cs +++ b/Netch/Controllers/Mode/HTTPController.cs @@ -19,7 +19,7 @@ namespace Netch.Controllers public HTTPController() { - AkaName = "HTTP"; + Name = "HTTP"; Ready = true; } diff --git a/Netch/Controllers/Mode/NFController.cs b/Netch/Controllers/Mode/NFController.cs index f947fed3..16c7184e 100644 --- a/Netch/Controllers/Mode/NFController.cs +++ b/Netch/Controllers/Mode/NFController.cs @@ -25,9 +25,7 @@ namespace Netch.Controllers static NFController() { - // 生成系统版本 - var winNTver = $"{Environment.OSVersion.Version.Major.ToString()}.{Environment.OSVersion.Version.Minor.ToString()}"; - switch (winNTver) + switch ($"{Environment.OSVersion.Version.Major}.{Environment.OSVersion.Version.Minor}") { case "10.0": BinDriver = "Win-10.sys"; @@ -41,7 +39,7 @@ namespace Netch.Controllers BinDriver = "Win-7.sys"; break; default: - Logging.Error($"不支持的系统版本:{winNTver}"); + Logging.Error($"不支持的系统版本:{Environment.OSVersion.Version}"); return; } @@ -131,11 +129,11 @@ namespace Netch.Controllers // 防止其他程序占用 重置 NF 百万连接数限制 NFService.Stop(); NFService.WaitForStatus(ServiceControllerStatus.Stopped); - MainForm.Instance.StatusText(i18N.Translate("Starting netfilter2 Service")); + Global.MainForm.StatusText(i18N.Translate("Starting netfilter2 Service")); NFService.Start(); break; case ServiceControllerStatus.Stopped: - MainForm.Instance.StatusText(i18N.Translate("Starting netfilter2 Service")); + Global.MainForm.StatusText(i18N.Translate("Starting netfilter2 Service")); NFService.Start(); break; } @@ -208,12 +206,12 @@ namespace Netch.Controllers return false; } - MainForm.Instance.StatusText(i18N.Translate("Register driver")); + Global.MainForm.StatusText(i18N.Translate("Register driver")); // 注册驱动文件 var result = NFAPI.nf_registerDriver("netfilter2"); if (result == NF_STATUS.NF_STATUS_SUCCESS) { - Logging.Info($"驱动安装成功,当前驱动版本:{DriverVersion(DriverVersion(SystemDriver))}"); + Logging.Info($"驱动安装成功,当前驱动版本:{DriverVersion(SystemDriver)}"); } else { @@ -226,7 +224,7 @@ namespace Netch.Controllers private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { - if (!WriteLog(e)) return; + if (!Write(e.Data)) return; if (State == State.Starting) { if (Instance.HasExited) diff --git a/Netch/Controllers/Mode/TUNTAPController.cs b/Netch/Controllers/Mode/TUNTAPController.cs index 479756bc..c6dd0b64 100644 --- a/Netch/Controllers/Mode/TUNTAPController.cs +++ b/Netch/Controllers/Mode/TUNTAPController.cs @@ -62,7 +62,7 @@ namespace Netch.Controllers /// public bool SetupBypass() { - MainForm.Instance.StatusText(i18N.Translate("SetupBypass")); + Global.MainForm.StatusText(i18N.Translate("SetupBypass")); Logging.Info("设置绕行规则 → 设置让服务器 IP 走直连"); // 让服务器 IP 走直连 foreach (var address in _serverAddresses) @@ -310,7 +310,7 @@ namespace Netch.Controllers { if (!Ready) return false; - MainForm.Instance.StatusText(i18N.Translate("Starting Tap")); + Global.MainForm.StatusText(i18N.Translate("Starting Tap")); _savedMode = mode; _savedServer = server; @@ -391,7 +391,7 @@ namespace Netch.Controllers private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { - if (!WriteLog(e)) return; + if (!Write(e.Data)) return; if (State == State.Starting) { if (e.Data.Contains("Running")) diff --git a/Netch/Forms/MainForm.Control.cs b/Netch/Forms/MainForm.Control.cs index 100a6925..62344bd6 100644 --- a/Netch/Forms/MainForm.Control.cs +++ b/Netch/Forms/MainForm.Control.cs @@ -15,9 +15,13 @@ namespace Netch.Forms partial class MainForm { - public void ControlFun() + private bool _isFirstCloseWindow = true; + + private void ControlFun() { - SaveConfigs(); + //防止模式选择框变成蓝色:D + ModeComboBox.Select(0, 0); + if (State == State.Waiting || State == State.Stopped) { // 服务器、模式 需选择 @@ -33,36 +37,23 @@ namespace Netch.Forms return; } - //MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = false; - UpdateStatus(State.Starting); - Firewall.AddNetchFwRules(); - Task.Run(() => { + Task.Run(Firewall.AddNetchFwRules); + var server = ServerComboBox.SelectedItem as Models.Server; var mode = ModeComboBox.SelectedItem as Models.Mode; - MainController ??= new MainController(); - - var startResult = MainController.Start(server, mode); - - if (startResult) + if (_mainController.Start(server, mode)) { Task.Run(() => { - UpdateStatus(State.Started); - StatusText(i18N.Translate(StateExtension.GetStatusString(State)) + PortText(server.Type,mode.Type)); - - LastUploadBandwidth = 0; - //LastDownloadBandwidth = 0; - //UploadSpeedLabel.Text = "↑: 0 KB/s"; - DownloadSpeedLabel.Text = "↑↓: 0 KB/s"; - UsedBandwidthLabel.Text = $"{i18N.Translate("Used",": ")}0 KB"; - UsedBandwidthLabel.Visible = UploadSpeedLabel.Visible = DownloadSpeedLabel.Visible = true; - UploadSpeedLabel.Visible = false; - Bandwidth.NetTraffic(server, mode, MainController); + UpdateStatus(State.Started, + i18N.Translate(StateExtension.GetStatusString(State.Started)) + PortText(server.Type, mode.Type)); + + Bandwidth.NetTraffic(server, mode, _mainController); }); // 如果勾选启动后最小化 @@ -71,7 +62,7 @@ namespace Netch.Forms WindowState = FormWindowState.Minimized; NotifyIcon.Visible = true; - if (IsFirstOpened) + if (_isFirstCloseWindow) { // 显示提示语 NotifyIcon.ShowBalloonTip(5, @@ -80,7 +71,7 @@ namespace Netch.Forms "Netch is now minimized to the notification bar, double click this icon to restore."), ToolTipIcon.Info); - IsFirstOpened = false; + _isFirstCloseWindow = false; } Hide(); @@ -111,8 +102,7 @@ namespace Netch.Forms } else { - UpdateStatus(State.Stopped); - StatusText(i18N.Translate("Start failed")); + UpdateStatus(State.Stopped, i18N.Translate("Start failed")); } }); } @@ -120,17 +110,17 @@ namespace Netch.Forms { // 停止 UpdateStatus(State.Stopping); - MainController.Stop(); - UpdateStatus(State.Stopped); - Task.Run(() => { + _mainController.Stop(); + UpdateStatus(State.Stopped); + TestServer(); }); } } - private string PortText(string serverType,int modeType) + private string PortText(string serverType, int modeType) { var text = new StringBuilder(" ("); text.Append(Global.Settings.LocalAddress == "0.0.0.0" @@ -148,7 +138,7 @@ namespace Netch.Forms else { // 不可控HTTP - text.Clear(); + return ""; } } else @@ -163,14 +153,12 @@ namespace Netch.Forms $" | HTTP {i18N.Translate("Local Port", ": ")}{Global.Settings.HTTPLocalPort}"); } } - if (text.Length > 0) - { - text.Append(")"); - } + text.Append(")"); return text.ToString(); } + public void OnBandwidthUpdated(long download) { try @@ -198,7 +186,7 @@ namespace Netch.Forms } UsedBandwidthLabel.Text = - $"{i18N.Translate("Used",": ")}{Bandwidth.Compute(upload + download)}"; + $"{i18N.Translate("Used", ": ")}{Bandwidth.Compute(upload + download)}"; UploadSpeedLabel.Text = $"↑: {Bandwidth.Compute(upload - LastUploadBandwidth)}/s"; DownloadSpeedLabel.Text = $"↓: {Bandwidth.Compute(download - LastDownloadBandwidth)}/s"; diff --git a/Netch/Forms/MainForm.MenuStrip.cs b/Netch/Forms/MainForm.MenuStrip.cs index de7cb2ab..10d82f72 100644 --- a/Netch/Forms/MainForm.MenuStrip.cs +++ b/Netch/Forms/MainForm.MenuStrip.cs @@ -1,5 +1,4 @@ using System; -using System.Data; using System.Linq; using System.Net; using System.ServiceProcess; @@ -134,8 +133,8 @@ namespace Netch.Forms Remark = "ProxyUpdate", Type = 5 }; - MainController = new MainController(); - MainController.Start(ServerComboBox.SelectedItem as Models.Server, mode); + _mainController = new MainController(); + _mainController.Start(ServerComboBox.SelectedItem as Models.Server, mode); } foreach (var item in Global.Settings.SubscribeLink) @@ -165,8 +164,8 @@ namespace Netch.Forms } catch (Exception) { - // ignored - } + // ignored + } Global.Settings.Server = Global.Settings.Server.Where(server => server.Group != item.Remark).ToList(); var result = ShareLink.Parse(response); @@ -203,7 +202,7 @@ namespace Netch.Forms { MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true; ControlButton.Text = i18N.Translate("Start"); - MainController.Stop(); + _mainController.Stop(); NatTypeStatusLabel.Text = ""; } @@ -213,7 +212,6 @@ namespace Netch.Forms MenuStrip.Enabled = ConfigurationGroupBox.Enabled = ControlButton.Enabled = SettingsButton.Enabled = true; UpdateStatus(bak_State); StatusLabel.Text = bak_StateText; - }).ContinueWith(task => { BeginInvoke(new Action(() => { UpdateServersFromSubscribeLinksToolStripMenuItem.Enabled = true; })); }); NotifyIcon.ShowBalloonTip(5, @@ -380,8 +378,8 @@ namespace Netch.Forms Remark = "ProxyUpdate", Type = 5 }; - MainController = new MainController(); - MainController.Start(ServerComboBox.SelectedItem as Models.Server, mode); + _mainController = new MainController(); + _mainController.Start(ServerComboBox.SelectedItem as Models.Server, mode); using var client = new WebClient(); @@ -403,7 +401,7 @@ namespace Netch.Forms finally { UpdateStatus(State.Waiting); - MainController.Stop(); + _mainController.Stop(); } }); } diff --git a/Netch/Forms/MainForm.Profile.cs b/Netch/Forms/MainForm.Profile.cs index 0866986b..2f919f34 100644 --- a/Netch/Forms/MainForm.Profile.cs +++ b/Netch/Forms/MainForm.Profile.cs @@ -12,19 +12,18 @@ namespace Netch.Forms public partial class Dummy { } partial class MainForm { - /// init at private int _sizeHeight; - private int _controlHeight; - private int _profileBoxHeight; + + private int _profileConfigurationHeight; + private int _profileGroupboxHeight; private int _configurationGroupBoxHeight; private void InitProfile() { + // Clear foreach (var button in ProfileButtons) - { button.Dispose(); - } ProfileButtons.Clear(); ProfileTable.ColumnStyles.Clear(); @@ -33,51 +32,51 @@ namespace Netch.Forms var numProfile = Global.Settings.ProfileCount; if (numProfile == 0) { + // Hide Profile GroupBox, Change window size configLayoutPanel.RowStyles[2].SizeType = SizeType.Percent; configLayoutPanel.RowStyles[2].Height = 0; ProfileGroupBox.Visible = false; - ConfigurationGroupBox.Size = new Size(ConfigurationGroupBox.Size.Width, _configurationGroupBoxHeight - _controlHeight); - Size = new Size(Size.Width, _sizeHeight - (_controlHeight + _profileBoxHeight)); - - return; + ConfigurationGroupBox.Size = new Size(ConfigurationGroupBox.Size.Width, _configurationGroupBoxHeight - _profileConfigurationHeight); + Size = new Size(Size.Width, _sizeHeight - (_profileConfigurationHeight + _profileGroupboxHeight)); } - - configLayoutPanel.RowStyles[2].SizeType = SizeType.AutoSize; - ProfileGroupBox.Visible = true; - ConfigurationGroupBox.Size = new Size(ConfigurationGroupBox.Size.Width, _configurationGroupBoxHeight); - Size = new Size(Size.Width, _sizeHeight); - - - ProfileTable.ColumnCount = numProfile; - - while (Global.Settings.Profiles.Count < numProfile) + else { - Global.Settings.Profiles.Add(new Profile()); - } + // Load Profiles + ProfileTable.ColumnCount = numProfile; - // buttons - for (var i = 0; i < numProfile; ++i) - { - var b = new Button(); - ProfileTable.Controls.Add(b, i, 0); - b.Location = new Point(i * 100, 0); - b.Click += ProfileButton_Click; - b.Dock = DockStyle.Fill; - b.Text = !Global.Settings.Profiles[i].IsDummy ? Global.Settings.Profiles[i].ProfileName : i18N.Translate("None"); + while (Global.Settings.Profiles.Count < numProfile) + { + Global.Settings.Profiles.Add(new Profile()); + } - ProfileButtons.Add(b); - } + for (var i = 0; i < numProfile; ++i) + { + var b = new Button(); + b.Click += ProfileButton_Click; + b.Dock = DockStyle.Fill; + b.Text = !Global.Settings.Profiles[i].IsDummy ? Global.Settings.Profiles[i].ProfileName : i18N.Translate("None"); - // equal column - for (var i = 1; i <= ProfileTable.RowCount; i++) - { - ProfileTable.RowStyles.Add(new RowStyle(SizeType.Percent, 1)); - } + ProfileTable.Controls.Add(b, i, 0); + ProfileButtons.Add(b); + } - for (var i = 1; i <= ProfileTable.ColumnCount; i++) - { - ProfileTable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 1)); + // equal column + for (var i = 1; i <= ProfileTable.RowCount; i++) + { + ProfileTable.RowStyles.Add(new RowStyle(SizeType.Percent, 1)); + } + + for (var i = 1; i <= ProfileTable.ColumnCount; i++) + { + ProfileTable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 1)); + } + + if (Size.Height == _sizeHeight) return; + configLayoutPanel.RowStyles[2].SizeType = SizeType.AutoSize; + ProfileGroupBox.Visible = true; + ConfigurationGroupBox.Size = new Size(ConfigurationGroupBox.Size.Width, _configurationGroupBoxHeight); + Size = new Size(Size.Width, _sizeHeight); } } @@ -129,14 +128,18 @@ namespace Netch.Forms Global.Settings.Profiles[index] = new Profile(selectedServer, selectedMode, name); } - public List