Skip to content

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

test(windows): add the Windows test suite and run it in the build workflow

AnoF-Cyber9a61cc138ecd
diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml
index d733172..46f367a 100644
--- a/.github/workflows/build-windows.yml
+++ b/.github/workflows/build-windows.yml
@@ -2,9 +2,9 @@ name: Build Windows
on:
push:
- branches: [ main, dev ]
+ branches: [ master, dev ]
pull_request:
- branches: [ main, dev ]
+ branches: [ master, dev ]
workflow_dispatch:
permissions:
@@ -66,6 +66,31 @@ jobs:
}
shell: pwsh
+ # Tests build from the real sources and never load the WinDivert driver or touch the network, so they run on
+ # a hosted runner. They run before the build so a failing change is reported first. See Windows\tests\.
+ - name: Run tests (engine, profiles, parsers, service, proxy protocols, CLI, static checks)
+ run: |
+ cd Windows
+ .\tests\run_tests.ps1 -SkipUi
+ shell: pwsh
+
+ # The GUI tests create real windows (the Proxy Rules window and the main window) and need a desktop session;
+ # they are a separate step so a runner without one is easy to tell apart from a real failure.
+ - name: Run GUI tests (Proxy Rules window, main window, dialogs)
+ run: |
+ cd Windows
+ .\tests\run_tests.ps1 -Only test_rules_ui,test_main_ui,test_dialogs_ui
+ shell: pwsh
+
+ - name: Upload test output on failure
+ if: failure()
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
+ with:
+ name: ProxyBridge-Test-Output-${{ github.sha }}
+ path: Windows/tests/out/*.txt
+ if-no-files-found: ignore
+ retention-days: 7
+
- name: Build project
run: |
cd Windows
diff --git a/.gitignore b/.gitignore
index c8d2130..9a7f357 100644
--- a/.gitignore
+++ b/.gitignore
@@ -130,3 +130,4 @@ Windows/*.obj
Windows/**/*.obj
Windows/gui/*.res
Windows/**/*.res
+Windows/tests/out/
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6a7fd98..5b35784 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -175,6 +175,23 @@ All compiled files are placed in `Windows/output/` directory:
- `WinDivert.dll`, `WinDivert64.sys` - WinDivert files
- `ProxyBridge-Setup-4.2.0.exe` - Installer (if NSIS installed)
+**Running the tests:**
+```powershell
+cd ProxyBridge/Windows
+.\tests\run_tests.ps1 # build and run everything (exit code 0 = all passed)
+.\tests\run_tests.ps1 -SkipUi # without the two GUI tests (no desktop session)
+.\tests\run_tests.ps1 -Only test_engine,test_cli
+```
+The tests are small console programs in `Windows/tests/` compiled from the real source files; they never load the
+WinDivert driver or reach the internet (only the WinDivert headers and import library are needed; a few tests use
+loopback sockets or private named pipes). They cover rule matching, profiles and the JSON parser, the DNS reply parser,
+the SOCKS5/HTTP handshakes against a fake proxy, the service's request handler and pipe permissions, the connection
+table, the CLI helpers, and the GUI windows (created for real, with a stubbed engine). A set of static checks also
+verifies that the version number agrees everywhere and that the installer script keeps its safety properties. The `Build Windows` workflow runs the same script on every push and pull
+request, before the build. **Please add or update a test when you change behavior**, for example a new rule-matching
+case in `test_engine.c`, a profile-format change in `test_profile.c`, or a new window feature in `test_rules_ui.c` /
+`test_main_ui.c`.
+
**Project Structure:**
- `Windows/src/` - C library core (ProxyBridge.c, ProxyBridge.h)
- `ProxyBridge.c` - Main packet interception logic
@@ -185,6 +202,7 @@ All compiled files are placed in `Windows/output/` directory:
- `main.c` - CLI application for headless operation
- `Windows/installer/` - NSIS installer script
- `ProxyBridge.nsi` - Installer configuration
+- `Windows/tests/` - Test programs and `run_tests.ps1` (run by the Windows workflow)
- `Windows/compile.ps1` - Build script
- `Windows/output/` - Compiled binaries (created by compile.ps1)
diff --git a/Windows/tests/pbtest.h b/Windows/tests/pbtest.h
new file mode 100644
index 0000000..d080c0f
--- /dev/null
+++ b/Windows/tests/pbtest.h
@@ -0,0 +1,43 @@
+// pbtest.h - minimal check macros shared by the Windows test programs (no framework needed).
+//
+// Every test program is a stand-alone console exe: it prints one line per failed check, a summary line, and
+// returns 0 when every check passed (1 otherwise). tests\run_tests.ps1 builds and runs all of them.
+#ifndef PB_TEST_H
+#define PB_TEST_H
+
+#include <windows.h>
+#include <stdio.h>
+
+static int g_checks = 0, g_fails = 0;
+
+// Output is unbuffered (set before main runs), so a crash can never swallow the lines printed so far.
+static void pb_unbuffer(void) { setvbuf(stdout, NULL, _IONBF, 0); }
+#pragma section(".CRT$XCU", read)
+__declspec(allocate(".CRT$XCU")) static void (*pb_unbuffer_init)(void) = pb_unbuffer;
+
+#define CHECK(c) do { g_checks++; if (!(c)) { g_fails++; printf(" FAIL %s:%d %s\n", __FILE__, __LINE__, #c); } } while (0)
+
+// Prints the summary line and returns the process exit code.
+static int pbtest_done(const char* name)
+{
+ if (g_fails) printf("%s: FAILED (%d of %d checks failed)\n", name, g_fails, g_checks);
+ else printf("%s: OK (%d checks)\n", name, g_checks);
+ return g_fails ? 1 : 0;
+}
+
+// Guard-page buffer for parser tests: the copy of `data` ends exactly where unreadable memory begins, so reading
+// even one byte past the end crashes the test (a crash is reported as a failure by run_tests.ps1).
+// Free with pb_guard_release(base).
+static BYTE* pb_guarded(const void* data, size_t len, void** base)
+{
+ SYSTEM_INFO si; GetSystemInfo(&si); size_t pg = si.dwPageSize;
+ size_t body = ((len ? len : 1) + pg - 1) / pg * pg;
+ BYTE* mem = (BYTE*)VirtualAlloc(NULL, body + pg, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
+ DWORD old; VirtualProtect(mem + body, pg, PAGE_NOACCESS, &old);
+ BYTE* p = mem + body - len;
+ if (len) memcpy(p, data, len);
+ *base = mem; return p;
+}
+static void pb_guard_release(void* base) { VirtualFree(base, 0, MEM_RELEASE); }
+
+#endif
diff --git a/Windows/tests/run_tests.ps1 b/Windows/tests/run_tests.ps1
new file mode 100644
index 0000000..7e65d57
--- /dev/null
+++ b/Windows/tests/run_tests.ps1
@@ -0,0 +1,207 @@
+<#
+.SYNOPSIS
+ Builds and runs the ProxyBridge Windows tests. Exit code 0 = everything passed.
+
+.DESCRIPTION
+ Each test is a small console program (tests\test_*.c) compiled with MSVC from the real source files, so the
+ tests exercise the shipping code. Nothing loads the WinDivert driver and nothing talks to the internet; some
+ tests use loopback sockets or private named pipes, the GUI tests create real windows (they need a desktop
+ session) and replace the engine API with recording stubs. A few static checks (PowerShell) guard release hygiene.
+
+ test_hosts Target Hosts list helpers (clean-up, IP/domain split and merge)
+ test_profile profile files: old-format migration, save format, long lists, hostile input
+ test_json the JSON parser/writer: escapes, malformed input, nesting limit, round trips
+ test_proto the app <-> service wire protocol reader/writer
+ test_service the service's request handler and the named-pipe permission list
+ test_engine rule matching: IP or domain, IPv4/IPv6, ports, localhost flag, main switch
+ test_rules_match individual matchers (IP, port, process, domain patterns) and rule ordering/API
+ test_conntrack connection table (#209) and the Connections-log rules (Log Every Connection)
+ test_dns the DNS reply parser behind domain rules (guard-page hardened)
+ test_proxy_protocols SOCKS5 and HTTP CONNECT handshakes against a scripted fake proxy
+ test_cli the command-line client's host-list helpers
+ test_gui_misc updater version logic, EN/ZH string table, log filters, log store, conversions
+ test_rules_ui the Proxy Rules window (search, row mapping, keyboard) [needs a desktop]
+ test_main_ui the main window (main switch menu, Log Every Connection) [needs a desktop]
+ test_dialogs_ui rule editor, servers list, filters list, About box [needs a desktop]
+ static_checks version numbers agree everywhere, installer script safety, workflow wiring
+
+.PARAMETER WinDivertPath WinDivert SDK folder (headers + import library only; the driver is never loaded).
+.PARAMETER SkipUi Do not run the GUI tests (for a session without a desktop).
+.PARAMETER Only Run only the named tests, for example: -Only test_engine,static_checks
+#>
+param(
+ [string]$WinDivertPath = "C:\WinDivert-2.2.2-A",
+ [switch]$SkipUi,
+ [string[]]$Only
+)
+
+$ErrorActionPreference = 'Stop'
+$WinRoot = Split-Path -Parent $PSScriptRoot # ...\Windows
+$RepoRoot = Split-Path -Parent $WinRoot
+$Out = Join-Path $PSScriptRoot 'out'
+$Arch = 'x64'
+
+if (-not (Test-Path (Join-Path $WinDivertPath 'include\windivert.h'))) {
+ Write-Host "ERROR: WinDivert SDK not found at $WinDivertPath (pass -WinDivertPath)" -ForegroundColor Red
+ exit 2
+}
+
+# --- locate the MSVC environment the same way compile.ps1 does -----------------------------------------------------
+$vcvars = $null
+$vsWhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
+if (Test-Path $vsWhere) {
+ $vsPath = & $vsWhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
+ if ($vsPath) {
+ $cand = Join-Path $vsPath 'VC\Auxiliary\Build\vcvarsall.bat'
+ if (Test-Path $cand) { $vcvars = $cand }
+ }
+}
+if (-not $vcvars -and -not (Get-Command cl.exe -ErrorAction SilentlyContinue)) {
+ Write-Host "ERROR: Visual Studio C++ tools not found (run from a Developer prompt or install the C++ workload)" -ForegroundColor Red
+ exit 2
+}
+
+if (Test-Path $Out) { [IO.Directory]::Delete($Out, $true) }
+New-Item -ItemType Directory -Path $Out | Out-Null
+
+$core = 'ProxyBridge.c','pb_util.c','pb_process.c','pb_rules.c','pb_proxy.c','pb_dns.c','pb_socks5.c','pb_http.c','pb_conntrack.c','pb_relay.c','pb_sockmap.c' | ForEach-Object { "src\$_" }
+$warn = '/W3 /wd4100 /wd4189 /wd4267 /wd4244 /wd4996'
+$wdInc = "/I`"$WinDivertPath\include`""
+$wdLib = "/LIBPATH:`"$WinDivertPath\$Arch`""
+
+$clPlain = "/D_CRT_SECURE_NO_WARNINGS"
+$clUni = "/utf-8 /DUNICODE /D_UNICODE /D_CRT_SECURE_NO_WARNINGS"
+$clCore = "/Isrc $wdInc /DPROXYBRIDGE_EXPORTS /D_CRT_SECURE_NO_WARNINGS /D_WINSOCK_DEPRECATED_NO_WARNINGS"
+$lnCore = "$wdLib WinDivert.lib ws2_32.lib iphlpapi.lib advapi32.lib"
+$lnProf = 'user32.lib advapi32.lib shell32.lib'
+$lnGui = '/SUBSYSTEM:CONSOLE /ENTRY:wWinMainCRTStartup user32.lib gdi32.lib comctl32.lib shell32.lib comdlg32.lib winhttp.lib advapi32.lib dwmapi.lib uxtheme.lib'
+$prof = 'gui\profile\profile.c'
+$res = "$Out\app.res"
+
+# n = name, src = sources, cl = compiler flags, link = linker arguments, ui = needs a desktop session
+$tests = @(
+ @{ n='test_hosts'; src=@('tests\test_hosts.c', $prof); cl=$clUni; link=$lnProf; ui=$false },
+ @{ n='test_profile'; src=@('tests\test_profile.c', $prof); cl=$clUni; link=$lnProf; ui=$false },
+ @{ n='test_json'; src=@('tests\test_json.c'); cl=$clPlain; link=''; ui=$false },
+ @{ n='test_proto'; src=@('tests\test_proto.c'); cl=$clPlain; link=''; ui=$false },
+ @{ n='test_service'; src=@('tests\test_service.c'); cl="$clPlain /DUNICODE /D_UNICODE"; link='user32.lib advapi32.lib'; ui=$false },
+ @{ n='test_engine'; src=@('tests\test_engine.c') + $core; cl=$clCore; link=$lnCore; ui=$false },
+ @{ n='test_rules_match'; src=@('tests\test_rules_match.c') + $core; cl=$clCore; link=$lnCore; ui=$false },
+ @{ n='test_conntrack'; src=@('tests\test_conntrack.c') + $core; cl=$clCore; link=$lnCore; ui=$false },
+ @{ n='test_dns'; src=@('tests\test_dns.c') + $core; cl=$clCore; link=$lnCore; ui=$false },
+ @{ n='test_proxy_protocols'; src=@('tests\test_proxy_protocols.c') + $core; cl=$clCore; link=$lnCore; ui=$false },
+ @{ n='test_cli'; src=@('tests\test_cli.c'); cl="$clPlain /D_WINSOCK_DEPRECATED_NO_WARNINGS /D_WIN32_WINNT=0x0601"; link='winhttp.lib shell32.lib advapi32.lib'; ui=$false },
+ @{ n='test_gui_misc'; src=@('tests\test_gui_misc.c', $prof); cl=$clUni; link=$lnGui; ui=$false },
+ @{ n='test_rules_ui'; src=@('tests\test_rules_ui.c', $prof, $res); cl=$clUni; link=$lnGui; ui=$true },
+ @{ n='test_main_ui'; src=@('tests\test_main_ui.c', $prof, $res); cl=$clUni; link=$lnGui; ui=$true },
+ @{ n='test_dialogs_ui'; src=@('tests\test_dialogs_ui.c', $prof, $res); cl=$clUni; link=$lnGui; ui=$true }
+)
+$runStatic = $true
+if ($Only) { $tests = $tests | Where-Object { $Only -contains $_.n }; $runStatic = ($Only -contains 'static_checks') }
+if ($SkipUi) { $tests = $tests | Where-Object { -not $_.ui } }
+
+function Invoke-Msvc([string]$name, [string]$body) {
+ $bat = Join-Path $Out "$name.bat"
+ $lines = @('@echo off')
+ if ($vcvars) { $lines += "call `"$vcvars`" $Arch >nul" }
+ $lines += "cd /d `"$WinRoot`""
+ $lines += $body
+ Set-Content -Path $bat -Value $lines -Encoding ASCII
+ $log = & cmd /c "`"$bat`" 2>&1"
+ return @{ code = $LASTEXITCODE; log = $log }
+}
+
+# resources for the GUI tests (menus, dialogs, icon, manifest) come from the real app.rc
+if ($tests | Where-Object { $_.src -contains $res }) {
+ $r = Invoke-Msvc 'rc' "cd /d `"$WinRoot\gui\res`" && rc /nologo /fo `"$Out\app.res`" app.rc"
+ if ($r.code -ne 0) { Write-Host "Resource compile failed:`n$($r.log -join "`n")" -ForegroundColor Red; exit 2 }
+}
+
+$results = @()
+foreach ($t in $tests) {
+ $name = $t.n
+ Write-Host "`n=== $name" -ForegroundColor Cyan
+ $objDir = Join-Path $Out $name; New-Item -ItemType Directory -Path $objDir | Out-Null
+ $srcs = ($t.src | ForEach-Object { if ($_ -like '*:*') { "`"$_`"" } else { $_ } }) -join ' '
+ $cmd = "cl /nologo $warn $($t.cl) /Fo:`"$objDir\\`" $srcs /Fe:`"$Out\$name.exe`" /link $($t.link)"
+ $b = Invoke-Msvc "build_$name" $cmd
+ if ($b.code -ne 0 -or -not (Test-Path "$Out\$name.exe")) {
+ Write-Host "BUILD FAILED" -ForegroundColor Red
+ $b.log | Where-Object { $_ -match 'error|fatal|LNK' } | Select-Object -First 12 | ForEach-Object { Write-Host " $_" }
+ $results += [pscustomobject]@{ Test = $name; Result = 'BUILD FAILED' }
+ continue
+ }
+ $outTxt = Join-Path $Out "$name.out.txt"
+ $p = Start-Process -FilePath "$Out\$name.exe" -NoNewWindow -PassThru -RedirectStandardOutput $outTxt
+ if (-not $p.WaitForExit(240000)) { $p.Kill(); Write-Host "TIMEOUT (240 s)" -ForegroundColor Red; $results += [pscustomobject]@{ Test = $name; Result = 'TIMEOUT' }; continue }
+ Get-Content $outTxt | ForEach-Object { Write-Host " $_" }
+ $res1 = if ($p.ExitCode -eq 0) { 'PASS' } else { "FAIL (exit $($p.ExitCode))" }
+ $results += [pscustomobject]@{ Test = $name; Result = $res1 }
+}
+
+# ------------------------------------------------------------------------------------------------------------------
+# static checks: things that must stay consistent but that no compiler checks
+# ------------------------------------------------------------------------------------------------------------------
+if ($runStatic) {
+ Write-Host "`n=== static_checks" -ForegroundColor Cyan
+ $fails = New-Object System.Collections.Generic.List[string]; $n = 0
+ function Check([bool]$ok, [string]$what) { $script:n++; if (-not $ok) { $script:fails.Add($what); Write-Host " FAIL $what" } }
+ function Read-Text([string]$rel) { [IO.File]::ReadAllText((Join-Path $WinRoot $rel)) }
+
+ # 1. the version number is the same everywhere it is written
+ $resH = Read-Text 'gui\res\resource.h'
+ $maj = [regex]::Match($resH, 'PB_VER_MAJOR\s+(\d+)').Groups[1].Value; $min = [regex]::Match($resH, 'PB_VER_MINOR\s+(\d+)').Groups[1].Value
+ $pat = [regex]::Match($resH, 'PB_VER_PATCH\s+(\d+)').Groups[1].Value
+ $ver = "$maj.$min.$pat"
+ Check ($maj -ne '' -and $min -ne '' -and $pat -ne '') 'resource.h has PB_VER_MAJOR/MINOR/PATCH'
+ Check ([regex]::Match($resH, 'PB_VER_STR\s+"([^"]+)"').Groups[1].Value -eq $ver) "resource.h PB_VER_STR is $ver"
+ Check ([regex]::Match($resH, 'PB_VER_STRW\s+L"([^"]+)"').Groups[1].Value -eq $ver) "resource.h PB_VER_STRW is $ver"
+ $nsi = Read-Text 'installer\ProxyBridge.nsi'
+ Check ([regex]::Match($nsi, '!define PRODUCT_VERSION "([^"]+)"').Groups[1].Value -eq $ver) "installer PRODUCT_VERSION is $ver"
+ Check ([regex]::Match($nsi, 'VIProductVersion "([^"]+)"').Groups[1].Value -eq "$ver.0") "installer VIProductVersion is $ver.0"
+ Check ([regex]::Match((Read-Text 'cli\main.c'), '#define VERSION "([^"]+)"').Groups[1].Value -eq $ver) "cli VERSION is $ver"
+ Check ([regex]::Match((Read-Text 'src\pb_internal.h'), '#define VERSION "([^"]+)"').Groups[1].Value -eq $ver) "engine VERSION is $ver"
+ Check ([regex]::Match((Read-Text 'gui\res\app.manifest'), 'assemblyIdentity version="([^"]+)"').Groups[1].Value -eq "$ver.0") "app.manifest version is $ver.0"
+ Check ((Read-Text '..\CONTRIBUTING.md').Contains("ProxyBridge-Setup-$ver.exe")) "CONTRIBUTING.md names ProxyBridge-Setup-$ver.exe"
+
+ # 2. the installer: elevated, locked-down install folder, service ACL, normal-user launch, clean uninstall
+ Check ($nsi -match 'RequestExecutionLevel admin') 'installer runs elevated'
+ $ic = [regex]::Match($nsi, 'icacls "\$INSTDIR"[^\r\n]*').Value
+ Check ($ic -match '/inheritance:r') 'install folder: inheritance removed'
+ Check ($ic -match '\*S-1-5-18:\(OI\)\(CI\)F' -and $ic -match '\*S-1-5-32-544:\(OI\)\(CI\)F') 'install folder: SYSTEM and Administrators full control'
+ Check ($ic -match '\*S-1-5-32-545:\(OI\)\(CI\)RX' -and $ic -notmatch '\*S-1-5-32-545:[^ ]*(M|F|W)\b') 'install folder: Users read/execute only'
+ Check ($nsi -match '--setup-users') 'installer creates the ProxyBridge Users group (--setup-users)'
+ Check ($nsi -match 'MUI_FINISHPAGE_RUN_FUNCTION\s+LaunchAppAsUser' -and $nsi -match 'explorer\.exe') 'finish page launches the app through Explorer (normal user)'
+ Check ($nsi -notmatch 'MUI_FINISHPAGE_RUN\s+"') 'finish page does not start the exe directly from the elevated installer'
+ $sd = [regex]::Match($nsi, "sc sdset ProxyBridgeSvc `"([^`"]+)`"").Groups[1].Value
+ Check ($sd -ne '') 'service permission list (sc sdset) is set'
+ Check ($sd -notmatch ';;;(WD|AU|BU|AN|NU)\)') 'service permissions never grant Everyone / Authenticated / Users / Anonymous'
+ $iu = [regex]::Match($sd, '\(A;;([A-Z]+);;;IU\)').Groups[1].Value
+ if ($iu) { $rights = for ($i = 0; $i -lt $iu.Length; $i += 2) { $iu.Substring($i, 2) }; Check (-not ($rights | Where-Object { 'WP','DT','WD','WO','DC','SD' -contains $_ })) 'interactive users may start the service but not stop/reconfigure/delete it' }
+ Check ($nsi -match "sc delete ProxyBridgeSvc" -and $nsi -match 'localgroup "ProxyBridge Users" /delete' -and $nsi -match 'AllowedSids') 'uninstaller removes the service, the group and the saved SIDs'
+ Check ($nsi -match 'netsh advfirewall firewall delete rule') 'uninstaller/installer clean up firewall rules'
+
+ # 3. the pipe names and protocol version agree between the app and the service (one header, but make sure it is sane)
+ $proto = Read-Text 'src\service\pb_proto.h'
+ Check ([int][regex]::Match($proto, 'PB_PROTO_VERSION\s+(\d+)').Groups[1].Value -ge 4) 'service protocol version is at least 4'
+
+ # 4. wiring: every test source is run by this script, and the workflow runs this script
+ $self = [IO.File]::ReadAllText($PSCommandPath)
+ foreach ($f in Get-ChildItem $PSScriptRoot -Filter 'test_*.c') { Check ($self.Contains("n='$($f.BaseName)'")) "tests\$($f.Name) is registered in run_tests.ps1" }
+ $wf = [IO.File]::ReadAllText((Join-Path $RepoRoot '.github\workflows\build-windows.yml'))
+ Check ($wf -match 'tests\\run_tests\.ps1') 'build-windows.yml runs tests\run_tests.ps1'
+
+ $ok = ($fails.Count -eq 0)
+ Write-Host (" static_checks: " + $(if ($ok) { "OK ($n checks)" } else { "FAILED ($($fails.Count) of $n checks failed)" }))
+ $results += [pscustomobject]@{ Test = 'static_checks'; Result = $(if ($ok) { 'PASS' } else { 'FAIL' }) }
+}
+
+# the tests use private %APPDATA% folders under %TEMP%; remove what they left
+Get-ChildItem ([IO.Path]::GetTempPath()) -Directory -Filter 'pbtest_*' -ErrorAction SilentlyContinue | ForEach-Object { try { [IO.Directory]::Delete($_.FullName, $true) } catch {} }
+
+Write-Host "`n================ summary ================" -ForegroundColor Cyan
+$results | Format-Table -AutoSize | Out-String | Write-Host
+$bad = @($results | Where-Object { $_.Result -ne 'PASS' })
+if ($bad.Count -gt 0 -or $results.Count -eq 0) { Write-Host "$($bad.Count) of $($results.Count) test program(s) did not pass" -ForegroundColor Red; exit 1 }
+Write-Host "All $($results.Count) test programs passed" -ForegroundColor Green
+exit 0
diff --git a/Windows/tests/test_cli.c b/Windows/tests/test_cli.c
new file mode 100644
index 0000000..276d019
--- /dev/null
+++ b/Windows/tests/test_cli.c
@@ -0,0 +1,50 @@
+// test_cli.c - the helpers of the command-line client (cli\main.c): it applies the same host-list cleanup and
+// IP/domain sorting as the GUI to profile files, so a profile written by hand or by another platform still works.
+// cli\main.c is included as source so its static functions can be called directly.
+#define main pb_cli_main
+#include "../cli/main.c"
+#undef main
+#include "pbtest.h"
+
+static void norm(const char* in, const char* want)
+{
+ char buf[256]; strcpy_s(buf, sizeof buf, in); normalize_list(buf);
+ if (strcmp(buf, want)) { g_fails++; printf(" FAIL normalize [%s] -> [%s], wanted [%s]\n", in, buf, want); }
+ g_checks++;
+}
+
+static void sort(const char* hosts0, const char* doms0, const char* wantHosts, const char* wantDoms)
+{
+ char h[512], d[8192]; strcpy_s(h, sizeof h, hosts0); strcpy_s(d, sizeof d, doms0);
+ sort_hosts(h, sizeof h, d, sizeof d);
+ if (strcmp(h, wantHosts) || strcmp(d, wantDoms))
+ { g_fails++; printf(" FAIL sort [%s]+[%s] -> [%s] [%s], wanted [%s] [%s]\n", hosts0, doms0, h, d, wantHosts, wantDoms); }
+ g_checks++;
+}
+
+int main(void)
+{
+ norm("google.com;\r\n *.google.com ;\n,github.com;", "google.com;*.google.com;github.com");
+ norm("", ""); norm(";;", ""); norm("a\nb", "ab"); norm("*", "*");
+
+ CHECK(is_ip_token("10.0.0.0/8", 10) && is_ip_token("192.168.*.*", 11) && is_ip_token("1.2.3.4-1.2.3.9", 15));
+ CHECK(is_ip_token("::1", 3) && is_ip_token("fe80::1-fe80::ff", 16) && is_ip_token("2001:db8::/32", 13));
+ CHECK(!is_ip_token("github.com", 10) && !is_ip_token("*.github.com", 12) && !is_ip_token("abc.def", 7) && !is_ip_token("123.com", 7));
+
+ sort("10.*.*.*", "github.com;*.google.com", "10.*.*.*", "github.com;*.google.com");
+ sort("example.org;192.168.*.*", "*", "192.168.*.*", "example.org"); /* a domain typed with the IPs moves to the domains */
+ sort("*", "*", "*", "*"); sort("", "", "*", "*");
+ sort("10.0.0.1", "*", "10.0.0.1", "*"); /* "*" alone on a side means no restriction from it */
+ sort("*", "github.com", "*", "github.com");
+ sort("a.com;*", "b.com", "*", "*"); /* "*" next to other entries = any host */
+ sort("1.2.3.4-1.2.3.9;fe80::1-fe80::ff;::1", "x.org", "1.2.3.4-1.2.3.9;fe80::1-fe80::ff;::1", "x.org");
+ { /* addresses hiding in a huge domain list must not overflow the 512-byte hosts buffer */
+ char h[512] = "*", d[8192]; size_t k = 0;
+ for (int i = 0; i < 600; i++) k += sprintf_s(d + k, sizeof d - k, "10.%d.%d.1;", i % 250, i / 250);
+ strcpy_s(d + k, sizeof d - k, "x.org");
+ sort_hosts(h, sizeof h, d, sizeof d);
+ CHECK(strlen(h) < sizeof h && h[0] != 0 && h[strlen(h) - 1] != ';');
+ }
+
+ return pbtest_done("test_cli");
+}
diff --git a/Windows/tests/test_conntrack.c b/Windows/tests/test_conntrack.c
new file mode 100644
index 0000000..d117add
--- /dev/null
+++ b/Windows/tests/test_conntrack.c
@@ -0,0 +1,82 @@
+// test_conntrack.c - the connection table (src\pb_conntrack.c) and the Connections-log rules.
+// - issue #209: a TCP flow and a UDP flow (or IPv4 and IPv6) on the same local port are separate entries
+// - "Log every connection": default de-duplication, every TCP connection, one row per UDP flow
+// Linked from the real core sources; no driver is opened.
+#include "pb_internal.h"
+#include "pbtest.h"
+
+static UINT32 ip4(const char* s) { struct in_addr a; inet_pton(AF_INET, s, &a); return a.S_un.S_addr; }
+
+int main(void)
+{
+ UINT32 d1 = ip4("193.124.56.249"), d2 = ip4("8.8.8.8"), lanA = ip4("192.168.0.136"), lanB = ip4("10.8.0.5");
+ UINT32 dip; UINT16 dport;
+
+ /* 1. the reported case: a UDP flow on local port 55123 exists; a fresh TCP SYN uses the same numeric port */
+ add_connection(55123, TRUE, lanA, d1, 41001, 0); /* UDP seed */
+ CHECK(is_connection_tracked(55123, TRUE, FALSE) == TRUE);
+ CHECK(is_connection_tracked(55123, FALSE, FALSE) == FALSE); /* the TCP flow is NOT "already tracked" */
+ CHECK(get_connection(55123, FALSE, &dip, &dport) == FALSE); /* and borrows no destination from the UDP flow */
+ add_connection(55123, FALSE, lanA, d2, 41002, 0);
+ CHECK(get_connection(55123, TRUE, &dip, &dport) && dip == d1 && dport == 41001); /* UDP entry untouched */
+ CHECK(get_connection(55123, FALSE, &dip, &dport) && dip == d2 && dport == 41002); /* TCP entry independent */
+ remove_connection(55123, FALSE, FALSE);
+ CHECK(is_connection_tracked(55123, TRUE, FALSE) && !is_connection_tracked(55123, FALSE, FALSE)); /* removing TCP keeps UDP */
+ remove_connection(55123, TRUE, FALSE);
+ CHECK(!is_connection_tracked(55123, TRUE, FALSE));
+
+ /* 2. IPv4 and IPv6 on the same numeric port */
+ UINT8 s6[16] = {0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
+ UINT8 dst6[16] = {0x26, 0x06, 0x47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x11, 0x11};
+ add_connection(50000, FALSE, lanA, d1, 443, 0);
+ CHECK(is_connection_tracked(50000, FALSE, FALSE) && !is_connection_tracked(50000, FALSE, TRUE));
+ add_connection_v6(50000, FALSE, s6, dst6, 443, 0);
+ CHECK(is_connection_tracked(50000, FALSE, TRUE) && is_connection_tracked(50000, FALSE, FALSE));
+ remove_connection(50000, FALSE, TRUE);
+ CHECK(is_connection_tracked(50000, FALSE, FALSE) && !is_connection_tracked(50000, FALSE, TRUE));
+ remove_connection(50000, FALSE, FALSE);
+
+ /* 3. KNOWN LIMITATION (not a failure): two local addresses using the same port and protocol share one entry,
+ because the local address is stored but not part of the lookup key. Reported so a future fix shows up here. */
+ add_connection(51000, FALSE, lanA, d1, 443, 0);
+ add_connection(51000, FALSE, lanB, d2, 80, 0);
+ { UINT32 gd; UINT16 gp; BOOL ok = get_connection(51000, FALSE, &gd, &gp);
+ printf(" note: multi-IP, same port+protocol: second flow %s the first\n", (ok && gd == d2) ? "OVERWROTE (known limitation)" : "kept separate from"); }
+ remove_connection(51000, FALSE, FALSE);
+
+ /* 4. Connections log: default = one row per (process, destination, port, action) */
+ CHECK(g_log_every_connection == FALSE);
+ CHECK(connection_log_wanted(100, d1, 443, 50001, FALSE, RULE_ACTION_DIRECT) == TRUE);
+ add_logged_connection(100, d1, 443, RULE_ACTION_DIRECT);
+ CHECK(connection_log_wanted(100, d1, 443, 50002, FALSE, RULE_ACTION_DIRECT) == FALSE); /* same process+dest+port+action: skipped */
+ CHECK(connection_log_wanted(100, d1, 443, 50003, FALSE, RULE_ACTION_PROXY) == TRUE); /* different action: logged */
+ CHECK(connection_log_wanted(101, d1, 443, 50004, FALSE, RULE_ACTION_DIRECT) == TRUE); /* different process: logged */
+
+ /* 5. Log every connection: every new TCP connection, one row per UDP flow */
+ ProxyBridge_SetLogEveryConnection(TRUE);
+ CHECK(g_log_every_connection == TRUE);
+ for (int i = 0; i < 50; i++)
+ {
+ CHECK(connection_log_wanted(100, d1, 443, (UINT16)(51000 + i), FALSE, RULE_ACTION_DIRECT) == TRUE);
+ add_logged_connection(100, d1, 443, RULE_ACTION_DIRECT);
+ }
+ CHECK(connection_log_wanted(100, d1, 443, 51000, FALSE, RULE_ACTION_DIRECT) == TRUE); /* same TCP tuple again = a new connection: logged */
+ CHECK(connection_log_wanted(100, d1, 53, 52000, TRUE, RULE_ACTION_DIRECT) == TRUE); /* new UDP flow */
+ CHECK(connection_log_wanted(100, d1, 53, 52000, TRUE, RULE_ACTION_DIRECT) == FALSE); /* same flow again: not re-logged */
+ CHECK(connection_log_wanted(100, d1, 53, 52000, TRUE, RULE_ACTION_DIRECT) == FALSE); /* a repeating (e.g. blocked) sender does not flood */
+ CHECK(connection_log_wanted(100, d1, 53, 52001, TRUE, RULE_ACTION_DIRECT) == TRUE); /* other local port = another flow */
+ CHECK(connection_log_wanted(100, d1, 54, 52000, TRUE, RULE_ACTION_DIRECT) == TRUE); /* other destination port */
+ CHECK(connection_log_wanted(100, d1, 53, 52000, TRUE, RULE_ACTION_BLOCK) == TRUE); /* other action = new row */
+ CHECK(connection_log_wanted(102, d1, 53, 52000, TRUE, RULE_ACTION_DIRECT) == TRUE); /* other process */
+ int logged = 0; /* many flows: the table recycles, never crashes */
+ for (int i = 0; i < 5000; i++) logged += connection_log_wanted(200, (UINT32)i, 443, (UINT16)(10000 + (i % 40000)), TRUE, RULE_ACTION_DIRECT) ? 1 : 0;
+ CHECK(logged == 5000);
+
+ /* 6. back to the default: de-duplication works again from a clean slate */
+ ProxyBridge_SetLogEveryConnection(FALSE);
+ CHECK(connection_log_wanted(300, d1, 443, 1, FALSE, RULE_ACTION_DIRECT) == TRUE);
+ add_logged_connection(300, d1, 443, RULE_ACTION_DIRECT);
+ CHECK(connection_log_wanted(300, d1, 443, 2, FALSE, RULE_ACTION_DIRECT) == FALSE);
+
+ return pbtest_done("test_conntrack");
+}
diff --git a/Windows/tests/test_dialogs_ui.c b/Windows/tests/test_dialogs_ui.c
new file mode 100644
index 0000000..14302d9
--- /dev/null
+++ b/Windows/tests/test_dialogs_ui.c
@@ -0,0 +1,142 @@
+// test_dialogs_ui.c - the other windows of the app, created from the real dialog procedures and resources with a
+// stubbed engine: the rule editor (fields, the proxy-only localhost option, clean-up on OK), the proxy servers list,
+// the log filters list and the About box. Needs a desktop session. (Message boxes are never opened by these cases.)
+#define wWinMain pb_real_wWinMain
+#include "../gui/main.c"
+#undef wWinMain
+#include "pbtest.h"
+
+static UINT32 g_delProxy = 0;
+static UINT32 StubAddProxy(PBProxyType t, const char* ip, unsigned short p, const char* u, const char* pw, BOOL sd) { (void)t; (void)ip; (void)p; (void)u; (void)pw; (void)sd; return 500; }
+static BOOL StubDelProxy(UINT32 id) { g_delProxy = id; return TRUE; }
+
+static HWND g_dlg;
+static void Set(int id, const wchar_t* t) { SetDlgItemTextW(g_dlg, id, t); }
+static void Get(int id, wchar_t* out, int cch) { GetDlgItemTextW(g_dlg, id, out, cch); }
+static BOOL Visible(int id) { return IsWindowVisible(GetDlgItem(g_dlg, id)); }
+static BOOL Checked(int id) { return IsDlgButtonChecked(g_dlg, id) == BST_CHECKED; }
+static void Combo(int id, int sel) { SendDlgItemMessageW(g_dlg, id, CB_SETCURSEL, sel, 0); SendMessageW(g_dlg, WM_COMMAND, MAKEWPARAM(id, CBN_SELCHANGE), (LPARAM)GetDlgItem(g_dlg, id)); }
+static int ComboSel(int id) { return (int)SendDlgItemMessageW(g_dlg, id, CB_GETCURSEL, 0, 0); }
+static int ComboCount(int id) { return (int)SendDlgItemMessageW(g_dlg, id, CB_GETCOUNT, 0, 0); }
+
+static HWND OpenRuleEditor(PBRule* r)
+{
+ HWND d = CreateDialogParamW(g_hInst, MAKEINTRESOURCEW(IDD_RULE), NULL, RuleEditDlgProc, (LPARAM)r);
+ ShowWindow(d, SW_SHOW); /* a hidden dialog reports every control as invisible */
+ return d;
+}
+
+int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrev, PWSTR cmd, int show)
+{
+ (void)hPrev; (void)cmd; (void)show;
+ setvbuf(stdout, NULL, _IONBF, 0);
+ g_hInst = hInst;
+ CreateDarkBrushes();
+ wchar_t tmp[MAX_PATH]; GetTempPathW(MAX_PATH, tmp);
+ wchar_t sub[64]; _snwprintf_s(sub, 64, _TRUNCATE, L"pbtest_dialogs_%lu", GetCurrentProcessId()); wcscat_s(tmp, MAX_PATH, sub);
+ CreateDirectoryW(tmp, NULL); SetEnvironmentVariableW(L"APPDATA", tmp);
+ wcscpy_s(g_activeProfile, PB_NAME_MAX, L"uitest");
+ INITCOMMONCONTROLSEX icc = { sizeof(icc), ICC_LISTVIEW_CLASSES | ICC_STANDARD_CLASSES | ICC_LINK_CLASS };
+ InitCommonControlsEx(&icc);
+ g_api.AddProxyConfig = StubAddProxy; g_api.DeleteProxyConfig = StubDelProxy;
+
+ ZeroMemory(&g_profile, sizeof(g_profile));
+ PBConfig* a = &g_profile.cfg[g_profile.cfgCount++]; a->storedId = 1; a->nativeId = 11; lstrcpynW(a->name, L"Burp", 128); lstrcpynW(a->type, L"SOCKS5", 16); lstrcpynW(a->host, L"127.0.0.1", 128); lstrcpynW(a->port, L"1080", 16);
+ PBConfig* b = &g_profile.cfg[g_profile.cfgCount++]; b->storedId = 2; b->nativeId = 12; lstrcpynW(b->name, L"Corp", 128); lstrcpynW(b->type, L"HTTP", 16); lstrcpynW(b->host, L"10.0.0.9", 128); lstrcpynW(b->port, L"3128", 16);
+
+ /* ================= rule editor ================= */
+ { PBRule r; ZeroMemory(&r, sizeof r);
+ lstrcpynW(r.name, L"My rule", 128); lstrcpynW(r.proc, L"chrome.exe; edge.exe", PB_APPS_MAX); lstrcpynW(r.hosts, L"10.*.*.*;github.com;*.google.com", PB_HOSTS_MAX);
+ lstrcpynW(r.ports, L"80;443", 128); lstrcpynW(r.proto, L"TCP", 8); lstrcpynW(r.action, L"PROXY", 16); r.enabled = 1; r.localhost = 1; r.cfgStoredId = 2;
+ g_dlg = OpenRuleEditor(&r);
+ CHECK(g_dlg != NULL);
+ wchar_t t[2048];
+ Get(IDC_RE_NAME, t, 2048); CHECK(!wcscmp(t, L"My rule"));
+ Get(IDC_RE_APPS, t, 2048); CHECK(!wcscmp(t, L"chrome.exe; edge.exe"));
+ Get(IDC_RE_HOSTS, t, 2048); CHECK(!wcscmp(t, L"10.*.*.*;\r\ngithub.com;\r\n*.google.com")); /* one entry per line in the editor */
+ Get(IDC_RE_PORTS, t, 2048); CHECK(!wcscmp(t, L"80;443"));
+ CHECK(Checked(IDC_RE_ENABLED) && Checked(IDC_RE_LOCALHOST));
+ CHECK(ComboCount(IDC_RE_ACTION) == 2 + g_profile.cfgCount); /* Direct, Block, one per proxy */
+ CHECK(ComboSel(IDC_RE_ACTION) == 3); /* proxy #2 (stored id 2) */
+ CHECK(Visible(IDC_RE_LOCALHOST) && Visible(IDC_RE_EX_LOCAL)); /* a proxy is selected: the option is shown */
+ Combo(IDC_RE_ACTION, 0); CHECK(!Visible(IDC_RE_LOCALHOST) && !Visible(IDC_RE_EX_LOCAL)); /* Direct: hidden */
+ Combo(IDC_RE_ACTION, 1); CHECK(!Visible(IDC_RE_LOCALHOST)); /* Block: hidden */
+ Combo(IDC_RE_ACTION, 2); CHECK(Visible(IDC_RE_LOCALHOST) && Checked(IDC_RE_LOCALHOST)); /* back to a proxy: shown, still ticked */
+
+ /* OK: multi-line, messy host text is cleaned into one ';' list; the rule picks up every field */
+ Set(IDC_RE_NAME, L"");
+ Set(IDC_RE_HOSTS, L" a.com ;\r\n b.org ,\r\n\r\n 10.0.0.0\r\n");
+ Set(IDC_RE_PORTS, L"");
+ Combo(IDC_RE_ACTION, 3);
+ SendMessageW(g_dlg, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), (LPARAM)GetDlgItem(g_dlg, IDOK));
+ CHECK(!wcscmp(r.name, L"ProxyBridge Rule")); /* empty name gets the default */
+ CHECK(!wcscmp(r.hosts, L"a.com;b.org;10.0.0.0")); /* blanks, line breaks and empty entries removed */
+ CHECK(!wcscmp(r.ports, L"*") && !wcscmp(r.action, L"PROXY") && r.cfgStoredId == 2 && r.localhost == 1 && r.enabled == 1);
+ DestroyWindow(g_dlg); }
+
+ /* line breaks after a ';' are formatting only */
+ { PBRule r; ZeroMemory(&r, sizeof r); lstrcpynW(r.proc, L"*", 256); lstrcpynW(r.hosts, L"*", PB_HOSTS_MAX); lstrcpynW(r.ports, L"*", 128); lstrcpynW(r.proto, L"BOTH", 8); lstrcpynW(r.action, L"DIRECT", 16); r.enabled = 1;
+ g_dlg = OpenRuleEditor(&r);
+ Set(IDC_RE_HOSTS, L"x.com;\r\ny.org;\r\n");
+ SendMessageW(g_dlg, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), (LPARAM)GetDlgItem(g_dlg, IDOK));
+ CHECK(!wcscmp(r.hosts, L"x.com;y.org"));
+ DestroyWindow(g_dlg); }
+
+ /* localhost is saved only for proxy rules, and an empty hosts box means "any host" */
+ { PBRule r; ZeroMemory(&r, sizeof r); lstrcpynW(r.proc, L"x.exe", 256); lstrcpynW(r.hosts, L"*", PB_HOSTS_MAX); lstrcpynW(r.ports, L"*", 128); lstrcpynW(r.proto, L"BOTH", 8);
+ lstrcpynW(r.action, L"PROXY", 16); r.cfgStoredId = 1; r.localhost = 1; r.enabled = 1;
+ g_dlg = OpenRuleEditor(&r);
+ Combo(IDC_RE_ACTION, 1); /* Block */
+ Set(IDC_RE_HOSTS, L"");
+ SendMessageW(g_dlg, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), (LPARAM)GetDlgItem(g_dlg, IDOK));
+ CHECK(!wcscmp(r.action, L"BLOCK") && r.localhost == 0 && r.cfgStoredId == 0 && !wcscmp(r.hosts, L"*"));
+ DestroyWindow(g_dlg); }
+ { PBRule r; ZeroMemory(&r, sizeof r); lstrcpynW(r.proc, L"x.exe", 256); lstrcpynW(r.hosts, L"*", PB_HOSTS_MAX); lstrcpynW(r.ports, L"*", 128); lstrcpynW(r.proto, L"UDP", 8); lstrcpynW(r.action, L"DIRECT", 16); r.localhost = 1;
+ g_dlg = OpenRuleEditor(&r);
+ SendMessageW(g_dlg, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), (LPARAM)GetDlgItem(g_dlg, IDOK));
+ CHECK(!wcscmp(r.action, L"DIRECT") && r.localhost == 0 && !wcscmp(r.proto, L"UDP")); /* a stale flag on a Direct rule is dropped */
+ DestroyWindow(g_dlg); }
+
+ /* Cancel leaves the rule untouched */
+ { PBRule r; ZeroMemory(&r, sizeof r); lstrcpynW(r.name, L"keep", 128); lstrcpynW(r.proc, L"x.exe", 256); lstrcpynW(r.hosts, L"1.1.1.1", PB_HOSTS_MAX); lstrcpynW(r.ports, L"*", 128); lstrcpynW(r.proto, L"TCP", 8); lstrcpynW(r.action, L"DIRECT", 16);
+ g_dlg = OpenRuleEditor(&r);
+ Set(IDC_RE_NAME, L"changed"); Set(IDC_RE_HOSTS, L"2.2.2.2");
+ SendMessageW(g_dlg, WM_COMMAND, MAKEWPARAM(IDCANCEL, BN_CLICKED), (LPARAM)GetDlgItem(g_dlg, IDCANCEL));
+ CHECK(!wcscmp(r.name, L"keep") && !wcscmp(r.hosts, L"1.1.1.1"));
+ DestroyWindow(g_dlg); }
+
+ /* ================= proxy servers list ================= */
+ g_dlg = CreateDialogParamW(hInst, MAKEINTRESOURCEW(IDD_SERVERS), NULL, ServersDlgProc, 0);
+ CHECK(g_dlg != NULL);
+ { HWND lv = GetDlgItem(g_dlg, IDC_SV_LIST);
+ CHECK(ListView_GetItemCount(lv) == 2);
+ wchar_t t[128]; ListView_GetItemText(lv, 0, 0, t, 128); CHECK(!wcscmp(t, L"Burp"));
+ ListView_SetItemState(lv, 0, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
+ SendMessageW(g_dlg, WM_COMMAND, MAKEWPARAM(IDC_SV_REMOVE, BN_CLICKED), (LPARAM)GetDlgItem(g_dlg, IDC_SV_REMOVE));
+ CHECK(g_delProxy == 11 && g_profile.cfgCount == 1 && g_profile.cfg[0].storedId == 2 && ListView_GetItemCount(lv) == 1); /* the right proxy went */
+ SendMessageW(g_dlg, WM_COMMAND, MAKEWPARAM(IDC_SV_REMOVE, BN_CLICKED), (LPARAM)GetDlgItem(g_dlg, IDC_SV_REMOVE)); /* nothing selected: nothing happens */
+ CHECK(g_profile.cfgCount == 1);
+ DestroyWindow(g_dlg); }
+
+ /* ================= log filters list ================= */
+ g_profile.filterCount = 2;
+ lstrcpynW(g_profile.filter[0].mode, L"Include", 16); lstrcpynW(g_profile.filter[0].proc, L"chrome*", 256); lstrcpynW(g_profile.filter[0].ip, L"*", 64); lstrcpynW(g_profile.filter[0].port, L"*", 16); lstrcpynW(g_profile.filter[0].proto, L"All", 8); lstrcpynW(g_profile.filter[0].action, L"All", 16);
+ lstrcpynW(g_profile.filter[1].mode, L"Exclude", 16); lstrcpynW(g_profile.filter[1].proc, L"*", 256); lstrcpynW(g_profile.filter[1].ip, L"10.*", 64); lstrcpynW(g_profile.filter[1].port, L"*", 16); lstrcpynW(g_profile.filter[1].proto, L"All", 8); lstrcpynW(g_profile.filter[1].action, L"All", 16);
+ g_dlg = CreateDialogParamW(hInst, MAKEINTRESOURCEW(IDD_FILTERS), NULL, FiltersDlgProc, 0);
+ CHECK(g_dlg != NULL);
+ { HWND lv = GetDlgItem(g_dlg, IDC_FL_LIST);
+ CHECK(ListView_GetItemCount(lv) == 2);
+ ListView_SetItemState(lv, 1, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
+ SendMessageW(g_dlg, WM_COMMAND, MAKEWPARAM(IDC_FL_REMOVE, BN_CLICKED), (LPARAM)GetDlgItem(g_dlg, IDC_FL_REMOVE));
+ CHECK(g_profile.filterCount == 1 && !wcscmp(g_profile.filter[0].mode, L"Include") && ListView_GetItemCount(lv) == 1);
+ DestroyWindow(g_dlg); }
+
+ /* ================= About box ================= */
+ g_dlg = CreateDialogParamW(hInst, MAKEINTRESOURCEW(IDD_ABOUT), NULL, AboutDlgProc, 0);
+ CHECK(g_dlg != NULL);
+ { wchar_t t[256]; Get(IDC_AB_VER, t, 256); CHECK(wcsstr(t, PB_VER_STRW) != NULL); /* shows the real version */
+ Get(IDC_AB_TITLE, t, 256); CHECK(wcsstr(t, L"ProxyBridge") != NULL);
+ DestroyWindow(g_dlg); }
+
+ return pbtest_done("test_dialogs_ui");
+}
diff --git a/Windows/tests/test_dns.c b/Windows/tests/test_dns.c
new file mode 100644
index 0000000..3930c38
--- /dev/null
+++ b/Windows/tests/test_dns.c
@@ -0,0 +1,101 @@
+// test_dns.c - the DNS reply parser that feeds domain rules (src\pb_dns.c: snoop_dns_response, dns_parse_name).
+// It parses packets straight off the network, so every test here also runs the parser on a buffer that ends exactly
+// at a no-access guard page: reading even one byte past the packet crashes the test (and fails it).
+#include "pb_internal.h"
+#include "pbtest.h"
+
+/* guard-page buffer (pbtest.h): the data ends exactly where unreadable memory begins */
+#define guarded(data, len, base) pb_guarded((data), (size_t)(len), (base))
+#define release(base) pb_guard_release(base)
+
+/* ---- packet builder ---- */
+typedef struct { BYTE b[1500]; int n; } Pkt;
+static void u8(Pkt* p, int v) { p->b[p->n++] = (BYTE)v; }
+static void u16(Pkt* p, int v) { u8(p, v >> 8); u8(p, v); }
+static void u32(Pkt* p, UINT32 v) { u16(p, v >> 16); u16(p, v & 0xFFFF); }
+static void name(Pkt* p, const char* dotted)
+{
+ const char* s = dotted;
+ while (*s) { const char* e = strchr(s, '.'); int l = e ? (int)(e - s) : (int)strlen(s); u8(p, l); memcpy(p->b + p->n, s, l); p->n += l; if (!e) break; s = e + 1; }
+ u8(p, 0);
+}
+static void header(Pkt* p, int flags, int qd, int an) { p->n = 0; u16(p, 0x1234); u16(p, flags); u16(p, qd); u16(p, an); u16(p, 0); u16(p, 0); }
+static void question(Pkt* p, const char* n, int type) { name(p, n); u16(p, type); u16(p, 1); }
+static void answer_a(Pkt* p, const BYTE* ip) { u16(p, 0xC00C); u16(p, 1); u16(p, 1); u32(p, 60); u16(p, 4); memcpy(p->b + p->n, ip, 4); p->n += 4; }
+static void answer_aaaa(Pkt* p, const BYTE* ip6) { u16(p, 0xC00C); u16(p, 28); u16(p, 1); u32(p, 60); u16(p, 16); memcpy(p->b + p->n, ip6, 16); p->n += 16; }
+static void answer_cname(Pkt* p, const char* target) { u16(p, 0xC00C); u16(p, 5); u16(p, 1); u32(p, 60); int lenpos = p->n; u16(p, 0); int st = p->n; name(p, target); int l = p->n - st; p->b[lenpos] = (BYTE)(l >> 8); p->b[lenpos + 1] = (BYTE)l; }
+
+static BOOL fed(const Pkt* p) /* feed through a guarded buffer */
+{
+ void* base; BYTE* g = guarded(p->b, p->n, &base);
+ snoop_dns_response(g, p->n);
+ release(base); return TRUE;
+}
+static BOOL known(const BYTE* ip, const char* want)
+{
+ UINT32 v; memcpy(&v, ip, 4); char d[256];
+ return dns_cache_lookup(v, d, sizeof d) && !strcmp(d, want);
+}
+static BOOL unknown(const BYTE* ip) { UINT32 v; memcpy(&v, ip, 4); char d[256]; return !dns_cache_lookup(v, d, sizeof d); }
+
+int main(void)
+{
+ dns_cache_init();
+ const BYTE ipA[4] = { 93, 184, 216, 34 }, ipB[4] = { 10, 11, 12, 13 }, ipC[4] = { 1, 2, 3, 4 };
+ BYTE v6[16] = { 0x26, 0x06, 0x47, 0x00, 0x10, 0, 0, 0, 0, 0, 0, 0, 0xac, 0x42, 0x93, 0xf3 };
+ Pkt p;
+
+ /* 1. a normal A reply is learned */
+ header(&p, 0x8180, 1, 1); question(&p, "example.com", 1); answer_a(&p, ipA); fed(&p);
+ CHECK(known(ipA, "example.com"));
+
+ /* 2. AAAA reply */
+ header(&p, 0x8180, 1, 1); question(&p, "ipv6.example.org", 28); answer_aaaa(&p, v6); fed(&p);
+ { char d[256]; CHECK(dns_cache_lookup_v6(v6, d, sizeof d) && !strcmp(d, "ipv6.example.org")); }
+
+ /* 3. CNAME chain then two A records: every address is mapped to the NAME THE APP ASKED FOR */
+ header(&p, 0x8180, 1, 3); question(&p, "www.shop.example", 1);
+ answer_cname(&p, "cdn.example.net"); answer_a(&p, ipB); answer_a(&p, ipC); fed(&p);
+ CHECK(known(ipB, "www.shop.example") && known(ipC, "www.shop.example"));
+
+ /* 4. replies that must be ignored */
+ { BYTE ipX[4] = { 9, 9, 9, 1 };
+ header(&p, 0x0100, 1, 1); question(&p, "query.example", 1); answer_a(&p, ipX); fed(&p); CHECK(unknown(ipX)); /* a query, not a response */
+ header(&p, 0x8183, 1, 1); question(&p, "nx.example", 1); answer_a(&p, ipX); fed(&p); CHECK(unknown(ipX)); /* RCODE = NXDOMAIN */
+ header(&p, 0x8180, 1, 0); question(&p, "empty.example", 1); fed(&p); CHECK(unknown(ipX)); /* no answers */
+ header(&p, 0x8180, 1, 1); question(&p, "short.example", 1); u16(&p, 0xC00C); u16(&p, 1); u16(&p, 1); u32(&p, 60); u16(&p, 5); u32(&p, 0x09090901); u8(&p, 0); fed(&p);
+ CHECK(unknown(ipX)); /* A record with a 5-byte rdata */
+ BYTE tiny[11] = { 0 }; void* b; BYTE* g = guarded(tiny, 11, &b); snoop_dns_response(g, 11); release(b); } /* shorter than a header */
+
+ /* 5. hostile names: pointer loops, label overruns, over-long names */
+ { BYTE ipX[4] = { 9, 9, 9, 2 };
+ header(&p, 0x8180, 1, 1); u8(&p, 0xC0); u8(&p, 0x0C); u16(&p, 1); u16(&p, 1); answer_a(&p, ipX); fed(&p); /* the question name points at itself */
+ CHECK(unknown(ipX));
+ header(&p, 0x8180, 1, 1); u8(&p, 63); memset(p.b + p.n, 'a', 20); p.n += 20; fed(&p); /* label longer than the packet */
+ header(&p, 0x8180, 1, 1); for (int i = 0; i < 6; i++) { u8(&p, 63); memset(p.b + p.n, 'b', 63); p.n += 63; } u8(&p, 0);
+ u16(&p, 1); u16(&p, 1); answer_a(&p, ipX); fed(&p); /* name of 380+ characters */
+ CHECK(unknown(ipX)); }
+
+ /* 6. counts that lie: more answers or questions than the packet holds */
+ header(&p, 0x8180, 9, 9); question(&p, "liar.example", 1); fed(&p);
+ header(&p, 0x8180, 1, 500); question(&p, "liar2.example", 1); { BYTE ipL[4] = { 7, 7, 7, 7 }; answer_a(&p, ipL); fed(&p); CHECK(known(ipL, "liar2.example")); }
+
+ /* 7. every prefix of a valid reply, parsed from a buffer that ends exactly there (guard page after the last byte) */
+ header(&p, 0x8180, 1, 3); question(&p, "prefix.example.com", 1); answer_cname(&p, "t.example.net"); answer_a(&p, ipA); answer_aaaa(&p, v6);
+ for (int cut = 0; cut <= p.n; cut++) { void* b; BYTE* g = guarded(p.b, cut, &b); snoop_dns_response(g, cut); release(b); }
+ CHECK(TRUE);
+
+ /* 8. random packets, mutated valid packets, and random pointer soup: nothing may read outside the packet */
+ srand(2026);
+ int packets = 0;
+ for (int it = 0; it < 60000; it++)
+ {
+ Pkt r;
+ if (it % 3 == 0) { r.n = rand() % 200; for (int i = 0; i < r.n; i++) r.b[i] = (BYTE)rand(); if (r.n > 3 && rand() % 2) { r.b[2] |= 0x80; r.b[3] &= 0xF0; } }
+ else { r = p; int flips = 1 + rand() % 4; for (int f = 0; f < flips; f++) r.b[rand() % r.n] = (BYTE)(rand() % 4 ? 0xC0 + rand() % 3 : rand()); if (it % 3 == 2) r.n = rand() % (r.n + 1); }
+ void* b; BYTE* g = guarded(r.b, r.n, &b); snoop_dns_response(g, r.n); release(b); packets++;
+ }
+ CHECK(packets == 60000);
+
+ return pbtest_done("test_dns");
+}
diff --git a/Windows/tests/test_engine.c b/Windows/tests/test_engine.c
new file mode 100644
index 0000000..9b41164
--- /dev/null
+++ b/Windows/tests/test_engine.c
@@ -0,0 +1,112 @@
+// test_engine.c - the rule engine, linked from the real core sources (no driver is opened, no packet is captured):
+// - a rule's host part: IP entries OR domain entries (names come from the DNS snoop cache), IPv4 and IPv6
+// - ports still AND with hosts, wildcard-process rules, EditRule
+// - the per-rule "also proxy localhost" flag
+// - the main switch: paused = nothing is proxied or blocked for new connections
+#include "pb_internal.h"
+#include "pbtest.h"
+
+static UINT32 ip4(const char* s) { struct in_addr a; inet_pton(AF_INET, s, &a); return a.S_un.S_addr; }
+static RuleAction m4(const char* proc, const char* ip, int port) { UINT32 id = 0; return match_rule(proc, ip4(ip), (UINT16)port, FALSE, &id); }
+static RuleAction m6(const char* proc, const char* ip, int port) { UINT8 a[16]; inet_pton(AF_INET6, ip, a); UINT32 id = 0; return match_rule_v6(proc, a, (UINT16)port, FALSE, &id); }
+
+int main(void)
+{
+ dns_cache_init();
+ /* names the DNS tap "learned" */
+ dns_cache_store(ip4("140.82.112.3"), "github.com");
+ dns_cache_store(ip4("142.250.1.1"), "www.google.com");
+ dns_cache_store(ip4("10.9.9.9"), "intranet.corp");
+ { UINT8 a6[16]; inet_pton(AF_INET6, "2606:4700::1111", a6); dns_cache_store_v6(a6, "github.com"); }
+
+ /* 1. IP list AND domain list set on one rule: either is enough (it used to need both) */
+ UINT32 a = ProxyBridge_AddRule("chrome.exe", "10.*.*.*", "*", "github.com;*.google.com", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, FALSE);
+ CHECK(a != 0);
+ CHECK(m4("chrome.exe", "10.1.2.3", 443) == RULE_ACTION_PROXY); /* IP entry only (name unknown) */
+ CHECK(m4("chrome.exe", "10.9.9.9", 443) == RULE_ACTION_PROXY); /* IP entry; name intranet.corp not listed */
+ CHECK(m4("chrome.exe", "140.82.112.3", 443) == RULE_ACTION_PROXY); /* domain entry only (public IP) */
+ CHECK(m4("chrome.exe", "142.250.1.1", 80) == RULE_ACTION_PROXY); /* wildcard domain entry */
+ CHECK(m4("chrome.exe", "8.8.8.8", 443) == RULE_ACTION_DIRECT); /* neither */
+ CHECK(m4("chrome.exe", "93.184.216.34", 443) == RULE_ACTION_DIRECT); /* unknown name, not in the IP list */
+ CHECK(m4("firefox.exe", "10.1.2.3", 443) == RULE_ACTION_DIRECT); /* another process is unaffected */
+ ProxyBridge_DeleteRule(a);
+
+ /* 2. domains only (IP side "*"): an IP-only match must not leak in */
+ UINT32 b = ProxyBridge_AddRule("chrome.exe", "*", "*", "github.com", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, FALSE);
+ CHECK(m4("chrome.exe", "140.82.112.3", 443) == RULE_ACTION_PROXY);
+ CHECK(m4("chrome.exe", "142.250.1.1", 443) == RULE_ACTION_DIRECT);
+ CHECK(m4("chrome.exe", "10.1.2.3", 443) == RULE_ACTION_DIRECT);
+ ProxyBridge_DeleteRule(b);
+
+ /* 3. IPs only (domain side "*") */
+ UINT32 c = ProxyBridge_AddRule("chrome.exe", "192.168.*.*;10.0.0.1", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, FALSE);
+ CHECK(m4("chrome.exe", "192.168.4.4", 1) == RULE_ACTION_PROXY);
+ CHECK(m4("chrome.exe", "10.0.0.1", 1) == RULE_ACTION_PROXY);
+ CHECK(m4("chrome.exe", "140.82.112.3", 1) == RULE_ACTION_DIRECT);
+ ProxyBridge_DeleteRule(c);
+
+ /* 4. everything wildcard matches every host; ports still AND with hosts */
+ UINT32 d = ProxyBridge_AddRule("chrome.exe", "*", "443", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_BLOCK, 0, FALSE);
+ CHECK(m4("chrome.exe", "8.8.8.8", 443) == RULE_ACTION_BLOCK);
+ CHECK(m4("chrome.exe", "8.8.8.8", 80) == RULE_ACTION_DIRECT);
+ ProxyBridge_DeleteRule(d);
+ UINT32 e = ProxyBridge_AddRule("chrome.exe", "10.*.*.*", "443", "github.com", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, FALSE);
+ CHECK(m4("chrome.exe", "140.82.112.3", 443) == RULE_ACTION_PROXY && m4("chrome.exe", "140.82.112.3", 80) == RULE_ACTION_DIRECT);
+ CHECK(m4("chrome.exe", "10.5.5.5", 443) == RULE_ACTION_PROXY && m4("chrome.exe", "10.5.5.5", 80) == RULE_ACTION_DIRECT);
+ ProxyBridge_DeleteRule(e);
+
+ /* 5. a wildcard-process rule with filters uses the same either-or logic */
+ UINT32 f = ProxyBridge_AddRule("*", "10.*.*.*", "*", "github.com", RULE_PROTOCOL_BOTH, RULE_ACTION_BLOCK, 0, FALSE);
+ CHECK(m4("anything.exe", "140.82.112.3", 443) == RULE_ACTION_BLOCK);
+ CHECK(m4("anything.exe", "10.2.3.4", 443) == RULE_ACTION_BLOCK);
+ CHECK(m4("anything.exe", "8.8.8.8", 443) == RULE_ACTION_DIRECT);
+ ProxyBridge_DeleteRule(f);
+
+ /* 6. IPv6: address entry OR domain entry */
+ UINT32 g6 = ProxyBridge_AddRule("chrome.exe", "2001:db8::/32", "*", "github.com", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, FALSE);
+ CHECK(m6("chrome.exe", "2001:db8::1", 443) == RULE_ACTION_PROXY); /* address entry */
+ CHECK(m6("chrome.exe", "2606:4700::1111", 443) == RULE_ACTION_PROXY); /* domain entry (learned AAAA) */
+ CHECK(m6("chrome.exe", "2a00:1450::1", 443) == RULE_ACTION_DIRECT);
+ ProxyBridge_DeleteRule(g6);
+
+ /* 7. EditRule works with the new matching */
+ UINT32 h = ProxyBridge_AddRule("chrome.exe", "10.*.*.*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, FALSE);
+ CHECK(m4("chrome.exe", "140.82.112.3", 1) == RULE_ACTION_DIRECT);
+ CHECK(ProxyBridge_EditRule(h, "chrome.exe", "10.*.*.*", "*", "github.com", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, FALSE));
+ CHECK(m4("chrome.exe", "140.82.112.3", 1) == RULE_ACTION_PROXY && m4("chrome.exe", "10.1.1.1", 1) == RULE_ACTION_PROXY);
+ ProxyBridge_DeleteRule(h);
+
+ /* 8. per-rule "also proxy localhost": match_rule reports the matched rule's flag */
+ UINT32 l1 = ProxyBridge_AddRule("browser.exe", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, TRUE);
+ UINT32 l2 = ProxyBridge_AddRule("curl.exe", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, FALSE);
+ CHECK(m4("browser.exe", "127.0.0.1", 8080) == RULE_ACTION_PROXY && g_tl_rule_localhost == TRUE);
+ CHECK(m4("curl.exe", "127.0.0.1", 8080) == RULE_ACTION_PROXY && g_tl_rule_localhost == FALSE);
+ CHECK(ProxyBridge_EditRule(l2, "curl.exe", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, TRUE));
+ CHECK(m4("curl.exe", "127.0.0.1", 8080) == RULE_ACTION_PROXY && g_tl_rule_localhost == TRUE);
+ CHECK(m4("other.exe", "127.0.0.1", 8080) == RULE_ACTION_DIRECT && g_tl_rule_localhost == FALSE); /* no rule: no flag */
+ ProxyBridge_DeleteRule(l1); ProxyBridge_DeleteRule(l2);
+
+ /* 9. main switch: paused = no rule applies to new connections; enabling restores them */
+ UINT32 p1 = ProxyBridge_AddRule("chrome.exe", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, FALSE);
+ UINT32 p2 = ProxyBridge_AddRule("curl.exe", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_BLOCK, 0, FALSE);
+ CHECK(g_proxy_enabled == TRUE); /* on by default */
+ CHECK(m4("chrome.exe", "8.8.8.8", 443) == RULE_ACTION_PROXY && m4("curl.exe", "8.8.8.8", 443) == RULE_ACTION_BLOCK);
+ ProxyBridge_SetEnabled(FALSE);
+ CHECK(m4("chrome.exe", "8.8.8.8", 443) == RULE_ACTION_DIRECT); /* proxy rule paused */
+ CHECK(m4("curl.exe", "8.8.8.8", 443) == RULE_ACTION_DIRECT); /* block rule paused too */
+ { UINT8 a6[16] = {0x20, 0x01, 0x0d, 0xb8}; UINT32 idv = 77; CHECK(match_rule_v6("chrome.exe", a6, 443, FALSE, &idv) == RULE_ACTION_DIRECT && idv == 0); }
+ ProxyBridge_SetEnabled(FALSE); /* idempotent */
+ CHECK(m4("chrome.exe", "8.8.8.8", 443) == RULE_ACTION_DIRECT);
+ ProxyBridge_SetEnabled(TRUE);
+ CHECK(m4("chrome.exe", "8.8.8.8", 443) == RULE_ACTION_PROXY && m4("curl.exe", "8.8.8.8", 443) == RULE_ACTION_BLOCK);
+ ProxyBridge_DeleteRule(p1); ProxyBridge_DeleteRule(p2);
+
+ /* 10. rule list housekeeping: disabled rules are skipped; deleted rules are gone */
+ UINT32 x = ProxyBridge_AddRule("zzz.exe", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_BLOCK, 0, FALSE);
+ CHECK(m4("zzz.exe", "8.8.8.8", 1) == RULE_ACTION_BLOCK);
+ ProxyBridge_DisableRule(x); CHECK(m4("zzz.exe", "8.8.8.8", 1) == RULE_ACTION_DIRECT);
+ ProxyBridge_EnableRule(x); CHECK(m4("zzz.exe", "8.8.8.8", 1) == RULE_ACTION_BLOCK);
+ ProxyBridge_DeleteRule(x); CHECK(m4("zzz.exe", "8.8.8.8", 1) == RULE_ACTION_DIRECT);
+
+ return pbtest_done("test_engine");
+}
diff --git a/Windows/tests/test_gui_misc.c b/Windows/tests/test_gui_misc.c
new file mode 100644
index 0000000..11c877f
--- /dev/null
+++ b/Windows/tests/test_gui_misc.c
@@ -0,0 +1,127 @@
+// test_gui_misc.c - helpers that live inside the GUI (gui\main.c and its ui\ headers, included as source):
+// - the updater's version parsing/comparison
+// - the EN/ZH string table: complete, aligned with its ids, and printf-style placeholders identical in both languages
+// - connection-log filters (include / exclude, wildcards) and the bounded log store
+// - UTF-8 <-> UTF-16 conversion helpers
+// No window of the app is created except one plain EDIT control used by the log store.
+#define wWinMain pb_real_wWinMain
+#include "../gui/main.c"
+#undef wWinMain
+#include "pbtest.h"
+
+static void ver(const wchar_t* s, int a, int b, int c)
+{
+ int v[3]; UpdParseVer(s, v);
+ if (v[0] != a || v[1] != b || v[2] != c) { g_fails++; wprintf(L" FAIL UpdParseVer(%ls) = %d.%d.%d, wanted %d.%d.%d\n", s, v[0], v[1], v[2], a, b, c); }
+ g_checks++;
+}
+static int cmp(const wchar_t* x, const wchar_t* y) { int a[3], b[3]; UpdParseVer(x, a); UpdParseVer(y, b); return UpdVerCmp(a, b); }
+
+// Collects the conversion characters of a printf-style format ("%d of %d" -> "dd"), skipping "%%".
+static void conv(const wchar_t* f, char* out, size_t cap)
+{
+ size_t n = 0;
+ for (; *f; f++)
+ {
+ if (*f != L'%') continue;
+ f++;
+ if (*f == L'%') continue;
+ while (*f && wcschr(L"-+ #0123456789.lhIw", *f)) f++;
+ if (*f && n + 1 < cap) out[n++] = (char)*f;
+ if (!*f) break;
+ }
+ out[n] = 0;
+}
+
+static PBFilter F(const wchar_t* mode, const wchar_t* proc, const wchar_t* ip, const wchar_t* port, const wchar_t* proto, const wchar_t* action)
+{
+ PBFilter f; ZeroMemory(&f, sizeof f);
+ lstrcpynW(f.mode, mode, 16); lstrcpynW(f.proc, proc, 256); lstrcpynW(f.ip, ip, 64); lstrcpynW(f.port, port, 16); lstrcpynW(f.proto, proto, 8); lstrcpynW(f.action, action, 16);
+ return f;
+}
+
+int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrev, PWSTR cmd, int show)
+{
+ (void)hInst; (void)hPrev; (void)cmd; (void)show;
+ setvbuf(stdout, NULL, _IONBF, 0);
+
+ /* ================= updater: version parsing and comparison ================= */
+ ver(L"4.2.0", 4, 2, 0); ver(L"v4.2.0", 4, 2, 0); ver(L"4.2.0-Beta", 4, 2, 0); ver(L"4.0.13-Beta", 4, 0, 13);
+ ver(L"4.10.2", 4, 10, 2); ver(L"4.2", 4, 2, 0); ver(L"7", 7, 0, 0); ver(L"", 0, 0, 0); ver(L"abc", 0, 0, 0); ver(L"1.2.3.4", 1, 2, 3);
+ CHECK(cmp(L"4.10.0", L"4.9.0") > 0 && cmp(L"4.2.0", L"4.2.0") == 0 && cmp(L"4.1.9", L"4.2.0") < 0 && cmp(L"5.0.0", L"4.99.99") > 0);
+ CHECK(cmp(L"v4.2.1", L"4.2.0-Beta") > 0 && cmp(L"4.2.0-Beta", L"4.2.0") == 0);
+ CHECK(cmp(PB_VER_STRW, L"0.0.1") > 0); /* the app's own version parses and is real */
+ { int v[3]; UpdParseVer(PB_VER_STRW, v); CHECK(v[0] == PB_VER_MAJOR && v[1] == PB_VER_MINOR && v[2] == PB_VER_PATCH); } /* text and numbers agree */
+
+ /* ================= string table ================= */
+ int empty = 0, same = 0, badFmt = 0;
+ for (int i = 0; i < S_COUNT; i++)
+ {
+ const wchar_t* en = g_strings[i][0]; const wchar_t* zh = g_strings[i][1];
+ if (!en || !zh || !en[0] || !zh[0]) { empty++; wprintf(L" FAIL string id %d is missing or empty in %ls\n", i, (!en || !en[0]) ? L"English" : L"Chinese"); continue; }
+ if (!wcscmp(en, zh)) same++;
+ char ce[32], cz[32]; conv(en, ce, sizeof ce); conv(zh, cz, sizeof cz);
+ if (strcmp(ce, cz)) { badFmt++; wprintf(L" FAIL string id %d: placeholders differ between English (%hs) and Chinese (%hs)\n", i, ce, cz); }
+ }
+ CHECK(empty == 0 && badFmt == 0);
+ CHECK(S_COUNT > 100 && same * 5 < S_COUNT); /* most strings are really translated */
+ /* anchors: a mis-ordered id/table pair shows up here */
+ CHECK(wcsstr(g_strings[S_BTN_OK][0], L"OK") && wcsstr(g_strings[S_BTN_CANCEL][0], L"Cancel") && wcsstr(g_strings[S_DLG_RULES][0], L"Rules"));
+ CHECK(wcsstr(g_strings[S_M_ENABLE][0], L"Enable") && wcsstr(g_strings[S_M_LOGALL][0], L"Every") && wcsstr(g_strings[S_CHK_LOCALHOST][0], L"ocalhost"));
+ CHECK(wcsstr(g_strings[S_RULES_COUNT][0], L"%d") && wcsstr(g_strings[S_RULES_SEARCH][0], L"earch") && wcsstr(g_strings[S_TITLE_PAUSED][0], L"PAUSED"));
+ g_lang = 0; CHECK(T(S_BTN_OK) == g_strings[S_BTN_OK][0]);
+ g_lang = 1; CHECK(T(S_BTN_OK) == g_strings[S_BTN_OK][1]);
+ g_lang = 7; CHECK(T(S_BTN_OK) == g_strings[S_BTN_OK][1]); /* any non-zero language = Chinese, never out of range */
+ g_lang = 0;
+
+ /* ================= connection-log filters ================= */
+ CHECK(ContainsCI(L"Chrome.EXE", L"chrome") && !ContainsCI(L"firefox", L"chrome") && ContainsCI(L"abc", L""));
+ CHECK(GlobMatch(L"chrome.exe", L"chrome*") && GlobMatch(L"chrome.exe", L"*.exe") && GlobMatch(L"chrome.exe", L"c*e.e*e") && !GlobMatch(L"chrome.exe", L"*.bin"));
+ CHECK(GlobMatch(L"chrome.exe", L"*") && GlobMatch(L"chrome.exe", L"") && GlobMatch(L"chrome.exe", L"rome")); /* no '*' = contains */
+ CHECK(!GlobMatch(L"chrome.exe", L"hrome*") && !GlobMatch(L"chrome.exe", L"*chrom")); /* anchored when the pattern has no leading/trailing star */
+
+ PBFilter f1 = F(L"Include", L"chrome*", L"*", L"*", L"All", L"All");
+ CHECK(FilterRuleMatches(&f1, L"chrome.exe", L"1.2.3.4", L"443", L"TCP", L"Proxy") && !FilterRuleMatches(&f1, L"edge.exe", L"1.2.3.4", L"443", L"TCP", L"Proxy"));
+ PBFilter f2 = F(L"Exclude", L"*", L"10.*", L"*", L"UDP", L"All");
+ CHECK(FilterRuleMatches(&f2, L"x.exe", L"10.1.1.1", L"53", L"UDP", L"Direct") && !FilterRuleMatches(&f2, L"x.exe", L"10.1.1.1", L"53", L"TCP", L"Direct"));
+
+ g_fltCount = 0; /* no filters: everything shows */
+ CHECK(PassesLogFilters(L"a.exe", L"1.1.1.1", L"80", L"TCP", L"Direct"));
+ g_flt[0] = F(L"Exclude", L"noisy*", L"*", L"*", L"All", L"All"); g_fltCount = 1; /* exclude only: everything but noisy */
+ CHECK(!PassesLogFilters(L"noisy.exe", L"1.1.1.1", L"80", L"TCP", L"Direct") && PassesLogFilters(L"quiet.exe", L"1.1.1.1", L"80", L"TCP", L"Direct"));
+ g_flt[0] = F(L"Include", L"chrome*", L"*", L"*", L"All", L"All"); g_fltCount = 1; /* include only: only chrome */
+ CHECK(PassesLogFilters(L"chrome.exe", L"1.1.1.1", L"80", L"TCP", L"Direct") && !PassesLogFilters(L"edge.exe", L"1.1.1.1", L"80", L"TCP", L"Direct"));
+ g_flt[1] = F(L"Exclude", L"*", L"192.168.*", L"*", L"All", L"All"); g_fltCount = 2; /* exclude wins over include */
+ CHECK(PassesLogFilters(L"chrome.exe", L"8.8.8.8", L"80", L"TCP", L"Direct") && !PassesLogFilters(L"chrome.exe", L"192.168.1.5", L"80", L"TCP", L"Direct"));
+ g_flt[0] = F(L"Include", L"*", L"*", L"443", L"TCP", L"Proxy"); g_flt[1] = F(L"Include", L"*", L"*", L"53", L"UDP", L"All"); g_fltCount = 2; /* any include may match */
+ CHECK(PassesLogFilters(L"a.exe", L"1.1.1.1", L"443", L"TCP", L"Proxy") && PassesLogFilters(L"a.exe", L"1.1.1.1", L"53", L"UDP", L"Direct") &&
+ !PassesLogFilters(L"a.exe", L"1.1.1.1", L"443", L"TCP", L"Direct"));
+ g_fltCount = 0;
+
+ /* ================= log store: bounded, oldest dropped, auto-clear ================= */
+ { static LogStore s; ZeroMemory(&s, sizeof s);
+ s.edit = CreateWindowExW(0, L"EDIT", NULL, WS_POPUP | ES_MULTILINE, 0, 0, 10, 10, NULL, NULL, GetModuleHandleW(NULL), NULL);
+ CHECK(s.edit != NULL);
+ g_autoClear = FALSE;
+ for (int i = 0; i < LOG_MAX_LINES + 50; i++) { wchar_t l[40]; _snwprintf_s(l, 40, _TRUNCATE, L"line %d\r\n", i); LogStoreAdd(&s, l); }
+ CHECK(s.count == LOG_MAX_LINES);
+ CHECK(wcscmp(s.lines[0], L"line 50\r\n") == 0 && wcsncmp(s.lines[LOG_MAX_LINES - 1], L"line 4049", 9) == 0); /* the first 50 were dropped */
+ for (int i = 0; i < s.count; i++) free(s.lines[i]);
+ s.count = 0; SetWindowTextW(s.edit, L"");
+ g_autoClear = TRUE;
+ for (int i = 0; i < AUTO_CLEAR_LINES + 1; i++) LogStoreAdd(&s, L"x\r\n");
+ CHECK(s.count == 0); /* auto-clear wiped it at the threshold */
+ DestroyWindow(s.edit); g_autoClear = TRUE; }
+
+ /* ================= UTF-8 <-> UTF-16 helpers ================= */
+ { wchar_t* w = U2Wdup("plain"); CHECK(w && !wcscmp(w, L"plain")); free(w); }
+ { wchar_t* w = U2Wdup("caf\xC3\xA9 \xE4\xB8\xAD\xE6\x96\x87"); CHECK(w && !wcscmp(w, L"caf\x00e9 \x4e2d\x6587")); free(w); }
+ { wchar_t* w = U2Wdup(NULL); CHECK(w && w[0] == 0); free(w); }
+ { wchar_t* w = U2Wdup(""); CHECK(w && w[0] == 0); free(w); }
+ { char buf[64]; W2Ux(L"caf\x00e9 \x4e2d", buf, sizeof buf); CHECK(!strcmp(buf, "caf\xC3\xA9 \xE4\xB8\xAD")); }
+ { char buf[4]; memset(buf, 0x55, sizeof buf); W2Ux(L"this does not fit", buf, sizeof buf); CHECK(memchr(buf, 0, sizeof buf) != NULL); } /* too small: still terminated */
+ { char buf[8]; W2Ux(NULL, buf, sizeof buf); CHECK(buf[0] == 0); }
+ { wchar_t ts[16]; GetTimePrefix(ts, 16); CHECK(wcslen(ts) == 11 && ts[0] == L'[' && ts[3] == L':' && ts[6] == L':' && ts[9] == L']'); }
+
+ return pbtest_done("test_gui_misc");
+}
diff --git a/Windows/tests/test_hosts.c b/Windows/tests/test_hosts.c
new file mode 100644
index 0000000..8d387a6
--- /dev/null
+++ b/Windows/tests/test_hosts.c
@@ -0,0 +1,103 @@
+// test_hosts.c - the Target Hosts list helpers of the GUI (gui\profile\profile.c):
+// PB_ListNormalize / PB_ListFormat line breaks are display-only, cleaned before saving
+// PB_HostsSplit / PB_HostsMerge IPs and domain names are one list in the GUI, two keys in the profile file
+// Includes random-input checks with canary words to catch buffer overruns.
+#include <windows.h>
+#include <stdlib.h>
+#include <wchar.h>
+#include "../gui/profile/profile.h"
+#include "pbtest.h"
+
+static void norm(const wchar_t* in, const wchar_t* want)
+{
+ wchar_t buf[1024]; wcscpy_s(buf, ARRAYSIZE(buf), in);
+ PB_ListNormalize(buf);
+ if (wcscmp(buf, want)) { g_fails++; wprintf(L" FAIL normalize [%ls] -> [%ls], wanted [%ls]\n", in, buf, want); }
+ g_checks++;
+}
+
+static void split(const wchar_t* in, const wchar_t* wantIps, const wchar_t* wantDoms)
+{
+ size_t n = wcslen(in) + 2;
+ wchar_t* a = (wchar_t*)malloc(n * sizeof(wchar_t)); wchar_t* d = (wchar_t*)malloc(n * sizeof(wchar_t));
+ PB_HostsSplit(in, a, n, d, n);
+ if (wcscmp(a, wantIps) || wcscmp(d, wantDoms))
+ { g_fails++; wprintf(L" FAIL split [%ls] -> ips[%ls] doms[%ls], wanted [%ls] [%ls]\n", in, a, d, wantIps, wantDoms); }
+ g_checks++;
+ free(a); free(d);
+}
+
+static void merge(const wchar_t* ips, const wchar_t* doms, const wchar_t* want)
+{
+ wchar_t out[512]; PB_HostsMerge(ips, doms, out, ARRAYSIZE(out));
+ if (wcscmp(out, want)) { g_fails++; wprintf(L" FAIL merge [%ls]+[%ls] -> [%ls], wanted [%ls]\n", ips ? ips : L"(null)", doms ? doms : L"(null)", out, want); }
+ g_checks++;
+}
+
+int main(void)
+{
+ /* ---- normalize: line breaks and blanks are formatting only ---- */
+ norm(L"google.com;\r\n*.google.com;\r\n*.gstatic.com;\r\ngithub.com;\r\n*.github.com;\r\n",
+ L"google.com;*.google.com;*.gstatic.com;github.com;*.github.com");
+ norm(L" a ; b ,c ", L"a;b;c");
+ norm(L"a\r\nb", L"ab"); /* a line break alone is NOT a separator */
+ norm(L";;;", L""); norm(L"", L""); norm(L" \r\n\t ", L"");
+ norm(L"a;;b;;;c;", L"a;b;c");
+ norm(L"*", L"*");
+ norm(L"a b ; c", L"a b;c"); /* blanks inside an entry are kept */
+ norm(L"\x01x\x02;y", L"x;y"); /* control characters are dropped */
+ { wchar_t o[64]; PB_ListFormat(L"a;b;c", o, ARRAYSIZE(o)); CHECK(wcscmp(o, L"a;\r\nb;\r\nc") == 0); }
+ { wchar_t o[64]; PB_ListFormat(L"", o, ARRAYSIZE(o)); CHECK(o[0] == 0); }
+ { /* normalize(format(x)) == x */
+ wchar_t f[128], x[64] = L"a.com;b.com;*.c.org"; PB_ListFormat(x, f, ARRAYSIZE(f)); PB_ListNormalize(f); CHECK(wcscmp(f, x) == 0); }
+
+ /* ---- split: entry type decides the key ---- */
+ split(L"10.0.0.0/8;github.com;*.google.com;2001:db8::/32;192.168.*.*", L"10.0.0.0/8;2001:db8::/32;192.168.*.*", L"github.com;*.google.com");
+ split(L"github.com", L"*", L"github.com");
+ split(L"10.0.0.0/8", L"10.0.0.0/8", L"*");
+ split(L"*", L"*", L"*"); split(L"", L"*", L"*");
+ split(L"a.com;*;10.0.0.1", L"*", L"*"); /* a "*" anywhere = any host */
+ split(L"1.2.3.4-1.2.3.9;10.1-5.*.7;fe80::1-fe80::ff;::1;example-site.org;my-1.2.com;abc.def;123.com",
+ L"1.2.3.4-1.2.3.9;10.1-5.*.7;fe80::1-fe80::ff;::1", L"example-site.org;my-1.2.com;abc.def;123.com");
+ split(L" 10.0.0.1 ; github.com ,x.org ", L"10.0.0.1", L"github.com;x.org");
+
+ /* ---- merge: a side that is empty or "*" adds nothing ---- */
+ merge(L"10.0.0.0/8", L"github.com", L"10.0.0.0/8;github.com");
+ merge(L"*", L"github.com", L"github.com"); merge(L"10.0.0.1", L"*", L"10.0.0.1");
+ merge(L"*", L"*", L"*"); merge(L"", L"", L"*"); merge(NULL, NULL, L"*");
+ { wchar_t m[256], a[256], d[256]; /* split(merge(i, d)) gives back i and d */
+ PB_HostsMerge(L"10.0.0.0/8;192.168.*.*", L"github.com;*.x.org", m, ARRAYSIZE(m));
+ PB_HostsSplit(m, a, ARRAYSIZE(a), d, ARRAYSIZE(d));
+ CHECK(wcscmp(a, L"10.0.0.0/8;192.168.*.*") == 0 && wcscmp(d, L"github.com;*.x.org") == 0); }
+ { wchar_t out[16]; /* too long for the buffer: whole entries only, terminated */
+ PB_HostsMerge(L"aaaa.com;bbbb.com", L"cccc.com;dddd.com", out, ARRAYSIZE(out));
+ size_t m = wcslen(out);
+ CHECK(m < 16 && (m == 0 || out[m - 1] != L';'));
+ CHECK(wcscmp(out, L"aaaa.com;bbbb.com") == 0 || wcscmp(out, L"aaaa.com") == 0 || wcscmp(out, L"*") == 0); }
+
+ /* ---- random input: never grows, never overruns, always terminated, well formed ---- */
+ srand(777);
+ const wchar_t alpha[] = L"ab01.*-:/;, \r\n\tfZ\x01";
+ for (int it = 0; it < 100000; it++)
+ {
+ int n = rand() % 70; wchar_t* in = (wchar_t*)malloc(((size_t)n + 1 + 8) * sizeof(wchar_t));
+ for (int i = 0; i < n; i++) in[i] = alpha[rand() % (int)(ARRAYSIZE(alpha) - 1)];
+ in[n] = 0; for (int i = n + 1; i < n + 9; i++) in[i] = 0x7777;
+ PB_ListNormalize(in);
+ size_t m = wcslen(in);
+ if (m > (size_t)n) { g_fails++; puts(" FAIL normalize grew the text"); }
+ for (int i = n + 1; i < n + 9; i++) if (in[i] != 0x7777) { g_fails++; puts(" FAIL normalize wrote past the end"); break; }
+ for (size_t i = 0; i < m; i++) if (in[i] < L' ' || in[i] == L',') { g_fails++; puts(" FAIL normalize left a control char or comma"); break; }
+ if (m && (in[0] == L';' || in[m - 1] == L';' || in[0] == L' ' || in[m - 1] == L' ')) { g_fails++; puts(" FAIL normalize left an edge separator/blank"); }
+
+ size_t k = m + 2; wchar_t* a = (wchar_t*)malloc((k + 4) * sizeof(wchar_t)); wchar_t* d = (wchar_t*)malloc((k + 4) * sizeof(wchar_t));
+ for (size_t i = k; i < k + 4; i++) { a[i] = 0x7777; d[i] = 0x7777; }
+ PB_HostsSplit(in, a, k, d, k); /* exact-size buffers */
+ for (size_t i = k; i < k + 4; i++) if (a[i] != 0x7777 || d[i] != 0x7777) { g_fails++; puts(" FAIL split overran its buffers"); break; }
+ if (!a[0] || !d[0]) { g_fails++; puts(" FAIL split produced an empty side (must be *)"); }
+ free(in); free(a); free(d);
+ }
+ g_checks += 100000;
+
+ return pbtest_done("test_hosts");
+}
diff --git a/Windows/tests/test_json.c b/Windows/tests/test_json.c
new file mode 100644
index 0000000..3fa5f91
--- /dev/null
+++ b/Windows/tests/test_json.c
@@ -0,0 +1,96 @@
+// test_json.c - the small JSON parser/writer behind profiles and settings (gui\profile\json.h).
+// Covers valid documents, escapes, malformed and truncated input, the nesting limit, huge values, the writer's
+// escaping (and that what it writes parses back to the same text), and random garbage read through a guard page.
+#include <stdlib.h>
+#include <string.h>
+#include "../gui/profile/json.h"
+#include "pbtest.h"
+
+static JVal* P(const char* s) { return json_parse(s, strlen(s)); }
+
+int main(void)
+{
+ /* ---- valid documents ---- */
+ { JVal* v = P("{\"a\": 1, \"b\": \"text\", \"c\": true, \"d\": false, \"e\": null, \"f\": [1, 2, 3], \"g\": {\"h\": \"i\"}, \"n\": -12.5e1}");
+ CHECK(v && v->type == J_OBJ);
+ CHECK(json_long(v, "a", 0) == 1 && !strcmp(json_str(v, "b", ""), "text") && json_bool(v, "c", 0) == 1 && json_bool(v, "d", 1) == 0);
+ CHECK(json_get(v, "f") && json_get(v, "f")->type == J_ARR && json_get(v, "g")->type == J_OBJ);
+ CHECK(json_long(v, "n", 0) == -125);
+ CHECK(json_get(v, "missing") == NULL && json_long(v, "missing", 42) == 42 && !strcmp(json_str(v, "missing", "dflt"), "dflt") && json_bool(v, "missing", 1) == 1);
+ CHECK(json_long(v, "b", 7) == 7 || json_long(v, "b", 7) == 0); /* wrong type: a default, never a crash */
+ json_free(v); }
+ { JVal* v = P(" \r\n\t [ ] "); CHECK(v && v->type == J_ARR && v->child == NULL); json_free(v); }
+ { JVal* v = P("{}"); CHECK(v && v->type == J_OBJ && v->child == NULL); json_free(v); }
+
+ /* ---- string escapes ---- */
+ { JVal* v = P("{\"s\": \"a\\nb\\r\\tc\\\"d\\\\e\\/f\\bg\\fh\"}");
+ CHECK(v && !strcmp(json_str(v, "s", ""), "a\nb\r\tc\"d\\e/f\bg\fh")); json_free(v); }
+ { JVal* v = P("{\"s\": \"\\u0041\\u00e9\\u20ac\"}"); /* A, e-acute, euro sign */
+ CHECK(v && !strcmp(json_str(v, "s", ""), "A\xC3\xA9\xE2\x82\xAC")); json_free(v); }
+ { JVal* v = P("{\"s\": \"caf\xC3\xA9 \xE4\xB8\xAD\xE6\x96\x87\"}"); /* raw UTF-8 passes through */
+ CHECK(v && !strcmp(json_str(v, "s", ""), "caf\xC3\xA9 \xE4\xB8\xAD\xE6\x96\x87")); json_free(v); }
+ { JVal* v = P("{\"s\": \"x\\u12\"}"); CHECK(v == NULL || json_str(v, "s", NULL) == NULL || 1); json_free(v); } /* short \u escape: no crash */
+ { JVal* v = P("{\"s\": \"\\uZZZZ\"}"); json_free(v); CHECK(TRUE); } /* non-hex \u escape: no crash */
+ { JVal* v = P("{\"k\": \"unterminated"); json_free(v); CHECK(TRUE); }
+
+ /* ---- malformed and truncated documents never crash (guard page after the last byte) ---- */
+ { const char* docs[] = { "", " ", "{", "[", "{\"a\"", "{\"a\":", "{\"a\": 1,", "{\"a\": 1 \"b\": 2}", "[1,,2]", "[1 2]", "}", "]", "nul", "tru", "-", "\"", "\\",
+ "{\"a\": [1, 2", "{\"a\": {\"b\": {\"c\": " };
+ for (size_t i = 0; i < sizeof docs / sizeof *docs; i++)
+ { void* b; size_t n = strlen(docs[i]); BYTE* g = pb_guarded(docs[i], n, &b); JVal* v = json_parse((const char*)g, n); json_free(v); pb_guard_release(b); }
+ CHECK(TRUE); }
+ { const char* full = "{\"Version\": \"1.0\", \"ProxyRules\": [{\"Name\": \"a\", \"IsEnabled\": true, \"ProxyConfigId\": 12}, {\"Name\": \"b\\u00e9\"}], \"x\": [1, 2.5, null, false]}";
+ size_t n = strlen(full);
+ for (size_t cut = 0; cut <= n; cut++) /* every prefix, parsed from a buffer that ends exactly there */
+ { void* b; BYTE* g = pb_guarded(full, cut, &b); JVal* v = json_parse((const char*)g, cut); json_free(v); pb_guard_release(b); }
+ CHECK(TRUE); }
+
+ /* ---- nesting limit: deep documents are refused without exhausting the stack ---- */
+ { char deep[400]; int d = J_MAX_DEPTH;
+ memset(deep, '[', d); memset(deep + d, ']', d); deep[2 * d] = 0;
+ JVal* ok = P(deep); CHECK(ok != NULL); json_free(ok); /* exactly at the limit */
+ memset(deep, '[', d + 1); memset(deep + d + 1, ']', d + 1); deep[2 * (d + 1)] = 0;
+ JVal* over = P(deep); CHECK(over == NULL); json_free(over); } /* one more level: rejected */
+ { size_t n = 2000000; char* deep = (char*)malloc(n + 1); memset(deep, '[', n); deep[n] = 0; /* two million opening brackets */
+ JVal* v = json_parse(deep, n); CHECK(v == NULL); json_free(v); free(deep); }
+ { size_t n = 400000; char* deep = (char*)malloc(n + 1); for (size_t i = 0; i < n; i += 2) { deep[i] = '{'; deep[i + 1] = '"'; } deep[n] = 0;
+ JVal* v = json_parse(deep, n); json_free(v); free(deep); CHECK(TRUE); } /* nested objects with unterminated keys */
+
+ /* ---- big values ---- */
+ { size_t n = 6 * 1024 * 1024; char* s = (char*)malloc(n + 64); strcpy_s(s, 16, "{\"big\": \""); memset(s + 9, 'x', n); strcpy_s(s + 9 + n, 8, "\"}");
+ JVal* v = json_parse(s, 9 + n + 2); CHECK(v && strlen(json_str(v, "big", "")) == n); json_free(v); free(s); }
+ { StrBuf b; sb_init(&b); sb_put(&b, "["); for (int i = 0; i < 50000; i++) { if (i) sb_put(&b, ","); sb_put(&b, "{\"k\":1}"); } sb_put(&b, "]");
+ JVal* v = json_parse(b.buf, b.len); int cnt = 0; for (JVal* c = v ? v->child : NULL; c; c = c->next) cnt++; CHECK(cnt == 50000); json_free(v); sb_free(&b); }
+
+ /* ---- writer: escaping, and write -> parse gives back the same text ---- */
+ { StrBuf b; sb_init(&b); sb_json_str(&b, "q\"uote \\ back\nline\r\ttab\x01\x1f \xC3\xA9\xE4\xB8\xAD");
+ CHECK(strstr(b.buf, "\\\"") && strstr(b.buf, "\\\\") && strstr(b.buf, "\\n") && strstr(b.buf, "\\r") && strstr(b.buf, "\\t") && strstr(b.buf, "\\u0001") && strstr(b.buf, "\\u001f"));
+ CHECK(b.buf[0] == '"' && b.buf[b.len - 1] == '"');
+ sb_free(&b); }
+ { StrBuf b; sb_init(&b); sb_json_str(&b, NULL); CHECK(!strcmp(b.buf, "\"\"")); sb_free(&b); }
+ srand(31337);
+ for (int it = 0; it < 20000; it++)
+ {
+ char s[80]; int n = rand() % 70;
+ for (int i = 0; i < n; i++) { int r = rand() % 10; s[i] = (char)(r < 6 ? 0x20 + rand() % 0x5F : r < 8 ? "\"\\/\n\r\t\b\f"[rand() % 8] : 1 + rand() % 31); }
+ s[n] = 0;
+ StrBuf b; sb_init(&b); sb_put(&b, "{\"k\": "); sb_json_str(&b, s); sb_put(&b, "}");
+ JVal* v = json_parse(b.buf, b.len);
+ if (!v || strcmp(json_str(v, "k", "\x7f"), s)) { g_fails++; printf(" FAIL round trip of a %d-character string\n", n); }
+ json_free(v); sb_free(&b);
+ }
+ g_checks += 20000;
+
+ /* ---- random garbage and mutated documents (guard page): never crash, never hang ---- */
+ { const char* seed = "{\"A\": [1, true, null, \"s\\n\\u0041\"], \"B\": {\"C\": -1.5e3}}"; size_t sl = strlen(seed);
+ for (int it = 0; it < 40000; it++)
+ {
+ char buf[200]; size_t n;
+ if (it % 2) { n = (size_t)(rand() % 120); for (size_t i = 0; i < n; i++) buf[i] = (char)(rand() % 3 ? "{}[]\",:\\ 0123456789tfnul-.e"[rand() % 26] : rand()); }
+ else { n = sl; memcpy(buf, seed, sl); int fl = 1 + rand() % 4; for (int f = 0; f < fl; f++) buf[rand() % sl] = (char)(rand() % 4 ? "{}[]\",:\\"[rand() % 8] : rand()); if (it % 4 == 0) n = (size_t)(rand() % (int)(sl + 1)); }
+ void* b; BYTE* g = pb_guarded(buf, n, &b); JVal* v = json_parse((const char*)g, n); json_free(v); pb_guard_release(b);
+ }
+ g_checks += 40000; }
+
+ return pbtest_done("test_json");
+}
diff --git a/Windows/tests/test_main_ui.c b/Windows/tests/test_main_ui.c
new file mode 100644
index 0000000..9299ef7
--- /dev/null
+++ b/Windows/tests/test_main_ui.c
@@ -0,0 +1,99 @@
+// test_main_ui.c - creates the REAL main window (same setup as wWinMain, engine stubbed) and drives the menu:
+// Proxy -> Enable ProxyBridge (the main switch) menu item, title "(PAUSED)", tray tooltip, engine call, language rebuild
+// Settings -> Log Every Connection default off, toggles, tells the engine, saved with the profile
+// Needs a desktop session (it creates real windows).
+#define wWinMain pb_real_wWinMain
+#include "../gui/main.c"
+#undef wWinMain
+#include "pbtest.h"
+
+static int g_enabledCalls = 0, g_logAllCalls = 0;
+static BOOL g_lastEnabledArg = TRUE, g_lastLogAllArg = FALSE;
+static void StubSetEnabled(BOOL v) { g_enabledCalls++; g_lastEnabledArg = v; }
+static void StubSetLogAll(BOOL v) { g_logAllCalls++; g_lastLogAllArg = v; }
+static void StubSetTraffic(BOOL v) { (void)v; }
+static void StubSetLog(PBLogCallback cb) { (void)cb; }
+static void StubSetConn(PBConnectionCallback cb) { (void)cb; }
+
+static PBProfile g_probe;
+
+static BOOL MenuChecked(HWND h, UINT id) { UINT st = GetMenuState(GetMenu(h), id, MF_BYCOMMAND); return st != (UINT)-1 && (st & MF_CHECKED); }
+static BOOL MenuExists(HWND h, UINT id) { return GetMenuState(GetMenu(h), id, MF_BYCOMMAND) != (UINT)-1; }
+
+int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrev, PWSTR cmd, int show)
+{
+ (void)hPrev; (void)cmd; (void)show;
+ setvbuf(stdout, NULL, _IONBF, 0);
+ g_hInst = hInst;
+ wchar_t tmp[MAX_PATH]; GetTempPathW(MAX_PATH, tmp);
+ wchar_t sub[64]; _snwprintf_s(sub, 64, _TRUNCATE, L"pbtest_mainui_%lu", GetCurrentProcessId()); wcscat_s(tmp, MAX_PATH, sub);
+ CreateDirectoryW(tmp, NULL); SetEnvironmentVariableW(L"APPDATA", tmp);
+ wcscpy_s(g_activeProfile, PB_NAME_MAX, L"uitest");
+ INITCOMMONCONTROLSEX icc = { sizeof(icc), ICC_TAB_CLASSES | ICC_LISTVIEW_CLASSES | ICC_BAR_CLASSES | ICC_STANDARD_CLASSES | ICC_LINK_CLASS | ICC_PROGRESS_CLASS };
+ InitCommonControlsEx(&icc);
+ PB_ProfileDefaults(&g_profile, L"uitest");
+ g_api.SetEnabled = StubSetEnabled; g_api.SetTrafficLoggingEnabled = StubSetTraffic; g_api.SetLogEveryConnection = StubSetLogAll;
+ g_api.SetLogCallback = StubSetLog; g_api.SetConnectionCallback = StubSetConn;
+
+ CreateDarkBrushes();
+ WNDCLASSEXW wc; ZeroMemory(&wc, sizeof(wc));
+ wc.cbSize = sizeof(wc); wc.lpfnWndProc = WndProc; wc.hInstance = hInst;
+ wc.hIcon = (HICON)LoadImageW(hInst, MAKEINTRESOURCEW(IDI_APPICON), IMAGE_ICON, 0, 0, LR_DEFAULTSIZE); wc.hIconSm = wc.hIcon;
+ wc.hCursor = LoadCursorW(NULL, IDC_ARROW); wc.hbrBackground = g_brBg; wc.lpszClassName = WND_CLASS;
+ CHECK(RegisterClassExW(&wc) != 0);
+ g_hMain = CreateWindowExW(0, WND_CLASS, APP_TITLE, WS_OVERLAPPEDWINDOW, 100, 100, 1000, 700, NULL, NULL, hInst, NULL);
+ CHECK(g_hMain != NULL);
+ BuildMainMenu(g_hMain); DrawMenuBar(g_hMain); TrayAdd(g_hMain); SyncMenuChecks(g_hMain); RebuildProfileMenu(g_hMain); UpdateTitle();
+ g_api.SetEnabled(g_proxyEnabled); /* what startup does */
+
+ /* 1. on by default: the item exists, is checked, and nothing says "paused" */
+ wchar_t title[256]; GetWindowTextW(g_hMain, title, 256);
+ CHECK(MenuExists(g_hMain, IDM_PROXY_ENABLE) && MenuChecked(g_hMain, IDM_PROXY_ENABLE));
+ CHECK(g_proxyEnabled == TRUE && g_lastEnabledArg == TRUE);
+ CHECK(wcsstr(title, L"PAUSED") == NULL && wcsstr(g_tray.szTip, L"PAUSED") == NULL);
+
+ /* 2. switch off */
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDM_PROXY_ENABLE, 0), 0);
+ GetWindowTextW(g_hMain, title, 256);
+ CHECK(g_proxyEnabled == FALSE && g_lastEnabledArg == FALSE && g_enabledCalls == 2); /* told the engine */
+ CHECK(!MenuChecked(g_hMain, IDM_PROXY_ENABLE));
+ CHECK(wcsstr(title, L"PAUSED") != NULL && wcsstr(title, g_activeProfile) != NULL);
+ CHECK(g_trayAdded ? wcsstr(g_tray.szTip, L"PAUSED") != NULL : TRUE);
+ CHECK(wcsncmp(g_tray.szTip, APP_TITLE, wcslen(APP_TITLE)) == 0);
+
+ /* 3. switch back on */
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDM_PROXY_ENABLE, 0), 0);
+ GetWindowTextW(g_hMain, title, 256);
+ CHECK(g_proxyEnabled == TRUE && g_lastEnabledArg == TRUE && g_enabledCalls == 3);
+ CHECK(MenuChecked(g_hMain, IDM_PROXY_ENABLE));
+ CHECK(wcsstr(title, L"PAUSED") == NULL && wcsstr(g_tray.szTip, L"PAUSED") == NULL);
+
+ /* 4. the paused state survives a menu rebuild (language switch) and shows the translated marker */
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDM_PROXY_ENABLE, 0), 0); /* off again */
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDM_LANG_ZH, 0), 0);
+ CHECK(MenuExists(g_hMain, IDM_PROXY_ENABLE) && !MenuChecked(g_hMain, IDM_PROXY_ENABLE));
+ GetWindowTextW(g_hMain, title, 256);
+ CHECK(wcsstr(title, L"\x5df2\x6682\x505c") != NULL);
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDM_LANG_EN, 0), 0);
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDM_PROXY_ENABLE, 0), 0); /* on */
+ CHECK(MenuChecked(g_hMain, IDM_PROXY_ENABLE) && g_proxyEnabled);
+
+ /* 5. Log Every Connection: off by default, toggles, tells the engine, saved with the profile */
+ CHECK(MenuExists(g_hMain, IDM_SET_LOGALL));
+ CHECK(!MenuChecked(g_hMain, IDM_SET_LOGALL) && g_logEvery == FALSE && g_profile.logEveryConnection == 0);
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDM_SET_LOGALL, 0), 0);
+ CHECK(g_logEvery == TRUE && g_lastLogAllArg == TRUE && g_logAllCalls == 1);
+ CHECK(MenuChecked(g_hMain, IDM_SET_LOGALL) && g_profile.logEveryConnection == 1);
+ PB_ProfileLoad(g_activeProfile, &g_probe); /* it was saved */
+ CHECK(g_probe.logEveryConnection == 1);
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDM_SET_LOGALL, 0), 0);
+ CHECK(g_logEvery == FALSE && g_lastLogAllArg == FALSE && !MenuChecked(g_hMain, IDM_SET_LOGALL));
+ PB_ProfileLoad(g_activeProfile, &g_probe);
+ CHECK(g_probe.logEveryConnection == 0);
+ PB_ProfileDefaults(&g_probe, L"x"); /* a profile without the key: off */
+ CHECK(g_probe.logEveryConnection == 0);
+
+ TrayRemove();
+ DestroyWindow(g_hMain);
+ return pbtest_done("test_main_ui");
+}
diff --git a/Windows/tests/test_profile.c b/Windows/tests/test_profile.c
new file mode 100644
index 0000000..47aa6fc
--- /dev/null
+++ b/Windows/tests/test_profile.c
@@ -0,0 +1,126 @@
+// test_profile.c - profile files (gui\profile\profile.c): loading old-format files, saving the cross-platform
+// format, long Target Hosts lists, per-rule localhost, Log Every Connection, and hostile (oversized) input.
+// Uses a private %APPDATA% so the real profiles are never touched.
+#include <windows.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../gui/profile/profile.h"
+#include "pbtest.h"
+
+static PBProfile g, h; /* a profile is large (many rules x long host lists): keep them off the stack */
+
+static void write_file(const wchar_t* path, const char* txt)
+{
+ HANDLE f = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
+ DWORD w; WriteFile(f, txt, (DWORD)strlen(txt), &w, NULL); CloseHandle(f);
+}
+static char* read_file(const wchar_t* path)
+{
+ HANDLE f = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
+ if (f == INVALID_HANDLE_VALUE) return _strdup("");
+ DWORD n = GetFileSize(f, NULL), r; char* b = (char*)malloc(n + 1); ReadFile(f, b, n, &r, NULL); b[n] = 0; CloseHandle(f); return b;
+}
+static void rm_tree(const wchar_t* dir)
+{
+ wchar_t pat[MAX_PATH]; _snwprintf_s(pat, MAX_PATH, _TRUNCATE, L"%s\\*", dir);
+ WIN32_FIND_DATAW fd; HANDLE f = FindFirstFileW(pat, &fd);
+ if (f != INVALID_HANDLE_VALUE)
+ {
+ do {
+ if (!wcscmp(fd.cFileName, L".") || !wcscmp(fd.cFileName, L"..")) continue;
+ wchar_t p[MAX_PATH]; _snwprintf_s(p, MAX_PATH, _TRUNCATE, L"%s\\%s", dir, fd.cFileName);
+ if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) rm_tree(p); else DeleteFileW(p);
+ } while (FindNextFileW(f, &fd));
+ FindClose(f);
+ }
+ RemoveDirectoryW(dir);
+}
+
+int main(void)
+{
+ wchar_t root[MAX_PATH]; GetTempPathW(MAX_PATH, root);
+ wchar_t sub[64]; _snwprintf_s(sub, 64, _TRUNCATE, L"pbtest_profile_%lu", GetCurrentProcessId());
+ wcscat_s(root, MAX_PATH, sub);
+ CreateDirectoryW(root, NULL); SetEnvironmentVariableW(L"APPDATA", root);
+ wchar_t dir[MAX_PATH], pdir[MAX_PATH];
+ _snwprintf_s(dir, MAX_PATH, _TRUNCATE, L"%s\\ProxyBridge", root); CreateDirectoryW(dir, NULL);
+ _snwprintf_s(pdir, MAX_PATH, _TRUNCATE, L"%s\\profiles", dir); CreateDirectoryW(pdir, NULL);
+ wchar_t p1[MAX_PATH]; _snwprintf_s(p1, MAX_PATH, _TRUNCATE, L"%s\\old.pbprofile", pdir);
+
+ /* 1. an old-format profile: one global LocalhostViaProxy, IPs and domains in two keys, a domain typed in TargetHosts,
+ and a stray line break inside the domains */
+ write_file(p1, "{\"Version\":\"1.0\",\"LocalhostViaProxy\":true,\"ProxyRules\":["
+ "{\"Name\":\"a\",\"ProcessName\":\"chrome.exe\",\"TargetHosts\":\"10.*.*.*\",\"TargetPorts\":\"*\",\"TargetDomains\":\"github.com;\\r\\n*.google.com\",\"Protocol\":\"TCP\",\"Action\":\"PROXY\",\"IsEnabled\":true,\"ProxyConfigId\":1},"
+ "{\"Name\":\"b\",\"ProcessName\":\"x.exe\",\"TargetHosts\":\"example.org;192.168.*.*\",\"TargetPorts\":\"*\",\"TargetDomains\":\"*\",\"Protocol\":\"TCP\",\"Action\":\"DIRECT\",\"IsEnabled\":true,\"ProxyConfigId\":0},"
+ "{\"Name\":\"c\",\"ProcessName\":\"y.exe\",\"TargetHosts\":\"*\",\"TargetPorts\":\"*\",\"TargetDomains\":\"*\",\"Protocol\":\"TCP\",\"Action\":\"DIRECT\",\"IsEnabled\":true,\"ProxyConfigId\":0}]}");
+ PB_ProfileLoad(L"old", &g);
+ CHECK(g.ruleCount == 3);
+ CHECK(wcscmp(g.rule[0].hosts, L"10.*.*.*;github.com;*.google.com") == 0); /* IPs + domains merged into one list */
+ CHECK(wcsstr(g.rule[1].hosts, L"example.org") && wcsstr(g.rule[1].hosts, L"192.168.*.*"));
+ CHECK(wcscmp(g.rule[2].hosts, L"*") == 0);
+ CHECK(g.rule[0].localhost == 1 && g.rule[1].localhost == 1); /* the old global value became each rule's default */
+ CHECK(g.logEveryConnection == 0); /* a setting the old file does not have: off */
+
+ /* 2. saving writes the two keys other ProxyBridge apps read; a domain typed with the IPs lands in TargetDomains */
+ CHECK(PB_ProfileSave(L"new", &g));
+ wchar_t p2[MAX_PATH]; _snwprintf_s(p2, MAX_PATH, _TRUNCATE, L"%s\\new.pbprofile", pdir);
+ char* js = read_file(p2);
+ CHECK(strstr(js, "\"TargetHosts\": \"10.*.*.*\"") != NULL);
+ CHECK(strstr(js, "\"TargetDomains\": \"github.com;*.google.com\"") != NULL);
+ CHECK(strstr(js, "\"TargetHosts\": \"192.168.*.*\"") != NULL);
+ CHECK(strstr(js, "\"TargetDomains\": \"example.org\"") != NULL);
+ CHECK(strstr(js, "\"LocalhostViaProxy\": true") != NULL); /* now per rule */
+ free(js);
+ PB_ProfileLoad(L"new", &h);
+ CHECK(h.ruleCount == 3 && wcscmp(h.rule[0].hosts, g.rule[0].hosts) == 0);
+ CHECK(wcscmp(h.rule[1].hosts, L"192.168.*.*;example.org") == 0); /* same entries, IPs first */
+
+ /* 3. per-rule localhost and Log Every Connection round-trip */
+ memset(&g, 0, sizeof g);
+ g.ruleCount = 2; g.logEveryConnection = 1;
+ for (int i = 0; i < 2; i++)
+ {
+ PBRule* r = &g.rule[i];
+ wcscpy_s(r->name, 128, i ? L"b" : L"a"); wcscpy_s(r->proc, PB_APPS_MAX, L"*"); wcscpy_s(r->hosts, PB_HOSTS_MAX, L"*");
+ wcscpy_s(r->ports, 128, L"*"); wcscpy_s(r->proto, 8, L"TCP"); wcscpy_s(r->action, 16, L"PROXY"); r->enabled = 1; r->localhost = i; /* a: off, b: on */
+ }
+ CHECK(PB_ProfileSave(L"flags", &g));
+ PB_ProfileLoad(L"flags", &h);
+ CHECK(h.ruleCount == 2 && h.rule[0].localhost == 0 && h.rule[1].localhost == 1 && h.logEveryConnection == 1);
+
+ /* 4. a long list (about 8000 characters) survives save + load without truncation */
+ memset(&g, 0, sizeof g); g.ruleCount = 1;
+ PBRule* r0 = &g.rule[0];
+ wcscpy_s(r0->name, 128, L"big"); wcscpy_s(r0->proc, PB_APPS_MAX, L"*"); wcscpy_s(r0->ports, 128, L"*");
+ wcscpy_s(r0->proto, 8, L"TCP"); wcscpy_s(r0->action, 16, L"DIRECT"); r0->enabled = 1;
+ size_t o = 0; int n = 0;
+ while (o + 30 < 8000) o += swprintf(r0->hosts + o, PB_HOSTS_MAX - o, L"%lshost%d.example.org", o ? L";" : L"", n++);
+ size_t want = wcslen(r0->hosts);
+ CHECK(want > 7900);
+ CHECK(PB_ProfileSave(L"big", &g));
+ PB_ProfileLoad(L"big", &h);
+ CHECK(h.ruleCount == 1 && wcslen(h.rule[0].hosts) == want && wcscmp(h.rule[0].hosts, r0->hosts) == 0);
+
+ /* 5. hostile file: 40,000-character TargetHosts and TargetDomains - cut cleanly, no crash, always terminated */
+ char* huge = (char*)malloc(200000); size_t k = 0;
+ k += sprintf(huge + k, "{\"ProxyRules\":[{\"Name\":\"h\",\"ProcessName\":\"*\",\"TargetHosts\":\"");
+ for (int i = 0; k < 40000; i++) k += sprintf(huge + k, "a%d.org;", i);
+ k += sprintf(huge + k, "\",\"TargetPorts\":\"*\",\"TargetDomains\":\"");
+ for (int i = 0; k < 80000; i++) k += sprintf(huge + k, "b%d.net;", i);
+ k += sprintf(huge + k, "\",\"Protocol\":\"TCP\",\"Action\":\"DIRECT\"}]}");
+ wchar_t p3[MAX_PATH]; _snwprintf_s(p3, MAX_PATH, _TRUNCATE, L"%s\\huge.pbprofile", pdir); write_file(p3, huge); free(huge);
+ memset(&h, 0x55, sizeof h); /* poison: nothing may be left unterminated */
+ PB_ProfileLoad(L"huge", &h);
+ CHECK(h.ruleCount == 1 && wcslen(h.rule[0].hosts) < PB_HOSTS_MAX);
+ size_t hl = wcslen(h.rule[0].hosts); CHECK(hl > 0 && h.rule[0].hosts[hl - 1] != L';');
+ CHECK(PB_ProfileSave(L"huge2", &h));
+
+ /* 6. broken JSON does not crash and yields usable defaults */
+ wchar_t p4[MAX_PATH]; _snwprintf_s(p4, MAX_PATH, _TRUNCATE, L"%s\\broken.pbprofile", pdir);
+ write_file(p4, "{\"ProxyRules\": [ {\"Name\": \"x\", ");
+ PB_ProfileLoad(L"broken", &h);
+ CHECK(h.ruleCount >= 0 && h.ruleCount <= PB_MAX_RULE);
+
+ rm_tree(root);
+ return pbtest_done("test_profile");
+}
diff --git a/Windows/tests/test_proto.c b/Windows/tests/test_proto.c
new file mode 100644
index 0000000..fed0156
--- /dev/null
+++ b/Windows/tests/test_proto.c
@@ -0,0 +1,59 @@
+// test_proto.c - the wire protocol between the app and the engine service (src\service\pb_proto.h).
+// The reader/writer must reject malformed or hostile messages without overrunning anything.
+#include <windows.h>
+#include <string.h>
+#include <stdlib.h>
+#include "../src/service/pb_proto.h"
+#include "pbtest.h"
+
+int main(void)
+{
+ /* ---- writer ---- */
+ { BYTE buf[64]; PbW w; PbW_Init(&w, buf, sizeof buf);
+ PbW_U32(&w, 7); PbW_Str(&w, "abc"); PbW_Str(&w, NULL); PbW_Str(&w, "");
+ CHECK(w.ok && w.len == 4 + (4 + 3) + 4 + 4);
+ PbR r; PbR_Init(&r, buf, w.len); char s[16]; BOOL isNull;
+ CHECK(PbR_U32(&r) == 7);
+ PbR_Str(&r, s, sizeof s, &isNull); CHECK(r.ok && !isNull && strcmp(s, "abc") == 0);
+ PbR_Str(&r, s, sizeof s, &isNull); CHECK(r.ok && isNull && s[0] == 0); /* NULL string survives the trip */
+ PbR_Str(&r, s, sizeof s, &isNull); CHECK(r.ok && !isNull && s[0] == 0); /* empty string is not NULL */
+ CHECK(r.pos == r.len); }
+ { BYTE buf[8]; PbW w; PbW_Init(&w, buf, sizeof buf); /* writer overflow flips ok, never writes past */
+ PbW_U32(&w, 1); PbW_U32(&w, 2); CHECK(w.ok); PbW_U32(&w, 3); CHECK(!w.ok && w.len == 8); }
+ { BYTE buf[16]; PbW w; PbW_Init(&w, buf, sizeof buf); PbW_Str(&w, "0123456789abcdefXYZ"); CHECK(!w.ok); }
+ { static char big[PB_STR_MAX + 8]; memset(big, 'a', sizeof big - 1); big[sizeof big - 1] = 0;
+ static BYTE buf[PB_MSG_MAX]; PbW w; PbW_Init(&w, buf, sizeof buf); PbW_Str(&w, big); CHECK(!w.ok); } /* longer than PB_STR_MAX */
+
+ /* ---- reader: malformed input ---- */
+ { BYTE b[3] = {1, 2, 3}; PbR r; PbR_Init(&r, b, 3); PbR_U32(&r); CHECK(!r.ok); } /* too short for a u32 */
+ { BYTE b[8] = {0xFF, 0xFF, 0xFF, 0x7F, 'a', 'b', 'c', 'd'}; PbR r; PbR_Init(&r, b, 8); char s[8];
+ PbR_Str(&r, s, sizeof s, NULL); CHECK(!r.ok && s[0] == 0); } /* declared length far beyond the message */
+ { BYTE b[8] = {10, 0, 0, 0, 'a', 'b', 'c', 'd'}; PbR r; PbR_Init(&r, b, 8); char s[8];
+ PbR_Str(&r, s, sizeof s, NULL); CHECK(!r.ok); } /* length 10, only 4 bytes present */
+ { BYTE b[4 + PB_STR_MAX + 16]; UINT32 n = PB_STR_MAX + 1; memcpy(b, &n, 4); memset(b + 4, 'a', PB_STR_MAX + 1);
+ PbR r; PbR_Init(&r, b, sizeof b); char s[16]; PbR_Str(&r, s, sizeof s, NULL); CHECK(!r.ok); } /* above PB_STR_MAX */
+ { BYTE b[4 + 20]; UINT32 n = 20; memcpy(b, &n, 4); memset(b + 4, 'x', 20); /* reply bigger than the caller's buffer: truncated + terminated */
+ PbR r; PbR_Init(&r, b, sizeof b); char s[8]; memset(s, 0x55, sizeof s); PbR_Str(&r, s, sizeof s, NULL);
+ CHECK(r.ok && strlen(s) == 7 && s[7] == 0); }
+ { BYTE b[4]; PbR r; PbR_Init(&r, b, 0); CHECK(PbR_U32(&r) == 0 && !r.ok); char s[4]; PbR_Str(&r, s, sizeof s, NULL); CHECK(!r.ok); } /* empty message; stays failed */
+
+ /* ---- random messages: parsing never reads or writes outside its buffers ---- */
+ srand(4242);
+ for (int it = 0; it < 50000; it++)
+ {
+ int n = rand() % 48; BYTE* m = (BYTE*)malloc((size_t)n + 16);
+ for (int i = 0; i < n; i++) m[i] = (BYTE)(rand() % 3 ? rand() % 12 : rand()); /* small lengths are common, big ones rare */
+ PbR r; PbR_Init(&r, m, (DWORD)n);
+ for (int f = 0; f < 6; f++)
+ {
+ char s[12]; memset(s, 0x55, sizeof s);
+ if (f % 2) { PbR_U32(&r); }
+ else { PbR_Str(&r, s, sizeof s, NULL); size_t l = strnlen(s, sizeof s); if (l >= sizeof s) { g_fails++; puts(" FAIL unterminated string from reader"); } }
+ if (r.pos > r.len) { g_fails++; puts(" FAIL reader moved past the end"); break; }
+ }
+ free(m);
+ }
+ g_checks += 50000;
+
+ return pbtest_done("test_proto");
+}
diff --git a/Windows/tests/test_proxy_protocols.c b/Windows/tests/test_proxy_protocols.c
new file mode 100644
index 0000000..44be447
--- /dev/null
+++ b/Windows/tests/test_proxy_protocols.c
@@ -0,0 +1,222 @@
+// test_proxy_protocols.c - the proxy client handshakes (src\pb_socks5.c, src\pb_http.c) against a scripted fake
+// proxy server on loopback (ephemeral port, one short connection per case; no driver, no real proxy):
+// SOCKS5: greeting, username/password auth, CONNECT (IPv4, IPv6, domain), every reply code, every BND.ADDR type,
+// malformed and truncated replies, UDP ASSOCIATE
+// HTTP: CONNECT request format, Proxy-Authorization, status handling, cached host names, over-long requests
+#include "pb_internal.h"
+#include "pbtest.h"
+
+typedef struct {
+ BYTE method; /* SOCKS5: auth method the server picks (0 none, 2 user/pass, 0xFF unacceptable, ...) */
+ BYTE auth_status; /* SOCKS5: 0 = credentials accepted */
+ BYTE reply[600]; int reply_len; /* raw reply sent after the request (SOCKS5 reply / HTTP response) */
+ int close_at; /* 1 = close after the greeting, 2 = after auth, 3 = after the request without a reply */
+ BOOL http;
+ /* captured */
+ BYTE greeting[16]; int greeting_len;
+ char user[300], pass[300];
+ BYTE req[600]; int req_len;
+ char http_req[4096]; int http_len;
+} Script;
+
+typedef struct { SOCKET listener; Script* sc; HANDLE thread; } Srv;
+
+static BOOL rx(SOCKET s, BYTE* b, int n) { int got = 0; while (got < n) { int r = recv(s, (char*)b + got, n - got, 0); if (r <= 0) return FALSE; got += r; } return TRUE; }
+
+static DWORD WINAPI server_thread(LPVOID p)
+{
+ Srv* sv = (Srv*)p; Script* sc = sv->sc;
+ SOCKET c = accept(sv->listener, NULL, NULL);
+ if (c == INVALID_SOCKET) return 0;
+ DWORD to = 3000; setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, (char*)&to, sizeof to);
+ BYTE b[1100];
+
+ if (sc->http)
+ {
+ int n = 0;
+ while (n < (int)sizeof(sc->http_req) - 1)
+ {
+ int r = recv(c, sc->http_req + n, 1, 0); if (r <= 0) break; n++; sc->http_req[n] = 0;
+ if (n >= 4 && !strcmp(sc->http_req + n - 4, "\r\n\r\n")) break;
+ }
+ sc->http_len = n;
+ if (sc->reply_len) send(c, (char*)sc->reply, sc->reply_len, 0);
+ closesocket(c); return 0;
+ }
+
+ if (!rx(c, b, 2)) { closesocket(c); return 0; }
+ int nm = b[1]; if (nm > 14) nm = 14;
+ if (nm && !rx(c, b + 2, nm)) { closesocket(c); return 0; }
+ sc->greeting_len = 2 + nm; memcpy(sc->greeting, b, sc->greeting_len);
+ if (sc->close_at == 1) { closesocket(c); return 0; }
+ BYTE sel[2] = { 5, sc->method }; send(c, (char*)sel, 2, 0);
+ if (sc->method == 2)
+ {
+ if (!rx(c, b, 2)) { closesocket(c); return 0; }
+ int ul = b[1]; if (!rx(c, b + 2, ul + 1)) { closesocket(c); return 0; }
+ memcpy(sc->user, b + 2, ul); sc->user[ul] = 0;
+ int pl = b[2 + ul]; if (!rx(c, b + 3 + ul, pl)) { closesocket(c); return 0; }
+ memcpy(sc->pass, b + 3 + ul, pl); sc->pass[pl] = 0;
+ BYTE ar[2] = { 1, sc->auth_status }; send(c, (char*)ar, 2, 0);
+ if (sc->auth_status != 0 || sc->close_at == 2) { closesocket(c); return 0; }
+ }
+ else if (sc->method != 0) { closesocket(c); return 0; }
+
+ if (!rx(c, b, 4)) { closesocket(c); return 0; }
+ int rest = (b[3] == 1) ? 6 : (b[3] == 4) ? 18 : 0;
+ if (b[3] == 3) { if (!rx(c, b + 4, 1)) { closesocket(c); return 0; } rest = b[4] + 2; if (!rx(c, b + 5, rest)) { closesocket(c); return 0; } sc->req_len = 5 + rest; }
+ else { if (rest && !rx(c, b + 4, rest)) { closesocket(c); return 0; } sc->req_len = 4 + rest; }
+ memcpy(sc->req, b, sc->req_len);
+ if (sc->close_at != 3 && sc->reply_len) send(c, (char*)sc->reply, sc->reply_len, 0);
+ Sleep(20); /* let the client read the reply before the FIN */
+ closesocket(c); return 0;
+}
+
+/* starts the fake server and returns a connected client socket */
+static SOCKET start(Srv* sv, Script* sc)
+{
+ memset(sv, 0, sizeof *sv); sv->sc = sc;
+ sv->listener = socket(AF_INET, SOCK_STREAM, 0);
+ struct sockaddr_in a; memset(&a, 0, sizeof a); a.sin_family = AF_INET; a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ bind(sv->listener, (struct sockaddr*)&a, sizeof a); listen(sv->listener, 1);
+ int len = sizeof a; getsockname(sv->listener, (struct sockaddr*)&a, &len);
+ sv->thread = CreateThread(NULL, 0, server_thread, sv, 0, NULL);
+ SOCKET c = socket(AF_INET, SOCK_STREAM, 0);
+ DWORD to = 3000; setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, (char*)&to, sizeof to);
+ connect(c, (struct sockaddr*)&a, sizeof a);
+ return c;
+}
+static void finish(Srv* sv, SOCKET c) { closesocket(c); WaitForSingleObject(sv->thread, 8000); CloseHandle(sv->thread); closesocket(sv->listener); }
+
+static UINT32 ip4(const char* s) { struct in_addr a; inet_pton(AF_INET, s, &a); return a.S_un.S_addr; }
+static void set_reply(Script* sc, const BYTE* r, int n) { memcpy(sc->reply, r, n); sc->reply_len = n; }
+static void set_text(Script* sc, const char* t) { sc->reply_len = (int)strlen(t); memcpy(sc->reply, t, sc->reply_len); }
+
+/* one SOCKS5 IPv4 CONNECT with a given reply; returns the client's result */
+static int s5_v4(Script* sc, const PROXY_CONFIG* cfg)
+{
+ Srv sv; SOCKET c = start(&sv, sc);
+ int r = socks5_connect(c, ip4("1.2.3.4"), 443, cfg);
+ finish(&sv, c); return r;
+}
+static const BYTE OKREPLY[10] = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 };
+
+int main(void)
+{
+ WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa);
+ PROXY_CONFIG none; memset(&none, 0, sizeof none);
+ PROXY_CONFIG auth; memset(&auth, 0, sizeof auth); strcpy_s(auth.username, sizeof auth.username, "alice"); strcpy_s(auth.password, sizeof auth.password, "s3cret");
+ Script sc;
+
+ /* ---- SOCKS5 CONNECT, no authentication ---- */
+ memset(&sc, 0, sizeof sc); set_reply(&sc, OKREPLY, 10);
+ CHECK(s5_v4(&sc, &none) == 0);
+ CHECK(sc.greeting_len == 3 && sc.greeting[0] == 5 && sc.greeting[1] == 1 && sc.greeting[2] == 0); /* offers "no auth" only */
+ CHECK(sc.req_len == 10 && !memcmp(sc.req, "\x05\x01\x00\x01\x01\x02\x03\x04\x01\xBB", 10)); /* CONNECT 1.2.3.4:443 */
+
+ /* ---- username/password (RFC 1929) ---- */
+ memset(&sc, 0, sizeof sc); sc.method = 2; set_reply(&sc, OKREPLY, 10);
+ CHECK(s5_v4(&sc, &auth) == 0);
+ CHECK(sc.greeting_len == 4 && sc.greeting[1] == 2 && sc.greeting[2] == 0 && sc.greeting[3] == 2); /* offers none + user/pass */
+ CHECK(!strcmp(sc.user, "alice") && !strcmp(sc.pass, "s3cret"));
+ memset(&sc, 0, sizeof sc); sc.method = 2; sc.auth_status = 1; set_reply(&sc, OKREPLY, 10);
+ CHECK(s5_v4(&sc, &auth) == -1); /* wrong password */
+ memset(&sc, 0, sizeof sc); sc.method = 2; set_reply(&sc, OKREPLY, 10);
+ CHECK(s5_v4(&sc, &none) == -1); /* server wants auth, we have none */
+ memset(&sc, 0, sizeof sc); sc.method = 0xFF; set_reply(&sc, OKREPLY, 10);
+ CHECK(s5_v4(&sc, &none) == -1); /* no acceptable method */
+ memset(&sc, 0, sizeof sc); sc.method = 3; set_reply(&sc, OKREPLY, 10);
+ CHECK(s5_v4(&sc, &none) == -1); /* unsupported method */
+ { PROXY_CONFIG big = auth; memset(big.username, 'u', 255); big.username[255] = 0; memset(big.password, 'p', 255); big.password[255] = 0;
+ memset(&sc, 0, sizeof sc); sc.method = 2; set_reply(&sc, OKREPLY, 10);
+ CHECK(s5_v4(&sc, &big) == 0 && strlen(sc.user) == 255 && strlen(sc.pass) == 255); } /* longest credentials fit */
+
+ /* ---- every REP code is a failure ---- */
+ for (int rep = 1; rep <= 8; rep++)
+ {
+ BYTE r[10] = { 5, (BYTE)rep, 0, 1, 0, 0, 0, 0, 0, 0 };
+ memset(&sc, 0, sizeof sc); set_reply(&sc, r, 10);
+ CHECK(s5_v4(&sc, &none) == -1);
+ }
+
+ /* ---- BND.ADDR of any type is parsed and drained, whatever the request used ---- */
+ { BYTE r[22] = { 5, 0, 0, 4 }; memset(&sc, 0, sizeof sc); set_reply(&sc, r, 22); CHECK(s5_v4(&sc, &none) == 0); } /* IPv6 */
+ { BYTE r[8] = { 5, 0, 0, 3, 5, 'a', 'b', 'c' }; memcpy(r + 8 - 0, "", 0);
+ BYTE full[4 + 1 + 5 + 2] = { 5, 0, 0, 3, 5, 'a', 'b', 'c', 'd', 'e', 0, 80 }; memset(&sc, 0, sizeof sc); set_reply(&sc, full, sizeof full); CHECK(s5_v4(&sc, &none) == 0); (void)r; }
+ { BYTE full[4 + 1 + 255 + 2] = { 5, 0, 0, 3, 255 }; memset(&sc, 0, sizeof sc); set_reply(&sc, full, sizeof full); CHECK(s5_v4(&sc, &none) == 0); } /* longest domain */
+ { BYTE r[10] = { 5, 0, 0, 9, 0, 0, 0, 0, 0, 0 }; memset(&sc, 0, sizeof sc); set_reply(&sc, r, 10); CHECK(s5_v4(&sc, &none) == -1); } /* unknown ATYP */
+ { BYTE r[10] = { 4, 0, 0, 1, 0, 0, 0, 0, 0, 0 }; memset(&sc, 0, sizeof sc); set_reply(&sc, r, 10); CHECK(s5_v4(&sc, &none) == -1); } /* wrong version */
+ { BYTE r[6] = { 5, 0, 0, 1, 0, 0 }; memset(&sc, 0, sizeof sc); set_reply(&sc, r, 6); CHECK(s5_v4(&sc, &none) == -1); } /* truncated, then closed */
+ { BYTE r[3] = { 5, 0, 0 }; memset(&sc, 0, sizeof sc); set_reply(&sc, r, 3); CHECK(s5_v4(&sc, &none) == -1); }
+ memset(&sc, 0, sizeof sc); sc.close_at = 1; set_reply(&sc, OKREPLY, 10); CHECK(s5_v4(&sc, &none) == -1); /* server hangs up after the greeting */
+ memset(&sc, 0, sizeof sc); sc.close_at = 3; set_reply(&sc, OKREPLY, 10); CHECK(s5_v4(&sc, &none) == -1); /* ... or after the request, without a reply */
+
+ /* ---- CONNECT by domain name ---- */
+ { Srv sv; memset(&sc, 0, sizeof sc); set_reply(&sc, OKREPLY, 10);
+ SOCKET c = start(&sv, &sc); int r = socks5_connect_domain(c, "example.com", 8443, &none); finish(&sv, c);
+ CHECK(r == 0 && sc.req[3] == 3 && sc.req[4] == 11 && !memcmp(sc.req + 5, "example.com", 11) && sc.req[16] == 0x20 && sc.req[17] == 0xFB); }
+ { Srv sv; memset(&sc, 0, sizeof sc); set_reply(&sc, OKREPLY, 10);
+ SOCKET c = start(&sv, &sc); int r = socks5_connect_domain(c, "", 80, &none); finish(&sv, c); CHECK(r == -1); } /* empty name */
+ { char name[300]; memset(name, 'a', 299); name[299] = 0; Srv sv; memset(&sc, 0, sizeof sc); set_reply(&sc, OKREPLY, 10);
+ SOCKET c = start(&sv, &sc); int r = socks5_connect_domain(c, name, 80, &none); finish(&sv, c);
+ CHECK(r == 0 && sc.req[4] == 255 && sc.req_len == 5 + 255 + 2); } /* over-long name is cut to 255, never overflows */
+
+ /* ---- CONNECT by IPv6 address ---- */
+ { UINT8 a6[16]; inet_pton(AF_INET6, "2001:db8::7", a6); Srv sv; memset(&sc, 0, sizeof sc); set_reply(&sc, OKREPLY, 10);
+ SOCKET c = start(&sv, &sc); int r = socks5_connect_v6(c, a6, 443, &none); finish(&sv, c);
+ CHECK(r == 0 && sc.req[3] == 4 && !memcmp(sc.req + 4, a6, 16) && sc.req[20] == 0x01 && sc.req[21] == 0xBB); }
+
+ /* ---- UDP ASSOCIATE ---- */
+ { BYTE r[10] = { 5, 0, 0, 1, 127, 0, 0, 1, 0x15, 0xB3 }; /* relay 127.0.0.1:5555 */
+ Srv sv; memset(&sc, 0, sizeof sc); set_reply(&sc, r, 10);
+ SOCKET c = start(&sv, &sc); struct sockaddr_in ra; memset(&ra, 0, sizeof ra);
+ int rc = socks5_udp_associate_with_config(c, &ra, &none); finish(&sv, c);
+ CHECK(rc == 0 && sc.req[1] == 3 && ra.sin_family == AF_INET && ra.sin_addr.s_addr == htonl(INADDR_LOOPBACK) && ntohs(ra.sin_port) == 5555); }
+ { BYTE r[22] = { 5, 0, 0, 4 }; /* IPv6 relay endpoint cannot be used */
+ Srv sv; memset(&sc, 0, sizeof sc); set_reply(&sc, r, 22);
+ SOCKET c = start(&sv, &sc); struct sockaddr_in ra; memset(&ra, 0, sizeof ra); int rc = socks5_udp_associate_with_config(c, &ra, &none); finish(&sv, c); CHECK(rc == -1); }
+ { BYTE r[10] = { 5, 7, 0, 1, 0, 0, 0, 0, 0, 0 }; /* command not supported */
+ Srv sv; memset(&sc, 0, sizeof sc); set_reply(&sc, r, 10);
+ SOCKET c = start(&sv, &sc); struct sockaddr_in ra; memset(&ra, 0, sizeof ra); int rc = socks5_udp_associate_with_config(c, &ra, &none); finish(&sv, c); CHECK(rc == -1); }
+
+ /* ================= HTTP CONNECT ================= */
+ dns_cache_init();
+ { Srv sv; memset(&sc, 0, sizeof sc); sc.http = TRUE; set_text(&sc, "HTTP/1.1 200 Connection established\r\n\r\n");
+ SOCKET c = start(&sv, &sc); int r = http_connect(c, ip4("1.2.3.4"), 443, &none); finish(&sv, c);
+ CHECK(r == 0);
+ CHECK(strncmp(sc.http_req, "CONNECT 1.2.3.4:443 HTTP/1.1\r\n", 30) == 0 && strstr(sc.http_req, "Host: 1.2.3.4:443\r\n") && !strstr(sc.http_req, "Proxy-Authorization")); }
+ { Srv sv; memset(&sc, 0, sizeof sc); sc.http = TRUE; set_text(&sc, "HTTP/1.0 200 OK\r\n\r\n");
+ SOCKET c = start(&sv, &sc); int r = http_connect(c, ip4("1.2.3.4"), 443, &auth); finish(&sv, c);
+ CHECK(r == 0 && strstr(sc.http_req, "Proxy-Authorization: Basic YWxpY2U6czNjcmV0\r\n") != NULL); } /* base64("alice:s3cret") */
+ { const char* bad[] = { "HTTP/1.1 407 Proxy Authentication Required\r\n\r\n", "HTTP/1.1 502 Bad Gateway\r\n\r\n", "HTTP/1.1 403 Forbidden\r\n\r\n",
+ "SSH-2.0-OpenSSH_9.0\r\n", "HTTP/1.1\r\n\r\n", "HTTP/1.1 abc\r\n\r\n", "" };
+ for (int i = 0; i < 7; i++)
+ { Srv sv; memset(&sc, 0, sizeof sc); sc.http = TRUE; set_text(&sc, bad[i]);
+ SOCKET c = start(&sv, &sc); int r = http_connect(c, ip4("1.2.3.4"), 443, &none); finish(&sv, c); CHECK(r == -1); } }
+ /* a cached host name is used only when the proxy config asks for it */
+ dns_cache_store(ip4("93.184.216.34"), "example.com");
+ { PROXY_CONFIG withDomain = none; withDomain.send_domain_to_proxy = TRUE;
+ Srv sv; memset(&sc, 0, sizeof sc); sc.http = TRUE; set_text(&sc, "HTTP/1.1 200 OK\r\n\r\n");
+ SOCKET c = start(&sv, &sc); int r = http_connect(c, ip4("93.184.216.34"), 80, &withDomain); finish(&sv, c);
+ CHECK(r == 0 && strncmp(sc.http_req, "CONNECT example.com:80 HTTP/1.1", 31) == 0);
+ memset(&sc, 0, sizeof sc); sc.http = TRUE; set_text(&sc, "HTTP/1.1 200 OK\r\n\r\n");
+ c = start(&sv, &sc); r = http_connect(c, ip4("93.184.216.34"), 80, &none); finish(&sv, c);
+ CHECK(r == 0 && strncmp(sc.http_req, "CONNECT 93.184.216.34:80 HTTP/1.1", 33) == 0); }
+ { UINT8 a6[16]; inet_pton(AF_INET6, "2001:db8::7", a6); Srv sv; memset(&sc, 0, sizeof sc); sc.http = TRUE; set_text(&sc, "HTTP/1.1 200 OK\r\n\r\n");
+ SOCKET c = start(&sv, &sc); int r = http_connect_v6(c, a6, 443, &none); finish(&sv, c);
+ CHECK(r == 0 && strncmp(sc.http_req, "CONNECT [2001:db8::7]:443 HTTP/1.1", 34) == 0); }
+
+ /* a request that does not fit its buffer (very long credentials AND a very long cached name) must be refused:
+ send() must never be asked for more bytes than the buffer holds (that would leak stack memory to the proxy) */
+ { PROXY_CONFIG big = auth; big.send_domain_to_proxy = TRUE;
+ memset(big.username, 'u', 255); big.username[255] = 0; memset(big.password, 'p', 255); big.password[255] = 0;
+ char longname[256]; memset(longname, 'n', 240); strcpy_s(longname + 240, sizeof longname - 240, ".example.com");
+ dns_cache_store(ip4("203.0.113.9"), longname);
+ Srv sv; memset(&sc, 0, sizeof sc); sc.http = TRUE; set_text(&sc, "HTTP/1.1 200 OK\r\n\r\n");
+ SOCKET c = start(&sv, &sc); int r = http_connect(c, ip4("203.0.113.9"), 443, &big); finish(&sv, c);
+ CHECK(r == -1);
+ CHECK(sc.http_len <= HTTP_BUFFER_SIZE); }
+
+ WSACleanup();
+ return pbtest_done("test_proxy_protocols");
+}
diff --git a/Windows/tests/test_rules_match.c b/Windows/tests/test_rules_match.c
new file mode 100644
index 0000000..c8f1d2e
--- /dev/null
+++ b/Windows/tests/test_rules_match.c
@@ -0,0 +1,116 @@
+// test_rules_match.c - the individual matchers of the rule engine (src\pb_rules.c) and the rule list API:
+// IPv4 / IPv6 patterns, port lists, process patterns (names, paths, wildcards), domain patterns and lists,
+// rule ordering (first match wins, fully wildcard process rules last), Add/Edit/Delete/Move validation.
+#include "pb_internal.h"
+#include "pbtest.h"
+
+static UINT32 ip4(const char* s) { struct in_addr a; inet_pton(AF_INET, s, &a); return a.S_un.S_addr; }
+static BOOL v6(const char* pat, const char* addr) { UINT8 a[16]; inet_pton(AF_INET6, addr, a); return match_ip_pattern_v6(pat, a); }
+static RuleAction m4(const char* proc, const char* ip, int port) { UINT32 id = 0; return match_rule(proc, ip4(ip), (UINT16)port, FALSE, &id); }
+
+int main(void)
+{
+ /* ================= IPv4 patterns ================= */
+ CHECK(match_ip_pattern("192.168.1.1", ip4("192.168.1.1")) && !match_ip_pattern("192.168.1.1", ip4("192.168.1.2")));
+ CHECK(match_ip_pattern("192.168.*.*", ip4("192.168.77.8")) && !match_ip_pattern("192.168.*.*", ip4("192.169.1.1")));
+ CHECK(match_ip_pattern("*.*.*.*", ip4("8.8.4.4")) && match_ip_pattern("*", ip4("8.8.4.4")) && match_ip_pattern(NULL, ip4("8.8.4.4")));
+ CHECK(match_ip_pattern("10.*.*.7", ip4("10.1.2.7")) && !match_ip_pattern("10.*.*.7", ip4("10.1.2.8")));
+ CHECK(!match_ip_pattern("10.0.0.5-10.0.0.9", ip4("10.0.0.4")) && match_ip_pattern("10.0.0.5-10.0.0.9", ip4("10.0.0.5")) &&
+ match_ip_pattern("10.0.0.5-10.0.0.9", ip4("10.0.0.9")) && !match_ip_pattern("10.0.0.5-10.0.0.9", ip4("10.0.0.10"))); /* inclusive */
+ CHECK(match_ip_pattern("10.1.0.0-10.5.255.255", ip4("10.3.9.9")) && !match_ip_pattern("10.1.0.0-10.5.255.255", ip4("10.6.0.0"))); /* crosses octets */
+ CHECK(!match_ip_pattern("10.0.0.9-10.0.0.5", ip4("10.0.0.7"))); /* reversed range */
+ CHECK(!match_ip_pattern("10.0.0", ip4("10.0.0.1")) && !match_ip_pattern("", ip4("10.0.0.1")) && !match_ip_pattern("abc", ip4("1.1.1.1")));
+ { char longp[400]; memset(longp, '1', 399); longp[399] = 0; CHECK(!match_ip_pattern(longp, ip4("1.1.1.1"))); } /* oversize: no crash */
+ CHECK(match_ip_list("192.168.1.1;10.0.0.1", ip4("10.0.0.1")) && !match_ip_list("192.168.1.1;10.0.0.1", ip4("11.0.0.1")));
+ CHECK(match_ip_list("192.168.1.1; 10.0.0.1", ip4("10.0.0.1"))); /* a blank after ';' is fine */
+ CHECK(match_ip_list("", ip4("1.1.1.1")) && match_ip_list("*", ip4("1.1.1.1")));
+ CHECK(!match_ip_list(";", ip4("1.1.1.1"))); /* only separators: matches nothing (the GUI turns this into "*") */
+
+ /* ================= IPv6 patterns ================= */
+ CHECK(v6("::1", "::1") && !v6("::1", "::2") && v6("*", "2001:db8::5"));
+ CHECK(v6("2001:db8::/32", "2001:db8:ffff::1") && !v6("2001:db8::/32", "2001:db9::1"));
+ CHECK(v6("fe80::/10", "fe80::1") && v6("fe80::/10", "febf::1") && !v6("fe80::/10", "fec0::1"));
+ CHECK(v6("::/0", "2a00::1") && v6("::1/128", "::1") && !v6("::1/128", "::2") && !v6("::/129", "::1"));
+ CHECK(v6("2001:db8::1-2001:db8::ff", "2001:db8::80") && !v6("2001:db8::1-2001:db8::ff", "2001:db8::100"));
+ CHECK(!v6("10.0.0.0", "::1") && !v6("garbage:::", "::1")); /* IPv4 patterns never match IPv6 */
+ { char longp[300]; memset(longp, 'a', 299); longp[299] = 0; longp[3] = ':'; CHECK(!v6(longp, "::1")); } /* oversize: no crash */
+
+ /* ================= ports ================= */
+ CHECK(match_port_pattern("80", 80) && !match_port_pattern("80", 81) && match_port_pattern("*", 5));
+ CHECK(match_port_pattern("8000-9000", 8000) && match_port_pattern("8000-9000", 9000) && match_port_pattern("8000-9000", 8500) &&
+ !match_port_pattern("8000-9000", 7999) && !match_port_pattern("8000-9000", 9001));
+ CHECK(match_port_list("80;443;8000-9000", 443) && match_port_list("80,443", 443) && match_port_list("80; 443", 443) && !match_port_list("80;443", 8080));
+ CHECK(match_port_list("", 1) && match_port_list("*", 65535));
+
+ /* ================= process patterns ================= */
+ CHECK(wildcard_match("*steam*", "mysteamclient.exe") && wildcard_match("fire*.exe", "FireFox.EXE") && wildcard_match("*.bin", "a.bin"));
+ CHECK(!wildcard_match("fire*.exe", "chrome.exe") && wildcard_match("**", "x") && wildcard_match("*", "") && !wildcard_match("a", "") && wildcard_match("a*b*c", "aXXbYYc"));
+ CHECK(match_process_pattern("chrome.exe", "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe")); /* name matches the file name of a path */
+ CHECK(match_process_pattern("CHROME.EXE", "chrome.exe") && !match_process_pattern("chrome.exe", "chromedriver.exe"));
+ CHECK(match_process_pattern("C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe", "c:\\program files\\google\\chrome\\application\\chrome.exe"));
+ CHECK(!match_process_pattern("C:\\Other\\chrome.exe", "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe")); /* a path pattern must match the whole path */
+ CHECK(match_process_pattern("C:\\Program Files\\*\\chrome.exe", "C:\\Program Files\\Google\\chrome.exe"));
+ CHECK(match_process_pattern("*", "anything.exe") && match_process_pattern(NULL, "anything.exe"));
+ CHECK(match_process_list("firefox.exe;chrome.exe", "chrome.exe") && match_process_list("firefox.exe, chrome.exe", "chrome.exe") && !match_process_list("firefox.exe;edge.exe", "chrome.exe"));
+ CHECK(match_process_list("\"C:\\Program Files\\App\\my app.exe\"", "C:\\Program Files\\App\\my app.exe")); /* quoted path with a space */
+ CHECK(match_process_list(" chrome.exe ", "chrome.exe") && match_process_list("", "x.exe") && match_process_list("*", "x.exe") && match_process_list(NULL, "x.exe"));
+ { char many[8192]; size_t o = 0; for (int i = 0; i < 700; i++) o += sprintf_s(many + o, sizeof many - o, "app%d.exe;", i); strcat_s(many, sizeof many, "target.exe");
+ CHECK(match_process_list(many, "target.exe") && match_process_list(many, "app5.exe") && !match_process_list(many, "nope.exe")); } /* list longer than the stack buffer */
+
+ /* ================= domain patterns ================= */
+ CHECK(match_domain_pattern("github.com", "GitHub.com") && !match_domain_pattern("github.com", "api.github.com"));
+ CHECK(match_domain_pattern("*.github.com", "api.github.com") && match_domain_pattern("*.github.com", "github.com")); /* the apex matches too */
+ CHECK(!match_domain_pattern("*.github.com", "evilgithub.com") && !match_domain_pattern("*.github.com", "github.com.evil.org"));
+ CHECK(match_domain_pattern("*google*", "www.google.co.uk") && match_domain_pattern("*", "x") && match_domain_pattern("", "x"));
+ CHECK(!match_domain_pattern("github.com", "") && !match_domain_pattern("github.com", NULL)); /* unknown name: only "*" matches */
+ CHECK(match_domain_list("a.com;*.b.org;c.net", "x.b.org") && match_domain_list("a.com, c.net", "c.net") && !match_domain_list("a.com;c.net", "d.net"));
+ CHECK(match_domain_list("", NULL) && match_domain_list("*", NULL) && !match_domain_list("a.com", NULL));
+ { static char many[16384]; size_t o = 0; for (int i = 0; i < 600; i++) o += sprintf_s(many + o, sizeof many - o, "host%d.example.org;", i); strcat_s(many, sizeof many, "*.last.example");
+ CHECK(match_domain_list(many, "x.last.example") && match_domain_list(many, "host42.example.org") && !match_domain_list(many, "host9999.example.org")); }
+
+ /* ================= rule list API ================= */
+ CHECK(ProxyBridge_AddRule(NULL, "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_DIRECT, 0, FALSE) == 0); /* a rule needs a process */
+ CHECK(ProxyBridge_AddRule("", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_DIRECT, 0, FALSE) == 0);
+ CHECK(!ProxyBridge_EditRule(0, "a.exe", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_DIRECT, 0, FALSE));
+ CHECK(!ProxyBridge_EditRule(99999, "a.exe", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_DIRECT, 0, FALSE));
+ CHECK(!ProxyBridge_EditRule(1, NULL, "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_DIRECT, 0, FALSE));
+ CHECK(!ProxyBridge_DeleteRule(99999) && !ProxyBridge_EnableRule(99999) && !ProxyBridge_DisableRule(99999));
+ CHECK(ProxyBridge_GetRulePosition(99999) == 0);
+
+ /* a rule with NULL/empty target lists is a wildcard rule (stored as "*") */
+ { UINT32 w = ProxyBridge_AddRule("wild.exe", NULL, NULL, NULL, RULE_PROTOCOL_BOTH, RULE_ACTION_BLOCK, 0, FALSE);
+ CHECK(w != 0 && m4("wild.exe", "8.8.8.8", 443) == RULE_ACTION_BLOCK); ProxyBridge_DeleteRule(w); }
+
+ /* protocol filter: a TCP-only rule ignores UDP flows and vice versa */
+ { UINT32 t = ProxyBridge_AddRule("p.exe", "*", "*", "*", RULE_PROTOCOL_TCP, RULE_ACTION_BLOCK, 0, FALSE);
+ UINT32 id = 0;
+ CHECK(match_rule("p.exe", ip4("1.1.1.1"), 53, FALSE, &id) == RULE_ACTION_BLOCK && match_rule("p.exe", ip4("1.1.1.1"), 53, TRUE, &id) == RULE_ACTION_DIRECT);
+ ProxyBridge_DeleteRule(t); }
+
+ /* ordering: first matching rule in the list wins; a fully wildcard "*" process rule is only used last */
+ { UINT32 a = ProxyBridge_AddRule("chrome.exe", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_PROXY, 0, FALSE);
+ UINT32 b = ProxyBridge_AddRule("chrome.exe", "10.*.*.*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_DIRECT, 0, FALSE);
+ CHECK(ProxyBridge_GetRulePosition(a) == 1 && ProxyBridge_GetRulePosition(b) == 2);
+ CHECK(m4("chrome.exe", "10.1.1.1", 80) == RULE_ACTION_PROXY); /* A first: it covers everything */
+ CHECK(ProxyBridge_MoveRuleToPosition(b, 1) == TRUE);
+ CHECK(ProxyBridge_GetRulePosition(b) == 1 && ProxyBridge_GetRulePosition(a) == 2);
+ CHECK(m4("chrome.exe", "10.1.1.1", 80) == RULE_ACTION_DIRECT && m4("chrome.exe", "8.8.8.8", 80) == RULE_ACTION_PROXY);
+ UINT32 wcard = ProxyBridge_AddRule("*", "*", "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_BLOCK, 0, FALSE); /* added last, matches every program */
+ CHECK(m4("chrome.exe", "8.8.8.8", 80) == RULE_ACTION_PROXY); /* specific rules still win */
+ CHECK(m4("other.exe", "8.8.8.8", 80) == RULE_ACTION_BLOCK); /* everything else falls to it */
+ ProxyBridge_MoveRuleToPosition(wcard, 1);
+ CHECK(m4("chrome.exe", "8.8.8.8", 80) == RULE_ACTION_PROXY); /* ... even when it is listed first */
+ ProxyBridge_MoveRuleToPosition(a, 99); /* an out-of-range position must not corrupt the list */
+ UINT32 pa = ProxyBridge_GetRulePosition(a), pb = ProxyBridge_GetRulePosition(b), pw = ProxyBridge_GetRulePosition(wcard);
+ CHECK(pa >= 1 && pa <= 3 && pb >= 1 && pb <= 3 && pw >= 1 && pw <= 3 && pa != pb && pb != pw && pa != pw);
+ ProxyBridge_DeleteRule(a); ProxyBridge_DeleteRule(b); ProxyBridge_DeleteRule(wcard);
+ CHECK(m4("chrome.exe", "8.8.8.8", 80) == RULE_ACTION_DIRECT); }
+
+ /* very long target lists are accepted and stored without truncation */
+ { char hosts[20000]; size_t o = 0; for (int i = 0; i < 1500; i++) o += sprintf_s(hosts + o, sizeof hosts - o, "10.%d.%d.1;", i / 250, i % 250);
+ UINT32 big = ProxyBridge_AddRule("longlist.exe", hosts, "*", "*", RULE_PROTOCOL_BOTH, RULE_ACTION_BLOCK, 0, FALSE);
+ CHECK(big != 0 && m4("longlist.exe", "10.5.249.1", 1) == RULE_ACTION_BLOCK && m4("longlist.exe", "10.5.249.2", 1) == RULE_ACTION_DIRECT);
+ ProxyBridge_DeleteRule(big); }
+
+ return pbtest_done("test_rules_match");
+}
diff --git a/Windows/tests/test_rules_ui.c b/Windows/tests/test_rules_ui.c
new file mode 100644
index 0000000..80fa38f
--- /dev/null
+++ b/Windows/tests/test_rules_ui.c
@@ -0,0 +1,170 @@
+// test_rules_ui.c - drives the REAL Proxy Rules window (RulesDlgProc from gui\ui\dialogs.h) with a stubbed engine:
+// search/filter, the row -> rule mapping (Edit / Clone / Remove / check boxes act on the rule you see), the
+// keyboard shortcuts, Move Up/Down only without a search, and a reopened window starting unfiltered.
+// Needs a desktop session (it creates real windows); the engine API is replaced by recording stubs.
+#define wWinMain pb_real_wWinMain
+#include "../gui/main.c"
+#undef wWinMain
+#include "pbtest.h"
+
+/* ---- engine stubs: they only record what the window asked for ---- */
+static UINT32 g_lastDeleted, g_lastEnabled, g_lastDisabled, g_lastMovedId, g_lastMovedPos, g_nextId = 1000;
+static UINT32 StubAdd(const char* a, const char* b, const char* c, const char* d, PBRuleProtocol p, PBRuleAction e, UINT32 f, BOOL g) { (void)a;(void)b;(void)c;(void)d;(void)p;(void)e;(void)f;(void)g; return g_nextId++; }
+static BOOL StubEdit(UINT32 id, const char* a, const char* b, const char* c, const char* d, PBRuleProtocol p, PBRuleAction e, UINT32 f, BOOL g) { (void)id;(void)a;(void)b;(void)c;(void)d;(void)p;(void)e;(void)f;(void)g; return TRUE; }
+static BOOL StubDelete(UINT32 id) { g_lastDeleted = id; return TRUE; }
+static BOOL StubEnable(UINT32 id) { g_lastEnabled = id; return TRUE; }
+static BOOL StubDisable(UINT32 id) { g_lastDisabled = id; return TRUE; }
+static BOOL StubMove(UINT32 id, UINT32 pos) { g_lastMovedId = id; g_lastMovedPos = pos; return TRUE; }
+
+static void AddRuleToProfile(const wchar_t* name, const wchar_t* proc, const wchar_t* hosts, const wchar_t* action, UINT32 nativeId)
+{
+ PBRule* r = &g_profile.rule[g_profile.ruleCount++];
+ ZeroMemory(r, sizeof(*r));
+ lstrcpynW(r->name, name, 128); lstrcpynW(r->proc, proc, PB_APPS_MAX); lstrcpynW(r->hosts, hosts, PB_HOSTS_MAX);
+ lstrcpynW(r->ports, L"*", 128); lstrcpynW(r->proto, L"TCP", 8); lstrcpynW(r->action, action, 16);
+ r->enabled = 1; r->nativeId = nativeId;
+}
+
+static HWND g_dlg, g_lv, g_search;
+static int Rows(void) { return ListView_GetItemCount(g_lv); }
+static BOOL RowIs(int row, const wchar_t* name) { wchar_t b[128]; ListView_GetItemText(g_lv, row, 1, b, 128); return wcscmp(b, name) == 0; }
+static void Type(const wchar_t* text) { SetWindowTextW(g_search, text); } /* fires EN_CHANGE synchronously */
+static void SelectRow(int row) { ListView_SetItemState(g_lv, row, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); }
+static void Click(int id) { SendMessageW(g_dlg, WM_COMMAND, MAKEWPARAM(id, BN_CLICKED), (LPARAM)GetDlgItem(g_dlg, id)); }
+static BOOL HaveForeground(void) { return GetForegroundWindow() == g_dlg; }
+
+int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrev, PWSTR cmd, int show)
+{
+ (void)hPrev; (void)cmd; (void)show;
+ setvbuf(stdout, NULL, _IONBF, 0);
+ g_hInst = hInst;
+ CreateDarkBrushes(); /* the same brushes the real app creates at startup */
+ wchar_t tmp[MAX_PATH]; GetTempPathW(MAX_PATH, tmp);
+ wchar_t sub[64]; _snwprintf_s(sub, 64, _TRUNCATE, L"pbtest_rulesui_%lu", GetCurrentProcessId()); wcscat_s(tmp, MAX_PATH, sub);
+ CreateDirectoryW(tmp, NULL); SetEnvironmentVariableW(L"APPDATA", tmp); /* SaveActive() writes the profile here */
+ wcscpy_s(g_activeProfile, PB_NAME_MAX, L"uitest");
+ INITCOMMONCONTROLSEX icc = { sizeof(icc), ICC_LISTVIEW_CLASSES | ICC_STANDARD_CLASSES | ICC_LINK_CLASS };
+ InitCommonControlsEx(&icc);
+
+ g_api.AddRule = StubAdd; g_api.EditRule = StubEdit; g_api.DeleteRule = StubDelete;
+ g_api.EnableRule = StubEnable; g_api.DisableRule = StubDisable; g_api.MoveRuleToPosition = StubMove;
+
+ ZeroMemory(&g_profile, sizeof(g_profile));
+ PBConfig* c = &g_profile.cfg[g_profile.cfgCount++];
+ c->storedId = 1; lstrcpynW(c->name, L"Burp", 128); lstrcpynW(c->type, L"SOCKS5", 16); lstrcpynW(c->host, L"127.0.0.1", 128); lstrcpynW(c->port, L"1080", 16);
+ AddRuleToProfile(L"Chrome to Burp", L"chrome.exe", L"*", L"PROXY", 101); /* index 0 */
+ AddRuleToProfile(L"Firefox direct", L"firefox.exe", L"192.168.*.*", L"DIRECT", 102); /* index 1 */
+ AddRuleToProfile(L"Chrome internal", L"chrome.exe; edge.exe", L"10.*.*.*;corp.local", L"DIRECT", 103); /* index 2 */
+ AddRuleToProfile(L"Block telemetry", L"*", L"telemetry.example.com", L"BLOCK", 104); /* index 3 */
+ AddRuleToProfile(L"curl github", L"curl.exe", L"github.com;*.github.com", L"PROXY", 105); /* index 4 */
+ g_profile.rule[0].cfgStoredId = 1; g_profile.rule[4].cfgStoredId = 1;
+
+ g_dlg = CreateDialogParamW(hInst, MAKEINTRESOURCEW(IDD_RULES), NULL, RulesDlgProc, 0);
+ CHECK(g_dlg != NULL);
+ ShowWindow(g_dlg, SW_SHOW); SetForegroundWindow(g_dlg); SetActiveWindow(g_dlg);
+ g_lv = GetDlgItem(g_dlg, IDC_RL_LIST); g_search = GetDlgItem(g_dlg, IDC_RL_SEARCH);
+ CHECK(g_lv && g_search && GetDlgItem(g_dlg, IDC_RL_COUNT) && GetDlgItem(g_dlg, IDC_RL_CLEAR));
+ if (!HaveForeground()) puts(" note: the window is not the foreground window here; focus-movement checks are skipped");
+
+ /* 1. opens with the full list, an empty search box, reordering on, clear off */
+ CHECK(Rows() == 5 && g_rlMapN == 5);
+ CHECK(IsWindowEnabled(GetDlgItem(g_dlg, IDC_RL_UP)) && IsWindowEnabled(GetDlgItem(g_dlg, IDC_RL_DOWN)));
+ CHECK(!IsWindowEnabled(GetDlgItem(g_dlg, IDC_RL_CLEAR)));
+
+ /* 2. filter by process name (case-insensitive) */
+ Type(L"CHROME");
+ CHECK(Rows() == 2 && RowIs(0, L"Chrome to Burp") && RowIs(1, L"Chrome internal"));
+ CHECK(g_rlMap[0] == 0 && g_rlMap[1] == 2);
+ wchar_t cnt[160]; GetDlgItemTextW(g_dlg, IDC_RL_COUNT, cnt, 160);
+ CHECK(wcsstr(cnt, L"2 of 5") != NULL);
+ CHECK(!IsWindowEnabled(GetDlgItem(g_dlg, IDC_RL_UP)) && !IsWindowEnabled(GetDlgItem(g_dlg, IDC_RL_DOWN))); /* no reordering of a partial view */
+ CHECK(IsWindowEnabled(GetDlgItem(g_dlg, IDC_RL_CLEAR)));
+
+ /* 3. several words must ALL match, across columns */
+ Type(L"chrome corp"); CHECK(Rows() == 1 && RowIs(0, L"Chrome internal"));
+ Type(L"chrome burp"); CHECK(Rows() == 1 && RowIs(0, L"Chrome to Burp")); /* the proxy column is searched */
+ Type(L"chrome nonsense"); CHECK(Rows() == 0);
+ GetDlgItemTextW(g_dlg, IDC_RL_COUNT, cnt, 160); CHECK(wcsstr(cnt, L"0 of 5") != NULL);
+
+ /* 4. hosts (IP and domain), action */
+ Type(L"192.168"); CHECK(Rows() == 1 && RowIs(0, L"Firefox direct"));
+ Type(L"github.com"); CHECK(Rows() == 1 && RowIs(0, L"curl github"));
+ Type(L"block"); CHECK(Rows() == 1 && RowIs(0, L"Block telemetry"));
+ Type(L"direct"); CHECK(Rows() == 2);
+
+ /* 5. actions on a filtered list act on the RIGHT rule (row 1 of "chrome" is rule index 2, not 1) */
+ Type(L"chrome"); CHECK(Rows() == 2);
+ ListView_SetCheckState(g_lv, 1, FALSE); /* untick "Chrome internal" */
+ CHECK(g_profile.rule[2].enabled == 0 && g_profile.rule[0].enabled == 1 && g_profile.rule[1].enabled == 1);
+ CHECK(g_lastDisabled == 103);
+ ListView_SetCheckState(g_lv, 1, TRUE);
+ CHECK(g_profile.rule[2].enabled == 1 && g_lastEnabled == 103);
+
+ SelectRow(1); /* "Chrome internal" = rule index 2 */
+ Click(IDC_RL_CLONE);
+ CHECK(g_profile.ruleCount == 6);
+ CHECK(wcscmp(g_profile.rule[3].name, L"Chrome internal") == 0 && wcscmp(g_profile.rule[2].name, L"Chrome internal") == 0); /* slotted right after its source */
+ CHECK(g_lastMovedPos == 4); /* engine position = source index 2 + 2 */
+ CHECK(Rows() == 3); /* the clone matches the same search */
+ CHECK(SelectedRuleIndex(g_lv) == 3); /* and is selected */
+
+ Click(IDC_RL_REMOVE); /* removes the selected clone (rule index 3) */
+ CHECK(g_profile.ruleCount == 5 && g_lastDeleted >= 1000);
+ CHECK(wcscmp(g_profile.rule[3].name, L"Block telemetry") == 0 && Rows() == 2);
+
+ SelectRow(0); /* "Chrome to Burp" */
+ Click(IDC_RL_REMOVE);
+ CHECK(g_lastDeleted == 101 && g_profile.ruleCount == 4);
+ CHECK(wcscmp(g_profile.rule[0].name, L"Firefox direct") == 0);
+ CHECK(Rows() == 1 && RowIs(0, L"Chrome internal"));
+ CHECK(g_profile.rule[1].nativeId == 103); /* the right engine rule survived */
+
+ /* 6. Clear restores the full list and reordering */
+ Click(IDC_RL_CLEAR);
+ CHECK(Rows() == 4 && g_rlWordN == 0);
+ CHECK(IsWindowEnabled(GetDlgItem(g_dlg, IDC_RL_UP)) && !IsWindowEnabled(GetDlgItem(g_dlg, IDC_RL_CLEAR)));
+ GetDlgItemTextW(g_dlg, IDC_RL_SEARCH, cnt, 160); CHECK(cnt[0] == 0);
+
+ /* 7. reordering on the full list still works */
+ SelectRow(0);
+ Click(IDC_RL_DOWN);
+ CHECK(wcscmp(g_profile.rule[0].name, L"Chrome internal") == 0 && wcscmp(g_profile.rule[1].name, L"Firefox direct") == 0);
+ CHECK(g_lastMovedId == g_profile.rule[1].nativeId && g_lastMovedPos == 2);
+ CHECK(SelectedRuleIndex(g_lv) == 1 && RowIs(1, L"Firefox direct"));
+
+ /* 8. keyboard: type-to-search from the list, Down / Enter to the list, Esc clears */
+ SetFocus(g_lv);
+ SendMessageW(g_lv, WM_CHAR, L'f', 0); /* a printable key in the list starts a search */
+ wchar_t t[16]; GetWindowTextW(g_search, t, 16);
+ CHECK(wcscmp(t, L"f") == 0);
+ if (HaveForeground()) CHECK(GetFocus() == g_search);
+ CHECK(Rows() >= 1 && g_rlWordN == 1);
+ SendMessageW(g_search, WM_KEYDOWN, VK_DOWN, 0); /* Down: into the list, first row selected */
+ CHECK(ListView_GetNextItem(g_lv, -1, LVNI_SELECTED) == 0);
+ if (HaveForeground()) CHECK(GetFocus() == g_lv);
+ SendMessageW(g_lv, WM_KEYDOWN, VK_ESCAPE, 0); /* Esc in the list clears an active search */
+ GetWindowTextW(g_search, t, 16);
+ CHECK(t[0] == 0 && g_rlWordN == 0 && Rows() == 4);
+ Type(L"firefox"); SendMessageW(g_search, WM_KEYDOWN, VK_ESCAPE, 0); /* Esc in the box clears it */
+ CHECK(GetWindowTextLengthW(g_search) == 0 && Rows() == 4);
+ Type(L"firefox"); SendMessageW(g_search, WM_KEYDOWN, VK_RETURN, 0); /* Enter hands over to the list */
+ if (HaveForeground()) CHECK(GetFocus() == g_lv);
+ Type(L""); SetFocus(g_lv); SendMessageW(g_lv, WM_CHAR, L' ', 0); /* space is NOT type-to-search (it toggles the check box) */
+ CHECK(GetWindowTextLengthW(g_search) == 0);
+
+ /* 9. odd input: a very long query, blanks only, more words than supported */
+ wchar_t longq[300]; for (int i = 0; i < 299; i++) longq[i] = (i % 6 == 5) ? L' ' : L'a'; longq[299] = 0;
+ Type(longq); CHECK(Rows() == 0);
+ Type(L" \t "); CHECK(Rows() == 4 && g_rlWordN == 0); /* blanks only = no filter */
+ Type(L"a b c d e f g h i j k"); CHECK(g_rlWordN == RL_MAX_WORDS);
+
+ /* 10. a reopened window starts unfiltered */
+ Type(L"firefox");
+ DestroyWindow(g_dlg);
+ g_dlg = CreateDialogParamW(hInst, MAKEINTRESOURCEW(IDD_RULES), NULL, RulesDlgProc, 0);
+ g_lv = GetDlgItem(g_dlg, IDC_RL_LIST); g_search = GetDlgItem(g_dlg, IDC_RL_SEARCH);
+ CHECK(Rows() == g_profile.ruleCount && g_rlWordN == 0 && GetWindowTextLengthW(g_search) == 0);
+ DestroyWindow(g_dlg);
+
+ return pbtest_done("test_rules_ui");
+}
diff --git a/Windows/tests/test_service.c b/Windows/tests/test_service.c
new file mode 100644
index 0000000..0ed689b
--- /dev/null
+++ b/Windows/tests/test_service.c
@@ -0,0 +1,148 @@
+// test_service.c - the engine service (src\service\pb_service.c), included as source so its static functions can be
+// called directly, with the engine API replaced by recording stubs:
+// - the request handler: every operation, argument decoding (NULL strings, flags), validation and malformed input
+// - the named-pipe permission list: SYSTEM and Administrators only (plus the optional per-user SIDs), no one else
+// - pipe-name squatting protection (FILE_FLAG_FIRST_PIPE_INSTANCE) and the SID sanity check used for the ACL
+// No service is started and the real ProxyBridge pipes are never touched (the pipe tests use a private pipe name).
+#define wmain pb_svc_wmain
+#include "../src/service/pb_service.c"
+#undef wmain
+#include <aclapi.h>
+#include "pbtest.h"
+
+/* ---- engine stubs ---- */
+static struct { PBProxyType type; char ip[64]; unsigned short port; char user[64], pass[64]; BOOL userNull, passNull, sd; UINT32 id; int calls; } P;
+static struct { UINT32 id; char proc[128], hosts[128], ports[64], domains[128]; BOOL procNull, hostsNull, portsNull, domainsNull;
+ PBRuleProtocol proto; PBRuleAction act; UINT32 cfg; BOOL localhost; int adds, edits; } R;
+static UINT32 g_enabled, g_disabled, g_deleted, g_moveId, g_movePos, g_posQuery, g_delProxy;
+static int g_trafficArg = -1, g_enableArg = -1, g_logAllArg = -1, g_cleared = 0, g_started = 0, g_stopped = 0;
+
+static void cp(char* d, size_t n, const char* s) { if (s) strncpy_s(d, n, s, _TRUNCATE); else d[0] = 0; } /* long fuzz strings are cut, not fatal */
+static UINT32 SAddProxy(PBProxyType t, const char* ip, unsigned short port, const char* u, const char* p, BOOL sd) { P.type = t; cp(P.ip, 64, ip); P.port = port; cp(P.user, 64, u); cp(P.pass, 64, p); P.userNull = !u; P.passNull = !p; P.sd = sd; P.calls++; return 41; }
+static BOOL SEditProxy(UINT32 id, PBProxyType t, const char* ip, unsigned short port, const char* u, const char* p, BOOL sd) { P.id = id; SAddProxy(t, ip, port, u, p, sd); return TRUE; }
+static BOOL SDelProxy(UINT32 id) { g_delProxy = id; return TRUE; }
+static UINT32 SAddRule(const char* a, const char* b, const char* c, const char* d, PBRuleProtocol pr, PBRuleAction ac, UINT32 cfg, BOOL lh)
+{ cp(R.proc, 128, a); cp(R.hosts, 128, b); cp(R.ports, 64, c); cp(R.domains, 128, d); R.procNull = !a; R.hostsNull = !b; R.portsNull = !c; R.domainsNull = !d; R.proto = pr; R.act = ac; R.cfg = cfg; R.localhost = lh; R.adds++; return 77; }
+static BOOL SEditRule(UINT32 id, const char* a, const char* b, const char* c, const char* d, PBRuleProtocol pr, PBRuleAction ac, UINT32 cfg, BOOL lh) { R.id = id; SAddRule(a, b, c, d, pr, ac, cfg, lh); R.adds--; R.edits++; return TRUE; }
+static BOOL SEnable(UINT32 id) { g_enabled = id; return TRUE; }
+static BOOL SDisable(UINT32 id) { g_disabled = id; return TRUE; }
+static BOOL SDelete(UINT32 id) { g_deleted = id; return TRUE; }
+static BOOL SMove(UINT32 id, UINT32 pos) { g_moveId = id; g_movePos = pos; return TRUE; }
+static UINT32 SGetPos(UINT32 id) { g_posQuery = id; return 5; }
+static void STraffic(BOOL v) { g_trafficArg = v; }
+static void SEnabled(BOOL v) { g_enableArg = v; }
+static void SLogAll(BOOL v) { g_logAllArg = v; }
+static void SClear(void) { g_cleared++; }
+static BOOL SStart(void) { g_started++; return TRUE; }
+static BOOL SStop(void) { g_stopped++; return FALSE; }
+
+/* ---- request helpers ---- */
+static BYTE rq[PB_MSG_MAX], rs[PB_MSG_MAX];
+static PbW W;
+static void begin(UINT32 op) { PbW_Init(&W, rq, sizeof rq); PbW_U32(&W, op); }
+static BOOL run(UINT32* ret) { PbW resp; PbW_Init(&resp, rs, sizeof rs); BOOL ok = Dispatch(rq, W.len, &resp); if (ok && ret) { PbR r; PbR_Init(&r, rs, resp.len); *ret = PbR_U32(&r); } return ok; }
+
+int main(void)
+{
+ setvbuf(stdout, NULL, _IONBF, 0);
+ g_api.AddProxyConfig = SAddProxy; g_api.EditProxyConfig = SEditProxy; g_api.DeleteProxyConfig = SDelProxy;
+ g_api.AddRule = SAddRule; g_api.EditRule = SEditRule; g_api.EnableRule = SEnable; g_api.DisableRule = SDisable; g_api.DeleteRule = SDelete;
+ g_api.MoveRuleToPosition = SMove; g_api.GetRulePosition = SGetPos;
+ g_api.SetTrafficLoggingEnabled = STraffic; g_api.SetEnabled = SEnabled; g_api.SetLogEveryConnection = SLogAll; g_api.ClearConnectionLogs = SClear;
+ g_api.Start = SStart; g_api.Stop = SStop; g_api.TestProxyConfigEx = NULL;
+ UINT32 ret;
+
+ /* ================= request handler ================= */
+ begin(PBOP_HELLO); CHECK(run(&ret) && ret == PB_PROTO_VERSION && PB_PROTO_VERSION >= 4);
+ begin(PBOP_ADD_PROXY); PbW_U32(&W, 1); PbW_Str(&W, "127.0.0.1"); PbW_U32(&W, 1080); PbW_Str(&W, "alice"); PbW_Str(&W, "pw"); PbW_U32(&W, 1);
+ CHECK(run(&ret) && ret == 41 && P.type == 1 && !strcmp(P.ip, "127.0.0.1") && P.port == 1080 && !strcmp(P.user, "alice") && !strcmp(P.pass, "pw") && P.sd);
+ begin(PBOP_ADD_PROXY); PbW_U32(&W, 0); PbW_Str(&W, "10.0.0.1"); PbW_U32(&W, 8080); PbW_Str(&W, NULL); PbW_Str(&W, NULL); PbW_U32(&W, 0);
+ CHECK(run(&ret) && P.type == 0 && P.userNull && P.passNull && !P.sd); /* NULL strings reach the engine as NULL */
+ begin(PBOP_ADD_PROXY); PbW_U32(&W, 2); PbW_Str(&W, "x"); PbW_U32(&W, 1); PbW_Str(&W, NULL); PbW_Str(&W, NULL); PbW_U32(&W, 0); { int c = P.calls; CHECK(!run(&ret) && P.calls == c); } /* unknown type */
+ begin(PBOP_ADD_PROXY); PbW_U32(&W, 1); PbW_Str(&W, "x"); PbW_U32(&W, 70000); PbW_Str(&W, NULL); PbW_Str(&W, NULL); PbW_U32(&W, 0); { int c = P.calls; CHECK(!run(&ret) && P.calls == c); } /* port > 65535 */
+ begin(PBOP_ADD_PROXY); PbW_U32(&W, 1); { int c = P.calls; CHECK(!run(&ret) && P.calls == c); } /* truncated */
+ begin(PBOP_EDIT_PROXY); PbW_U32(&W, 9); PbW_U32(&W, 1); PbW_Str(&W, "h"); PbW_U32(&W, 5); PbW_Str(&W, NULL); PbW_Str(&W, NULL); PbW_U32(&W, 1);
+ CHECK(run(&ret) && P.id == 9 && P.type == 1 && P.port == 5);
+ begin(PBOP_DELETE_PROXY); PbW_U32(&W, 12); CHECK(run(&ret) && ret == 1 && g_delProxy == 12);
+
+ begin(PBOP_ADD_RULE); PbW_Str(&W, "chrome.exe"); PbW_Str(&W, "10.*.*.*"); PbW_Str(&W, "443"); PbW_Str(&W, "github.com"); PbW_U32(&W, 0); PbW_U32(&W, 0); PbW_U32(&W, 3); PbW_U32(&W, 1);
+ CHECK(run(&ret) && ret == 77 && !strcmp(R.proc, "chrome.exe") && !strcmp(R.hosts, "10.*.*.*") && !strcmp(R.ports, "443") && !strcmp(R.domains, "github.com"));
+ CHECK(R.proto == 0 && R.act == 0 && R.cfg == 3 && R.localhost == TRUE); /* the per-rule localhost flag arrives */
+ begin(PBOP_ADD_RULE); PbW_Str(&W, "x.exe"); PbW_Str(&W, NULL); PbW_Str(&W, NULL); PbW_Str(&W, NULL); PbW_U32(&W, 2); PbW_U32(&W, 2); PbW_U32(&W, 0); PbW_U32(&W, 0);
+ CHECK(run(&ret) && R.hostsNull && R.portsNull && R.domainsNull && !R.procNull && R.proto == 2 && R.act == 2 && R.localhost == FALSE);
+ begin(PBOP_ADD_RULE); PbW_Str(&W, "x.exe"); PbW_Str(&W, "*"); PbW_Str(&W, "*"); PbW_Str(&W, "*"); PbW_U32(&W, 3); PbW_U32(&W, 0); PbW_U32(&W, 0); PbW_U32(&W, 0);
+ { int c = R.adds; CHECK(!run(&ret) && R.adds == c); } /* protocol 3 is invalid */
+ begin(PBOP_ADD_RULE); PbW_Str(&W, "x.exe"); PbW_Str(&W, "*"); PbW_Str(&W, "*"); PbW_Str(&W, "*"); PbW_U32(&W, 0); PbW_U32(&W, 3); PbW_U32(&W, 0); PbW_U32(&W, 0);
+ { int c = R.adds; CHECK(!run(&ret) && R.adds == c); } /* action 3 is invalid */
+ begin(PBOP_ADD_RULE); PbW_Str(&W, "x.exe"); PbW_Str(&W, "*"); PbW_Str(&W, "*"); PbW_Str(&W, "*"); PbW_U32(&W, 0); PbW_U32(&W, 0); PbW_U32(&W, 0);
+ { int c = R.adds; CHECK(!run(&ret) && R.adds == c); } /* an old client without the localhost field */
+ begin(PBOP_EDIT_RULE); PbW_U32(&W, 5); PbW_Str(&W, "e.exe"); PbW_Str(&W, "1.1.1.1"); PbW_Str(&W, "80"); PbW_Str(&W, "*"); PbW_U32(&W, 1); PbW_U32(&W, 1); PbW_U32(&W, 2); PbW_U32(&W, 1);
+ CHECK(run(&ret) && R.id == 5 && !strcmp(R.proc, "e.exe") && R.localhost == TRUE && R.edits == 1);
+ begin(PBOP_ENABLE_RULE); PbW_U32(&W, 4); CHECK(run(&ret) && g_enabled == 4);
+ begin(PBOP_DISABLE_RULE); PbW_U32(&W, 6); CHECK(run(&ret) && g_disabled == 6);
+ begin(PBOP_DELETE_RULE); PbW_U32(&W, 8); CHECK(run(&ret) && g_deleted == 8);
+ begin(PBOP_MOVE_RULE); PbW_U32(&W, 2); PbW_U32(&W, 9); CHECK(run(&ret) && g_moveId == 2 && g_movePos == 9);
+ begin(PBOP_GET_RULE_POS); PbW_U32(&W, 3); CHECK(run(&ret) && ret == 5 && g_posQuery == 3);
+ begin(PBOP_ENABLE_RULE); CHECK(!run(&ret)); /* missing id */
+
+ begin(PBOP_SET_TRAFFIC_LOG); PbW_U32(&W, 1); CHECK(run(&ret) && g_trafficArg == 1);
+ begin(PBOP_SET_TRAFFIC_LOG); PbW_U32(&W, 0); CHECK(run(&ret) && g_trafficArg == 0);
+ begin(PBOP_SET_ENABLED); PbW_U32(&W, 0); CHECK(run(&ret) && g_enableArg == 0); /* main switch */
+ begin(PBOP_SET_ENABLED); PbW_U32(&W, 1); CHECK(run(&ret) && g_enableArg == 1);
+ begin(PBOP_SET_ENABLED); PbW_U32(&W, 7); CHECK(run(&ret) && g_enableArg == 1); /* any non-zero value is "on" */
+ begin(PBOP_SET_LOG_ALL); PbW_U32(&W, 1); CHECK(run(&ret) && g_logAllArg == 1);
+ begin(PBOP_SET_ENABLED); CHECK(!run(&ret)); /* argument missing */
+ begin(PBOP_CLEAR_CONN_LOGS); CHECK(run(&ret) && g_cleared == 1);
+ begin(PBOP_START); CHECK(run(&ret) && ret == 1 && g_started == 1);
+ begin(PBOP_STOP); CHECK(run(&ret) && ret == 0 && g_stopped == 1);
+
+ /* unknown operations and garbage are rejected without touching the engine */
+ begin(0); CHECK(!run(&ret));
+ begin(9999); CHECK(!run(&ret));
+ PbW_Init(&W, rq, sizeof rq); CHECK(!run(&ret)); /* empty request */
+ { int a = R.adds + P.calls; srand(99);
+ for (int it = 0; it < 30000; it++) /* random requests: no crash, no overrun (guard page) */
+ {
+ int n = rand() % 120; BYTE tmp[160];
+ for (int i = 0; i < n; i++) tmp[i] = (BYTE)(rand() % 4 ? rand() % 40 : rand());
+ if (n >= 4 && it % 2) { UINT32 op = 1 + rand() % (PBOP_SET_LOG_ALL + 1); memcpy(tmp, &op, 4); }
+ void* base; BYTE* g = pb_guarded(tmp, (size_t)n, &base);
+ PbW resp; PbW_Init(&resp, rs, sizeof rs); Dispatch(g, (DWORD)n, &resp);
+ pb_guard_release(base);
+ }
+ g_checks += 30000; (void)a; }
+
+ /* ================= pipe permission list ================= */
+ wchar_t sddl[1024]; BuildPipeSddl(sddl, ARRAYSIZE(sddl));
+ CHECK(wcsncmp(sddl, L"D:(A;;GA;;;SY)(A;;GA;;;BA)", 25) == 0); /* SYSTEM + Administrators always */
+ const wchar_t* bad[] = { L";;;WD)", L";;;IU)", L";;;AU)", L";;;BU)", L";;;NU)", L";;;AN)", L";;;S-1-1-0)", L";;;S-1-5-4)", L";;;S-1-5-11)", L";;;S-1-5-32-545)" };
+ for (int i = 0; i < ARRAYSIZE(bad); i++) CHECK(wcsstr(sddl, bad[i]) == NULL); /* never Everyone / interactive / authenticated / users / anonymous */
+ { PSECURITY_DESCRIPTOR psd = NULL; CHECK(ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, SDDL_REVISION_1, &psd, NULL)); if (psd) LocalFree(psd); } /* well formed */
+
+ CHECK(LooksLikeSid(L"S-1-5-21-1004336348-1177238915-682003330-1001") && LooksLikeSid(L"S-1-5-18"));
+ CHECK(!LooksLikeSid(L"") && !LooksLikeSid(L"S") && !LooksLikeSid(L"X-1-5-18") && !LooksLikeSid(L"S-1-5-18)(A;;GA;;;WD") && !LooksLikeSid(L"S-1-5-18 ") && !LooksLikeSid(L"s-1-5-18"));
+ { wchar_t longsid[200]; wcscpy_s(longsid, 200, L"S-1"); for (int i = 0; i < 20; i++) wcscat_s(longsid, 200, L"-12345"); CHECK(!LooksLikeSid(longsid)); } /* 123 characters: too long */
+
+ /* the pipe created by MakePipe really carries that list, and a second owner of the same name is refused */
+ { wchar_t name[80]; _snwprintf_s(name, 80, _TRUNCATE, L"\\\\.\\pipe\\pbtest_%lu", GetCurrentProcessId());
+ HANDLE h1 = MakePipe(name, TRUE, PIPE_ACCESS_DUPLEX);
+ CHECK(h1 != INVALID_HANDLE_VALUE);
+ if (h1 != INVALID_HANDLE_VALUE)
+ {
+ PSECURITY_DESCRIPTOR sd = NULL; PACL dacl = NULL;
+ if (GetSecurityInfo(h1, SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &dacl, NULL, &sd) == ERROR_SUCCESS)
+ {
+ LPWSTR s = NULL; ConvertSecurityDescriptorToStringSecurityDescriptorW(sd, SDDL_REVISION_1, DACL_SECURITY_INFORMATION, &s, NULL);
+ CHECK(s && wcsstr(s, L";;;SY)") && wcsstr(s, L";;;BA)") && !wcsstr(s, L";;;WD)") && !wcsstr(s, L";;;IU)") && !wcsstr(s, L";;;AU)") && !wcsstr(s, L";;;BU)"));
+ if (s) LocalFree(s);
+ LocalFree(sd);
+ }
+ else CHECK(FALSE);
+ HANDLE h2 = MakePipe(name, TRUE, PIPE_ACCESS_DUPLEX); /* someone else squatting on the name */
+ CHECK(h2 == INVALID_HANDLE_VALUE);
+ if (h2 != INVALID_HANDLE_VALUE) CloseHandle(h2);
+ CloseHandle(h1);
+ } }
+
+ return pbtest_done("test_service");
+}