Skip to content

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

Fixed #42

Sourav Kalal2b88cdad9694
diff --git a/Windows/gui/App.axaml.cs b/Windows/gui/App.axaml.cs
index 4929a9d..6747264 100644
--- a/Windows/gui/App.axaml.cs
+++ b/Windows/gui/App.axaml.cs
@@ -5,38 +5,64 @@ using Avalonia.Controls;
using ProxyBridge.GUI.ViewModels;
using ProxyBridge.GUI.Views;
using System;
+using System.Threading;
+using System.Threading.Tasks;
namespace ProxyBridge.GUI;
public class App : Application
{
- public override void Initialize()
- {
- AvaloniaXamlLoader.Load(this);
- }
+ private EventWaitHandle? _showWindowEvent;
+ private CancellationTokenSource? _eventListenerCts;
+ private const string EventName = "Global\\ProxyBridge_ShowWindow_Event_v3.0";
+
+ public override void Initialize() => AvaloniaXamlLoader.Load(this);
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
- desktop.MainWindow = new MainWindow
+ desktop.MainWindow = new MainWindow { DataContext = new MainWindowViewModel() };
+
+ try
{
- DataContext = new MainWindowViewModel()
- };
+ _showWindowEvent = new EventWaitHandle(false, EventResetMode.AutoReset, EventName);
+ _eventListenerCts = new CancellationTokenSource();
+ Task.Run(() => ListenForActivationSignal(_eventListenerCts.Token));
+ }
+ catch { }
- // save config during shutdown
desktop.ShutdownRequested += (s, e) =>
{
- if (desktop.MainWindow?.DataContext is MainWindowViewModel vm)
- {
- vm.Cleanup();
- }
+ _eventListenerCts?.Cancel();
+ _showWindowEvent?.Dispose();
+ (desktop.MainWindow?.DataContext as MainWindowViewModel)?.Cleanup();
};
+
+ desktop.ShutdownMode = Avalonia.Controls.ShutdownMode.OnMainWindowClose;
}
base.OnFrameworkInitializationCompleted();
}
- // https://docs.avaloniaui.net/docs/reference/controls/tray-icon
+
+ private async Task ListenForActivationSignal(CancellationToken token)
+ {
+ while (!token.IsCancellationRequested)
+ {
+ try
+ {
+ var signaled = await Task.Run(() => _showWindowEvent?.WaitOne(1000) ?? false, token);
+ if (signaled && !token.IsCancellationRequested)
+ {
+ await Avalonia.Threading.Dispatcher.UIThread.InvokeAsync(() =>
+ TrayIcon_Show(null, EventArgs.Empty));
+ }
+ }
+ catch (OperationCanceledException) { break; }
+ catch { }
+ }
+ }
+
public void TrayIcon_Show(object? sender, EventArgs e)
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
@@ -53,9 +79,6 @@ public class App : Application
public void TrayIcon_Exit(object? sender, EventArgs e)
{
- if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
- {
- desktop.Shutdown();
- }
+ (ApplicationLifetime as IClassicDesktopStyleApplicationLifetime)?.Shutdown();
}
}
diff --git a/Windows/gui/Program.cs b/Windows/gui/Program.cs
index c41d535..255fe87 100644
--- a/Windows/gui/Program.cs
+++ b/Windows/gui/Program.cs
@@ -1,15 +1,45 @@
using Avalonia;
using System;
+using System.Threading;
namespace ProxyBridge.GUI;
class Program
{
+ private static Mutex? _instanceMutex;
+ private const string MutexName = "Global\\ProxyBridge_SingleInstance_Mutex_v3.0";
+ private const string EventName = "Global\\ProxyBridge_ShowWindow_Event_v3.0";
+
[STAThread]
public static void Main(string[] args)
{
- BuildAvaloniaApp()
- .StartWithClassicDesktopLifetime(args);
+ _instanceMutex = new Mutex(true, MutexName, out bool isNewInstance);
+
+ if (!isNewInstance)
+ {
+ SignalExistingInstance();
+ return;
+ }
+
+ try
+ {
+ BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
+ }
+ finally
+ {
+ _instanceMutex?.ReleaseMutex();
+ _instanceMutex?.Dispose();
+ }
+ }
+
+ private static void SignalExistingInstance()
+ {
+ try
+ {
+ using var showEvent = EventWaitHandle.OpenExisting(EventName);
+ showEvent.Set();
+ }
+ catch { }
}
public static AppBuilder BuildAvaloniaApp()
diff --git a/Windows/gui/Services/ProxyBridgeService.cs b/Windows/gui/Services/ProxyBridgeService.cs
index 13a277e..7c3532d 100644
--- a/Windows/gui/Services/ProxyBridgeService.cs
+++ b/Windows/gui/Services/ProxyBridgeService.cs
@@ -134,27 +134,7 @@ public class ProxyBridgeService : IDisposable
{
if (_isRunning)
{
- Stop();
-
- // WinDivert takes few seconds to stop
- System.Threading.Thread.Sleep(500);
-
- // STOP WinDivert kernel driver
- try
- {
- var psi = new System.Diagnostics.ProcessStartInfo
- {
- FileName = "sc.exe",
- Arguments = "stop WinDivert",
- WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
- CreateNoWindow = true,
- UseShellExecute = false
- };
- var process = System.Diagnostics.Process.Start(psi);
- process?.WaitForExit(2000);
- }
- catch {
- }
+ Stop(); // removing the threads, C code handle close no need to manually handle drives
}
GC.SuppressFinalize(this);
}
diff --git a/Windows/gui/ViewModels/MainWindowViewModel.cs b/Windows/gui/ViewModels/MainWindowViewModel.cs
index ec40b04..c477bd3 100644
--- a/Windows/gui/ViewModels/MainWindowViewModel.cs
+++ b/Windows/gui/ViewModels/MainWindowViewModel.cs
@@ -29,6 +29,7 @@ public class MainWindowViewModel : ViewModelBase
private string _newProxyAction = "PROXY";
private Window? _mainWindow;
private ProxyBridgeService? _proxyService;
+ private bool _isServiceInitialized = false;
private string _currentProxyType = "SOCKS5";
private string _currentProxyIp = "";
@@ -44,6 +45,11 @@ public class MainWindowViewModel : ViewModelBase
public void SetMainWindow(Window window)
{
_mainWindow = window;
+
+ if (_isServiceInitialized)
+ return;
+
+ _isServiceInitialized = true;
LoadConfiguration();
try
@@ -257,6 +263,7 @@ public class MainWindowViewModel : ViewModelBase
if (SetProperty(ref _dnsViaProxy, value))
{
_proxyService?.SetDnsViaProxy(value);
+ SaveConfigurationInternal();
ActivityLog += $"[{DateTime.Now:HH:mm:ss}] DNS via Proxy: {(value ? "Enabled" : "Disabled")}\n";
}
}
@@ -327,6 +334,7 @@ public class MainWindowViewModel : ViewModelBase
_currentProxyUsername = username;
_currentProxyPassword = password;
+ SaveConfigurationInternal();
string authInfo = string.IsNullOrEmpty(username) ? "" : " (with auth)";
ActivityLog += $"[{DateTime.Now:HH:mm:ss}] Saved proxy settings: {type} {ip}:{port}{authInfo}\n";
}
@@ -373,6 +381,7 @@ public class MainWindowViewModel : ViewModelBase
rule.RuleId = ruleId;
rule.Index = ProxyRules.Count + 1;
ProxyRules.Add(rule);
+ SaveConfigurationInternal();
ActivityLog += $"[{DateTime.Now:HH:mm:ss}] Added rule: {rule.ProcessName} ({rule.TargetHosts}:{rule.TargetPorts} {rule.Protocol}) -> {rule.Action} (ID: {ruleId})\n";
}
else
@@ -385,7 +394,8 @@ public class MainWindowViewModel : ViewModelBase
{
window.Close();
},
- proxyService: _proxyService
+ proxyService: _proxyService,
+ onConfigChanged: SaveConfigurationInternal
);
window.DataContext = viewModel;
@@ -435,7 +445,7 @@ public class MainWindowViewModel : ViewModelBase
ToggleCloseToTrayCommand = new RelayCommand(() =>
{
CloseToTray = !CloseToTray;
- SaveConfiguration();
+ SaveConfigurationInternal();
});
CloseDialogCommand = new RelayCommand(CloseDialogs);
@@ -481,6 +491,7 @@ public class MainWindowViewModel : ViewModelBase
{
rule.RuleId = ruleId;
ProxyRules.Add(rule);
+ SaveConfigurationInternal();
ActivityLog += $"[{DateTime.Now:HH:mm:ss}] Added rule: {NewProcessName} -> {NewProxyAction}\n";
IsAddRuleViewOpen = false;
NewProcessName = "";
@@ -579,36 +590,14 @@ public class MainWindowViewModel : ViewModelBase
public void Cleanup()
{
- try
- {
- var config = new AppConfig
- {
- ProxyType = _currentProxyType,
- ProxyIp = _currentProxyIp,
- ProxyPort = _currentProxyPort,
- ProxyUsername = _currentProxyUsername,
- ProxyPassword = _currentProxyPassword,
- DnsViaProxy = _dnsViaProxy,
- Language = _currentLanguage,
- CloseToTray = _closeToTray,
- ProxyRules = ProxyRules.Select(r => new ProxyRuleConfig
- {
- ProcessName = r.ProcessName,
- TargetHosts = r.TargetHosts,
- TargetPorts = r.TargetPorts,
- Protocol = r.Protocol,
- Action = r.Action,
- IsEnabled = r.IsEnabled
- }).ToList()
- };
+ // this something can be improved maybe config doesnt need save during cleanup
+ try { SaveConfigurationInternal(); } catch { }
- ConfigManager.SaveConfig(config);
- }
+ try { _proxyService?.Dispose(); _proxyService = null; }
catch { }
+ }
- _proxyService?.Dispose();
- _proxyService = null;
- } private void LoadConfiguration()
+ private void LoadConfiguration()
{
try
{
@@ -648,7 +637,12 @@ public class MainWindowViewModel : ViewModelBase
}
}
- private void SaveConfiguration()
+ private void SaveConfigurationInternal()
+ {
+ Task.Run(() => SaveConfigurationInternalAsync());
+ }
+
+ private void SaveConfigurationInternalAsync()
{
try
{
@@ -673,15 +667,9 @@ public class MainWindowViewModel : ViewModelBase
}).ToList()
};
- if (ConfigManager.SaveConfig(config))
- {
- ActivityLog += $"[{DateTime.Now:HH:mm:ss}] Configuration saved successfully\n";
- }
- }
- catch (Exception ex)
- {
- ActivityLog += $"[{DateTime.Now:HH:mm:ss}] Failed to save configuration: {ex.Message}\n";
+ ConfigManager.SaveConfig(config);
}
+ catch { }
}
}
diff --git a/Windows/gui/ViewModels/ProxyRulesViewModel.cs b/Windows/gui/ViewModels/ProxyRulesViewModel.cs
index f18170b..24e6520 100644
--- a/Windows/gui/ViewModels/ProxyRulesViewModel.cs
+++ b/Windows/gui/ViewModels/ProxyRulesViewModel.cs
@@ -24,6 +24,7 @@ public class ProxyRulesViewModel : ViewModelBase
private string _processNameError = "";
private Action<ProxyRule>? _onAddRule;
private Action? _onClose;
+ private Action? _onConfigChanged;
private ProxyBridgeService? _proxyService;
private Window? _window;
@@ -94,12 +95,13 @@ public class ProxyRulesViewModel : ViewModelBase
_window = window;
}
- public ProxyRulesViewModel(ObservableCollection<ProxyRule> proxyRules, Action<ProxyRule> onAddRule, Action onClose, ProxyBridgeService? proxyService = null)
+ public ProxyRulesViewModel(ObservableCollection<ProxyRule> proxyRules, Action<ProxyRule> onAddRule, Action onClose, ProxyBridgeService? proxyService = null, Action? onConfigChanged = null)
{
ProxyRules = proxyRules;
_onAddRule = onAddRule;
_onClose = onClose;
_proxyService = proxyService;
+ _onConfigChanged = onConfigChanged;
foreach (var rule in ProxyRules)
{
@@ -167,6 +169,7 @@ public class ProxyRulesViewModel : ViewModelBase
existingRule.Protocol = NewProtocol;
existingRule.Action = NewProxyAction;
}
+ _onConfigChanged?.Invoke();
}
_isEditMode = false;
@@ -271,6 +274,7 @@ public class ProxyRulesViewModel : ViewModelBase
if (_proxyService.DeleteRule(rule.RuleId))
{
ProxyRules.Remove(rule);
+ _onConfigChanged?.Invoke();
}
}
});
@@ -406,6 +410,7 @@ public class ProxyRulesViewModel : ViewModelBase
{
_proxyService.DisableRule(rule.RuleId);
}
+ _onConfigChanged?.Invoke();
}
else if (e.PropertyName == nameof(ProxyRule.IsSelected))
{