Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
feat(windows): run GUI unprivileged via ProxyBridgeSvc engine service
AnoF-Cyber1b1d78177ca4
diff --git a/.gitignore b/.gitignoreindex b5a6895..33c21d3 100644--- a/.gitignore+++ b/.gitignore@@ -100,4 +100,9 @@ Linux/cli/proxybridge-cliLinux/src/libproxybridge.soLinux/src/ProxyBridge.oAndroid/**-iOS/**\ No newline at end of file+iOS/**+# Windows build intermediates (MSVC import lib / export file / objects)+Windows/*.exp+Windows/*.lib+Windows/*.obj+Windows/**/*.objdiff --git a/Windows/compile.ps1 b/Windows/compile.ps1index 1f5c3b8..b0272c4 100644--- a/Windows/compile.ps1+++ b/Windows/compile.ps1@@ -264,6 +264,30 @@ if ($success) {Write-Host " Skipped: MSVC not found" -ForegroundColor Yellow}+ # ── Build engine service ─────────────────────────────────────────────────+ # ProxyBridgeSvc.exe runs as LocalSystem (registered by the installer) and owns+ # ProxyBridgeCore.dll / WinDivert, so ProxyBridge.exe itself does not need admin.+ Write-Host "`nBuilding service..." -ForegroundColor Green+ if ($script:foundVcvarsPath -and (Test-Path $script:foundVcvarsPath)) {+ $svcArgs = "/nologo /O2 /GL /Gy /W4 /MT /GS /guard:cf /sdl /DNDEBUG /D_CRT_SECURE_NO_WARNINGS /DUNICODE /D_UNICODE " ++ "src\service\pb_service.c " ++ "/link /LTCG /OPT:REF /OPT:ICF /RELEASE /DYNAMICBASE /HIGHENTROPYVA /NXCOMPAT /guard:cf /CETCOMPAT /SUBSYSTEM:CONSOLE " ++ "advapi32.lib " ++ "/OUT:ProxyBridgeSvc.exe"+ $svcCmd = "`"$script:foundVcvarsPath`" $script:foundArch >nul && cl.exe $svcArgs"+ $svcOut = cmd /c $svcCmd '2>&1'+ if ($LASTEXITCODE -eq 0) {+ Move-Item "ProxyBridgeSvc.exe" -Destination $OutputDir -Force+ Write-Host " Service built: ProxyBridgeSvc.exe" -ForegroundColor Gray+ Remove-Item "*.obj" -Force -ErrorAction SilentlyContinue+ } else {+ Write-Host " Service build failed!" -ForegroundColor Red+ Write-Host $svcOut+ }+ } else {+ Write-Host " Skipped: MSVC not found" -ForegroundColor Yellow+ }+if (-not $NoSign) {Write-Host "`nSigning binaries..." -ForegroundColor Green$filesToSign = Get-ChildItem $OutputDir -Include *.exe,*.dll -Recursediff --git a/Windows/gui/api/pb_api.h b/Windows/gui/api/pb_api.hindex 386b5aa..828c0d6 100644--- a/Windows/gui/api/pb_api.h+++ b/Windows/gui/api/pb_api.h@@ -67,7 +67,9 @@ typedef struct {// Loads ProxyBridgeCore.dll (from the exe's directory) and resolves every export.// Returns TRUE only if the DLL and all required functions were found.-static BOOL PB_Load(PBApi* api)+// Used by ProxyBridgeSvc.exe (the service that owns the engine) and as the GUI's+// elevated fallback when the service is not installed. See pb_ipc.h for the normal path.+static BOOL PB_LoadDirect(PBApi* api){ZeroMemory(api, sizeof(*api));@@ -79,7 +81,9 @@ static BOOL PB_Load(PBApi* api)lstrcatW(path, L"ProxyBridgeCore.dll");api->dll = LoadLibraryW(path);+#ifndef PB_NO_SEARCH_FALLBACKif (!api->dll) api->dll = LoadLibraryW(L"ProxyBridgeCore.dll"); // fallback to search path+#endifif (!api->dll) return FALSE;#define PB_BIND(field, name) \@@ -110,4 +114,10 @@ static BOOL PB_Load(PBApi* api)return TRUE;}+static void PB_UnloadDirect(PBApi* api)+{+ if (api->dll) FreeLibrary(api->dll);+ ZeroMemory(api, sizeof(*api));+}+#endif // PB_API_Hdiff --git a/Windows/gui/api/pb_ipc.h b/Windows/gui/api/pb_ipc.hnew file mode 100644index 0000000..2cde8f5--- /dev/null+++ b/Windows/gui/api/pb_ipc.h@@ -0,0 +1,226 @@+// pb_ipc.h - PBApi backed by ProxyBridgeSvc.exe over named pipes (see src/service/pb_proto.h).+//+// This is how the unprivileged GUI drives the engine: the service (LocalSystem, installed+// once by the installer) owns ProxyBridgeCore.dll and WinDivert; the GUI only needs to open+// the pipes. The function table is identical to the one PB_LoadDirect() fills in, so the+// rest of the GUI does not know which path is in use.+//+// Callbacks (log / connection / proxy-test lines) are delivered on a reader thread, the same+// "native thread - never touch UI directly" contract as the in-process engine.+#ifndef PB_IPC_H+#define PB_IPC_H++#include "pb_api.h"+#include "../../src/service/pb_proto.h"++enum { PB_IPC_OK = 0, PB_IPC_NO_SERVICE, PB_IPC_BUSY, PB_IPC_BAD_VERSION };++static HANDLE g_ipcCtl = INVALID_HANDLE_VALUE;+static HANDLE g_ipcEvt = INVALID_HANDLE_VALUE;+static HANDLE g_ipcReader = NULL;+static CRITICAL_SECTION g_ipcLock; // one request/response at a time+static CRITICAL_SECTION g_ipcTestLock; // one proxy test at a time+static BOOL g_ipcInit = FALSE;+static HANDLE g_ipcTestDone = NULL;+static volatile LONG g_ipcTestResult = -1;+static PBLogCallback g_ipcLogCb = NULL;+static PBConnectionCallback g_ipcConnCb = NULL;+static PBTestLogCallback g_ipcTestCb = NULL;+static void* g_ipcTestUser = NULL;++// events+static DWORD WINAPI PbIpcReader(LPVOID arg)+{+ (void)arg;+ BYTE buf[PB_MSG_MAX];+ for (;;)+ {+ DWORD n = 0;+ if (!ReadFile(g_ipcEvt, buf, sizeof(buf), &n, NULL)) break;+ PbR r; PbR_Init(&r, buf, n);+ UINT32 type = PbR_U32(&r);+ char a[8192], b[8192], c[8192];+ if (type == PBEVT_LOG)+ {+ PbR_Str(&r, a, sizeof(a), NULL);+ if (r.ok && g_ipcLogCb) g_ipcLogCb(a);+ }+ else if (type == PBEVT_CONN)+ {+ PbR_Str(&r, a, sizeof(a), NULL); UINT32 pid = PbR_U32(&r);+ PbR_Str(&r, b, sizeof(b), NULL); UINT32 port = PbR_U32(&r);+ PbR_Str(&r, c, sizeof(c), NULL);+ if (r.ok && g_ipcConnCb) g_ipcConnCb(a, pid, b, (unsigned short)port, c);+ }+ else if (type == PBEVT_TEST_LINE)+ {+ PbR_Str(&r, a, sizeof(a), NULL);+ if (r.ok && g_ipcTestCb) g_ipcTestCb(a, g_ipcTestUser);+ }+ else if (type == PBEVT_TEST_DONE)+ {+ UINT32 rc = PbR_U32(&r);+ if (r.ok) { InterlockedExchange(&g_ipcTestResult, (LONG)rc); SetEvent(g_ipcTestDone); }+ }+ }+ SetEvent(g_ipcTestDone); // service went away: release a pending proxy test+ return 0;+}++// Sends one request, returns the response's leading u32 (0 on any failure).+static UINT32 PbIpcCall(const BYTE *req, DWORD len)+{+ UINT32 ret = 0;+ BYTE rsp[64];+ EnterCriticalSection(&g_ipcLock);+ if (g_ipcCtl != INVALID_HANDLE_VALUE)+ {+ DWORD n = 0;+ if (WriteFile(g_ipcCtl, req, len, &n, NULL) && ReadFile(g_ipcCtl, rsp, sizeof(rsp), &n, NULL) && n >= 4)+ memcpy(&ret, rsp, 4);+ else { CloseHandle(g_ipcCtl); g_ipcCtl = INVALID_HANDLE_VALUE; } // service gone+ }+ LeaveCriticalSection(&g_ipcLock);+ return ret;+}++#define PBIPC_BEGIN(opcode) BYTE _b[PB_MSG_MAX]; PbW _w; PbW_Init(&_w, _b, sizeof(_b)); PbW_U32(&_w, (opcode))+#define PBIPC_END() return _w.ok ? PbIpcCall(_b, _w.len) : 0++static UINT32 IpcAddProxyConfig(PBProxyType t, const char* ip, unsigned short port, const char* u, const char* p, BOOL sd)+{ PBIPC_BEGIN(PBOP_ADD_PROXY); PbW_U32(&_w, t); PbW_Str(&_w, ip); PbW_U32(&_w, port); PbW_Str(&_w, u); PbW_Str(&_w, p); PbW_U32(&_w, sd != 0); PBIPC_END(); }+static BOOL IpcEditProxyConfig(UINT32 id, PBProxyType t, const char* ip, unsigned short port, const char* u, const char* p, BOOL sd)+{ PBIPC_BEGIN(PBOP_EDIT_PROXY); PbW_U32(&_w, id); PbW_U32(&_w, t); PbW_Str(&_w, ip); PbW_U32(&_w, port); PbW_Str(&_w, u); PbW_Str(&_w, p); PbW_U32(&_w, sd != 0); PBIPC_END(); }+static BOOL IpcDeleteProxyConfig(UINT32 id)+{ PBIPC_BEGIN(PBOP_DELETE_PROXY); PbW_U32(&_w, id); PBIPC_END(); }++static int IpcTestProxyConfig(UINT32 id, const char* host, unsigned short port, char* out, size_t cap)+{ (void)id; (void)host; (void)port; if (out && cap) out[0] = 0; return -1; } // unused by the GUI (see TestProxyConfigEx)++static int IpcTestProxyConfigEx(UINT32 id, const char* host, unsigned short port, PBTestLogCallback cb, void* user)+{+ int rc = -1;+ EnterCriticalSection(&g_ipcTestLock);+ g_ipcTestCb = cb; g_ipcTestUser = user;+ ResetEvent(g_ipcTestDone);+ InterlockedExchange(&g_ipcTestResult, -1);+ {+ PBIPC_BEGIN(PBOP_TEST_PROXY_START); PbW_U32(&_w, id); PbW_Str(&_w, host); PbW_U32(&_w, port);+ if (_w.ok && PbIpcCall(_b, _w.len))+ {+ WaitForSingleObject(g_ipcTestDone, 120000);+ rc = (int)g_ipcTestResult;+ }+ }+ g_ipcTestCb = NULL;+ LeaveCriticalSection(&g_ipcTestLock);+ return rc;+}++static UINT32 IpcAddRule(const char* proc, const char* hosts, const char* ports, const char* domains, PBRuleProtocol pr, PBRuleAction ac, UINT32 cfg)+{ PBIPC_BEGIN(PBOP_ADD_RULE); PbW_Str(&_w, proc); PbW_Str(&_w, hosts); PbW_Str(&_w, ports); PbW_Str(&_w, domains); PbW_U32(&_w, pr); PbW_U32(&_w, ac); PbW_U32(&_w, cfg); PBIPC_END(); }+static BOOL IpcEditRule(UINT32 id, const char* proc, const char* hosts, const char* ports, const char* domains, PBRuleProtocol pr, PBRuleAction ac, UINT32 cfg)+{ PBIPC_BEGIN(PBOP_EDIT_RULE); PbW_U32(&_w, id); PbW_Str(&_w, proc); PbW_Str(&_w, hosts); PbW_Str(&_w, ports); PbW_Str(&_w, domains); PbW_U32(&_w, pr); PbW_U32(&_w, ac); PbW_U32(&_w, cfg); PBIPC_END(); }+static BOOL IpcEnableRule(UINT32 id) { PBIPC_BEGIN(PBOP_ENABLE_RULE); PbW_U32(&_w, id); PBIPC_END(); }+static BOOL IpcDisableRule(UINT32 id) { PBIPC_BEGIN(PBOP_DISABLE_RULE); PbW_U32(&_w, id); PBIPC_END(); }+static BOOL IpcDeleteRule(UINT32 id) { PBIPC_BEGIN(PBOP_DELETE_RULE); PbW_U32(&_w, id); PBIPC_END(); }+static BOOL IpcMoveRule(UINT32 id, UINT32 pos) { PBIPC_BEGIN(PBOP_MOVE_RULE); PbW_U32(&_w, id); PbW_U32(&_w, pos); PBIPC_END(); }+static UINT32 IpcGetRulePos(UINT32 id) { PBIPC_BEGIN(PBOP_GET_RULE_POS); PbW_U32(&_w, id); PBIPC_END(); }+static void IpcSetLocalhost(BOOL v) { PBIPC_BEGIN(PBOP_SET_LOCALHOST); PbW_U32(&_w, v != 0); PbIpcCall(_b, _w.len); }+static void IpcSetTrafficLog(BOOL v) { PBIPC_BEGIN(PBOP_SET_TRAFFIC_LOG); PbW_U32(&_w, v != 0); PbIpcCall(_b, _w.len); }+static void IpcClearConnLogs(void) { PBIPC_BEGIN(PBOP_CLEAR_CONN_LOGS); PbIpcCall(_b, _w.len); }+static void IpcSetLogCallback(PBLogCallback cb) { g_ipcLogCb = cb; }+static void IpcSetConnectionCallback(PBConnectionCallback cb) { g_ipcConnCb = cb; }+static BOOL IpcStart(void) { PBIPC_BEGIN(PBOP_START); PBIPC_END(); }+static BOOL IpcStop(void) { PBIPC_BEGIN(PBOP_STOP); PBIPC_END(); }++// Asks the SCM to start the service (the installer grants interactive users this right).+static void PbIpcTryStartService(void)+{+ SC_HANDLE scm = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);+ if (!scm) return;+ SC_HANDLE svc = OpenServiceW(scm, PB_SERVICE_NAME, SERVICE_START | SERVICE_QUERY_STATUS);+ if (svc)+ {+ StartServiceW(svc, 0, NULL);+ SERVICE_STATUS st;+ for (int i = 0; i < 50; i++) // up to ~5 s for START_PENDING -> RUNNING+ {+ if (!QueryServiceStatus(svc, &st) || st.dwCurrentState == SERVICE_RUNNING) break;+ Sleep(100);+ }+ CloseServiceHandle(svc);+ }+ CloseServiceHandle(scm);+}++static HANDLE PbIpcOpen(const wchar_t* name, DWORD access, DWORD* err)+{+ for (int tries = 0; tries < 20; tries++)+ {+ HANDLE h = CreateFileW(name, access, 0, NULL, OPEN_EXISTING, 0, NULL);+ if (h != INVALID_HANDLE_VALUE)+ {+ DWORD mode = PIPE_READMODE_MESSAGE;+ SetNamedPipeHandleState(h, &mode, NULL, NULL);+ return h;+ }+ *err = GetLastError();+ if (*err != ERROR_PIPE_BUSY) break;+ Sleep(100);+ }+ return INVALID_HANDLE_VALUE;+}++// Connects to the service and fills `api` with pipe-backed functions.+// Returns PB_IPC_OK, or why not (PB_IPC_NO_SERVICE = not installed / not running).+static int PB_LoadService(PBApi* api)+{+ if (!g_ipcInit)+ {+ InitializeCriticalSection(&g_ipcLock);+ InitializeCriticalSection(&g_ipcTestLock);+ g_ipcTestDone = CreateEventW(NULL, TRUE, FALSE, NULL);+ g_ipcInit = TRUE;+ }++ DWORD err = 0;+ HANDLE ctl = PbIpcOpen(PB_PIPE_CTL, GENERIC_READ | GENERIC_WRITE, &err);+ if (ctl == INVALID_HANDLE_VALUE && err == ERROR_FILE_NOT_FOUND)+ {+ PbIpcTryStartService();+ ctl = PbIpcOpen(PB_PIPE_CTL, GENERIC_READ | GENERIC_WRITE, &err);+ }+ if (ctl == INVALID_HANDLE_VALUE)+ return (err == ERROR_PIPE_BUSY) ? PB_IPC_BUSY : PB_IPC_NO_SERVICE;++ HANDLE evt = PbIpcOpen(PB_PIPE_EVT, GENERIC_READ, &err);+ if (evt == INVALID_HANDLE_VALUE) { CloseHandle(ctl); return (err == ERROR_PIPE_BUSY) ? PB_IPC_BUSY : PB_IPC_NO_SERVICE; }++ g_ipcCtl = ctl; g_ipcEvt = evt;+ {+ PBIPC_BEGIN(PBOP_HELLO);+ if (PbIpcCall(_b, _w.len) != PB_PROTO_VERSION)+ {+ CloseHandle(g_ipcCtl); g_ipcCtl = INVALID_HANDLE_VALUE;+ CloseHandle(g_ipcEvt); g_ipcEvt = INVALID_HANDLE_VALUE;+ return PB_IPC_BAD_VERSION;+ }+ }+ g_ipcReader = CreateThread(NULL, 0, PbIpcReader, NULL, 0, NULL);++ ZeroMemory(api, sizeof(*api));+ api->AddProxyConfig = IpcAddProxyConfig; api->EditProxyConfig = IpcEditProxyConfig;+ api->DeleteProxyConfig = IpcDeleteProxyConfig; api->TestProxyConfig = IpcTestProxyConfig;+ api->TestProxyConfigEx = IpcTestProxyConfigEx; api->AddRule = IpcAddRule;+ api->EnableRule = IpcEnableRule; api->DisableRule = IpcDisableRule;+ api->DeleteRule = IpcDeleteRule; api->EditRule = IpcEditRule;+ api->MoveRuleToPosition = IpcMoveRule; api->GetRulePosition = IpcGetRulePos;+ api->SetLocalhostViaProxy = IpcSetLocalhost; api->SetLogCallback = IpcSetLogCallback;+ api->SetConnectionCallback = IpcSetConnectionCallback;+ api->SetTrafficLoggingEnabled = IpcSetTrafficLog;+ api->ClearConnectionLogs = IpcClearConnLogs; api->Start = IpcStart; api->Stop = IpcStop;+ return PB_IPC_OK;+}++#endif // PB_IPC_Hdiff --git a/Windows/gui/main.c b/Windows/gui/main.cindex 93617af..38b9bd4 100644--- a/Windows/gui/main.c+++ b/Windows/gui/main.c@@ -24,6 +24,7 @@#include <stdlib.h>#include "res/resource.h"#include "api/pb_api.h"+#include "api/pb_ipc.h"#include "profile/profile.h"#include "loc/loc.h"@@ -920,6 +921,59 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)#include "ui/dialogs.h"+// Connects to the engine. Normal path: the ProxyBridgeSvc service (installed once by setup)+// so this process stays unprivileged. Fallback for a portable/unzipped copy with no service:+// load ProxyBridgeCore.dll in-process, which needs elevation - relaunch elevated once.+static BOOL IsElevated(void)+{+ BOOL elevated = FALSE; HANDLE tok = NULL;+ if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &tok))+ {+ TOKEN_ELEVATION te; DWORD n = 0;+ if (GetTokenInformation(tok, TokenElevation, &te, sizeof(te), &n)) elevated = te.TokenIsElevated != 0;+ CloseHandle(tok);+ }+ return elevated;+}++static BOOL ConnectEngine(void)+{+ int rc = PB_LoadService(&g_api);+ if (rc == PB_IPC_OK) return TRUE;++ if (rc == PB_IPC_BUSY)+ {+ MessageBoxW(NULL, L"Another ProxyBridge window (possibly in a different user session) is already "+ L"connected to the ProxyBridge service.\nClose it and try again.",+ APP_TITLE, MB_OK | MB_ICONWARNING);+ return FALSE;+ }+ if (rc == PB_IPC_BAD_VERSION)+ {+ MessageBoxW(NULL, L"The installed ProxyBridge service is a different version than this program.\n"+ L"Re-run the ProxyBridge installer.", APP_TITLE, MB_OK | MB_ICONERROR);+ return FALSE;+ }++ // No service: portable mode.+ if (!IsElevated())+ {+ wchar_t exe[MAX_PATH]; GetModuleFileNameW(NULL, exe, MAX_PATH);+ SHELLEXECUTEINFOW sei; ZeroMemory(&sei, sizeof(sei));+ sei.cbSize = sizeof(sei); sei.lpVerb = L"runas"; sei.lpFile = exe; sei.nShow = SW_SHOWNORMAL;+ ShellExecuteExW(&sei); // on UAC cancel just exit+ return FALSE;+ }+ if (!PB_LoadDirect(&g_api))+ {+ MessageBoxW(NULL, L"Could not load ProxyBridgeCore.dll.\n"+ L"Make sure it is in the same folder as this executable.",+ APP_TITLE, MB_OK | MB_ICONERROR);+ return FALSE;+ }+ return TRUE;+}+// entry pointint WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrev, PWSTR cmd, int show){@@ -930,14 +984,6 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrev, PWSTR cmd, int show)INITCOMMONCONTROLSEX icc = { sizeof(icc), ICC_TAB_CLASSES | ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES | ICC_STANDARD_CLASSES | ICC_LINK_CLASS | ICC_PROGRESS_CLASS };InitCommonControlsEx(&icc);- if (!PB_Load(&g_api))- {- MessageBoxW(NULL, L"Could not load ProxyBridgeCore.dll.\n"- L"Make sure it is in the same folder as this executable.",- APP_TITLE, MB_OK | MB_ICONERROR);- return 1;- }-// Load the active profile.PB_GetActiveProfile(g_activeProfile, PB_NAME_MAX);PB_ProfileLoad(g_activeProfile, &g_profile);@@ -946,14 +992,17 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrev, PWSTR cmd, int show)g_closeToTray = g_profile.closeToTray;g_lang = (_wcsicmp(g_profile.language, L"zh") == 0) ? 1 : 0;- // Refuse to start if another GUI or the CLI is already running - they'd both grab the- // WinDivert driver and the same relay ports.+ // Refuse to start if another GUI or the CLI is already running - they'd both drive the+ // same engine (the service accepts one client at a time) and the same relay ports.if (AnotherInstanceRunning()){MessageBoxW(NULL, T(S_ERR_RUNNING), APP_TITLE, MB_OK | MB_ICONWARNING);return 0;}+ if (!ConnectEngine())+ return 1;+g_autoClear = g_profile.autoClearLogs;g_startup = StartupIsEnabled();ApplyFilterSnapshot();diff --git a/Windows/gui/res/app.manifest b/Windows/gui/res/app.manifestindex 9a0b5c3..9d3042a 100644--- a/Windows/gui/res/app.manifest+++ b/Windows/gui/res/app.manifest@@ -1,11 +1,12 @@<?xml version="1.0" encoding="UTF-8" standalone="yes"?><assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"><assemblyIdentity version="4.0.13.0" processorArchitecture="*" name="InterceptSuite.ProxyBridge.NativeGUI" type="win32"/>- <!-- Require administrator: WinDivert needs elevation to load its kernel driver. -->+ <!-- No elevation: the WinDivert-owning engine runs in the ProxyBridgeSvc service (installed+ once by the setup program), and this GUI talks to it over a named pipe. --><trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"><security><requestedPrivileges>- <requestedExecutionLevel level="requireAdministrator" uiAccess="false"/>+ <requestedExecutionLevel level="asInvoker" uiAccess="false"/></requestedPrivileges></security></trustInfo>diff --git a/Windows/gui/ui/startup.h b/Windows/gui/ui/startup.hindex 5c8c391..dca017f 100644--- a/Windows/gui/ui/startup.h+++ b/Windows/gui/ui/startup.h@@ -26,7 +26,12 @@ static BOOL AnotherInstanceRunning(void)return found;}-// Run at Startup (schtasks logon task)+// Run at Startup: HKCU\...\Run value. Per-user, so it needs no elevation (the engine lives in+// the ProxyBridgeSvc service). Older versions used an elevated "ProxyBridge" logon task; it is+// removed here when the setting is toggled (and by the uninstaller).+#define PB_RUN_KEY L"Software\\Microsoft\\Windows\\CurrentVersion\\Run"+#define PB_RUN_VALUE L"ProxyBridge"+// Runs schtasks.exe hidden and returns its exit code (0 = success / task exists).static DWORD RunSchtasks(const wchar_t* args){@@ -44,23 +49,28 @@ static DWORD RunSchtasks(const wchar_t* args)}static BOOL StartupIsEnabled(void){- return RunSchtasks(L"/Query /TN \"ProxyBridge\"") == 0;+ HKEY k; BOOL on = FALSE;+ if (RegOpenKeyExW(HKEY_CURRENT_USER, PB_RUN_KEY, 0, KEY_QUERY_VALUE, &k) == ERROR_SUCCESS)+ {+ on = RegQueryValueExW(k, PB_RUN_VALUE, NULL, NULL, NULL, NULL) == ERROR_SUCCESS;+ RegCloseKey(k);+ }+ return on;}static void StartupSet(BOOL enable){+ HKEY k;+ if (RegCreateKeyExW(HKEY_CURRENT_USER, PB_RUN_KEY, 0, NULL, 0, KEY_SET_VALUE, NULL, &k, NULL) != ERROR_SUCCESS) return;if (enable){wchar_t exe[MAX_PATH]; GetModuleFileNameW(NULL, exe, MAX_PATH);- wchar_t args[1200];- // ONLOGON task launching the exe minimized, highest run level.- // The short delay lets the shell/tray come up first so the tray icon appears- _snwprintf_s(args, 1200, _TRUNCATE,- L"/Create /F /TN \"ProxyBridge\" /TR \"\\\"%s\\\" --minimized\" /SC ONLOGON /DELAY 0000:15 /RL HIGHEST",- exe);- args[1199] = 0;- RunSchtasks(args);+ wchar_t cmd[MAX_PATH + 32];+ _snwprintf_s(cmd, ARRAYSIZE(cmd), _TRUNCATE, L"\"%s\" --minimized", exe);+ RegSetValueExW(k, PB_RUN_VALUE, 0, REG_SZ, (const BYTE*)cmd, (DWORD)((wcslen(cmd) + 1) * sizeof(wchar_t)));}- else RunSchtasks(L"/Delete /F /TN \"ProxyBridge\"");+ else RegDeleteValueW(k, PB_RUN_VALUE);+ RegCloseKey(k);+ RunSchtasks(L"/Delete /F /TN \"ProxyBridge\""); // legacy elevated logon task (no-op if absent / not admin)}#endif // PB_UI_STARTUP_Hdiff --git a/Windows/installer/ProxyBridge.nsi b/Windows/installer/ProxyBridge.nsiindex 6ba1d55..84f7294 100644--- a/Windows/installer/ProxyBridge.nsi+++ b/Windows/installer/ProxyBridge.nsi@@ -63,6 +63,12 @@ Section "MainSection" SEC01Sleep 1500install_proceed:+ ; Stop the engine service first (it holds ProxyBridgeCore.dll / WinDivert64.sys open), then+ ; remove the legacy elevated logon task older versions created.+ nsExec::ExecToLog 'sc stop ProxyBridgeSvc'+ Sleep 1500+ nsExec::ExecToLog 'schtasks /Delete /F /TN "ProxyBridge"'+; Stop and unload the WinDivert driver so WinDivert64.sys can be replaced.nsExec::ExecToLog 'sc stop WinDivert'nsExec::ExecToLog 'sc delete WinDivert'@@ -77,6 +83,7 @@ Section "MainSection" SEC01File "..\output\ProxyBridge.exe"File "..\output\ProxyBridge_CLI.exe"File "..\output\ProxyBridgeCore.dll"+ File "..\output\ProxyBridgeSvc.exe"File "..\output\WinDivert.dll"File "..\output\WinDivert64.sys"@@ -86,6 +93,15 @@ Section "MainSection" SEC01Delete "$INSTDIR\libHarfBuzzSharp.dll"Delete "$INSTDIR\libSkiaSharp.dll"+ ; Register the engine service once. It runs as LocalSystem and starts with Windows, so the+ ; ProxyBridge app itself never needs administrator rights. The service ACL lets interactive+ ; users start it (never stop or reconfigure it), in case it was stopped.+ nsExec::ExecToLog 'sc delete ProxyBridgeSvc'+ nsExec::ExecToLog 'sc create ProxyBridgeSvc binPath= "\"$INSTDIR\ProxyBridgeSvc.exe\"" start= auto DisplayName= "ProxyBridge Service"'+ nsExec::ExecToLog 'sc description ProxyBridgeSvc "Privileged traffic-redirection engine for ProxyBridge. Lets the ProxyBridge app run without administrator rights."'+ nsExec::ExecToLog 'sc sdset ProxyBridgeSvc "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWRPLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)"'+ nsExec::ExecToLog 'sc start ProxyBridgeSvc'+CreateDirectory "$SMPROGRAMS\${PRODUCT_NAME}"CreateShortCut "$SMPROGRAMS\${PRODUCT_NAME}\${PRODUCT_NAME}.lnk" "$INSTDIR\ProxyBridge.exe"CreateShortCut "$DESKTOP\${PRODUCT_NAME}.lnk" "$INSTDIR\ProxyBridge.exe"@@ -124,8 +140,14 @@ Section UninstallSleep 1500uninst_proceed:- ; Remove the "Run at Startup" logon task the GUI may have created.+ ; Remove the engine service, and the legacy "Run at Startup" logon task older versions created.+ nsExec::ExecToLog 'sc stop ProxyBridgeSvc'+ Sleep 1500+ nsExec::ExecToLog 'sc delete ProxyBridgeSvc'nsExec::ExecToLog 'schtasks /Delete /F /TN "ProxyBridge"'+ ; The per-user Run entry is removed for the account running the uninstaller; other users'+ ; entries just point at a missing exe and are harmless.+ DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "ProxyBridge"; Stop the WinDivert driver first so WinDivert64.sys isn't held open.nsExec::ExecToLog 'sc stop WinDivert'@@ -136,6 +158,7 @@ Section UninstallDelete "$INSTDIR\ProxyBridge.exe"Delete "$INSTDIR\ProxyBridge_CLI.exe"Delete "$INSTDIR\ProxyBridgeCore.dll"+ Delete "$INSTDIR\ProxyBridgeSvc.exe"Delete "$INSTDIR\WinDivert.dll"Delete "$INSTDIR\WinDivert64.sys"Delete "$INSTDIR\uninst.exe"diff --git a/Windows/src/service/pb_proto.h b/Windows/src/service/pb_proto.hnew file mode 100644index 0000000..5b6a809--- /dev/null+++ b/Windows/src/service/pb_proto.h@@ -0,0 +1,99 @@+// pb_proto.h - wire protocol between ProxyBridge.exe (unprivileged GUI) and+// ProxyBridgeSvc.exe (LocalSystem service that owns ProxyBridgeCore.dll / WinDivert).+//+// Two message-mode named pipes, one client at a time:+// PB_PIPE_CTL request/response. Client writes one request message, reads one response.+// PB_PIPE_EVT service -> client only: log lines, connection events, proxy-test output.+//+// Every message is a flat byte buffer built with PbW (writer) and parsed with PbR (reader).+// request : u32 op, args...+// response : u32 ret, extra...+// event : u32 type, fields...+// Integers are little-endian u32. A string is u32 length + bytes (no NUL);+// length 0xFFFFFFFF means NULL.+#ifndef PB_PROTO_H+#define PB_PROTO_H++#include <windows.h>++#define PB_SERVICE_NAME L"ProxyBridgeSvc"+#define PB_PIPE_CTL L"\\\\.\\pipe\\ProxyBridgeCtl"+#define PB_PIPE_EVT L"\\\\.\\pipe\\ProxyBridgeEvt"+#define PB_PROTO_VERSION 1+#define PB_MSG_MAX (64u * 1024u)+#define PB_STR_MAX (32u * 1024u)+#define PB_NULL_STR 0xFFFFFFFFu++enum {+ PBOP_HELLO = 1, // () -> PB_PROTO_VERSION+ PBOP_ADD_PROXY, // type, ip, port, user, pass, sendDomain -> id+ PBOP_EDIT_PROXY, // id, type, ip, port, user, pass, sendDomain -> bool+ PBOP_DELETE_PROXY, // id -> bool+ PBOP_TEST_PROXY_START, // id, host, port -> bool (result arrives as PBEVT_TEST_DONE)+ PBOP_ADD_RULE, // proc, hosts, ports, domains, proto, action, cfgId -> id+ PBOP_ENABLE_RULE, // id -> bool+ PBOP_DISABLE_RULE, // id -> bool+ PBOP_DELETE_RULE, // id -> bool+ PBOP_EDIT_RULE, // id, proc, hosts, ports, domains, proto, action, cfgId -> bool+ PBOP_MOVE_RULE, // id, pos -> bool+ PBOP_GET_RULE_POS, // id -> pos+ PBOP_SET_LOCALHOST, // bool -> 0+ PBOP_SET_TRAFFIC_LOG, // bool -> 0+ PBOP_CLEAR_CONN_LOGS, // () -> 0+ PBOP_START, // () -> bool+ PBOP_STOP // () -> bool+};++enum {+ PBEVT_LOG = 1, // str message+ PBEVT_CONN, // str process, u32 pid, str ip, u32 port, str info+ PBEVT_TEST_LINE, // str line+ PBEVT_TEST_DONE // u32 result (int)+};++// writer+typedef struct { BYTE *buf; DWORD len; DWORD cap; BOOL ok; } PbW;++static void PbW_Init(PbW *w, BYTE *buf, DWORD cap) { w->buf = buf; w->len = 0; w->cap = cap; w->ok = TRUE; }+static void PbW_U32(PbW *w, UINT32 v)+{+ if (!w->ok || w->len + 4 > w->cap) { w->ok = FALSE; return; }+ memcpy(w->buf + w->len, &v, 4); w->len += 4;+}+static void PbW_Str(PbW *w, const char *s)+{+ if (s == NULL) { PbW_U32(w, PB_NULL_STR); return; }+ size_t n = strlen(s);+ if (n > PB_STR_MAX) { w->ok = FALSE; return; }+ PbW_U32(w, (UINT32)n);+ if (!w->ok || w->len + n > w->cap) { w->ok = FALSE; return; }+ memcpy(w->buf + w->len, s, n); w->len += (DWORD)n;+}++// reader (bounds-checked: any malformed message just flips ok to FALSE)+typedef struct { const BYTE *buf; DWORD len; DWORD pos; BOOL ok; } PbR;++static void PbR_Init(PbR *r, const BYTE *buf, DWORD len) { r->buf = buf; r->len = len; r->pos = 0; r->ok = TRUE; }+static UINT32 PbR_U32(PbR *r)+{+ UINT32 v = 0;+ if (!r->ok || r->pos + 4 > r->len) { r->ok = FALSE; return 0; }+ memcpy(&v, r->buf + r->pos, 4); r->pos += 4;+ return v;+}+// Copies into out (always NUL-terminated, truncated to outCap-1). Returns FALSE if the string+// was NULL (out[0] = 0) or the message is malformed. *isNull is set for the NULL case.+static void PbR_Str(PbR *r, char *out, size_t outCap, BOOL *isNull)+{+ out[0] = 0;+ if (isNull) *isNull = FALSE;+ UINT32 n = PbR_U32(r);+ if (!r->ok) return;+ if (n == PB_NULL_STR) { if (isNull) *isNull = TRUE; return; }+ if (n > PB_STR_MAX || r->pos + n > r->len) { r->ok = FALSE; return; }+ size_t c = n < outCap - 1 ? n : outCap - 1;+ memcpy(out, r->buf + r->pos, c); out[c] = 0;+ r->pos += n;+}++#endif // PB_PROTO_Hdiff --git a/Windows/src/service/pb_service.c b/Windows/src/service/pb_service.cnew file mode 100644index 0000000..ab07b35--- /dev/null+++ b/Windows/src/service/pb_service.c@@ -0,0 +1,307 @@+// pb_service.c - ProxyBridgeSvc.exe+//+// LocalSystem Windows service that owns ProxyBridgeCore.dll (and so the WinDivert driver).+// The installer registers it once (admin); after that the GUI runs as a normal user and+// drives the engine over two named pipes (see pb_proto.h). This is why ProxyBridge.exe no+// longer needs "Run as administrator".+//+// One client at a time. When the client goes away (exit or crash) the engine is stopped and+// the core DLL is unloaded, so the next client starts from a clean state.++#define WIN32_LEAN_AND_MEAN+#include <windows.h>+#include <sddl.h>+#include <stdio.h>+#include <string.h>+#include <stdlib.h>+#include "pb_proto.h"+#define PB_NO_SEARCH_FALLBACK // SYSTEM service: load the engine only from our own directory+#include "../../gui/api/pb_api.h"++// pipe access: SYSTEM + Administrators full, interactive (logged-on, local) users read/write.+// Network logons are not in this list, and PIPE_REJECT_REMOTE_CLIENTS blocks remote access too.+#define PB_PIPE_SDDL L"D:(A;;GA;;;SY)(A;;GA;;;BA)(A;;GRGW;;;IU)"++static SERVICE_STATUS_HANDLE g_ssh = NULL;+static SERVICE_STATUS g_status;+static volatile LONG g_stop = 0;+static HANDLE g_worker = NULL; // thread running the accept/serve loop++static HANDLE g_ctl = INVALID_HANDLE_VALUE;+static HANDLE g_evt = INVALID_HANDLE_VALUE;+static PBApi g_api;+static CRITICAL_SECTION g_evt_lock; // serialises event writes from engine threads+static volatile LONG g_evt_live = 0; // 1 while an event pipe client is attached++static void SetState(DWORD state, DWORD exitCode)+{+ g_status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;+ g_status.dwCurrentState = state;+ g_status.dwControlsAccepted = (state == SERVICE_START_PENDING) ? 0 : (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN);+ g_status.dwWin32ExitCode = exitCode;+ g_status.dwWaitHint = (state == SERVICE_STOP_PENDING || state == SERVICE_START_PENDING) ? 10000 : 0;+ if (g_ssh) SetServiceStatus(g_ssh, &g_status);+}++// events (called from engine threads)+static void SendEvent(const BYTE *buf, DWORD len)+{+ if (!g_evt_live) return;+ EnterCriticalSection(&g_evt_lock);+ if (g_evt_live && g_evt != INVALID_HANDLE_VALUE)+ {+ DWORD wr = 0;+ if (!WriteFile(g_evt, buf, len, &wr, NULL)) InterlockedExchange(&g_evt_live, 0);+ }+ LeaveCriticalSection(&g_evt_lock);+}++static void OnLog(const char *msg)+{+ BYTE b[8192]; PbW w; PbW_Init(&w, b, sizeof(b));+ PbW_U32(&w, PBEVT_LOG); PbW_Str(&w, msg);+ if (w.ok) SendEvent(b, w.len);+}++static void OnConn(const char *proc, DWORD pid, const char *ip, unsigned short port, const char *info)+{+ BYTE b[8192]; PbW w; PbW_Init(&w, b, sizeof(b));+ PbW_U32(&w, PBEVT_CONN); PbW_Str(&w, proc); PbW_U32(&w, pid);+ PbW_Str(&w, ip); PbW_U32(&w, port); PbW_Str(&w, info);+ if (w.ok) SendEvent(b, w.len);+}++// proxy test runs on its own thread so the request that started it returns immediately+static volatile LONG g_test_busy = 0;+typedef struct { UINT32 id; char host[512]; unsigned short port; } TestJob;++static void TestLineCb(const char *line, void *user)+{+ (void)user;+ BYTE b[8192]; PbW w; PbW_Init(&w, b, sizeof(b));+ PbW_U32(&w, PBEVT_TEST_LINE); PbW_Str(&w, line);+ if (w.ok) SendEvent(b, w.len);+}++static DWORD WINAPI TestThread(LPVOID arg)+{+ TestJob *j = (TestJob *)arg;+ int rc = g_api.TestProxyConfigEx ? g_api.TestProxyConfigEx(j->id, j->host, j->port, TestLineCb, NULL) : -1;+ BYTE b[16]; PbW w; PbW_Init(&w, b, sizeof(b));+ PbW_U32(&w, PBEVT_TEST_DONE); PbW_U32(&w, (UINT32)rc);+ SendEvent(b, w.len);+ free(j);+ InterlockedExchange(&g_test_busy, 0);+ return 0;+}++// request dispatch. Returns FALSE if the request was malformed.+static BOOL Dispatch(const BYTE *req, DWORD reqLen, PbW *resp)+{+ PbR r; PbR_Init(&r, req, reqLen);+ UINT32 op = PbR_U32(&r);+ UINT32 ret = 0;++ // scratch for string args+ static char proc[PB_STR_MAX + 1], hosts[PB_STR_MAX + 1], ports[4096], domains[PB_STR_MAX + 1];+ static char ip[512], user[512], pass[512], host[512];+ BOOL nUser = FALSE, nPass = FALSE, nHosts = FALSE, nPorts = FALSE, nDomains = FALSE, nProc = FALSE;++ switch (op)+ {+ case PBOP_HELLO: ret = PB_PROTO_VERSION; break;++ case PBOP_ADD_PROXY: {+ UINT32 type = PbR_U32(&r); PbR_Str(&r, ip, sizeof(ip), NULL); UINT32 port = PbR_U32(&r);+ PbR_Str(&r, user, sizeof(user), &nUser); PbR_Str(&r, pass, sizeof(pass), &nPass);+ UINT32 sd = PbR_U32(&r);+ if (!r.ok || type > 1 || port > 65535) return FALSE;+ ret = g_api.AddProxyConfig((PBProxyType)type, ip, (unsigned short)port, nUser ? NULL : user, nPass ? NULL : pass, sd != 0);+ break; }+ case PBOP_EDIT_PROXY: {+ UINT32 id = PbR_U32(&r), type = PbR_U32(&r); PbR_Str(&r, ip, sizeof(ip), NULL); UINT32 port = PbR_U32(&r);+ PbR_Str(&r, user, sizeof(user), &nUser); PbR_Str(&r, pass, sizeof(pass), &nPass);+ UINT32 sd = PbR_U32(&r);+ if (!r.ok || type > 1 || port > 65535) return FALSE;+ ret = g_api.EditProxyConfig(id, (PBProxyType)type, ip, (unsigned short)port, nUser ? NULL : user, nPass ? NULL : pass, sd != 0);+ break; }+ case PBOP_DELETE_PROXY: { UINT32 id = PbR_U32(&r); if (!r.ok) return FALSE; ret = g_api.DeleteProxyConfig(id); break; }++ case PBOP_TEST_PROXY_START: {+ UINT32 id = PbR_U32(&r); PbR_Str(&r, host, sizeof(host), NULL); UINT32 port = PbR_U32(&r);+ if (!r.ok || port > 65535) return FALSE;+ if (InterlockedCompareExchange(&g_test_busy, 1, 0) != 0) { ret = 0; break; }+ TestJob *j = (TestJob *)calloc(1, sizeof(*j));+ if (!j) { InterlockedExchange(&g_test_busy, 0); ret = 0; break; }+ j->id = id; j->port = (unsigned short)port; strncpy_s(j->host, sizeof(j->host), host, _TRUNCATE);+ HANDLE t = CreateThread(NULL, 0, TestThread, j, 0, NULL);+ if (!t) { free(j); InterlockedExchange(&g_test_busy, 0); ret = 0; break; }+ CloseHandle(t); ret = 1;+ break; }++ case PBOP_ADD_RULE: case PBOP_EDIT_RULE: {+ UINT32 id = (op == PBOP_EDIT_RULE) ? PbR_U32(&r) : 0;+ PbR_Str(&r, proc, sizeof(proc), &nProc); PbR_Str(&r, hosts, sizeof(hosts), &nHosts);+ PbR_Str(&r, ports, sizeof(ports), &nPorts); PbR_Str(&r, domains, sizeof(domains), &nDomains);+ UINT32 proto = PbR_U32(&r), action = PbR_U32(&r), cfg = PbR_U32(&r);+ if (!r.ok || proto > 2 || action > 2) return FALSE;+ if (op == PBOP_ADD_RULE)+ ret = g_api.AddRule(nProc ? NULL : proc, nHosts ? NULL : hosts, nPorts ? NULL : ports, nDomains ? NULL : domains,+ (PBRuleProtocol)proto, (PBRuleAction)action, cfg);+ else+ ret = g_api.EditRule(id, nProc ? NULL : proc, nHosts ? NULL : hosts, nPorts ? NULL : ports, nDomains ? NULL : domains,+ (PBRuleProtocol)proto, (PBRuleAction)action, cfg);+ break; }+ case PBOP_ENABLE_RULE: { UINT32 id = PbR_U32(&r); if (!r.ok) return FALSE; ret = g_api.EnableRule(id); break; }+ case PBOP_DISABLE_RULE: { UINT32 id = PbR_U32(&r); if (!r.ok) return FALSE; ret = g_api.DisableRule(id); break; }+ case PBOP_DELETE_RULE: { UINT32 id = PbR_U32(&r); if (!r.ok) return FALSE; ret = g_api.DeleteRule(id); break; }+ case PBOP_MOVE_RULE: { UINT32 id = PbR_U32(&r), pos = PbR_U32(&r); if (!r.ok) return FALSE; ret = g_api.MoveRuleToPosition(id, pos); break; }+ case PBOP_GET_RULE_POS: { UINT32 id = PbR_U32(&r); if (!r.ok) return FALSE; ret = g_api.GetRulePosition(id); break; }++ case PBOP_SET_LOCALHOST: { UINT32 v = PbR_U32(&r); if (!r.ok) return FALSE; g_api.SetLocalhostViaProxy(v != 0); break; }+ case PBOP_SET_TRAFFIC_LOG: { UINT32 v = PbR_U32(&r); if (!r.ok) return FALSE; g_api.SetTrafficLoggingEnabled(v != 0); break; }+ case PBOP_CLEAR_CONN_LOGS: g_api.ClearConnectionLogs(); break;+ case PBOP_START: ret = g_api.Start(); break;+ case PBOP_STOP: ret = g_api.Stop(); break;+ default: return FALSE;+ }+ PbW_U32(resp, ret);+ return TRUE;+}++static void ClosePipes(void)+{+ InterlockedExchange(&g_evt_live, 0);+ EnterCriticalSection(&g_evt_lock);+ if (g_evt != INVALID_HANDLE_VALUE) { DisconnectNamedPipe(g_evt); CloseHandle(g_evt); g_evt = INVALID_HANDLE_VALUE; }+ LeaveCriticalSection(&g_evt_lock);+ if (g_ctl != INVALID_HANDLE_VALUE) { DisconnectNamedPipe(g_ctl); CloseHandle(g_ctl); g_ctl = INVALID_HANDLE_VALUE; }+}++static HANDLE MakePipe(const wchar_t *name, BOOL first, DWORD openMode)+{+ SECURITY_ATTRIBUTES sa; ZeroMemory(&sa, sizeof(sa)); sa.nLength = sizeof(sa);+ if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(PB_PIPE_SDDL, SDDL_REVISION_1, &sa.lpSecurityDescriptor, NULL))+ return INVALID_HANDLE_VALUE;+ HANDLE h = CreateNamedPipeW(name,+ openMode | (first ? FILE_FLAG_FIRST_PIPE_INSTANCE : 0),+ PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,+ 1, // single instance: one client at a time+ PB_MSG_MAX, PB_MSG_MAX, 0, &sa);+ LocalFree(sa.lpSecurityDescriptor);+ return h;+}++// ConnectNamedPipe on a helper thread so a client that opens the control pipe but never+// opens the event pipe cannot wedge the service.+typedef struct { HANDLE pipe; BOOL ok; } ConnJob;+static DWORD WINAPI ConnThread(LPVOID a)+{+ ConnJob *c = (ConnJob *)a;+ c->ok = ConnectNamedPipe(c->pipe, NULL) || GetLastError() == ERROR_PIPE_CONNECTED;+ return 0;+}++static void ServeClient(void)+{+ BYTE req[PB_MSG_MAX], rsp[PB_MSG_MAX];++ // fresh engine for every client+ if (!PB_LoadDirect(&g_api)) return;+ g_api.SetLogCallback(OnLog);+ g_api.SetConnectionCallback(OnConn);+ InterlockedExchange(&g_evt_live, 1);++ for (;;)+ {+ DWORD n = 0;+ if (!ReadFile(g_ctl, req, sizeof(req), &n, NULL) || g_stop) break;+ PbW w; PbW_Init(&w, rsp, sizeof(rsp));+ if (!Dispatch(req, n, &w) || !w.ok) break; // malformed -> drop the client+ DWORD wr = 0;+ if (!WriteFile(g_ctl, rsp, w.len, &wr, NULL)) break;+ }++ // client gone: stop capture and unload the engine (DllMain detach frees rules/configs)+ InterlockedExchange(&g_evt_live, 0);+ if (g_api.Stop) g_api.Stop();+ if (g_api.SetLogCallback) g_api.SetLogCallback(NULL);+ if (g_api.SetConnectionCallback) g_api.SetConnectionCallback(NULL);+ PB_UnloadDirect(&g_api);+}++static DWORD WINAPI WorkerMain(LPVOID arg)+{+ (void)arg;+ BOOL first = TRUE;+ while (!g_stop)+ {+ g_ctl = MakePipe(PB_PIPE_CTL, first, PIPE_ACCESS_DUPLEX);+ g_evt = MakePipe(PB_PIPE_EVT, first, PIPE_ACCESS_OUTBOUND);+ if (g_ctl == INVALID_HANDLE_VALUE || g_evt == INVALID_HANDLE_VALUE) { ClosePipes(); Sleep(1000); continue; }+ first = FALSE;++ if (!ConnectNamedPipe(g_ctl, NULL) && GetLastError() != ERROR_PIPE_CONNECTED) { ClosePipes(); continue; }+ if (g_stop) { ClosePipes(); break; }++ ConnJob cj = { g_evt, FALSE };+ HANDLE ct = CreateThread(NULL, 0, ConnThread, &cj, 0, NULL);+ if (ct)+ {+ if (WaitForSingleObject(ct, 5000) == WAIT_TIMEOUT)+ {+ CancelSynchronousIo(ct);+ WaitForSingleObject(ct, INFINITE);+ }+ CloseHandle(ct);+ }+ if (cj.ok && !g_stop) ServeClient();+ ClosePipes();+ }+ return 0;+}++static void WINAPI SvcCtrl(DWORD code)+{+ if (code == SERVICE_CONTROL_STOP || code == SERVICE_CONTROL_SHUTDOWN)+ {+ SetState(SERVICE_STOP_PENDING, 0);+ InterlockedExchange(&g_stop, 1);+ if (g_worker) CancelSynchronousIo(g_worker); // unblock ReadFile / ConnectNamedPipe+ // wake a ConnectNamedPipe that has not started yet+ HANDLE h = CreateFileW(PB_PIPE_CTL, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);+ if (h != INVALID_HANDLE_VALUE) CloseHandle(h);+ }+}++static void WINAPI SvcMain(DWORD argc, LPWSTR *argv)+{+ (void)argc; (void)argv;+ g_ssh = RegisterServiceCtrlHandlerW(PB_SERVICE_NAME, SvcCtrl);+ if (!g_ssh) return;+ InitializeCriticalSection(&g_evt_lock);+ SetState(SERVICE_START_PENDING, 0);++ g_worker = CreateThread(NULL, 0, WorkerMain, NULL, 0, NULL);+ if (!g_worker) { SetState(SERVICE_STOPPED, GetLastError()); return; }+ SetState(SERVICE_RUNNING, 0);++ WaitForSingleObject(g_worker, INFINITE);+ CloseHandle(g_worker); g_worker = NULL;+ DeleteCriticalSection(&g_evt_lock);+ SetState(SERVICE_STOPPED, 0);+}++int wmain(void)+{+ // The engine DLL is loaded from our own directory by absolute path (PB_LoadDirect), and the+ // service must never search the CWD / PATH for it.+ SetDllDirectoryW(L"");+ SERVICE_TABLE_ENTRYW table[] = { { (LPWSTR)PB_SERVICE_NAME, SvcMain }, { NULL, NULL } };+ if (!StartServiceCtrlDispatcherW(table))+ {+ fwprintf(stderr, L"ProxyBridgeSvc is a Windows service; it is started by the Service Control Manager.\n");+ return 1;+ }+ return 0;+}