Skip to content

Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic

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.cs
new file mode 100644
index 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.cs
index 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.cs
index 8f191ce..9906e49 100644
--- a/Windows/gui/Services/SettingsService.cs
+++ b/Windows/gui/Services/SettingsService.cs
@@ -20,39 +20,27 @@ public class SettingsService
public 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.cs
index 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 settings
if (!string.IsNullOrEmpty(_currentProxyIp) &&
!string.IsNullOrEmpty(_currentProxyPort) &&
ushort.TryParse(_currentProxyPort, out ushort portNum))
@@ -137,10 +134,8 @@ public class MainWindowViewModel : ViewModelBase
_currentProxyPassword);
}
- // Start the proxy bridge
if (_proxyService.Start())
{
- // Apply config proxy rules, Need to see if this cause UI issues/slow/freeze
foreach (var rule in ProxyRules)
{
uint ruleId = _proxyService.AddRule(
@@ -278,7 +273,7 @@ public class MainWindowViewModel : ViewModelBase
public 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 : ViewModelBase
else
{
_connectionLogTimer?.Stop();
- // Clear pending logs when disabled
lock (_connectionLogLock)
{
_pendingConnectionLogs.Clear();
@@ -363,7 +357,6 @@ public class MainWindowViewModel : ViewModelBase
set => SetProperty(ref _startWithWindows, value);
}
- // Commands
public ICommand ShowProxySettingsCommand { get; }
public ICommand ShowProxyRulesCommand { get; }
public ICommand ShowAboutCommand { get; }
@@ -478,10 +471,7 @@ public class MainWindowViewModel : ViewModelBase
ShowAboutCommand = 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 cleanup
try { 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 : ViewModelBase
var 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.cs
index 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 : ViewModelBase
AddRuleCommand = 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 char
if (!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 : ViewModelBase
if (_isEditMode && _proxyService != null)
{
- // Edit existing rule
if (_proxyService.EditRule(_currentEditingRuleId, NewProcessName, NewTargetHosts, NewTargetPorts, NewProtocol, NewProxyAction))
{
- // Update the rule in the ObservableCollection
var existingRule = ProxyRules.FirstOrDefault(r => r.RuleId == _currentEditingRuleId);
if (existingRule != null)
{
@@ -178,7 +168,6 @@ public class ProxyRulesViewModel : ViewModelBase
}
else
{
- // Add new rule
var 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.cs
index 0d75bfe..8e0447d 100644
--- a/Windows/gui/ViewModels/ProxySettingsViewModel.cs
+++ b/Windows/gui/ViewModels/ProxySettingsViewModel.cs
@@ -139,29 +139,8 @@ public class ProxySettingsViewModel : ViewModelBase
SaveCommand = 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 first
if (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 : ViewModelBase
TestOutput = "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.cs
index ed94669..f77477b 100644
--- a/Windows/gui/ViewModels/UpdateCheckViewModel.cs
+++ b/Windows/gui/ViewModels/UpdateCheckViewModel.cs
@@ -37,7 +37,6 @@ public class UpdateCheckViewModel : ViewModelBase
DownloadNowCommand = new RelayCommand(async () => await DownloadAndInstallAsync(), () => IsUpdateAvailable && !IsDownloading);
CloseCommand = new RelayCommand(onClose);
- // Start checking immediately
_ = CheckForUpdatesAsync();
}
@@ -154,7 +153,6 @@ public class UpdateCheckViewModel : ViewModelBase
LatestVersionColor = "#FF007ACC";
}
- // Refresh command can execute state
(DownloadNowCommand as RelayCommand)?.RaiseCanExecuteChanged();
}
catch (Exception ex)
@@ -202,9 +200,8 @@ public class UpdateCheckViewModel : ViewModelBase
if (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);
}
else
diff --git a/Windows/gui/ViewModels/UpdateNotificationViewModel.cs b/Windows/gui/ViewModels/UpdateNotificationViewModel.cs
index 8d51a22..98f34cf 100644
--- a/Windows/gui/ViewModels/UpdateNotificationViewModel.cs
+++ b/Windows/gui/ViewModels/UpdateNotificationViewModel.cs
@@ -141,14 +141,12 @@ public class UpdateNotificationViewModel : ViewModelBase
DownloadStatus = "Download complete. Starting installation...";
DownloadProgress = 100;
- // Start the installer and exit the current application
Process.Start(new ProcessStartInfo
{
FileName = filePath,
UseShellExecute = true
});
- // Close the current application
Environment.Exit(0);
}
catch (Exception ex)
diff --git a/Windows/installer/ProxyBridge.nsi b/Windows/installer/ProxyBridge.nsi
index 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}"