Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
Fixed #57 - config load and save error due to race condition - added code optimization - removed unwanted code - added compression in nsis installer
Sourav Kalal82f48779ad3d
diff --git a/Windows/gui/Common/ValidationHelper.cs b/Windows/gui/Common/ValidationHelper.csnew file mode 100644index 0000000..de3d381--- /dev/null+++ b/Windows/gui/Common/ValidationHelper.cs@@ -0,0 +1,59 @@+using System;++namespace ProxyBridge.GUI.Common;++// handles common validation patterns+public static class ValidationHelper+{+ public static string DefaultIfEmpty(string value, string defaultValue = "*")+ {+ return string.IsNullOrWhiteSpace(value) ? defaultValue : value;+ }++ public static bool ValidateNotEmpty(string value, string errorMessage, Action<string> setError)+ {+ if (string.IsNullOrWhiteSpace(value))+ {+ setError(errorMessage);+ return false;+ }+ setError("");+ return true;+ }++ public static bool ValidatePort(string portStr, Action<string> setError)+ {+ if (string.IsNullOrWhiteSpace(portStr))+ {+ setError("Port is required");+ return false;+ }++ if (!int.TryParse(portStr, out int port) || port < 1 || port > 65535)+ {+ setError("Port must be between 1 and 65535");+ return false;+ }++ setError("");+ return true;+ }++ public static bool ValidateIpOrDomain(string value, Func<string, bool> validator, Action<string> setError)+ {+ if (string.IsNullOrWhiteSpace(value))+ {+ setError("IP address or hostname is required");+ return false;+ }++ if (!validator(value))+ {+ setError("Invalid IP address or hostname");+ return false;+ }++ setError("");+ return true;+ }+}diff --git a/Windows/gui/Services/ConfigManager.cs b/Windows/gui/Services/ConfigManager.csindex 1ce26d9..b1b5055 100644--- a/Windows/gui/Services/ConfigManager.cs+++ b/Windows/gui/Services/ConfigManager.cs@@ -38,52 +38,91 @@ internal partial class AppConfigJsonContext : JsonSerializerContext{}-public static class ConfigManager+internal static class AtomicFileHelper{- private static readonly string ConfigDirectory = Path.Combine(- Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),- "ProxyBridge"- );- // C:\Users\<username>\AppData\Roaming\ProxyBridge\config.json-- private static readonly string ConfigFilePath = Path.Combine(ConfigDirectory, "config.json");-- public static bool SaveConfig(AppConfig config)+ public static bool AtomicWrite(string filePath, string content){+ var tempPath = filePath + ".tmp";try{- if (!Directory.Exists(ConfigDirectory))+ var directory = Path.GetDirectoryName(filePath);+ if (directory != null && !Directory.Exists(directory)){- Directory.CreateDirectory(ConfigDirectory);+ Directory.CreateDirectory(directory);}- var json = JsonSerializer.Serialize(config, AppConfigJsonContext.Default.AppConfig);- File.WriteAllText(ConfigFilePath, json);+ File.WriteAllText(tempPath, content);+ File.Move(tempPath, filePath, overwrite: true);return true;}catch{+ try+ {+ if (File.Exists(tempPath))+ {+ File.Delete(tempPath);+ }+ }+ catch { }return false;}}- public static AppConfig LoadConfig()+ public static string? SafeReadFile(string filePath){try{- if (!File.Exists(ConfigFilePath))+ if (!File.Exists(filePath)){- return new AppConfig();+ return null;}- var json = File.ReadAllText(ConfigFilePath);- var config = JsonSerializer.Deserialize(json, AppConfigJsonContext.Default.AppConfig);- return config ?? new AppConfig();+ var content = File.ReadAllText(filePath);+ return string.IsNullOrWhiteSpace(content) ? null : content;}catch+ {+ return null;+ }+ }+}++public static class ConfigManager+{+ private static readonly string ConfigDirectory = Path.Combine(+ Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),+ "ProxyBridge"+ );++ private static readonly string ConfigFilePath = Path.Combine(ConfigDirectory, "config.json");++ public static bool SaveConfig(AppConfig config)+ {+ var json = JsonSerializer.Serialize(config, AppConfigJsonContext.Default.AppConfig);+ return AtomicFileHelper.AtomicWrite(ConfigFilePath, json);+ }++ public static AppConfig LoadConfig()+ {+ var json = AtomicFileHelper.SafeReadFile(ConfigFilePath);+ if (json == null){return new AppConfig();}++ try+ {+ var config = JsonSerializer.Deserialize(json, AppConfigJsonContext.Default.AppConfig);+ if (config != null)+ {+ config.ProxyRules ??= new List<ProxyRuleConfig>();+ return config;+ }+ }+ catch { }++ return new AppConfig();}public static bool ConfigExists()diff --git a/Windows/gui/Services/SettingsService.cs b/Windows/gui/Services/SettingsService.csindex 8f191ce..9906e49 100644--- a/Windows/gui/Services/SettingsService.cs+++ b/Windows/gui/Services/SettingsService.cs@@ -20,39 +20,27 @@ public class SettingsServicepublic AppSettings LoadSettings(){+ var json = AtomicFileHelper.SafeReadFile(SettingsPath);+ if (json == null)+ {+ return new AppSettings();+ }+try{- if (File.Exists(SettingsPath))- {- var json = File.ReadAllText(SettingsPath);- var settings = JsonSerializer.Deserialize(json, AppSettingsContext.Default.AppSettings);- return settings ?? new AppSettings();- }+ var settings = JsonSerializer.Deserialize(json, AppSettingsContext.Default.AppSettings);+ return settings ?? new AppSettings();}catch{- // If there's any error loading settings, return defaults+ return new AppSettings();}-- return new AppSettings();}public void SaveSettings(AppSettings settings){- try- {- var directory = Path.GetDirectoryName(SettingsPath);- if (directory != null && !Directory.Exists(directory))- {- Directory.CreateDirectory(directory);- }-- var json = JsonSerializer.Serialize(settings, AppSettingsContext.Default.AppSettings);- File.WriteAllText(SettingsPath, json);- }- catch- {- }+ var json = JsonSerializer.Serialize(settings, AppSettingsContext.Default.AppSettings);+ AtomicFileHelper.AtomicWrite(SettingsPath, json);}public void SetStartupWithWindows(bool enable)diff --git a/Windows/gui/ViewModels/MainWindowViewModel.cs b/Windows/gui/ViewModels/MainWindowViewModel.csindex 7f1cc15..84688d6 100644--- a/Windows/gui/ViewModels/MainWindowViewModel.cs+++ b/Windows/gui/ViewModels/MainWindowViewModel.cs@@ -121,10 +121,7 @@ public class MainWindowViewModel : ViewModelBase};_activityLogTimer.Start();- // Apply config DNS setting_proxyService.SetDnsViaProxy(_dnsViaProxy);-- // Apply comfig proxy settingsif (!string.IsNullOrEmpty(_currentProxyIp) &&!string.IsNullOrEmpty(_currentProxyPort) &&ushort.TryParse(_currentProxyPort, out ushort portNum))@@ -137,10 +134,8 @@ public class MainWindowViewModel : ViewModelBase_currentProxyPassword);}- // Start the proxy bridgeif (_proxyService.Start()){- // Apply config proxy rules, Need to see if this cause UI issues/slow/freezeforeach (var rule in ProxyRules){uint ruleId = _proxyService.AddRule(@@ -278,7 +273,7 @@ public class MainWindowViewModel : ViewModelBasepublic ObservableCollection<ProxyRule> ProxyRules { get; } = new();- private bool _dnsViaProxy = true; // Default TRUE+ private bool _dnsViaProxy = true;public bool DnsViaProxy{get => _dnsViaProxy;@@ -293,7 +288,7 @@ public class MainWindowViewModel : ViewModelBase}}- private bool _isTrafficLoggingEnabled = true; // Default TRUE+ private bool _isTrafficLoggingEnabled = true;public bool IsTrafficLoggingEnabled{get => _isTrafficLoggingEnabled;@@ -309,7 +304,6 @@ public class MainWindowViewModel : ViewModelBaseelse{_connectionLogTimer?.Stop();- // Clear pending logs when disabledlock (_connectionLogLock){_pendingConnectionLogs.Clear();@@ -363,7 +357,6 @@ public class MainWindowViewModel : ViewModelBaseset => SetProperty(ref _startWithWindows, value);}- // Commandspublic ICommand ShowProxySettingsCommand { get; }public ICommand ShowProxyRulesCommand { get; }public ICommand ShowAboutCommand { get; }@@ -478,10 +471,7 @@ public class MainWindowViewModel : ViewModelBaseShowAboutCommand = new RelayCommand(async () =>{- var viewModel = new AboutViewModel(() =>- {- // Window will be closed- });+ var viewModel = new AboutViewModel(() => { });var window = new Views.AboutWindow{@@ -672,19 +662,13 @@ public class MainWindowViewModel : ViewModelBase_ = notificationWindow.ShowDialog(_mainWindow);}}- catch- {- // silently fail- }+ catch { }}public void Cleanup(){- // this something can be improved maybe config doesnt need save during cleanuptry { SaveConfigurationInternal(); } catch { }-- try { _proxyService?.Dispose(); _proxyService = null; }- catch { }+ try { _proxyService?.Dispose(); _proxyService = null; } catch { }}private string FilterLog(string log, string searchText)@@ -716,34 +700,45 @@ public class MainWindowViewModel : ViewModelBasevar config = ConfigManager.LoadConfig();- _currentProxyType = config.ProxyType;- _currentProxyIp = config.ProxyIp;- _currentProxyPort = config.ProxyPort;- _currentProxyUsername = config.ProxyUsername;- _currentProxyPassword = config.ProxyPassword;+ _currentProxyType = ValidationHelper.DefaultIfEmpty(config.ProxyType, "SOCKS5");+ _currentProxyIp = ValidationHelper.DefaultIfEmpty(config.ProxyIp, "");+ _currentProxyPort = ValidationHelper.DefaultIfEmpty(config.ProxyPort, "");+ _currentProxyUsername = config.ProxyUsername ?? "";+ _currentProxyPassword = config.ProxyPassword ?? "";DnsViaProxy = config.DnsViaProxy;CloseToTray = config.CloseToTray;IsTrafficLoggingEnabled = config.IsTrafficLoggingEnabled;- _currentLanguage = config.Language;- _loc.CurrentCulture = new System.Globalization.CultureInfo(config.Language);- EnglishCheckmark = config.Language == "en" ? "✓" : "";- ChineseCheckmark = config.Language == "zh" ? "✓" : "";+ if (!string.IsNullOrWhiteSpace(config.Language))+ {+ _currentLanguage = config.Language;+ _loc.CurrentCulture = new System.Globalization.CultureInfo(config.Language);+ EnglishCheckmark = config.Language == "en" ? "✓" : "";+ ChineseCheckmark = config.Language == "zh" ? "✓" : "";+ }- foreach (var ruleConfig in config.ProxyRules)+ if (config.ProxyRules != null && config.ProxyRules.Count > 0){- var rule = new ProxyRule+ foreach (var ruleConfig in config.ProxyRules){- ProcessName = ruleConfig.ProcessName,- TargetHosts = ruleConfig.TargetHosts,- TargetPorts = ruleConfig.TargetPorts,- Protocol = ruleConfig.Protocol,- Action = ruleConfig.Action,- IsEnabled = ruleConfig.IsEnabled- };- ProxyRules.Add(rule);+ if (string.IsNullOrWhiteSpace(ruleConfig.ProcessName))+ continue;++ var rule = new ProxyRule+ {+ ProcessName = ruleConfig.ProcessName,+ TargetHosts = ValidationHelper.DefaultIfEmpty(ruleConfig.TargetHosts),+ TargetPorts = ValidationHelper.DefaultIfEmpty(ruleConfig.TargetPorts),+ Protocol = ValidationHelper.DefaultIfEmpty(ruleConfig.Protocol, "TCP"),+ Action = ValidationHelper.DefaultIfEmpty(ruleConfig.Action, "PROXY"),+ IsEnabled = ruleConfig.IsEnabled+ };+ ProxyRules.Add(rule);+ }}++ QueueActivityLog("Configuration loaded successfully");}catch (Exception ex){diff --git a/Windows/gui/ViewModels/ProxyRulesViewModel.cs b/Windows/gui/ViewModels/ProxyRulesViewModel.csindex 630d04e..61ebb77 100644--- a/Windows/gui/ViewModels/ProxyRulesViewModel.cs+++ b/Windows/gui/ViewModels/ProxyRulesViewModel.cs@@ -96,6 +96,16 @@ public class ProxyRulesViewModel : ViewModelBase_window = window;}+ private void ResetRuleForm()+ {+ NewProcessName = "*";+ NewTargetHosts = "*";+ NewTargetPorts = "*";+ NewProtocol = "TCP";+ NewProxyAction = "PROXY";+ ProcessNameError = "";+ }+public ProxyRulesViewModel(ObservableCollection<ProxyRule> proxyRules, Action<ProxyRule> onAddRule, Action onClose, ProxyBridgeService? proxyService = null, Action? onConfigChanged = null){ProxyRules = proxyRules;@@ -111,34 +121,16 @@ public class ProxyRulesViewModel : ViewModelBaseAddRuleCommand = new RelayCommand(() =>{- NewProcessName = "*";- NewTargetHosts = "*";- NewTargetPorts = "*";- NewProtocol = "TCP";- NewProxyAction = "PROXY";- ProcessNameError = "";+ ResetRuleForm();IsAddRuleViewOpen = true;});SaveNewRuleCommand = new RelayCommand(() =>{- // Use "*" if empty- if (string.IsNullOrWhiteSpace(NewProcessName))- {- NewProcessName = "*";- }-- if (string.IsNullOrWhiteSpace(NewTargetHosts))- {- NewTargetHosts = "*";- }-- if (string.IsNullOrWhiteSpace(NewTargetPorts))- {- NewTargetPorts = "*";- }+ NewProcessName = ValidationHelper.DefaultIfEmpty(NewProcessName);+ NewTargetHosts = ValidationHelper.DefaultIfEmpty(NewTargetHosts);+ NewTargetPorts = ValidationHelper.DefaultIfEmpty(NewTargetPorts);- // This could be an issue if app name contain charif (!System.Text.RegularExpressions.Regex.IsMatch(NewProcessName, @"^[a-zA-Z0-9\s._\-*;""\\:()]+$")){ProcessNameError = "Invalid characters in process name. Only letters, numbers, spaces, dots, dashes, underscores, semicolons, quotes, parentheses, and * are allowed";@@ -157,10 +149,8 @@ public class ProxyRulesViewModel : ViewModelBaseif (_isEditMode && _proxyService != null){- // Edit existing ruleif (_proxyService.EditRule(_currentEditingRuleId, NewProcessName, NewTargetHosts, NewTargetPorts, NewProtocol, NewProxyAction)){- // Update the rule in the ObservableCollectionvar existingRule = ProxyRules.FirstOrDefault(r => r.RuleId == _currentEditingRuleId);if (existingRule != null){@@ -178,7 +168,6 @@ public class ProxyRulesViewModel : ViewModelBase}else{- // Add new rulevar newRule = new ProxyRule{ProcessName = NewProcessName,@@ -190,27 +179,14 @@ public class ProxyRulesViewModel : ViewModelBase};newRule.PropertyChanged += Rule_PropertyChanged;-_onAddRule?.Invoke(newRule);}IsAddRuleViewOpen = false;-- // Reset to defaults- NewProcessName = "*";- NewTargetHosts = "*";- NewTargetPorts = "*";- NewProtocol = "TCP";- NewProxyAction = "PROXY";- ProcessNameError = "";+ ResetRuleForm();}); CancelAddRuleCommand = new RelayCommand(() =>{- NewProcessName = "*";- NewTargetHosts = "*";- NewTargetPorts = "*";- NewProtocol = "TCP";- NewProxyAction = "PROXY";- ProcessNameError = "";+ ResetRuleForm();IsAddRuleViewOpen = false;});diff --git a/Windows/gui/ViewModels/ProxySettingsViewModel.cs b/Windows/gui/ViewModels/ProxySettingsViewModel.csindex 0d75bfe..8e0447d 100644--- a/Windows/gui/ViewModels/ProxySettingsViewModel.cs+++ b/Windows/gui/ViewModels/ProxySettingsViewModel.cs@@ -139,29 +139,8 @@ public class ProxySettingsViewModel : ViewModelBaseSaveCommand = new RelayCommand(() =>{- bool isValid = true;-- if (string.IsNullOrWhiteSpace(ProxyIp))- {- IpError = "IP address or hostname is required";- isValid = false;- }- else if (!IsValidIpOrDomain(ProxyIp))- {- IpError = "Invalid IP address or hostname";- isValid = false;- }-- if (string.IsNullOrWhiteSpace(ProxyPort))- {- PortError = "Port is required";- isValid = false;- }- else if (!int.TryParse(ProxyPort, out int port) || port < 1 || port > 65535)- {- PortError = "Port must be between 1 and 65535";- isValid = false;- }+ bool isValid = ValidationHelper.ValidateIpOrDomain(ProxyIp, IsValidIpOrDomain, msg => IpError = msg)+ && ValidationHelper.ValidatePort(ProxyPort, msg => PortError = msg);if (isValid){@@ -189,14 +168,13 @@ public class ProxySettingsViewModel : ViewModelBase{if (IsTesting) return;- // Validate inputs firstif (string.IsNullOrWhiteSpace(ProxyIp)){TestOutput = "ERROR: Please configure proxy IP address or hostname first";return;}- if (string.IsNullOrWhiteSpace(ProxyPort) || !ushort.TryParse(ProxyPort, out ushort proxyPortNum))+ if (!ushort.TryParse(ProxyPort, out ushort proxyPortNum)){TestOutput = "ERROR: Please configure valid proxy port first";return;@@ -218,7 +196,7 @@ public class ProxySettingsViewModel : ViewModelBaseTestOutput = "Testing connection...\n";try- { // First apply current settings temporarily+ {if (_proxyService != null){_proxyService.SetProxyConfig(ProxyType, ProxyIp, proxyPortNum, ProxyUsername ?? "", ProxyPassword ?? "");diff --git a/Windows/gui/ViewModels/UpdateCheckViewModel.cs b/Windows/gui/ViewModels/UpdateCheckViewModel.csindex ed94669..f77477b 100644--- a/Windows/gui/ViewModels/UpdateCheckViewModel.cs+++ b/Windows/gui/ViewModels/UpdateCheckViewModel.cs@@ -37,7 +37,6 @@ public class UpdateCheckViewModel : ViewModelBaseDownloadNowCommand = new RelayCommand(async () => await DownloadAndInstallAsync(), () => IsUpdateAvailable && !IsDownloading);CloseCommand = new RelayCommand(onClose);- // Start checking immediately_ = CheckForUpdatesAsync();}@@ -154,7 +153,6 @@ public class UpdateCheckViewModel : ViewModelBaseLatestVersionColor = "#FF007ACC";}- // Refresh command can execute state(DownloadNowCommand as RelayCommand)?.RaiseCanExecuteChanged();}catch (Exception ex)@@ -202,9 +200,8 @@ public class UpdateCheckViewModel : ViewModelBaseif (installerPath != null){DownloadStatus = "Download complete. Starting installer...";- await Task.Delay(1000); // Brief pause to show completion+ await Task.Delay(1000);- // This will close the current app and start the installer_updateService.InstallUpdateAndExit(installerPath);}elsediff --git a/Windows/gui/ViewModels/UpdateNotificationViewModel.cs b/Windows/gui/ViewModels/UpdateNotificationViewModel.csindex 8d51a22..98f34cf 100644--- a/Windows/gui/ViewModels/UpdateNotificationViewModel.cs+++ b/Windows/gui/ViewModels/UpdateNotificationViewModel.cs@@ -141,14 +141,12 @@ public class UpdateNotificationViewModel : ViewModelBaseDownloadStatus = "Download complete. Starting installation...";DownloadProgress = 100;- // Start the installer and exit the current applicationProcess.Start(new ProcessStartInfo{FileName = filePath,UseShellExecute = true});- // Close the current applicationEnvironment.Exit(0);}catch (Exception ex)diff --git a/Windows/installer/ProxyBridge.nsi b/Windows/installer/ProxyBridge.nsiindex 707c986..e3a3704 100644--- a/Windows/installer/ProxyBridge.nsi+++ b/Windows/installer/ProxyBridge.nsi@@ -5,8 +5,13 @@!define PRODUCT_UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${PRODUCT_NAME}"!define PRODUCT_UNINST_ROOT_KEY "HKLM"+Unicode True+!include "MUI2.nsh"+SetCompressor /SOLID lzma+SetCompressorDictSize 64+Name "${PRODUCT_NAME} ${PRODUCT_VERSION}"OutFile "ProxyBridge-Setup-${PRODUCT_VERSION}.exe"InstallDir "$PROGRAMFILES64\${PRODUCT_NAME}"