Skip to content

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

feat(windows): Live Connections tab

AnoF-Cyber7d8e1473a651
diff --git a/Windows/README.md b/Windows/README.md
index cc43168..31036a7 100644
--- a/Windows/README.md
+++ b/Windows/README.md
@@ -55,7 +55,7 @@ Launch `ProxyBridge.exe` with Administrator privileges for an intuitive graphica
#### Proxy Settings
<p align="center">
- <img src="../img/proxy-setting.png" alt="Proxy Settings" width="600"/>
+ <img src="../img/Windows/Proxy-Server.png" alt="Proxy Settings" width="600"/>
</p>
1. Click **Proxy** tab in the main window
@@ -91,11 +91,7 @@ ProxyBridge supports multiple proxy server configurations simultaneously. Each p
#### Process Rules
<p align="center">
- <img src="../img/proxy-rule.png" alt="Add Process Rule" width="600"/>
-</p>
-
-<p align="center">
- <img src="../img/proxy-rule2.png" alt="Process Rules List" width="600"/>
+ <img src="../img/Windows/Proxy-Rules.png" alt="Process Rules List" width="600"/>
</p>
1. Click **Proxy** tab in the main window
@@ -210,10 +206,19 @@ ProxyBridge allows you to export selected rules to a `.pbprofile` JSON file and
#### Activity Monitoring
<p align="center">
- <img src="../img/ProxyBridge.png" alt="Active Connections" width="600"/>
+ <img src="../img/Windows/Connections.png" alt="Active Connections" width="600"/>
+</p>
+
+<p align="center">
+ <img src="../img/Windows/Live%20Connection.png" alt="Live Connections" width="600"/>
</p>
- View real-time connection activity in the **Connections** tab
+- See what is relayed right now in the **Live Connections** tab: one row per proxied TCP connection or UDP flow with the
+ application, target, time, proxy and bytes sent / received. A finished connection turns grey and stays in the list
+ (with its final byte counts) until you press **Clear closed**; the list keeps up to 1200 rows and replaces the oldest finished
+ one when full. Direct and blocked traffic is not listed (ProxyBridge only sees the first packet of those). The tab polls once
+ a second, and only while it is open.
- Monitor all TCP and UDP connections system-wide
- See routing status per connection: **PROXY**, **DIRECT**, or **BLOCK**
- Search and filter by process name, IP, port, or routing status
diff --git a/Windows/gui/api/pb_api.h b/Windows/gui/api/pb_api.h
index c18b1b7..e78ea04 100644
--- a/Windows/gui/api/pb_api.h
+++ b/Windows/gui/api/pb_api.h
@@ -13,6 +13,22 @@ typedef enum { PB_PROXY_HTTP = 0, PB_PROXY_SOCKS5 = 1 } PBProxyType;
typedef enum { PB_ACTION_PROXY = 0, PB_ACTION_DIRECT = 1, PB_ACTION_BLOCK = 2 } PBRuleAction;
typedef enum { PB_PROTO_TCP = 0, PB_PROTO_UDP = 1, PB_PROTO_BOTH = 2 } PBRuleProtocol;
+// one live connection (must match PB_FLOW in ../../src/ProxyBridge.h)
+typedef struct {
+ UINT64 id;
+ UINT32 pid;
+ UINT32 proxy_config_id;
+ UINT32 rule_id; // 0 = not known
+ UINT32 age_ms; // 0xFFFFFFFF = not known
+ UINT64 sent, received; // payload bytes application -> proxy, proxy -> application
+ UINT16 port;
+ UINT8 is_udp, is_ipv6;
+ UINT8 dest[16];
+ char name[40]; // process image name (UTF-8)
+ char host[64]; // destination: domain if known, else address (UTF-8)
+} PBFlow;
+#define PB_FLOWS_MAX_GUI 400
+
// callbacks (native thread - never touch UI directly from these)
typedef void (*PBLogCallback)(const char* message);
typedef void (*PBConnectionCallback)(const char* process_name, DWORD pid,
@@ -39,6 +55,7 @@ typedef void (*PFN_SetTrafficLoggingEnabled)(BOOL);
typedef void (*PFN_SetEnabled)(BOOL);
typedef void (*PFN_SetLogEveryConnection)(BOOL);
typedef void (*PFN_ClearConnectionLogs)(void);
+typedef UINT32 (*PFN_GetFlows)(PBFlow*, UINT32);
typedef BOOL (*PFN_Start)(void);
typedef BOOL (*PFN_Stop)(void);
@@ -63,6 +80,7 @@ typedef struct {
PFN_SetEnabled SetEnabled;
PFN_SetLogEveryConnection SetLogEveryConnection;
PFN_ClearConnectionLogs ClearConnectionLogs;
+ PFN_GetFlows GetFlows;
PFN_Start Start;
PFN_Stop Stop;
} PBApi;
@@ -109,6 +127,7 @@ static BOOL PB_LoadDirect(PBApi* api)
PB_BIND(SetEnabled, "SetEnabled");
PB_BIND(SetLogEveryConnection, "SetLogEveryConnection");
PB_BIND(ClearConnectionLogs, "ClearConnectionLogs");
+ PB_BIND(GetFlows, "GetFlows");
PB_BIND(Start, "Start");
PB_BIND(Stop, "Stop");
#undef PB_BIND
diff --git a/Windows/gui/api/pb_ipc.h b/Windows/gui/api/pb_ipc.h
index 82fca01..8afd073 100644
--- a/Windows/gui/api/pb_ipc.h
+++ b/Windows/gui/api/pb_ipc.h
@@ -67,20 +67,29 @@ static DWORD WINAPI PbIpcReader(LPVOID arg)
return 0;
}
-// Sends one request, returns the response's leading u32 (0 on any failure).
-static UINT32 PbIpcCall(const BYTE *req, DWORD len)
+// Sends one request and reads the whole response into rsp. FALSE on any failure (the pipe is dropped).
+static BOOL PbIpcExchange(const BYTE *req, DWORD len, BYTE *rsp, DWORD cap, DWORD *got)
{
- UINT32 ret = 0;
- BYTE rsp[64];
+ BOOL ok = FALSE;
+ *got = 0;
EnterCriticalSection(&g_ipcLock);
if (g_ipcCtl != INVALID_HANDLE_VALUE)
{
DWORD n = 0;
- if (WriteFile(g_ipcCtl, req, len, &n, NULL) && ReadFile(g_ipcCtl, rsp, sizeof(rsp), &n, NULL) && n >= 4)
- memcpy(&ret, rsp, 4);
+ if (WriteFile(g_ipcCtl, req, len, &n, NULL) && ReadFile(g_ipcCtl, rsp, cap, &n, NULL) && n >= 4) { *got = n; ok = TRUE; }
else { CloseHandle(g_ipcCtl); g_ipcCtl = INVALID_HANDLE_VALUE; } // service gone
}
LeaveCriticalSection(&g_ipcLock);
+ return ok;
+}
+
+// Sends one request, returns the response's leading u32 (0 on any failure).
+static UINT32 PbIpcCall(const BYTE *req, DWORD len)
+{
+ UINT32 ret = 0;
+ BYTE rsp[64];
+ DWORD n = 0;
+ if (PbIpcExchange(req, len, rsp, sizeof(rsp), &n)) memcpy(&ret, rsp, 4);
return ret;
}
@@ -129,6 +138,35 @@ static UINT32 IpcGetRulePos(UINT32 id) { PBIPC_BEGIN(PBOP_GET_RULE_POS); PbW_U32
static void IpcSetTrafficLog(BOOL v) { PBIPC_BEGIN(PBOP_SET_TRAFFIC_LOG); PbW_U32(&_w, v != 0); PbIpcCall(_b, _w.len); }
static void IpcClearConnLogs(void) { PBIPC_BEGIN(PBOP_CLEAR_CONN_LOGS); PbIpcCall(_b, _w.len); }
static void IpcSetLogAll(BOOL v) { PBIPC_BEGIN(PBOP_SET_LOG_ALL); PbW_U32(&_w, v != 0); PbIpcCall(_b, _w.len); }
+// Live connections: asks the service for up to max flows. Every field is bounds-checked; a malformed reply yields 0.
+static UINT32 IpcGetFlows(PBFlow *out, UINT32 max)
+{
+ if (out == NULL || max == 0) return 0;
+ if (max > PB_FLOWS_MAX_GUI) max = PB_FLOWS_MAX_GUI;
+ BYTE req[16]; PbW w; PbW_Init(&w, req, sizeof(req)); PbW_U32(&w, PBOP_GET_FLOWS); PbW_U32(&w, max);
+ static BYTE rsp[PB_MSG_MAX]; // one poller at a time (g_ipcLock is taken inside the exchange)
+ DWORD got = 0;
+ if (!PbIpcExchange(req, w.len, rsp, sizeof(rsp), &got)) return 0;
+ PbR r; PbR_Init(&r, rsp, got);
+ UINT32 n = PbR_U32(&r);
+ if (!r.ok || n > max) return 0;
+ UINT32 i = 0;
+ for (; i < n; i++)
+ {
+ PBFlow *f = &out[i];
+ ZeroMemory(f, sizeof(*f));
+ UINT32 lo = PbR_U32(&r), hi = PbR_U32(&r); f->id = ((UINT64)hi << 32) | lo;
+ f->pid = PbR_U32(&r);
+ UINT32 flags = PbR_U32(&r); f->is_udp = (flags & 1) != 0; f->is_ipv6 = (flags & 2) != 0;
+ UINT32 port = PbR_U32(&r); f->port = (UINT16)port;
+ f->proxy_config_id = PbR_U32(&r); f->rule_id = PbR_U32(&r); f->age_ms = PbR_U32(&r);
+ lo = PbR_U32(&r); hi = PbR_U32(&r); f->sent = ((UINT64)hi << 32) | lo;
+ lo = PbR_U32(&r); hi = PbR_U32(&r); f->received = ((UINT64)hi << 32) | lo;
+ PbR_Str(&r, f->name, sizeof(f->name), NULL); PbR_Str(&r, f->host, sizeof(f->host), NULL);
+ if (!r.ok || port > 65535) break;
+ }
+ return i == n ? n : 0;
+}
static void IpcSetEnabled(BOOL v) { PBIPC_BEGIN(PBOP_SET_ENABLED); PbW_U32(&_w, v != 0); PbIpcCall(_b, _w.len); }
static void IpcSetLogCallback(PBLogCallback cb) { g_ipcLogCb = cb; }
static void IpcSetConnectionCallback(PBConnectionCallback cb) { g_ipcConnCb = cb; }
@@ -248,6 +286,7 @@ static int PB_LoadService(PBApi* api)
api->SetConnectionCallback = IpcSetConnectionCallback;
api->SetTrafficLoggingEnabled = IpcSetTrafficLog; api->SetEnabled = IpcSetEnabled; api->SetLogEveryConnection = IpcSetLogAll;
api->ClearConnectionLogs = IpcClearConnLogs; api->Start = IpcStart; api->Stop = IpcStop;
+ api->GetFlows = IpcGetFlows;
return PB_IPC_OK;
}
diff --git a/Windows/gui/loc/loc.h b/Windows/gui/loc/loc.h
index 4fa61e0..a841030 100644
--- a/Windows/gui/loc/loc.h
+++ b/Windows/gui/loc/loc.h
@@ -29,6 +29,7 @@ enum {
S_COL_ADDR, S_COL_TYPE, S_RULES_HINT, S_RULES_SEARCH, S_RULES_COUNT,
S_BTN_RUNNING, S_DLG_PROCPICK, S_PP_SEARCH, S_PP_REFRESH, S_PP_FULLPATH, S_PP_NOTE, S_PP_STATUS,
S_PP_COL_NAME, S_PP_COL_PID, S_PP_COL_PATH, S_PP_FULL,
+ S_TAB_FLOWS, S_FL_COL_APP, S_FL_COL_TARGET, S_FL_COL_PROTO, S_FL_COL_STATUS, S_FL_COL_PROXY, S_FL_COL_SENT, S_FL_COL_RECV, S_FL_CLOSED, S_FL_CLEAR,
S_BTN_CHECK, S_TEST_OK, S_TEST_FAIL, S_TEST_TITLE,
S_DLG_CHECKER, S_BTN_RETEST, S_TEST_RUNNING, S_CK_HOST, S_BTN_BROWSE,
S_EX_APPS, S_EX_HOSTS, S_EX_PORTS, S_UDP_NOTE, S_EX_LOCALHOST,
@@ -151,6 +152,16 @@ static const wchar_t* const g_strings[S_COUNT][2] = {
/* S_PP_COL_PID */ { L"PID", L"PID" },
/* S_PP_COL_PATH */ { L"Executable path", L"可执行文件路径" },
/* S_PP_FULL */ { L"The Applications list is full (maximum %d characters): %d program(s) could not be added.", L"应用程序列表已满 (最多 %d 个字符): 有 %d 个程序无法添加。" },
+ /* S_TAB_FLOWS */ { L"Live Connections", L"实时连接" },
+ /* S_FL_COL_APP */ { L"Application (PID)", L"应用程序 (PID)" },
+ /* S_FL_COL_TARGET */ { L"Target", L"目标" },
+ /* S_FL_COL_PROTO */ { L"Protocol", L"协议" },
+ /* S_FL_COL_STATUS */ { L"Time / Status", L"时间 / 状态" },
+ /* S_FL_COL_PROXY */ { L"Rule : Proxy", L"规则 : 代理" },
+ /* S_FL_COL_SENT */ { L"Sent", L"已发送" },
+ /* S_FL_COL_RECV */ { L"Received", L"已接收" },
+ /* S_FL_CLOSED */ { L"Closed", L"已关闭" },
+ /* S_FL_CLEAR */ { L"Clear closed", L"清除已关闭" },
/* S_BTN_CHECK */ { L"Proxy Test", L"代理测试" },
/* S_TEST_OK */ { L"Proxy is reachable.\n\n%s", L"代理可访问。\n\n%s" },
/* S_TEST_FAIL */ { L"Proxy test failed.\n\n%s", L"代理测试失败。\n\n%s" },
diff --git a/Windows/gui/main.c b/Windows/gui/main.c
index 3b0b2df..e70a6a6 100644
--- a/Windows/gui/main.c
+++ b/Windows/gui/main.c
@@ -166,6 +166,7 @@ static const wchar_t* ProtoName(int i) { return i == 1 ? L"UDP" : i == 2 ? L"BO
// log panel + connection filters (split out)
#include "ui/logview.h"
+#include "ui/flows.h"
// forward decls
static void SaveActive(void);
@@ -435,6 +436,9 @@ static void RelocalizeUI(HWND hwnd)
TCITEMW ti; ti.mask = TCIF_TEXT;
ti.pszText = (LPWSTR)T(S_TAB_CONN); TabCtrl_SetItem(g_hTab, 0, &ti);
ti.pszText = (LPWSTR)T(S_TAB_ACT); TabCtrl_SetItem(g_hTab, 1, &ti);
+ ti.pszText = (LPWSTR)T(S_TAB_FLOWS); TabCtrl_SetItem(g_hTab, 2, &ti);
+ FlowsSetColumns();
+ SetWindowTextW(g_hFlowsClear, T(S_FL_CLEAR));
// The tab strip, the Clear buttons and the search cue banners all carry localized
// text too - refresh them here so a language switch updates them without a restart.
SetWindowTextW(g_hConnClear, T(S_BTN_CLEARLOGS));
@@ -502,6 +506,8 @@ static void ApplyZoom(HWND hwnd)
SendMessageW(g_hTab, WM_SETFONT, (WPARAM)g_hUi, TRUE);
SendMessageW(g_hConnLog, WM_SETFONT, (WPARAM)g_hMono, TRUE);
SendMessageW(g_hActLog, WM_SETFONT, (WPARAM)g_hMono, TRUE);
+ SendMessageW(g_hFlows, WM_SETFONT, (WPARAM)g_hUi, TRUE);
+ SendMessageW(g_hFlowsClear, WM_SETFONT, (WPARAM)g_hUi, TRUE);
SendMessageW(g_hConnSearch, WM_SETFONT, (WPARAM)g_hUi, TRUE);
SendMessageW(g_hActSearch, WM_SETFONT, (WPARAM)g_hUi, TRUE);
SendMessageW(g_hConnClear, WM_SETFONT, (WPARAM)g_hUi, TRUE);
@@ -564,11 +570,16 @@ static void LayoutMain(HWND hwnd)
MoveWindow(g_hActClear, 4 + searchW + gap, top - 1, clearW, barH - 2, TRUE);
MoveWindow(g_hConnLog, 2, logTop, rc.right - 4, logH, TRUE);
MoveWindow(g_hActLog, 2, logTop, rc.right - 4, logH, TRUE);
+ MoveWindow(g_hFlowsClear, 4, top - 1, clearW, barH - 2, TRUE);
+ MoveWindow(g_hFlows, 2, logTop, rc.right - 4, logH, TRUE);
}
static void SelectTab(int idx)
{
int c = (idx == 0) ? SW_SHOW : SW_HIDE;
int a = (idx == 1) ? SW_SHOW : SW_HIDE;
+ int f = (idx == 2) ? SW_SHOW : SW_HIDE;
+ ShowWindow(g_hFlows, f); ShowWindow(g_hFlowsClear, f);
+ FlowsActivate(g_hMain, idx == 2);
ShowWindow(g_hConnLog, c); ShowWindow(g_hConnSearch, c); ShowWindow(g_hConnClear, c);
ShowWindow(g_hActLog, a); ShowWindow(g_hActSearch, a); ShowWindow(g_hActClear, a);
}
@@ -676,6 +687,10 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
TCITEMW ti; ti.mask = TCIF_TEXT;
ti.pszText = (LPWSTR)T(S_TAB_CONN); TabCtrl_InsertItem(g_hTab, 0, &ti);
ti.pszText = (LPWSTR)T(S_TAB_ACT); TabCtrl_InsertItem(g_hTab, 1, &ti);
+ ti.pszText = (LPWSTR)T(S_TAB_FLOWS); TabCtrl_InsertItem(g_hTab, 2, &ti);
+ FlowsCreate(hwnd);
+ SendMessageW(g_hFlows, WM_SETFONT, (WPARAM)g_hUi, TRUE);
+ SendMessageW(g_hFlowsClear, WM_SETFONT, (WPARAM)g_hUi, TRUE);
DWORD es = WS_CHILD | ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL | WS_BORDER;
g_hConnLog = CreateWindowExW(0, L"EDIT", NULL, es | WS_VISIBLE, 0, 0, 0, 0, hwnd, NULL, g_hInst, NULL);
@@ -859,10 +874,12 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
case WM_NOTIFY:
{
LPNMHDR nh = (LPNMHDR)lp;
+ if (nh->hwndFrom == g_hFlows) return FlowsNotify(lp);
if (nh->hwndFrom == g_hTab && nh->code == TCN_SELCHANGE) SelectTab(TabCtrl_GetCurSel(g_hTab));
return 0;
}
case WM_TIMER:
+ if (wp == TIMER_FLOWS) { if (IsWindowVisible(hwnd) && !IsIconic(hwnd)) FlowsPollAsync(); return 0; } // only while the Live Connections tab is open
if (wp == TIMER_LOG)
{
int processed = LogStoreFlush(&g_connStore) + LogStoreFlush(&g_actStore);
@@ -886,6 +903,7 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
}
return 0;
}
+ case WM_APP_FLOWS: FlowsOnResult((UINT32)wp); return 0;
case WM_APP_TRAY:
if (LOWORD(lp) == WM_LBUTTONDBLCLK) ShowMainWindow(hwnd);
else if (LOWORD(lp) == WM_RBUTTONUP)
@@ -913,6 +931,7 @@ static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
}
switch (id)
{
+ case IDC_FLOWS_CLEAR: FlowsClearClosed(); return 0;
case IDM_PROXY_SETTINGS: DialogBoxW(g_hInst, MAKEINTRESOURCEW(IDD_SERVERS), hwnd, ServersDlgProc); return 0;
case IDM_PROXY_RULES: DialogBoxW(g_hInst, MAKEINTRESOURCEW(IDD_RULES), hwnd, RulesDlgProc); return 0;
case IDM_PROXY_ENABLE:
diff --git a/Windows/gui/ui/flows.h b/Windows/gui/ui/flows.h
new file mode 100644
index 0000000..4d22b21
--- /dev/null
+++ b/Windows/gui/ui/flows.h
@@ -0,0 +1,353 @@
+// flows.h - the "Live Connections" tab: the proxied TCP connections and UDP flows that are active right now.
+//
+// While the tab is open the engine is asked for a snapshot once a second. This file keeps the rows between snapshots,
+// notices the ones that vanished (they turn grey and stay listed until "Clear closed" is pressed; when FLOW_ROWS_MAX
+// rows are held the oldest finished one is replaced) and feeds a virtual ListView, which stores no text of its own -
+// cell text is produced on demand for the visible rows only. Leaving the tab stops the timer and frees the snapshot
+// buffer, so polling costs nothing while it is not looked at; the finished rows are kept.
+//
+// Included by main.c (after the log view); the pieces that need a window are at the bottom.
+
+#define FLOW_ROWS_MAX 1200 // hard cap on rows kept (live + finished); ~190 KB at most
+#define FLOW_POLL_MS 1000
+#define IDC_FLOWS 3010
+#define IDC_FLOWS_CLEAR 3011
+#define TIMER_FLOWS 2
+
+typedef struct {
+ UINT64 id;
+ DWORD pid;
+ UINT32 proxyId;
+ UINT32 ruleId; // engine id of the rule that matched (0 = not known)
+ ULONGLONG firstSeen; // tick when the connection started (engine age when known, else first poll that saw it)
+ ULONGLONG closedAt; // 0 = still alive
+ UINT64 sent, received;
+ UINT16 port;
+ UINT8 udp, v6;
+ char name[40]; // UTF-8
+ char host[64]; // UTF-8
+} FlowRow;
+
+static FlowRow* g_fl = NULL; // rows, in the order they appeared
+static int g_flN = 0, g_flCap = 0;
+static int* g_flView = NULL; // g_fl indexes in display order
+static int g_flSortCol = 3, g_flSortAsc = 0; // default: newest first
+static ULONGLONG g_flNow = 0; // tick of the last poll (cell text is computed against it)
+static HWND g_hFlows = NULL, g_hFlowsClear = NULL;
+static PBFlow* g_flSnap = NULL; // snapshot buffer, allocated only while the tab is open
+
+static void FlowsClear(void)
+{
+ free(g_fl); free(g_flView);
+ g_fl = NULL; g_flView = NULL; g_flN = g_flCap = 0;
+}
+
+// ---- display order ----
+static int FlowCmp(const void* a, const void* b)
+{
+ const FlowRow* x = &g_fl[*(const int*)a]; const FlowRow* y = &g_fl[*(const int*)b];
+ int c = 0;
+ switch (g_flSortCol)
+ {
+ case 0: c = _stricmp(x->name, y->name); if (!c) c = (x->pid > y->pid) - (x->pid < y->pid); break;
+ case 1: c = _stricmp(x->host, y->host); if (!c) c = (x->port > y->port) - (x->port < y->port); break;
+ case 2: c = (x->udp > y->udp) - (x->udp < y->udp); break;
+ case 3: c = (x->firstSeen > y->firstSeen) - (x->firstSeen < y->firstSeen); break; // ascending = longest running first
+ case 4: c = (x->ruleId > y->ruleId) - (x->ruleId < y->ruleId); if (!c) c = (x->proxyId > y->proxyId) - (x->proxyId < y->proxyId); break;
+ case 5: c = (x->sent > y->sent) - (x->sent < y->sent); break;
+ default: c = (x->received > y->received) - (x->received < y->received); break;
+ }
+ if (c == 0) c = (x->id > y->id) - (x->id < y->id); // stable
+ return g_flSortAsc ? c : -c;
+}
+static void FlowsSortView(void)
+{
+ for (int i = 0; i < g_flN; i++) g_flView[i] = i;
+ if (g_flN > 1) qsort(g_flView, (size_t)g_flN, sizeof(int), FlowCmp);
+}
+
+// ---- keeping the rows ----
+static void FlowSet(FlowRow* r, const PBFlow* s)
+{
+ r->pid = s->pid; r->proxyId = s->proxy_config_id; r->ruleId = s->rule_id; r->port = s->port; r->udp = s->is_udp; r->v6 = s->is_ipv6;
+ r->sent = s->sent; r->received = s->received;
+ memcpy(r->name, s->name, sizeof(r->name)); r->name[sizeof(r->name) - 1] = 0;
+ memcpy(r->host, s->host, sizeof(r->host)); r->host[sizeof(r->host) - 1] = 0;
+}
+
+// Merges one snapshot (n flows) into the rows. `truncated` = the engine had more flows than it returned, so a flow
+// that is missing from the snapshot may still be alive and must not be marked finished.
+static void FlowsApply(const PBFlow* snap, int n, BOOL truncated, ULONGLONG now)
+{
+ int oldN = g_flN;
+ unsigned char* seen = oldN > 0 ? (unsigned char*)calloc((size_t)oldN, 1) : NULL;
+ if (oldN > 0 && seen == NULL) return; // out of memory: keep what is shown
+
+ for (int i = 0; i < n; i++)
+ {
+ const PBFlow* s = &snap[i];
+ int j = 0;
+ while (j < oldN && g_fl[j].id != s->id) j++; // a few hundred rows at most, once a second
+ ULONGLONG start = (s->age_ms != 0xFFFFFFFFu && s->age_ms <= now) ? now - s->age_ms : now;
+ if (j < oldN)
+ {
+ seen[j] = 1;
+ FlowRow* r = &g_fl[j];
+ if (r->closedAt) { r->closedAt = 0; r->firstSeen = start; } // an idle UDP flow that woke up again
+ FlowSet(r, s);
+ }
+ else if (g_flN < FLOW_ROWS_MAX)
+ {
+ if (g_flN == g_flCap)
+ {
+ int nc = g_flCap ? g_flCap * 2 : 64;
+ FlowRow* g = (FlowRow*)realloc(g_fl, (size_t)nc * sizeof(FlowRow));
+ if (!g) continue;
+ g_fl = g; g_flCap = nc;
+ }
+ FlowRow* r = &g_fl[g_flN++];
+ ZeroMemory(r, sizeof(*r));
+ r->id = s->id; r->firstSeen = start;
+ FlowSet(r, s);
+ }
+ else // full: the oldest finished row makes room
+ {
+ int e = -1;
+ for (int q = 0; q < oldN; q++)
+ if (g_fl[q].closedAt && (e < 0 || g_fl[q].closedAt < g_fl[e].closedAt)) e = q;
+ if (e >= 0)
+ {
+ seen[e] = 1; // the new flow lives in this slot now
+ FlowRow* r = &g_fl[e];
+ ZeroMemory(r, sizeof(*r));
+ r->id = s->id; r->firstSeen = start;
+ FlowSet(r, s);
+ }
+ }
+ }
+ if (!truncated)
+ for (int j = 0; j < oldN; j++)
+ if (!seen[j] && g_fl[j].closedAt == 0) g_fl[j].closedAt = now;
+ free(seen);
+
+ int* v = (int*)realloc(g_flView, (size_t)(g_flN > 0 ? g_flN : 1) * sizeof(int));
+ if (!v) { g_flN = 0; return; }
+ g_flView = v;
+ g_flNow = now;
+ FlowsSortView();
+}
+
+// ---- cell text ----
+static void FlowDuration(ULONGLONG ms, wchar_t* out, int cch)
+{
+ ULONGLONG s = ms / 1000;
+ if (s >= 3600) _snwprintf_s(out, cch, _TRUNCATE, L"%llu:%02llu:%02llu", s / 3600, (s / 60) % 60, s % 60);
+ else _snwprintf_s(out, cch, _TRUNCATE, L"%llu:%02llu", s / 60, s % 60);
+}
+static void FlowBytes(UINT64 b, wchar_t* out, int cch)
+{
+ if (b < 1024) _snwprintf_s(out, cch, _TRUNCATE, L"%llu B", b);
+ else if (b < 1024ull * 1024) _snwprintf_s(out, cch, _TRUNCATE, L"%.1f KB", (double)b / 1024.0);
+ else if (b < 1024ull << 20) _snwprintf_s(out, cch, _TRUNCATE, L"%.1f MB", (double)b / (1024.0 * 1024.0));
+ else _snwprintf_s(out, cch, _TRUNCATE, L"%.2f GB", (double)b / (1024.0 * 1024.0 * 1024.0));
+}
+static void FlowUtf8(const char* s, wchar_t* out, int cch)
+{
+ if (cch <= 0) return;
+ if (MultiByteToWideChar(CP_UTF8, 0, s, -1, out, cch) == 0) out[0] = 0;
+}
+// "Rule : Proxy Name (SOCKS5 host:port)" - which rule sent the connection through which proxy. A rule that is no longer
+// in the profile (or an engine that does not say) leaves just the proxy; the engine uses the first proxy for id 0.
+static void FlowRuleProxy(UINT32 ruleId, UINT32 proxyId, wchar_t* out, int cch)
+{
+ wchar_t rule[128]; rule[0] = 0;
+ if (ruleId)
+ for (int i = 0; i < g_profile.ruleCount; i++)
+ if (g_profile.rule[i].nativeId == ruleId) { lstrcpynW(rule, g_profile.rule[i].name[0] ? g_profile.rule[i].name : g_profile.rule[i].proc, 128); break; }
+ wchar_t prox[320];
+ const PBConfig* c = NULL;
+ for (int i = 0; i < g_profile.cfgCount && !c; i++)
+ if (g_profile.cfg[i].nativeId == proxyId || (proxyId == 0 && i == 0)) c = &g_profile.cfg[i];
+ if (c) _snwprintf_s(prox, ARRAYSIZE(prox), _TRUNCATE, L"%s (%s %s:%s)", c->name[0] ? c->name : c->host, c->type, c->host, c->port);
+ else _snwprintf_s(prox, ARRAYSIZE(prox), _TRUNCATE, L"#%lu", (unsigned long)proxyId);
+ if (rule[0]) _snwprintf_s(out, cch, _TRUNCATE, L"%s : %s", rule, prox);
+ else lstrcpynW(out, prox, cch);
+}
+
+static void FlowText(const FlowRow* r, int col, ULONGLONG now, wchar_t* out, int cch)
+{
+ wchar_t a[96], b[64];
+ if (cch <= 0) return;
+ out[0] = 0;
+ switch (col)
+ {
+ case 0:
+ if (r->name[0]) { FlowUtf8(r->name, a, 96); _snwprintf_s(out, cch, _TRUNCATE, L"%s (%lu)", a, (unsigned long)r->pid); }
+ else _snwprintf_s(out, cch, _TRUNCATE, L"PID %lu", (unsigned long)r->pid);
+ break;
+ case 1:
+ FlowUtf8(r->host, a, 96);
+ if (wcschr(a, L':')) _snwprintf_s(out, cch, _TRUNCATE, L"[%s]:%u", a, r->port); // an IPv6 literal
+ else _snwprintf_s(out, cch, _TRUNCATE, L"%s:%u", a, r->port);
+ break;
+ case 2: lstrcpynW(out, r->udp ? L"UDP" : L"TCP", cch); break;
+ case 3:
+ if (r->closedAt) { FlowDuration(r->closedAt - r->firstSeen, b, 64); _snwprintf_s(out, cch, _TRUNCATE, L"%s %s", T(S_FL_CLOSED), b); }
+ else FlowDuration(now > r->firstSeen ? now - r->firstSeen : 0, out, cch);
+ break;
+ case 4: FlowRuleProxy(r->ruleId, r->proxyId, out, cch); break;
+ case 5: FlowBytes(r->sent, out, cch); break;
+ default: FlowBytes(r->received, out, cch); break;
+ }
+}
+
+// ---- the window ----
+static void DarkListView(HWND lv, DWORD extraExStyle); // dialogs.h
+
+static const int g_flColStr[7] = { S_FL_COL_APP, S_FL_COL_TARGET, S_FL_COL_PROTO, S_FL_COL_STATUS, S_FL_COL_PROXY, S_FL_COL_SENT, S_FL_COL_RECV };
+
+static void FlowsSetColumns(void)
+{
+ for (int i = 0; i < 7; i++)
+ {
+ LVCOLUMNW c; c.mask = LVCF_TEXT; c.pszText = (LPWSTR)T(g_flColStr[i]);
+ ListView_SetColumn(g_hFlows, i, &c);
+ }
+}
+
+static HWND FlowsCreate(HWND parent)
+{
+ g_hFlows = CreateWindowExW(0, WC_LISTVIEWW, NULL,
+ WS_CHILD | WS_BORDER | WS_TABSTOP | LVS_REPORT | LVS_OWNERDATA | LVS_SHOWSELALWAYS | LVS_SINGLESEL,
+ 0, 0, 0, 0, parent, (HMENU)(UINT_PTR)IDC_FLOWS, g_hInst, NULL);
+ if (!g_hFlows) return NULL;
+ DarkListView(g_hFlows, LVS_EX_LABELTIP);
+ static const int w[7] = { 190, 250, 70, 120, 330, 90, 90 };
+ LVCOLUMNW c; c.mask = LVCF_TEXT | LVCF_WIDTH;
+ for (int i = 0; i < 7; i++) { c.pszText = (LPWSTR)T(g_flColStr[i]); c.cx = Sc(w[i]); ListView_InsertColumn(g_hFlows, i, &c); }
+ g_hFlowsClear = CreateWindowExW(0, L"BUTTON", T(S_FL_CLEAR), WS_CHILD | BS_PUSHBUTTON | WS_TABSTOP,
+ 0, 0, 0, 0, parent, (HMENU)(UINT_PTR)IDC_FLOWS_CLEAR, g_hInst, NULL);
+ return g_hFlows;
+}
+
+// "Clear closed": removes every finished row; connections that are still alive stay.
+static void FlowsClearClosed(void)
+{
+ int k = 0;
+ for (int j = 0; j < g_flN; j++) if (g_fl[j].closedAt == 0) g_fl[k++] = g_fl[j];
+ g_flN = k;
+ if (g_flView) FlowsSortView();
+ if (g_hFlows) { ListView_SetItemCountEx(g_hFlows, g_flN, LVSICF_NOINVALIDATEALL); InvalidateRect(g_hFlows, NULL, FALSE); }
+}
+
+// Merges the snapshot sitting in g_flSnap (n flows) into the rows and refreshes the list. UI thread.
+static void FlowsShowSnapshot(UINT32 n)
+{
+ if (n > PB_FLOWS_MAX_GUI) n = PB_FLOWS_MAX_GUI;
+ FlowsApply(g_flSnap, (int)n, n >= PB_FLOWS_MAX_GUI, GetTickCount64());
+ ListView_SetItemCountEx(g_hFlows, g_flN, LVSICF_NOINVALIDATEALL | LVSICF_NOSCROLL);
+ InvalidateRect(g_hFlows, NULL, FALSE);
+}
+
+// Asking the engine goes over a pipe to the service. The timer must never freeze the window if the service is slow,
+// so the call runs on a short-lived worker thread and posts the result back; a poll that is still waiting is not
+// started twice. (FlowsPoll is the same thing done in place, for the tests.)
+#define WM_APP_FLOWS (WM_APP + 20)
+static volatile LONG g_flBusy = 0; // 1 while a worker owns g_flSnap
+static BOOL g_flActive = FALSE; // the tab is open
+static HWND g_flMain = NULL;
+
+static void FlowsPoll(void)
+{
+ if (!g_hFlows || !g_api.GetFlows || g_flBusy) return;
+ if (!g_flSnap) g_flSnap = (PBFlow*)malloc(sizeof(PBFlow) * PB_FLOWS_MAX_GUI);
+ if (!g_flSnap) return;
+ FlowsShowSnapshot(g_api.GetFlows(g_flSnap, PB_FLOWS_MAX_GUI));
+}
+
+static DWORD WINAPI FlowsWorker(LPVOID arg)
+{
+ (void)arg;
+ UINT32 n = g_api.GetFlows(g_flSnap, PB_FLOWS_MAX_GUI);
+ PostMessageW(g_flMain, WM_APP_FLOWS, (WPARAM)n, 0);
+ return 0;
+}
+
+static void FlowsPollAsync(void)
+{
+ if (!g_hFlows || !g_api.GetFlows || !g_flActive) return;
+ if (InterlockedCompareExchange(&g_flBusy, 1, 0) != 0) return; // the last call has not come back yet
+ if (!g_flSnap) g_flSnap = (PBFlow*)malloc(sizeof(PBFlow) * PB_FLOWS_MAX_GUI);
+ HANDLE t = g_flSnap ? CreateThread(NULL, 0, FlowsWorker, NULL, 0, NULL) : NULL;
+ if (!t) { InterlockedExchange(&g_flBusy, 0); return; }
+ CloseHandle(t);
+}
+
+// WM_APP_FLOWS: the worker is done and g_flSnap holds `n` flows.
+static void FlowsOnResult(UINT32 n)
+{
+ if (g_flActive && g_flSnap) FlowsShowSnapshot(n);
+ if (!g_flActive) { free(g_flSnap); g_flSnap = NULL; } // the tab was closed while the call was out
+ InterlockedExchange(&g_flBusy, 0);
+}
+
+// Opening the tab starts polling. Leaving it stops the timer and frees the snapshot buffer; the rows stay (what was
+// alive is marked finished at that moment - if it is still running, the next poll after coming back revives it).
+static void FlowsActivate(HWND main, BOOL on)
+{
+ if (!g_hFlows) return;
+ g_flMain = main;
+ g_flActive = on;
+ if (on)
+ {
+ SetTimer(main, TIMER_FLOWS, FLOW_POLL_MS, NULL);
+ FlowsPollAsync();
+ }
+ else
+ {
+ KillTimer(main, TIMER_FLOWS);
+ if (!g_flBusy) { free(g_flSnap); g_flSnap = NULL; } // a worker still using it frees it in FlowsOnResult
+ ULONGLONG now = GetTickCount64();
+ for (int j = 0; j < g_flN; j++) if (g_fl[j].closedAt == 0) g_fl[j].closedAt = now;
+ }
+}
+
+// WM_NOTIFY from the list: cell text, header click sorting and grey text for finished connections.
+static LRESULT FlowsNotify(LPARAM lp)
+{
+ LPNMHDR nh = (LPNMHDR)lp;
+ switch (nh->code)
+ {
+ case LVN_GETDISPINFOW:
+ {
+ NMLVDISPINFOW* di = (NMLVDISPINFOW*)lp;
+ if ((di->item.mask & LVIF_TEXT) && di->item.pszText && di->item.cchTextMax > 0)
+ {
+ di->item.pszText[0] = 0;
+ if (di->item.iItem >= 0 && di->item.iItem < g_flN && di->item.iSubItem >= 0 && di->item.iSubItem < 7)
+ FlowText(&g_fl[g_flView[di->item.iItem]], di->item.iSubItem, g_flNow, di->item.pszText, di->item.cchTextMax);
+ }
+ return 0;
+ }
+ case LVN_COLUMNCLICK:
+ {
+ int c = ((NMLISTVIEW*)lp)->iSubItem;
+ if (c == g_flSortCol) g_flSortAsc = !g_flSortAsc; else { g_flSortCol = c; g_flSortAsc = (c <= 2); }
+ if (g_flN > 0) { FlowsSortView(); InvalidateRect(g_hFlows, NULL, FALSE); }
+ return 0;
+ }
+ case NM_CUSTOMDRAW:
+ {
+ NMLVCUSTOMDRAW* cd = (NMLVCUSTOMDRAW*)lp;
+ if (cd->nmcd.dwDrawStage == CDDS_PREPAINT) return CDRF_NOTIFYITEMDRAW;
+ if (cd->nmcd.dwDrawStage == CDDS_ITEMPREPAINT)
+ {
+ int i = (int)cd->nmcd.dwItemSpec;
+ if (i >= 0 && i < g_flN && g_fl[g_flView[i]].closedAt) cd->clrText = RGB(128, 128, 128);
+ return CDRF_NEWFONT;
+ }
+ return CDRF_DODEFAULT;
+ }
+ }
+ return 0;
+}
diff --git a/Windows/src/ProxyBridge.c b/Windows/src/ProxyBridge.c
index 8d5cf3c..3f3c43d 100644
--- a/Windows/src/ProxyBridge.c
+++ b/Windows/src/ProxyBridge.c
@@ -316,7 +316,7 @@ DWORD WINAPI packet_processor(LPVOID arg)
// HTTP proxy can't relay UDP - drop
continue;
}
- add_connection_v6(sp, TRUE, (const UINT8*)ipv6_header->SrcAddr, (const UINT8*)ipv6_header->DstAddr, dp, pcid6u);
+ add_connection_v6(sp, TRUE, (const UINT8*)ipv6_header->SrcAddr, (const UINT8*)ipv6_header->DstAddr, dp, pcid6u, pid6u, g_tl_rule_id);
udp_header->DstPort = htons(LOCAL_UDP_RELAY_PORT);
static const UINT8 _lb6up[16]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
@@ -531,7 +531,7 @@ DWORD WINAPI packet_processor(LPVOID arg)
}
else if (action6 == RULE_ACTION_PROXY)
{
- add_connection_v6(sp, FALSE, (const UINT8*)ipv6_header->SrcAddr, (const UINT8*)ipv6_header->DstAddr, dp, proxy_config_id6);
+ add_connection_v6(sp, FALSE, (const UINT8*)ipv6_header->SrcAddr, (const UINT8*)ipv6_header->DstAddr, dp, proxy_config_id6, pid6, g_tl_rule_id);
port_set_decided(sp);
tcp_header->DstPort = htons(g_local_relay_port);
@@ -721,7 +721,7 @@ DWORD WINAPI packet_processor(LPVOID arg)
if (action == RULE_ACTION_PROXY)
{
- add_connection(src_port, TRUE, src_ip, dest_ip, dest_port, proxy_config_id);
+ add_connection(src_port, TRUE, src_ip, dest_ip, dest_port, proxy_config_id, pid, g_tl_rule_id);
// redirect to UDP relay server at 127.0.0.1:34011
udp_header->DstPort = htons(LOCAL_UDP_RELAY_PORT);
@@ -983,7 +983,7 @@ DWORD WINAPI packet_processor(LPVOID arg)
}
else if (action == RULE_ACTION_PROXY)
{
- add_connection(src_port, FALSE, src_ip, orig_dest_ip, orig_dest_port, proxy_config_id);
+ add_connection(src_port, FALSE, src_ip, orig_dest_ip, orig_dest_port, proxy_config_id, pid, g_tl_rule_id);
// Mark this port as decided (not direct) so subsequent packets from
// the same source port skip the rule check. The is_connection_tracked
// branch above handles the actual per-packet redirect.
@@ -1041,6 +1041,56 @@ DWORD WINAPI packet_processor(LPVOID arg)
// until they end. TRUE (the default) applies the rules again.
// "Log every connection": FALSE (default) shows a connection once per (process, destination, port, action);
// TRUE logs every new TCP connection and every new UDP flow.
+// Copies at most `cap`-1 bytes of a UTF-8 string, never cutting a multi-byte character in half.
+static void copy_utf8(char *dst, size_t cap, const char *src)
+{
+ size_t n = strnlen(src, cap - 1);
+ if (src[n] != '\0') // cut: step back to the start of the character
+ while (n > 0 && ((unsigned char)src[n] & 0xC0) == 0x80) n--;
+ memcpy(dst, src, n);
+ dst[n] = '\0';
+}
+
+PROXYBRIDGE_API UINT32 ProxyBridge_GetFlows(PB_FLOW *out, UINT32 max)
+{
+ if (out == NULL || max == 0) return 0;
+ if (max > PB_FLOWS_MAX) max = PB_FLOWS_MAX;
+ UINT32 n = relay_flows_snapshot(out, max);
+ if (n < max) n += udp_flows_snapshot(out + n, max - n);
+
+ // Names and hosts are looked up here, after every engine lock was released. Process names come from a small
+ // cache (10 s): resolving one means opening the process (or, for a protected / already exited one, walking the
+ // whole process list), which is pointless to repeat every second for a connection that lives for minutes.
+ static struct { DWORD pid; ULONGLONG tick; char name[40]; } cache[64];
+ static volatile LONG cache_busy = 0;
+ ULONGLONG now = GetTickCount64();
+ BOOL have_cache = InterlockedCompareExchange(&cache_busy, 1, 0) == 0; // a second caller simply skips the cache
+ for (UINT32 i = 0; i < n; i++)
+ {
+ PB_FLOW *f = &out[i];
+ int slot = (int)(f->pid % 64);
+ if (have_cache && cache[slot].pid == f->pid && cache[slot].tick != 0 && now - cache[slot].tick < 10000)
+ copy_utf8(f->name, sizeof(f->name), cache[slot].name);
+ else
+ {
+ char full[MAX_PROCESS_NAME], nm[40];
+ nm[0] = '\0';
+ if (f->pid != 0 && get_process_name_from_pid(f->pid, full, sizeof(full)))
+ copy_utf8(nm, sizeof(nm), extract_filename(full));
+ copy_utf8(f->name, sizeof(f->name), nm);
+ if (have_cache) { cache[slot].pid = f->pid; cache[slot].tick = now; memcpy(cache[slot].name, nm, sizeof(nm)); }
+ }
+
+ char dom[256]; dom[0] = '\0';
+ BOOL have = f->is_ipv6 ? dns_cache_lookup_v6(f->dest, dom, sizeof(dom)) : dns_cache_lookup(*(UINT32 *)f->dest, dom, sizeof(dom));
+ if (have && dom[0] != '\0' && strlen(dom) < sizeof(f->host)) { strcpy_s(f->host, sizeof(f->host), dom); continue; }
+ if (f->is_ipv6) { struct in6_addr a6; memcpy(&a6, f->dest, 16); if (!inet_ntop(AF_INET6, &a6, f->host, sizeof(f->host))) f->host[0] = '\0'; }
+ else format_ip_address(*(UINT32 *)f->dest, f->host, sizeof(f->host));
+ }
+ if (have_cache) InterlockedExchange(&cache_busy, 0);
+ return n;
+}
+
PROXYBRIDGE_API void ProxyBridge_SetLogEveryConnection(BOOL enable)
{
g_log_every_connection = enable ? TRUE : FALSE;
diff --git a/Windows/src/ProxyBridge.h b/Windows/src/ProxyBridge.h
index 33f407e..e3d149f 100644
--- a/Windows/src/ProxyBridge.h
+++ b/Windows/src/ProxyBridge.h
@@ -61,6 +61,26 @@ PROXYBRIDGE_API BOOL ProxyBridge_DeleteRule(UINT32 rule_id);
PROXYBRIDGE_API BOOL ProxyBridge_EditRule(UINT32 rule_id, const char* process_name, const char* target_hosts, const char* target_ports, const char* target_domains, RuleProtocol protocol, RuleAction action, UINT32 proxy_config_id, BOOL localhost_via_proxy);
PROXYBRIDGE_API BOOL ProxyBridge_MoveRuleToPosition(UINT32 rule_id, UINT32 new_position); // Move rule to specific position (1=first, 2=second, etc)
PROXYBRIDGE_API UINT32 ProxyBridge_GetRulePosition(UINT32 rule_id); // Get current position of rule in list (1-based)
+// Live connections: the flows ProxyBridge is relaying right now (proxied TCP connections and proxied UDP flows).
+// Direct and blocked traffic is not part of it - the engine never sees its data.
+#define PB_FLOWS_MAX 400
+typedef struct {
+ UINT64 id; // stable for the life of the flow
+ UINT32 pid;
+ UINT32 proxy_config_id;
+ UINT32 rule_id; // the rule that sent it through the proxy (0 = not known)
+ UINT32 age_ms; // time since the flow started; 0xFFFFFFFF = not known (UDP)
+ UINT64 sent; // payload bytes application -> proxy
+ UINT64 received; // payload bytes proxy -> application
+ UINT16 port; // destination port
+ UINT8 is_udp;
+ UINT8 is_ipv6;
+ UINT8 dest[16]; // raw destination address (the engine resolves it into `host`)
+ char name[40]; // process image name (UTF-8)
+ char host[64]; // destination: the domain if known, otherwise the address (UTF-8)
+} PB_FLOW;
+// Fills `out` with up to `max` (at most PB_FLOWS_MAX) live flows, newest first. Cheap enough to poll about once a second.
+PROXYBRIDGE_API UINT32 ProxyBridge_GetFlows(PB_FLOW* out, UINT32 max);
PROXYBRIDGE_API void ProxyBridge_SetLogEveryConnection(BOOL enable); // FALSE (default): Connections log skips repeats; TRUE: every new connection
PROXYBRIDGE_API void ProxyBridge_SetEnabled(BOOL enable); // main switch: FALSE pauses all rules for new connections (default TRUE)
PROXYBRIDGE_API void ProxyBridge_SetLogCallback(LogCallback callback);
diff --git a/Windows/src/pb_conntrack.c b/Windows/src/pb_conntrack.c
index 18ccb30..1704a54 100644
--- a/Windows/src/pb_conntrack.c
+++ b/Windows/src/pb_conntrack.c
@@ -36,7 +36,7 @@ void rev_unlink(CONNECTION_INFO *c)
c->rev_next = NULL;
}
-void add_connection(UINT16 src_port, BOOL is_udp, UINT32 src_ip, UINT32 dest_ip, UINT16 dest_port, UINT32 proxy_config_id)
+void add_connection(UINT16 src_port, BOOL is_udp, UINT32 src_ip, UINT32 dest_ip, UINT16 dest_port, UINT32 proxy_config_id, DWORD pid, UINT32 rule_id)
{
AcquireSRWLockExclusive(&lock);
@@ -49,6 +49,8 @@ void add_connection(UINT16 src_port, BOOL is_udp, UINT32 src_ip, UINT32 dest_ip,
if (existing->src_port == src_port && existing->is_udp == is_udp && !existing->is_ipv6) {
rev_unlink(existing); // dest may change (port reuse) - re-key the reverse index
existing->is_ipv6 = FALSE;
+ existing->pid = pid;
+ existing->rule_id = rule_id;
existing->src_ip = src_ip;
existing->orig_dest_ip = dest_ip;
existing->orig_dest_port = dest_port;
@@ -71,6 +73,8 @@ void add_connection(UINT16 src_port, BOOL is_udp, UINT32 src_ip, UINT32 dest_ip,
conn->src_port = src_port;
conn->is_udp = is_udp;
+ conn->pid = pid;
+ conn->rule_id = rule_id;
conn->src_ip = src_ip;
conn->orig_dest_ip = dest_ip;
conn->orig_dest_port = dest_port;
@@ -85,7 +89,7 @@ void add_connection(UINT16 src_port, BOOL is_udp, UINT32 src_ip, UINT32 dest_ip,
ReleaseSRWLockExclusive(&lock);
}
-void add_connection_v6(UINT16 src_port, BOOL is_udp, const UINT8 src_ip6[16], const UINT8 dest_ip6[16], UINT16 dest_port, UINT32 proxy_config_id)
+void add_connection_v6(UINT16 src_port, BOOL is_udp, const UINT8 src_ip6[16], const UINT8 dest_ip6[16], UINT16 dest_port, UINT32 proxy_config_id, DWORD pid, UINT32 rule_id)
{
AcquireSRWLockExclusive(&lock);
@@ -96,6 +100,8 @@ void add_connection_v6(UINT16 src_port, BOOL is_udp, const UINT8 src_ip6[16], co
if (existing->src_port == src_port && existing->is_udp == is_udp && existing->is_ipv6) {
rev_unlink(existing); // dest may change (port reuse) - re-key the reverse index
existing->is_ipv6 = TRUE;
+ existing->pid = pid;
+ existing->rule_id = rule_id;
memcpy(existing->src_ip6, src_ip6, 16);
memcpy(existing->orig_dest_ip6, dest_ip6, 16);
existing->orig_dest_port = dest_port;
@@ -118,6 +124,8 @@ void add_connection_v6(UINT16 src_port, BOOL is_udp, const UINT8 src_ip6[16], co
conn->src_port = src_port;
conn->is_udp = is_udp;
+ conn->pid = pid;
+ conn->rule_id = rule_id;
conn->src_ip = 0;
conn->orig_dest_ip = 0;
conn->is_ipv6 = TRUE;
@@ -134,6 +142,11 @@ void add_connection_v6(UINT16 src_port, BOOL is_udp, const UINT8 src_ip6[16], co
}
BOOL get_connection_full_v6(UINT16 src_port, BOOL is_udp, UINT8 dest_ip6[16], UINT16 *dest_port, UINT32 *proxy_config_id)
+{
+ return get_connection_full_v6_x(src_port, is_udp, dest_ip6, dest_port, proxy_config_id, NULL, NULL, 0);
+}
+
+BOOL get_connection_full_v6_x(UINT16 src_port, BOOL is_udp, UINT8 dest_ip6[16], UINT16 *dest_port, UINT32 *proxy_config_id, DWORD *pid, UINT32 *rule_id, UINT32 acct_up)
{
BOOL found = FALSE;
AcquireSRWLockShared(&lock);
@@ -144,6 +157,9 @@ BOOL get_connection_full_v6(UINT16 src_port, BOOL is_udp, UINT8 dest_ip6[16], UI
memcpy(dest_ip6, conn->orig_dest_ip6, 16);
*dest_port = conn->orig_dest_port;
if (proxy_config_id != NULL) *proxy_config_id = conn->proxy_config_id;
+ if (pid != NULL) *pid = conn->pid;
+ if (rule_id != NULL) *rule_id = conn->rule_id;
+ if (acct_up) InterlockedExchangeAdd64(&conn->up_bytes, (LONG64)acct_up);
InterlockedExchange64((LONGLONG volatile*)&conn->last_activity, (LONGLONG)GetTickCount64());
found = TRUE;
break;
@@ -155,10 +171,11 @@ BOOL get_connection_full_v6(UINT16 src_port, BOOL is_udp, UINT8 dest_ip6[16], UI
}
// Reverse lookup for IPv6 UDP relay responses: find src addr+port by orig dest ip6+port
-BOOL find_v6_udp_sender(const UINT8 orig_dest_ip6[16], UINT16 orig_dest_port, UINT8 src_ip6[16], UINT16 *src_port)
+BOOL find_v6_udp_sender(const UINT8 orig_dest_ip6[16], UINT16 orig_dest_port, UINT8 src_ip6[16], UINT16 *src_port, UINT32 acct_down)
{
BOOL found = FALSE;
ULONGLONG best = 0;
+ CONNECTION_INFO *winner = NULL;
AcquireSRWLockShared(&lock);
// O(1): only the reverse bucket for this (dest ip6, dest port).
for (CONNECTION_INFO *conn = connection_rev_table[rev_hash_v6(orig_dest_ip6, orig_dest_port)];
@@ -170,9 +187,11 @@ BOOL find_v6_udp_sender(const UINT8 orig_dest_ip6[16], UINT16 orig_dest_port, UI
*src_port = conn->src_port;
best = conn->last_activity;
found = TRUE;
+ winner = conn;
}
}
}
+ if (winner != NULL && acct_down) InterlockedExchangeAdd64(&winner->down_bytes, (LONG64)acct_down);
ReleaseSRWLockShared(&lock);
return found;
}
@@ -302,6 +321,11 @@ BOOL get_connection(UINT16 src_port, BOOL is_udp, UINT32 *dest_ip, UINT16 *dest_
}
BOOL get_connection_full(UINT16 src_port, BOOL is_udp, UINT32 *dest_ip, UINT16 *dest_port, UINT32 *proxy_config_id)
+{
+ return get_connection_full_x(src_port, is_udp, dest_ip, dest_port, proxy_config_id, NULL, NULL, 0);
+}
+
+BOOL get_connection_full_x(UINT16 src_port, BOOL is_udp, UINT32 *dest_ip, UINT16 *dest_port, UINT32 *proxy_config_id, DWORD *pid, UINT32 *rule_id, UINT32 acct_up)
{
BOOL found = FALSE;
@@ -317,6 +341,9 @@ BOOL get_connection_full(UINT16 src_port, BOOL is_udp, UINT32 *dest_ip, UINT16 *
*dest_ip = conn->orig_dest_ip;
*dest_port = conn->orig_dest_port;
if (proxy_config_id != NULL) *proxy_config_id = conn->proxy_config_id;
+ if (pid != NULL) *pid = conn->pid;
+ if (rule_id != NULL) *rule_id = conn->rule_id;
+ if (acct_up) InterlockedExchangeAdd64(&conn->up_bytes, (LONG64)acct_up);
InterlockedExchange64((LONGLONG volatile*)&conn->last_activity, (LONGLONG)GetTickCount64());
found = TRUE;
break;
@@ -393,6 +420,41 @@ void connection_fin(UINT16 src_port, BOOL is_ipv6, UINT8 bit)
ReleaseSRWLockExclusive(&lock);
}
+// Live proxied UDP flows for the live connections view. A UDP flow has no close event, so "live" means traffic in the
+// last UDP_FLOW_LIVE_MS; the view marks it closed when it stops being listed. One pass over the table under the shared
+// lock (4096 buckets), only when a client polls.
+UINT32 udp_flows_snapshot(PB_FLOW *out, UINT32 max)
+{
+ UINT32 n = 0;
+ ULONGLONG now = GetTickCount64();
+ AcquireSRWLockShared(&lock);
+ for (int i = 0; i < CONNECTION_HASH_SIZE && n < max; i++)
+ {
+ for (CONNECTION_INFO *c = connection_hash_table[i]; c != NULL && n < max; c = c->next)
+ {
+ if (!c->is_udp || !c->is_tracked) continue;
+ ULONGLONG last = c->last_activity;
+ if (last <= now && now - last > UDP_FLOW_LIVE_MS) continue;
+ PB_FLOW *f = &out[n++];
+ ZeroMemory(f, sizeof(*f));
+ f->id = ((UINT64)1 << 63) | ((UINT64)c->src_port << 1) | (c->is_ipv6 ? 1u : 0u);
+ f->pid = c->pid;
+ f->proxy_config_id = c->proxy_config_id;
+ f->rule_id = c->rule_id;
+ f->age_ms = 0xFFFFFFFFu;
+ f->sent = (UINT64)c->up_bytes;
+ f->received = (UINT64)c->down_bytes;
+ f->port = c->orig_dest_port;
+ f->is_udp = 1;
+ f->is_ipv6 = c->is_ipv6 ? 1 : 0;
+ if (c->is_ipv6) memcpy(f->dest, c->orig_dest_ip6, 16);
+ else memcpy(f->dest, &c->orig_dest_ip, 4);
+ }
+ }
+ ReleaseSRWLockShared(&lock);
+ return n;
+}
+
void cleanup_stale_connections(void)
{
ULONGLONG now = GetTickCount64();
diff --git a/Windows/src/pb_internal.h b/Windows/src/pb_internal.h
index 5e2dd44..f690630 100644
--- a/Windows/src/pb_internal.h
+++ b/Windows/src/pb_internal.h
@@ -112,6 +112,10 @@ typedef struct CONNECTION_INFO {
UINT32 rev_bucket; // reverse bucket this entry is currently linked in
BOOL in_rev; // TRUE while linked in the reverse table
UINT8 fin_flags; // TCP: 1 = app sent FIN, 2 = relay sent FIN (entry dropped when both seen)
+ DWORD pid; // owning process (shown in the live connections view)
+ UINT32 rule_id; // rule that matched (live connections view)
+ volatile LONG64 up_bytes; // UDP: payload bytes app -> proxy
+ volatile LONG64 down_bytes; // UDP: payload bytes proxy -> app
} CONNECTION_INFO;
typedef struct {
@@ -121,6 +125,8 @@ typedef struct {
UINT32 proxy_config_id;
BOOL is_ipv6;
UINT8 orig_dest_ip6[16];
+ DWORD pid;
+ UINT32 rule_id;
} CONNECTION_CONFIG;
typedef struct {
@@ -214,6 +220,7 @@ extern UINT16 g_local_relay_port;
// Set by match_rule*_inner on the calling thread: the "localhost via proxy" flag of the rule that
// produced the last verdict (FALSE when nothing matched). Read right after check_process_rule*().
extern __declspec(thread) BOOL g_tl_rule_localhost;
+extern __declspec(thread) UINT32 g_tl_rule_id; // same for the id of the rule that produced the verdict (0 = none)
extern LogCallback g_log_callback;
extern ConnectionCallback g_connection_callback;
extern char *g_pidtbl_buf;
@@ -341,10 +348,11 @@ UINT32 rev_hash_v4(UINT32 dest_ip, UINT16 dest_port);
UINT32 rev_hash_v6(const UINT8 dest_ip6[16], UINT16 dest_port);
void rev_insert(CONNECTION_INFO *c);
void rev_unlink(CONNECTION_INFO *c);
-void add_connection(UINT16 src_port, BOOL is_udp, UINT32 src_ip, UINT32 dest_ip, UINT16 dest_port, UINT32 proxy_config_id);
-void add_connection_v6(UINT16 src_port, BOOL is_udp, const UINT8 src_ip6[16], const UINT8 dest_ip6[16], UINT16 dest_port, UINT32 proxy_config_id);
+void add_connection(UINT16 src_port, BOOL is_udp, UINT32 src_ip, UINT32 dest_ip, UINT16 dest_port, UINT32 proxy_config_id, DWORD pid, UINT32 rule_id);
+void add_connection_v6(UINT16 src_port, BOOL is_udp, const UINT8 src_ip6[16], const UINT8 dest_ip6[16], UINT16 dest_port, UINT32 proxy_config_id, DWORD pid, UINT32 rule_id);
BOOL get_connection_full_v6(UINT16 src_port, BOOL is_udp, UINT8 dest_ip6[16], UINT16 *dest_port, UINT32 *proxy_config_id);
-BOOL find_v6_udp_sender(const UINT8 orig_dest_ip6[16], UINT16 orig_dest_port, UINT8 src_ip6[16], UINT16 *src_port);
+// acct_down: payload bytes to add to the winning flow's "received" counter (0 = none)
+BOOL find_v6_udp_sender(const UINT8 orig_dest_ip6[16], UINT16 orig_dest_port, UINT8 src_ip6[16], UINT16 *src_port, UINT32 acct_down);
// UDP flow validation for the app->relay redirect. A UDP "connection" is keyed by source port
// only, so it must be re-checked on every datagram: (a) if the destination changed (a socket
// that moves to another server, e.g. a voice call migrating) the entry is retargeted, and
@@ -372,6 +380,13 @@ void connection_fin(UINT16 src_port, BOOL is_ipv6, UINT8 bit);
BOOL is_connection_tracked(UINT16 src_port, BOOL is_udp, BOOL is_ipv6);
BOOL get_connection(UINT16 src_port, BOOL is_udp, UINT32 *dest_ip, UINT16 *dest_port);
BOOL get_connection_full(UINT16 src_port, BOOL is_udp, UINT32 *dest_ip, UINT16 *dest_port, UINT32 *proxy_config_id);
+// Same lookups, plus the owning pid (optional) and an optional byte count added to the flow's "sent" counter under the
+// same lock (the UDP relay uses it so counting costs no extra lookup).
+BOOL get_connection_full_x(UINT16 src_port, BOOL is_udp, UINT32 *dest_ip, UINT16 *dest_port, UINT32 *proxy_config_id, DWORD *pid, UINT32 *rule_id, UINT32 acct_up);
+BOOL get_connection_full_v6_x(UINT16 src_port, BOOL is_udp, UINT8 dest_ip6[16], UINT16 *dest_port, UINT32 *proxy_config_id, DWORD *pid, UINT32 *rule_id, UINT32 acct_up);
+// Live proxied UDP flows (active in the last UDP_FLOW_LIVE_MS), newest table order; raw fields only.
+#define UDP_FLOW_LIVE_MS 30000
+UINT32 udp_flows_snapshot(PB_FLOW *out, UINT32 max);
UINT32 get_connection_proxy_id(UINT16 src_port, BOOL is_udp);
void remove_connection(UINT16 src_port, BOOL is_udp, BOOL is_ipv6);
void cleanup_stale_connections(void);
@@ -390,7 +405,10 @@ DWORD WINAPI one_way_relay(LPVOID arg);
DWORD WINAPI transfer_handler(LPVOID arg);
BOOL relay_pool_start(void); // IOCP relay pool (pb_relay.c)
void relay_pool_stop(void);
-BOOL relay_start(SOCKET client, SOCKET proxy);
+// What the live connections view shows about a relayed TCP connection (copied into the relay record).
+typedef struct { DWORD pid; UINT32 proxy_id; UINT32 rule_id; UINT16 port; BOOL v6; UINT8 dest[16]; } FLOW_META;
+BOOL relay_start(SOCKET client, SOCKET proxy, const FLOW_META *meta);
+UINT32 relay_flows_snapshot(PB_FLOW *out, UINT32 max); // live proxied TCP connections, newest first; raw fields only
extern volatile LONG g_active_relays;
extern volatile LONG g_handler_threads; // per-connection handshake threads still running (Stop waits for them)
diff --git a/Windows/src/pb_relay.c b/Windows/src/pb_relay.c
index bd36c2e..4a4c473 100644
--- a/Windows/src/pb_relay.c
+++ b/Windows/src/pb_relay.c
@@ -166,9 +166,9 @@ DWORD WINAPI udp_relay_server(LPVOID arg)
UINT32 dest_ip;
UINT16 dest_port;
- if (get_connection(from_port, TRUE, &dest_ip, &dest_port))
+ UINT32 proxy_config_id = 0;
+ if (get_connection_full_x(from_port, TRUE, &dest_ip, &dest_port, &proxy_config_id, NULL, NULL, (UINT32)recv_len))
{
- UINT32 proxy_config_id = get_connection_proxy_id(from_port, TRUE);
PROXY_CONFIG *cfg = find_proxy_config(proxy_config_id);
if (cfg == NULL || cfg->type != PROXY_TYPE_SOCKS5)
@@ -300,7 +300,10 @@ DWORD WINAPI udp_relay_server(LPVOID arg)
// Keep winner's session alive (update outside loop so comparisons above
// use the original, unmodified timestamps for all candidates).
if (winner_conn != NULL)
+ {
InterlockedExchange64((LONGLONG volatile*)&winner_conn->last_activity, (LONGLONG)GetTickCount64());
+ InterlockedExchangeAdd64(&winner_conn->down_bytes, (LONG64)(recv_len - 10));
+ }
ReleaseSRWLockShared(&lock);
if (found)
@@ -329,7 +332,7 @@ DWORD WINAPI udp_relay_server(LPVOID arg)
UINT8 target_ip6[16];
UINT16 target_port = 0;
- if (find_v6_udp_sender(src_ip6, src_port, target_ip6, &target_port) && udp_relay_socket6 != INVALID_SOCKET)
+ if (find_v6_udp_sender(src_ip6, src_port, target_ip6, &target_port, (UINT32)(recv_len - 22)) && udp_relay_socket6 != INVALID_SOCKET)
{
struct sockaddr_in6 t6;
memset(&t6, 0, sizeof(t6));
@@ -357,7 +360,7 @@ DWORD WINAPI udp_relay_server(LPVOID arg)
UINT16 dest_port = 0;
UINT32 proxy_config_id = 0;
- if (get_connection_full_v6(from_port, TRUE, dest_ip6, &dest_port, &proxy_config_id))
+ if (get_connection_full_v6_x(from_port, TRUE, dest_ip6, &dest_port, &proxy_config_id, NULL, NULL, (UINT32)recv_len))
{
PROXY_CONFIG *cfg = find_proxy_config(proxy_config_id);
if (cfg != NULL && cfg->type == PROXY_TYPE_SOCKS5)
@@ -515,7 +518,7 @@ DWORD WINAPI local_proxy_server(LPVOID arg)
conn_config->is_ipv6 = FALSE;
UINT16 client_port = ntohs(client_addr.sin_port);
- if (get_connection_full(client_port, FALSE, &conn_config->orig_dest_ip, &conn_config->orig_dest_port, &conn_config->proxy_config_id) &&
+ if (get_connection_full_x(client_port, FALSE, &conn_config->orig_dest_ip, &conn_config->orig_dest_port, &conn_config->proxy_config_id, &conn_config->pid, &conn_config->rule_id, 0) &&
relay_peer_ok_v4(client_addr.sin_addr.s_addr, conn_config->orig_dest_ip))
{
InterlockedIncrement(&g_handler_threads);
@@ -544,7 +547,7 @@ DWORD WINAPI local_proxy_server(LPVOID arg)
conn_config->is_ipv6 = TRUE;
UINT16 client_port = ntohs(client_addr6.sin6_port);
- if (get_connection_full_v6(client_port, FALSE, conn_config->orig_dest_ip6, &conn_config->orig_dest_port, &conn_config->proxy_config_id) &&
+ if (get_connection_full_v6_x(client_port, FALSE, conn_config->orig_dest_ip6, &conn_config->orig_dest_port, &conn_config->proxy_config_id, &conn_config->pid, &conn_config->rule_id, 0) &&
relay_peer_ok_v6(&client_addr6.sin6_addr, conn_config->orig_dest_ip6))
{
InterlockedIncrement(&g_handler_threads);
@@ -600,6 +603,10 @@ static DWORD WINAPI connection_handler_impl(LPVOID arg)
BOOL is_ipv6 = config->is_ipv6;
UINT8 dest_ip6[16];
if (is_ipv6) memcpy(dest_ip6, config->orig_dest_ip6, 16);
+ FLOW_META meta;
+ ZeroMemory(&meta, sizeof(meta));
+ meta.pid = config->pid; meta.proxy_id = proxy_config_id; meta.rule_id = config->rule_id; meta.port = dest_port; meta.v6 = is_ipv6;
+ if (is_ipv6) memcpy(meta.dest, dest_ip6, 16); else memcpy(meta.dest, &dest_ip, 4);
SOCKET socks_sock;
struct sockaddr_in socks_addr;
@@ -711,7 +718,7 @@ static DWORD WINAPI connection_handler_impl(LPVOID arg)
WSAIoctl(client_sock, SIO_KEEPALIVE_VALS, &keepalive_settings, sizeof(keepalive_settings), NULL, 0, &bytes_returned, NULL, NULL);
// Preferred path: hand both sockets to the IOCP pool (no per-connection threads).
- if (relay_start(client_sock, socks_sock))
+ if (relay_start(client_sock, socks_sock, &meta))
return 0;
TRANSFER_CONFIG *transfer_config = (TRANSFER_CONFIG *)malloc(sizeof(TRANSFER_CONFIG));
@@ -874,6 +881,7 @@ typedef struct {
char *buf; // NULL while waiting
DWORD len, off;
int state;
+ volatile LONG64 bytes; // payload bytes this direction has delivered (read by the live connections view)
} RELAY_DIR;
struct RELAY_CONN {
SOCKET s[2];
@@ -881,9 +889,13 @@ struct RELAY_CONN {
volatile LONG refs; // directions still alive
volatile LONG closing;
RELAY_CONN *prev, *next;
+ UINT64 id; // live connections view
+ ULONGLONG start;
+ FLOW_META meta;
};
volatile LONG g_active_relays = 0;
+static volatile LONG64 g_flow_seq = 0;
static HANDLE g_iocp = NULL;
static HANDLE g_relay_workers[16];
static int g_relay_nworkers = 0;
@@ -1003,6 +1015,7 @@ static DWORD WINAPI relay_worker(LPVOID arg)
break;
default: // RS_SEND
if (n == 0) { relay_dir_end(d); continue; }
+ InterlockedExchangeAdd64(&d->bytes, (LONG64)n);
d->off += n;
if (d->off < d->len) posted = relay_post_send(d);
else if (d->len < RELAY_BUF_SIZE / 4) posted = relay_post_wait(d); // lightly used: drop the buffer
@@ -1054,7 +1067,7 @@ void relay_pool_stop(void)
// Takes over both (already handshaken) sockets. Returns FALSE if the pool is unavailable; the
// caller then falls back to the blocking relay and still owns the sockets.
-BOOL relay_start(SOCKET client, SOCKET proxy)
+BOOL relay_start(SOCKET client, SOCKET proxy, const FLOW_META *meta)
{
if (g_iocp == NULL || !running) return FALSE;
@@ -1068,6 +1081,9 @@ BOOL relay_start(SOCKET client, SOCKET proxy)
}
rc->s[0] = client; rc->s[1] = proxy;
rc->refs = 2;
+ rc->id = (UINT64)InterlockedIncrement64(&g_flow_seq);
+ rc->start = GetTickCount64();
+ if (meta != NULL) rc->meta = *meta;
rc->dir[0].rc = rc; rc->dir[0].src = client; rc->dir[0].dst = proxy; // upload
rc->dir[1].rc = rc; rc->dir[1].src = proxy; rc->dir[1].dst = client; // download
@@ -1083,3 +1099,32 @@ BOOL relay_start(SOCKET client, SOCKET proxy)
if (!relay_post_wait(&rc->dir[1])) relay_dir_end(&rc->dir[1]);
return TRUE;
}
+
+// Live proxied TCP connections for the live connections view: raw fields copied under the relay list lock (a few
+// hundred nanoseconds per entry), newest first. Names and hosts are resolved by the caller after the lock is released.
+UINT32 relay_flows_snapshot(PB_FLOW *out, UINT32 max)
+{
+ UINT32 n = 0;
+ if (!g_relay_lock_ready || out == NULL) return 0;
+ ULONGLONG now = GetTickCount64();
+ EnterCriticalSection(&g_relay_lock);
+ for (RELAY_CONN *rc = g_relay_head; rc != NULL && n < max; rc = rc->next)
+ {
+ if (rc->closing) continue; // being torn down
+ PB_FLOW *f = &out[n++];
+ ZeroMemory(f, sizeof(*f));
+ f->id = rc->id;
+ f->pid = rc->meta.pid;
+ f->proxy_config_id = rc->meta.proxy_id;
+ f->rule_id = rc->meta.rule_id;
+ ULONGLONG age = now - rc->start;
+ f->age_ms = age > 0xFFFFFFFEull ? 0xFFFFFFFEu : (UINT32)age;
+ f->sent = (UINT64)rc->dir[0].bytes; // client -> proxy
+ f->received = (UINT64)rc->dir[1].bytes; // proxy -> client
+ f->port = rc->meta.port;
+ f->is_ipv6 = rc->meta.v6 ? 1 : 0;
+ memcpy(f->dest, rc->meta.dest, 16);
+ }
+ LeaveCriticalSection(&g_relay_lock);
+ return n;
+}
diff --git a/Windows/src/pb_rules.c b/Windows/src/pb_rules.c
index d9532ee..bbca1cd 100644
--- a/Windows/src/pb_rules.c
+++ b/Windows/src/pb_rules.c
@@ -39,10 +39,11 @@ static DWORD retry_tcp_pid(DWORD pid, BOOL ipv6, UINT32 src_ip, const UINT8 *src
}
__declspec(thread) BOOL g_tl_rule_localhost = FALSE;
+__declspec(thread) UINT32 g_tl_rule_id = 0;
RuleAction check_process_rule_v6(const UINT8 src_ip6[16], UINT16 src_port, const UINT8 dest_ip6[16], UINT16 dest_port, BOOL is_udp, DWORD *out_pid, UINT32 *out_proxy_config_id)
{
- g_tl_rule_localhost = FALSE;
+ g_tl_rule_localhost = FALSE; g_tl_rule_id = 0;
DWORD pid;
char process_name[MAX_PROCESS_NAME];
@@ -618,7 +619,7 @@ RuleAction match_rule_inner(const char *process_name, UINT32 dest_ip, UINT16 des
match_port_list(rule->target_ports, dest_port))
{
// Matched! Return this rule's action
- g_tl_rule_localhost = rule->localhost_via_proxy;
+ g_tl_rule_localhost = rule->localhost_via_proxy; g_tl_rule_id = rule->rule_id;
if (out_proxy_config_id != NULL) *out_proxy_config_id = rule->proxy_config_id;
return rule->action;
}
@@ -644,7 +645,7 @@ RuleAction match_rule_inner(const char *process_name, UINT32 dest_ip, UINT16 des
match_port_list(rule->target_ports, dest_port))
{
// All filters matched! Return this rule's action
- g_tl_rule_localhost = rule->localhost_via_proxy;
+ g_tl_rule_localhost = rule->localhost_via_proxy; g_tl_rule_id = rule->rule_id;
if (out_proxy_config_id != NULL) *out_proxy_config_id = rule->proxy_config_id;
return rule->action;
}
@@ -656,13 +657,13 @@ RuleAction match_rule_inner(const char *process_name, UINT32 dest_ip, UINT16 des
// No specific rule matched, use wildcard if available
if (wildcard_rule != NULL)
{
- g_tl_rule_localhost = wildcard_rule->localhost_via_proxy;
+ g_tl_rule_localhost = wildcard_rule->localhost_via_proxy; g_tl_rule_id = wildcard_rule->rule_id;
if (out_proxy_config_id != NULL) *out_proxy_config_id = wildcard_rule->proxy_config_id;
return wildcard_rule->action;
}
// No rule matched at all
- g_tl_rule_localhost = FALSE;
+ g_tl_rule_localhost = FALSE; g_tl_rule_id = 0;
if (out_proxy_config_id != NULL) *out_proxy_config_id = 0;
return RULE_ACTION_DIRECT;
}
@@ -673,7 +674,7 @@ RuleAction match_rule(const char *process_name, UINT32 dest_ip, UINT16 dest_port
{
if (!g_proxy_enabled) // paused: no rule applies
{
- g_tl_rule_localhost = FALSE;
+ g_tl_rule_localhost = FALSE; g_tl_rule_id = 0;
if (out_proxy_config_id != NULL) *out_proxy_config_id = 0;
return RULE_ACTION_DIRECT;
}
@@ -726,7 +727,7 @@ RuleAction match_rule_v6_inner(const char *process_name, const UINT8 dest_ip6[16
if (rule_host_match_v6(rule, dest_ip6, dst_domain) &&
match_port_list(rule->target_ports, dest_port))
{
- g_tl_rule_localhost = rule->localhost_via_proxy;
+ g_tl_rule_localhost = rule->localhost_via_proxy; g_tl_rule_id = rule->rule_id;
if (out_proxy_config_id != NULL) *out_proxy_config_id = rule->proxy_config_id;
return rule->action;
}
@@ -745,7 +746,7 @@ RuleAction match_rule_v6_inner(const char *process_name, const UINT8 dest_ip6[16
if (rule_host_match_v6(rule, dest_ip6, dst_domain) &&
match_port_list(rule->target_ports, dest_port))
{
- g_tl_rule_localhost = rule->localhost_via_proxy;
+ g_tl_rule_localhost = rule->localhost_via_proxy; g_tl_rule_id = rule->rule_id;
if (out_proxy_config_id != NULL) *out_proxy_config_id = rule->proxy_config_id;
return rule->action;
}
@@ -756,12 +757,12 @@ RuleAction match_rule_v6_inner(const char *process_name, const UINT8 dest_ip6[16
if (wildcard_rule != NULL)
{
- g_tl_rule_localhost = wildcard_rule->localhost_via_proxy;
+ g_tl_rule_localhost = wildcard_rule->localhost_via_proxy; g_tl_rule_id = wildcard_rule->rule_id;
if (out_proxy_config_id != NULL) *out_proxy_config_id = wildcard_rule->proxy_config_id;
return wildcard_rule->action;
}
- g_tl_rule_localhost = FALSE;
+ g_tl_rule_localhost = FALSE; g_tl_rule_id = 0;
if (out_proxy_config_id != NULL) *out_proxy_config_id = 0;
return RULE_ACTION_DIRECT;
}
@@ -770,7 +771,7 @@ RuleAction match_rule_v6(const char *process_name, const UINT8 dest_ip6[16], UIN
{
if (!g_proxy_enabled) // paused: no rule applies
{
- g_tl_rule_localhost = FALSE;
+ g_tl_rule_localhost = FALSE; g_tl_rule_id = 0;
if (out_proxy_config_id != NULL) *out_proxy_config_id = 0;
return RULE_ACTION_DIRECT;
}
@@ -782,7 +783,7 @@ RuleAction match_rule_v6(const char *process_name, const UINT8 dest_ip6[16], UIN
RuleAction check_process_rule(UINT32 src_ip, UINT16 src_port, UINT32 dest_ip, UINT16 dest_port, BOOL is_udp, DWORD *out_pid, UINT32 *out_proxy_config_id)
{
- g_tl_rule_localhost = FALSE;
+ g_tl_rule_localhost = FALSE; g_tl_rule_id = 0;
DWORD pid;
char process_name[MAX_PROCESS_NAME];
diff --git a/Windows/src/service/pb_proto.h b/Windows/src/service/pb_proto.h
index b084517..ea58e3a 100644
--- a/Windows/src/service/pb_proto.h
+++ b/Windows/src/service/pb_proto.h
@@ -19,7 +19,7 @@
#define PB_SERVICE_NAME L"ProxyBridgeSvc"
#define PB_PIPE_CTL L"\\\\.\\pipe\\ProxyBridgeCtl"
#define PB_PIPE_EVT L"\\\\.\\pipe\\ProxyBridgeEvt"
-#define PB_PROTO_VERSION 4 // 4: PBOP_SET_LOG_ALL; 3: PBOP_SET_ENABLED (main switch); 2: per-rule localhost flag
+#define PB_PROTO_VERSION 6 // 6: rule id per flow; 5: PBOP_GET_FLOWS (live connections); 4: PBOP_SET_LOG_ALL; 3: PBOP_SET_ENABLED (main switch); 2: per-rule localhost flag
#define PB_MSG_MAX (64u * 1024u)
#define PB_STR_MAX (32u * 1024u)
#define PB_NULL_STR 0xFFFFFFFFu
@@ -42,8 +42,11 @@ enum {
PBOP_START, // () -> bool
PBOP_STOP, // () -> bool
PBOP_SET_ENABLED, // bool -> 0 (main switch: 0 pauses all rules for new connections)
- PBOP_SET_LOG_ALL // bool -> 0 (1 = log every new connection, no de-duplication)
+ PBOP_SET_LOG_ALL, // bool -> 0 (1 = log every new connection, no de-duplication)
+ PBOP_GET_FLOWS // u32 max -> u32 count, then per flow: u32 idLo, idHi, pid, flags (1 = UDP, 2 = IPv6), port,
+ // proxyId, ruleId, ageMs (0xFFFFFFFF = unknown), sentLo, sentHi, recvLo, recvHi, str name, str host
};
+#define PB_FLOW_ROW_MAX (12u * 4u + (4u + 39u) + (4u + 63u)) // largest encoded flow row, in bytes
enum {
PBEVT_LOG = 1, // str message
diff --git a/Windows/src/service/pb_service.c b/Windows/src/service/pb_service.c
index 6b40df2..23e1b2b 100644
--- a/Windows/src/service/pb_service.c
+++ b/Windows/src/service/pb_service.c
@@ -173,6 +173,28 @@ static BOOL Dispatch(const BYTE *req, DWORD reqLen, PbW *resp)
case PBOP_CLEAR_CONN_LOGS: g_api.ClearConnectionLogs(); break;
case PBOP_SET_LOG_ALL: { UINT32 v = PbR_U32(&r); if (!r.ok) return FALSE; g_api.SetLogEveryConnection(v != 0); break; }
case PBOP_SET_ENABLED: { UINT32 v = PbR_U32(&r); if (!r.ok) return FALSE; g_api.SetEnabled(v != 0); break; }
+ case PBOP_GET_FLOWS: {
+ UINT32 max = PbR_U32(&r);
+ if (!r.ok) return FALSE;
+ if (max > PB_FLOWS_MAX_GUI) max = PB_FLOWS_MAX_GUI;
+ static PBFlow flows[PB_FLOWS_MAX_GUI];
+ UINT32 n = (g_api.GetFlows != NULL && max > 0) ? g_api.GetFlows(flows, max) : 0;
+ if (n > max) n = max;
+ if (n > (resp->cap - resp->len - 4) / PB_FLOW_ROW_MAX) n = (resp->cap - resp->len - 4) / PB_FLOW_ROW_MAX; // always fits
+ PbW_U32(resp, n);
+ for (UINT32 i = 0; i < n; i++)
+ {
+ PBFlow *f = &flows[i];
+ f->name[sizeof(f->name) - 1] = '\0'; f->host[sizeof(f->host) - 1] = '\0'; // never trust a terminator
+ PbW_U32(resp, (UINT32)f->id); PbW_U32(resp, (UINT32)(f->id >> 32));
+ PbW_U32(resp, f->pid); PbW_U32(resp, (f->is_udp ? 1u : 0u) | (f->is_ipv6 ? 2u : 0u));
+ PbW_U32(resp, f->port); PbW_U32(resp, f->proxy_config_id); PbW_U32(resp, f->rule_id); PbW_U32(resp, f->age_ms);
+ PbW_U32(resp, (UINT32)f->sent); PbW_U32(resp, (UINT32)(f->sent >> 32));
+ PbW_U32(resp, (UINT32)f->received); PbW_U32(resp, (UINT32)(f->received >> 32));
+ PbW_Str(resp, f->name); PbW_Str(resp, f->host);
+ }
+ return resp->ok;
+ }
case PBOP_START: ret = g_api.Start(); break;
case PBOP_STOP: ret = g_api.Stop(); break;
default: return FALSE;
diff --git a/Windows/tests/run_tests.ps1 b/Windows/tests/run_tests.ps1
index d020288..c67b33e 100644
--- a/Windows/tests/run_tests.ps1
+++ b/Windows/tests/run_tests.ps1
@@ -88,6 +88,7 @@ $tests = @(
@{ 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_flows'; src=@('tests\test_flows.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 },
@@ -183,7 +184,17 @@ if ($runStatic) {
# 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'
+ Check ([int][regex]::Match($proto, 'PB_PROTO_VERSION\s+(\d+)').Groups[1].Value -ge 5) 'service protocol version is at least 5'
+
+ # 3b. the string enum and the EN/ZH table in loc.h list the same names in the same order (a shifted table shows the
+ # wrong text everywhere after the mistake)
+ $loc = Read-Text 'gui\loc\loc.h'
+ $enumBody = [regex]::Match($loc, 'enum\s*\{(.*?)\bS_COUNT\b', 'Singleline').Groups[1].Value
+ $enumNames = [regex]::Matches($enumBody, '\bS_[A-Z0-9_]+\b') | ForEach-Object { $_.Value }
+ $tableNames = [regex]::Matches($loc, '/\*\s*(S_[A-Z0-9_]+)\s*\*/\s*\{') | ForEach-Object { $_.Groups[1].Value }
+ Check ($enumNames.Count -gt 100 -and $enumNames.Count -eq $tableNames.Count) 'loc.h: the string enum and the translation table have the same number of entries'
+ $badAt = -1; for ($i = 0; $i -lt [Math]::Min($enumNames.Count, $tableNames.Count); $i++) { if ($enumNames[$i] -ne $tableNames[$i]) { $badAt = $i; break } }
+ Check ($badAt -lt 0) ("loc.h: the translation table is in the same order as the enum" + $(if ($badAt -ge 0) { " (first difference: enum " + $enumNames[$badAt] + " vs table " + $tableNames[$badAt] + ")" } else { "" }))
# 4. wiring: every test source is run by this script, and the workflow runs this script
$self = [IO.File]::ReadAllText($PSCommandPath)
diff --git a/Windows/tests/test_conntrack.c b/Windows/tests/test_conntrack.c
index d117add..236a3b8 100644
--- a/Windows/tests/test_conntrack.c
+++ b/Windows/tests/test_conntrack.c
@@ -13,11 +13,11 @@ int main(void)
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 */
+ add_connection(55123, TRUE, lanA, d1, 41001, 0, 4242, 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);
+ add_connection(55123, FALSE, lanA, d2, 41002, 0, 4242, 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);
@@ -28,9 +28,9 @@ int main(void)
/* 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);
+ add_connection(50000, FALSE, lanA, d1, 443, 0, 4242, 0);
CHECK(is_connection_tracked(50000, FALSE, FALSE) && !is_connection_tracked(50000, FALSE, TRUE));
- add_connection_v6(50000, FALSE, s6, dst6, 443, 0);
+ add_connection_v6(50000, FALSE, s6, dst6, 443, 0, 4242, 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));
@@ -38,8 +38,8 @@ int main(void)
/* 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);
+ add_connection(51000, FALSE, lanA, d1, 443, 0, 4242, 0);
+ add_connection(51000, FALSE, lanB, d2, 80, 0, 4242, 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);
@@ -78,5 +78,48 @@ int main(void)
add_logged_connection(300, d1, 443, RULE_ACTION_DIRECT);
CHECK(connection_log_wanted(300, d1, 443, 2, FALSE, RULE_ACTION_DIRECT) == FALSE);
+ /* 7. live connections: proxied UDP flows, their owner and byte counters */
+ { PB_FLOW f[PB_FLOWS_MAX];
+ UINT8 d6[16] = {0x26, 0x06, 0x47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x11, 0x11};
+ CHECK(udp_flows_snapshot(f, PB_FLOWS_MAX) == 0); /* nothing tracked yet */
+ add_connection(60001, TRUE, lanA, d1, 3478, 5, 1111, 31); /* proxied UDP flow, owner pid 1111 */
+ add_connection(60002, FALSE, lanA, d2, 443, 5, 2222, 32); /* TCP is shown by the relay, not from here */
+ add_connection_v6(60003, TRUE, s6, d6, 443, 6, 3333, 33);
+ CHECK(udp_flows_snapshot(f, PB_FLOWS_MAX) == 2);
+ int v4 = -1, v6 = -1; for (int i = 0; i < 2; i++) { if (f[i].is_ipv6) v6 = i; else v4 = i; }
+ CHECK(v4 >= 0 && v6 >= 0);
+ if (v4 >= 0) CHECK(f[v4].is_udp && f[v4].pid == 1111 && f[v4].proxy_config_id == 5 && f[v4].rule_id == 31 && f[v4].port == 3478 && memcmp(f[v4].dest, &d1, 4) == 0 && f[v4].sent == 0 && f[v4].received == 0 && f[v4].age_ms == 0xFFFFFFFFu);
+ if (v6 >= 0) CHECK(f[v6].rule_id == 33 && f[v6].pid == 3333 && f[v6].port == 443 && memcmp(f[v6].dest, d6, 16) == 0 && f[v6].id != f[v4].id);
+ UINT64 id4 = f[v4].id;
+
+ UINT32 xd; UINT16 xp; UINT32 cfg = 0, rule = 0; DWORD pid = 0; /* app -> proxy: counted by the lookup the relay already does */
+ CHECK(get_connection_full_x(60001, TRUE, &xd, &xp, &cfg, &pid, &rule, 1200) && xd == d1 && xp == 3478 && cfg == 5 && pid == 1111 && rule == 31);
+ CHECK(get_connection_full_x(60001, TRUE, &xd, &xp, &cfg, &pid, &rule, 300));
+ UINT8 dd6[16]; CHECK(get_connection_full_v6_x(60003, TRUE, dd6, &xp, &cfg, &pid, &rule, 77) && pid == 3333);
+ UINT8 sr[16]; UINT16 sp; /* proxy -> app on IPv6 */
+ CHECK(find_v6_udp_sender(d6, 443, sr, &sp, 5000) && sp == 60003);
+ CHECK(udp_flows_snapshot(f, PB_FLOWS_MAX) == 2);
+ for (int i = 0; i < 2; i++)
+ {
+ if (!f[i].is_ipv6) CHECK(f[i].id == id4 && f[i].sent == 1500 && f[i].received == 0);
+ else CHECK(f[i].sent == 77 && f[i].received == 5000);
+ }
+ CHECK(get_connection_full(60001, TRUE, &xd, &xp, &cfg) && xd == d1); /* the old entry point still works and counts nothing */
+ CHECK(udp_flows_snapshot(f, 1) == 1); /* the caller's limit is respected */
+ CHECK(udp_flows_snapshot(f, 0) == 0);
+ remove_connection(60001, TRUE, FALSE); remove_connection(60002, FALSE, FALSE); remove_connection(60003, TRUE, TRUE);
+ CHECK(udp_flows_snapshot(f, PB_FLOWS_MAX) == 0); }
+
+ /* a flow that has been silent for longer than the live window is no longer listed */
+ { PB_FLOW f[4];
+ add_connection(60010, TRUE, lanA, d1, 53, 0, 1, 0);
+ CHECK(udp_flows_snapshot(f, 4) == 1);
+ AcquireSRWLockExclusive(&lock);
+ for (CONNECTION_INFO* c = connection_hash_table[60010 % CONNECTION_HASH_SIZE]; c; c = c->next)
+ if (c->src_port == 60010) c->last_activity = GetTickCount64() - (UDP_FLOW_LIVE_MS + 5000);
+ ReleaseSRWLockExclusive(&lock);
+ CHECK(udp_flows_snapshot(f, 4) == 0);
+ remove_connection(60010, TRUE, FALSE); }
+
return pbtest_done("test_conntrack");
}
diff --git a/Windows/tests/test_flows.c b/Windows/tests/test_flows.c
new file mode 100644
index 0000000..708acf8
--- /dev/null
+++ b/Windows/tests/test_flows.c
@@ -0,0 +1,112 @@
+// test_flows.c - live connections in the engine: the relay (src\pb_relay.c) really forwards bytes between two
+// loopback socket pairs, and the flow list that ProxyBridge_GetFlows() returns follows it:
+// - a proxied TCP connection appears with its owner (pid + process name), destination and proxy id
+// - the Sent / Received counters equal the bytes that were forwarded in each direction
+// - it disappears when either side closes, and nothing is leaked (the relay count returns to zero)
+// - the caller's limit is respected, bad arguments are harmless
+// No driver is opened and nothing leaves the machine.
+#include "pb_internal.h"
+#include "pbtest.h"
+#include <stddef.h>
+#include "../gui/api/pb_api.h"
+
+/* The app mirrors the engine's flow record (PBFlow in pb_api.h = PB_FLOW in ProxyBridge.h): when the engine DLL is
+ loaded directly the two must be byte for byte the same. */
+typedef char flow_size_matches[sizeof(PBFlow) == sizeof(PB_FLOW) ? 1 : -1];
+typedef char flow_fields_match[(offsetof(PBFlow, id) == offsetof(PB_FLOW, id) && offsetof(PBFlow, pid) == offsetof(PB_FLOW, pid) &&
+ offsetof(PBFlow, proxy_config_id) == offsetof(PB_FLOW, proxy_config_id) && offsetof(PBFlow, rule_id) == offsetof(PB_FLOW, rule_id) && offsetof(PBFlow, age_ms) == offsetof(PB_FLOW, age_ms) &&
+ offsetof(PBFlow, sent) == offsetof(PB_FLOW, sent) && offsetof(PBFlow, received) == offsetof(PB_FLOW, received) &&
+ offsetof(PBFlow, port) == offsetof(PB_FLOW, port) && offsetof(PBFlow, is_udp) == offsetof(PB_FLOW, is_udp) &&
+ offsetof(PBFlow, is_ipv6) == offsetof(PB_FLOW, is_ipv6) && offsetof(PBFlow, dest) == offsetof(PB_FLOW, dest) &&
+ offsetof(PBFlow, name) == offsetof(PB_FLOW, name) && offsetof(PBFlow, host) == offsetof(PB_FLOW, host) &&
+ PB_FLOWS_MAX_GUI == PB_FLOWS_MAX) ? 1 : -1];
+
+static BOOL make_pair(SOCKET* a, SOCKET* b)
+{
+ SOCKET ls = socket(AF_INET, SOCK_STREAM, 0);
+ struct sockaddr_in sa; int len = sizeof(sa);
+ memset(&sa, 0, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
+ if (bind(ls, (struct sockaddr*)&sa, sizeof(sa)) || listen(ls, 1) || getsockname(ls, (struct sockaddr*)&sa, &len)) { closesocket(ls); return FALSE; }
+ *a = socket(AF_INET, SOCK_STREAM, 0);
+ if (connect(*a, (struct sockaddr*)&sa, sizeof(sa))) { closesocket(ls); closesocket(*a); return FALSE; }
+ *b = accept(ls, NULL, NULL);
+ closesocket(ls);
+ return *b != INVALID_SOCKET;
+}
+
+static BOOL send_n(SOCKET s, int n) { char buf[4096]; memset(buf, 'x', sizeof buf); while (n > 0) { int c = n > (int)sizeof buf ? (int)sizeof buf : n; int r = send(s, buf, c, 0); if (r <= 0) return FALSE; n -= r; } return TRUE; }
+static BOOL recv_n_bytes(SOCKET s, int n) { char buf[4096]; while (n > 0) { int r = recv(s, buf, n > (int)sizeof buf ? (int)sizeof buf : n, 0); if (r <= 0) return FALSE; n -= r; } return TRUE; }
+
+// polls the engine until `pred` holds or ~4 s pass
+static PB_FLOW g_f[PB_FLOWS_MAX];
+static UINT32 g_n;
+static BOOL wait_flows(UINT32 want, UINT64 sent, UINT64 recv)
+{
+ for (int i = 0; i < 400; i++)
+ {
+ g_n = ProxyBridge_GetFlows(g_f, PB_FLOWS_MAX);
+ if (g_n == want && (want == 0 || (g_f[0].sent == sent && g_f[0].received == recv))) return TRUE;
+ Sleep(10);
+ }
+ return FALSE;
+}
+
+int main(void)
+{
+ WSADATA wsa; WSAStartup(MAKEWORD(2, 2), &wsa);
+ running = TRUE; /* relay_start() refuses to work on a stopped engine */
+ CHECK(relay_pool_start());
+
+ CHECK(ProxyBridge_GetFlows(NULL, 10) == 0); /* bad arguments are harmless */
+ { PB_FLOW one; CHECK(ProxyBridge_GetFlows(&one, 0) == 0); }
+ CHECK(wait_flows(0, 0, 0));
+
+ /* app <-> [relay] <-> proxy, as two loopback pairs */
+ SOCKET app, relayClient, relayProxy, proxy;
+ CHECK(make_pair(&app, &relayClient) && make_pair(&relayProxy, &proxy));
+ FLOW_META m; ZeroMemory(&m, sizeof m);
+ m.pid = GetCurrentProcessId(); m.proxy_id = 9; m.rule_id = 17; m.port = 443; m.v6 = FALSE;
+ UINT32 dest = 0x08080808u; memcpy(m.dest, &dest, 4); /* 8.8.8.8 */
+ CHECK(relay_start(relayClient, relayProxy, &m));
+
+ CHECK(wait_flows(1, 0, 0));
+ CHECK(g_n == 1 && g_f[0].pid == m.pid && g_f[0].proxy_config_id == 9 && g_f[0].rule_id == 17 && g_f[0].port == 443 && !g_f[0].is_udp && !g_f[0].is_ipv6);
+ CHECK(strlen(g_f[0].name) > 0 && _stricmp(g_f[0].name, "test_flows.exe") == 0); /* the process name, not the path */
+ CHECK(!strcmp(g_f[0].host, "8.8.8.8")); /* no domain known: the address */
+ CHECK(g_f[0].age_ms != 0xFFFFFFFFu && g_f[0].id != 0);
+ UINT64 id = g_f[0].id;
+
+ /* bytes are forwarded and counted per direction */
+ CHECK(send_n(app, 1000) && recv_n_bytes(proxy, 1000));
+ CHECK(send_n(proxy, 250000) && recv_n_bytes(app, 250000)); /* more than one read, so the counter must add up */
+ CHECK(wait_flows(1, 1000, 250000));
+ CHECK(g_f[0].id == id && g_f[0].sent == 1000 && g_f[0].received == 250000);
+
+ /* a second connection (IPv6 label) is listed newest first; the first one keeps its identity */
+ SOCKET app2, rc2, rp2, px2;
+ CHECK(make_pair(&app2, &rc2) && make_pair(&rp2, &px2));
+ FLOW_META m2; ZeroMemory(&m2, sizeof m2); m2.pid = GetCurrentProcessId(); m2.proxy_id = 3; m2.port = 80; m2.v6 = TRUE; m2.dest[15] = 1; /* ::1 */
+ CHECK(relay_start(rc2, rp2, &m2));
+ CHECK(wait_flows(2, 0, 0) || g_n == 2);
+ CHECK(g_n == 2 && g_f[0].id != id && g_f[0].is_ipv6 && !strcmp(g_f[0].host, "::1") && g_f[1].id == id && g_f[1].sent == 1000);
+ { PB_FLOW lim[1]; CHECK(ProxyBridge_GetFlows(lim, 1) == 1); } /* the caller's limit is respected */
+
+ /* closing the app side ends the flow; the other one is untouched */
+ closesocket(app);
+ CHECK(wait_flows(1, 0, 0) || g_n == 1);
+ CHECK(g_n == 1 && g_f[0].id != id);
+ char c; CHECK(recv(proxy, &c, 1, 0) <= 0); /* the proxy side saw the close too */
+ closesocket(proxy);
+
+ closesocket(app2);
+ CHECK(wait_flows(0, 0, 0));
+ for (int i = 0; i < 300 && g_active_relays > 0; i++) Sleep(10);
+ CHECK(g_active_relays == 0); /* nothing leaked */
+ closesocket(px2);
+
+ relay_pool_stop();
+ CHECK(relay_flows_snapshot(g_f, PB_FLOWS_MAX) == 0);
+ running = FALSE;
+ WSACleanup();
+ return pbtest_done("test_flows");
+}
diff --git a/Windows/tests/test_main_ui.c b/Windows/tests/test_main_ui.c
index 9299ef7..0fa49f0 100644
--- a/Windows/tests/test_main_ui.c
+++ b/Windows/tests/test_main_ui.c
@@ -17,6 +17,27 @@ static void StubSetConn(PBConnectionCallback cb) { (void)cb; }
static PBProfile g_probe;
+static PBFlow g_stubFlows[8]; static UINT32 g_stubN = 0; static int g_stubCalls = 0;
+static UINT32 StubGetFlows(PBFlow* out, UINT32 max) { g_stubCalls++; UINT32 n = g_stubN < max ? g_stubN : max; memcpy(out, g_stubFlows, n * sizeof(PBFlow)); return n; }
+/* lets the worker thread of an asynchronous poll finish and its result be applied, then stops the poll timer so the
+ test controls every further poll itself */
+static void PumpFlows(void)
+{
+ for (int i = 0; i < 600; i++)
+ {
+ MSG m; while (PeekMessageW(&m, NULL, 0, 0, PM_REMOVE)) DispatchMessageW(&m);
+ if (!g_flBusy) break;
+ Sleep(5);
+ }
+ KillTimer(g_hMain, TIMER_FLOWS);
+}
+static void MkFlow(PBFlow* f, UINT64 id, DWORD pid, const char* name, const char* host, int port, int udp, int v6, UINT32 age, UINT64 sent, UINT64 recv, UINT32 proxy)
+{
+ ZeroMemory(f, sizeof(*f));
+ f->id = id; f->pid = pid; f->port = (UINT16)port; f->is_udp = (UINT8)udp; f->is_ipv6 = (UINT8)v6; f->age_ms = age; f->sent = sent; f->received = recv; f->proxy_config_id = proxy;
+ strcpy_s(f->name, sizeof f->name, name); strcpy_s(f->host, sizeof f->host, host);
+}
+
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; }
@@ -93,6 +114,142 @@ int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrev, PWSTR cmd, int show)
PB_ProfileDefaults(&g_probe, L"x"); /* a profile without the key: off */
CHECK(g_probe.logEveryConnection == 0);
+ /* 6. Live Connections tab */
+ g_api.GetFlows = StubGetFlows;
+ { TCITEMW ti; wchar_t tx[64]; ti.mask = TCIF_TEXT; ti.pszText = tx; ti.cchTextMax = 64;
+ BOOL gi = TabCtrl_GetItem(g_hTab, 2, &ti); CHECK(TabCtrl_GetItemCount(g_hTab) == 3 && gi && !wcscmp(tx, L"Live Connections")); }
+ CHECK(g_hFlows != NULL && !IsWindowVisible(g_hFlows) && g_fl == NULL && g_flSnap == NULL); /* nothing is polled or held until opened */
+ ShowWindow(g_hMain, SW_SHOWNOACTIVATE);
+ g_stubN = 0;
+ SelectTab(2); /* opening the tab polls at once (on a worker thread) */
+ PumpFlows();
+ CHECK(IsWindowVisible(g_hFlows) && !IsWindowVisible(g_hConnLog) && !IsWindowVisible(g_hActLog) && g_stubCalls >= 1 && g_flN == 0 && g_flBusy == 0);
+
+ { PBFlow s[3];
+ g_profile.cfgCount = 1; g_profile.cfg[0].nativeId = 5; lstrcpynW(g_profile.cfg[0].name, L"Burp", 128); lstrcpynW(g_profile.cfg[0].type, L"SOCKS5", 16); lstrcpynW(g_profile.cfg[0].host, L"127.0.0.1", 128); lstrcpynW(g_profile.cfg[0].port, L"1080", 16);
+ g_profile.ruleCount = 1; g_profile.rule[0].nativeId = 21; lstrcpynW(g_profile.rule[0].name, L"Browsers", 128);
+ MkFlow(&s[0], 11, 4312, "chrome.exe", "example.com", 443, 0, 0, 65000, 2048, 5u * 1024 * 1024, 5); s[0].rule_id = 21;
+ MkFlow(&s[1], 12, 77, "game.exe", "203.0.113.7", 27015, 1, 0, 0xFFFFFFFFu, 0, 900, 5);
+ MkFlow(&s[2], 13, 9, "", "2606:4700::1111", 443, 0, 1, 1000, 1, 1, 99);
+ memcpy(g_stubFlows, s, sizeof s); g_stubN = 3;
+ FlowsPoll();
+ CHECK(g_flN == 3 && ListView_GetItemCount(g_hFlows) == 3 && g_stubCalls >= 2);
+ ULONGLONG now = g_flNow; wchar_t t[128];
+ int r = -1; for (int i = 0; i < g_flN; i++) if (g_fl[i].id == 11) r = i;
+ FlowText(&g_fl[r], 0, now, t, 128); CHECK(!wcscmp(t, L"chrome.exe (4312)"));
+ FlowText(&g_fl[r], 1, now, t, 128); CHECK(!wcscmp(t, L"example.com:443"));
+ FlowText(&g_fl[r], 2, now, t, 128); CHECK(!wcscmp(t, L"TCP"));
+ FlowText(&g_fl[r], 3, now, t, 128); CHECK(!wcscmp(t, L"1:05"));
+ FlowText(&g_fl[r], 4, now, t, 128); CHECK(!wcscmp(t, L"Browsers : Burp (SOCKS5 127.0.0.1:1080)"));
+ FlowRuleProxy(0, 5, t, 128); CHECK(!wcscmp(t, L"Burp (SOCKS5 127.0.0.1:1080)")); /* the engine did not say which rule */
+ FlowRuleProxy(55, 5, t, 128); CHECK(!wcscmp(t, L"Burp (SOCKS5 127.0.0.1:1080)")); /* a rule that is gone from the profile */
+ FlowRuleProxy(21, 0, t, 128); CHECK(!wcscmp(t, L"Browsers : Burp (SOCKS5 127.0.0.1:1080)")); /* proxy id 0 = the first proxy */
+ FlowText(&g_fl[r], 5, now, t, 128); CHECK(!wcscmp(t, L"2.0 KB"));
+ FlowText(&g_fl[r], 6, now, t, 128); CHECK(!wcscmp(t, L"5.0 MB"));
+ for (int i = 0; i < g_flN; i++)
+ {
+ if (g_fl[i].id == 12) { FlowText(&g_fl[i], 2, now, t, 128); CHECK(!wcscmp(t, L"UDP")); FlowText(&g_fl[i], 3, now, t, 128); CHECK(!wcscmp(t, L"0:00")); FlowText(&g_fl[i], 6, now, t, 128); CHECK(!wcscmp(t, L"900 B")); }
+ if (g_fl[i].id == 13) { FlowText(&g_fl[i], 0, now, t, 128); CHECK(!wcscmp(t, L"PID 9")); FlowText(&g_fl[i], 1, now, t, 128); CHECK(!wcscmp(t, L"[2606:4700::1111]:443")); FlowText(&g_fl[i], 4, now, t, 128); CHECK(!wcscmp(t, L"#99")); }
+ }
+
+ /* the list control asks for text on demand (virtual list: it keeps no text itself) */
+ { NMLVDISPINFOW di; ZeroMemory(&di, sizeof di); wchar_t buf[64] = L"";
+ di.hdr.hwndFrom = g_hFlows; di.hdr.idFrom = IDC_FLOWS; di.hdr.code = LVN_GETDISPINFOW;
+ di.item.mask = LVIF_TEXT; di.item.iItem = 0; di.item.iSubItem = 1; di.item.pszText = buf; di.item.cchTextMax = 64;
+ SendMessageW(g_hMain, WM_NOTIFY, IDC_FLOWS, (LPARAM)&di);
+ CHECK(wcslen(buf) > 0 && wcschr(buf, L':') != NULL);
+ di.item.iItem = 999; buf[0] = L'x'; SendMessageW(g_hMain, WM_NOTIFY, IDC_FLOWS, (LPARAM)&di); CHECK(buf[0] == 0); /* out of range: empty, no crash */
+ di.item.iItem = 0; di.item.iSubItem = 50; buf[0] = L'x'; SendMessageW(g_hMain, WM_NOTIFY, IDC_FLOWS, (LPARAM)&di); CHECK(buf[0] == 0); }
+
+ /* newest first by default; clicking a header sorts by it, clicking again reverses */
+ CHECK(g_fl[g_flView[0]].id == 13 || g_fl[g_flView[0]].firstSeen >= g_fl[g_flView[g_flN - 1]].firstSeen);
+ { NMLISTVIEW nm; ZeroMemory(&nm, sizeof nm); nm.hdr.hwndFrom = g_hFlows; nm.hdr.idFrom = IDC_FLOWS; nm.hdr.code = LVN_COLUMNCLICK; nm.iSubItem = 1;
+ SendMessageW(g_hMain, WM_NOTIFY, IDC_FLOWS, (LPARAM)&nm); /* by target, ascending */
+ CHECK(_stricmp(g_fl[g_flView[0]].host, g_fl[g_flView[1]].host) <= 0 && _stricmp(g_fl[g_flView[1]].host, g_fl[g_flView[2]].host) <= 0);
+ SendMessageW(g_hMain, WM_NOTIFY, IDC_FLOWS, (LPARAM)&nm); /* reversed */
+ CHECK(_stricmp(g_fl[g_flView[0]].host, g_fl[g_flView[1]].host) >= 0 && _stricmp(g_fl[g_flView[1]].host, g_fl[g_flView[2]].host) >= 0);
+ nm.iSubItem = 6; SendMessageW(g_hMain, WM_NOTIFY, IDC_FLOWS, (LPARAM)&nm); /* by received: biggest first */
+ CHECK(g_fl[g_flView[0]].received >= g_fl[g_flView[1]].received && g_fl[g_flView[1]].received >= g_fl[g_flView[2]].received); }
+
+ /* a flow that disappears turns grey and stays listed until "Clear closed" */
+ PBFlow keep[2]; keep[0] = s[1]; keep[1] = s[2];
+ FlowsApply(keep, 2, FALSE, now + 2000);
+ CHECK(g_flN == 3);
+ r = -1; for (int i = 0; i < g_flN; i++) if (g_fl[i].id == 11) r = i;
+ CHECK(r >= 0 && g_fl[r].closedAt == now + 2000);
+ FlowText(&g_fl[r], 3, now + 2000, t, 128); CHECK(!wcscmp(t, L"Closed 1:07")); /* total life, frozen */
+ { int vi = -1; for (int i = 0; i < g_flN; i++) if (g_flView[i] == r) vi = i;
+ NMLVCUSTOMDRAW cd; ZeroMemory(&cd, sizeof cd);
+ cd.nmcd.hdr.hwndFrom = g_hFlows; cd.nmcd.hdr.idFrom = IDC_FLOWS; cd.nmcd.hdr.code = NM_CUSTOMDRAW;
+ cd.nmcd.dwDrawStage = CDDS_PREPAINT; CHECK(SendMessageW(g_hMain, WM_NOTIFY, IDC_FLOWS, (LPARAM)&cd) == CDRF_NOTIFYITEMDRAW);
+ cd.nmcd.dwDrawStage = CDDS_ITEMPREPAINT; cd.nmcd.dwItemSpec = (DWORD_PTR)vi; cd.clrText = RGB(1, 2, 3);
+ SendMessageW(g_hMain, WM_NOTIFY, IDC_FLOWS, (LPARAM)&cd); CHECK(cd.clrText == RGB(128, 128, 128)); /* finished: grey */
+ cd.nmcd.dwItemSpec = (DWORD_PTR)((vi + 1) % g_flN); cd.clrText = RGB(1, 2, 3);
+ SendMessageW(g_hMain, WM_NOTIFY, IDC_FLOWS, (LPARAM)&cd); CHECK(cd.clrText == RGB(1, 2, 3)); } /* live rows keep the theme colour */
+ FlowsApply(keep, 2, FALSE, now + 3600000); /* an hour later: still there */
+ CHECK(g_flN == 3 && g_fl[r].id == 11 && g_fl[r].closedAt == now + 2000);
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDC_FLOWS_CLEAR, BN_CLICKED), (LPARAM)g_hFlowsClear); /* Clear closed */
+ CHECK(g_flN == 2 && ListView_GetItemCount(g_hFlows) == 2);
+ for (int i = 0; i < g_flN; i++) CHECK(g_fl[i].id != 11 && g_fl[i].closedAt == 0); /* live rows stay */
+ now += 3600000;
+
+ /* a truncated snapshot (more flows than were returned) never marks the missing ones as finished */
+ PBFlow only[1]; only[0] = s[1];
+ FlowsApply(only, 1, TRUE, now + 20000);
+ for (int i = 0; i < g_flN; i++) CHECK(g_fl[i].closedAt == 0);
+ FlowsApply(only, 1, FALSE, now + 21000);
+ { int closed = 0; for (int i = 0; i < g_flN; i++) closed += g_fl[i].closedAt != 0; CHECK(closed == 1); }
+
+ /* an idle UDP flow that wakes up again is a live row again with a fresh start */
+ FlowsApply(s + 2, 1, FALSE, now + 22000);
+ for (int i = 0; i < g_flN; i++) if (g_fl[i].id == 12) CHECK(g_fl[i].closedAt != 0);
+ s[1].age_ms = 0xFFFFFFFFu;
+ FlowsApply(s + 1, 1, FALSE, now + 23000);
+ for (int i = 0; i < g_flN; i++) if (g_fl[i].id == 12) CHECK(g_fl[i].closedAt == 0 && g_fl[i].firstSeen == now + 23000);
+
+ /* the engine/pipe going away (nothing returned) greys everything instead of crashing */
+ g_stubN = 0; FlowsPoll();
+ for (int i = 0; i < g_flN; i++) CHECK(g_fl[i].closedAt != 0);
+ }
+
+ /* memory stays bounded however many flows come and go */
+ { PBFlow* big = (PBFlow*)calloc(400, sizeof(PBFlow));
+ for (int round = 0; round < 6; round++)
+ {
+ for (int i = 0; i < 400; i++) MkFlow(&big[i], 1000 + round * 400 + i, 1, "x.exe", "h", 80, 0, 0, 10, 1, 1, 1);
+ FlowsApply(big, 400, TRUE, GetTickCount64());
+ }
+ CHECK(g_flN <= FLOW_ROWS_MAX && g_flView != NULL);
+ FlowsApply(big, 0, FALSE, GetTickCount64() + 1000); /* everything finishes ... */
+ for (int i = 0; i < g_flN; i++) CHECK(g_fl[i].closedAt != 0);
+ for (int i = 0; i < 400; i++) MkFlow(&big[i], 90000 + i, 1, "new.exe", "h", 80, 0, 0, 10, 1, 1, 1);
+ FlowsApply(big, 400, FALSE, GetTickCount64() + 2000); /* ... and new ones replace the oldest finished */
+ { int found = 0; for (int i = 0; i < g_flN; i++) if (g_fl[i].id >= 90000 && g_fl[i].closedAt == 0) found++; CHECK(found == 400 && g_flN <= FLOW_ROWS_MAX); }
+ free(big); }
+
+ /* the column titles follow the language */
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDM_LANG_ZH, 0), 0);
+ { TCITEMW ti; wchar_t tx[64]; ti.mask = TCIF_TEXT; ti.pszText = tx; ti.cchTextMax = 64;
+ CHECK(TabCtrl_GetItem(g_hTab, 2, &ti) && !wcscmp(tx, T(S_TAB_FLOWS)) && wcscmp(tx, L"Live Connections") != 0);
+ HWND hd = ListView_GetHeader(g_hFlows); HDITEMW hi; wchar_t col[64]; hi.mask = HDI_TEXT; hi.pszText = col; hi.cchTextMax = 64;
+ CHECK(Header_GetItem(hd, 0, &hi) && !wcscmp(col, T(S_FL_COL_APP))); }
+ SendMessageW(g_hMain, WM_COMMAND, MAKEWPARAM(IDM_LANG_EN, 0), 0);
+
+ /* leaving the tab stops polling and frees the snapshot buffer; the rows are kept, everything marked finished */
+ SelectTab(0);
+ CHECK(!IsWindowVisible(g_hFlows) && !IsWindowVisible(g_hFlowsClear) && g_flSnap == NULL && g_flN > 0);
+ for (int i = 0; i < g_flN; i++) CHECK(g_fl[i].closedAt != 0);
+ { UINT64 id0 = g_fl[0].id; PBFlow one; MkFlow(&one, id0, 5, "back.exe", "h", 1, 0, 0, 1000, 1, 1, 1); memcpy(g_stubFlows, &one, sizeof one); g_stubN = 1;
+ SelectTab(2); PumpFlows(); /* coming back: a connection still running is live again */
+ int alive = 0; for (int i = 0; i < g_flN; i++) alive += g_fl[i].closedAt == 0; CHECK(alive == 1 && IsWindowVisible(g_hFlowsClear));
+ SelectTab(0); }
+ { int c = g_stubCalls; MSG m; while (PeekMessageW(&m, NULL, 0, 0, PM_REMOVE)) DispatchMessageW(&m); CHECK(g_stubCalls == c); }
+
+ /* closing the tab while a poll is still out: the result is dropped and the buffer freed, nothing is left running */
+ SelectTab(2); SelectTab(0); PumpFlows();
+ CHECK(g_flBusy == 0 && g_flSnap == NULL && !g_flActive);
+ { int c = g_stubCalls; MSG m; Sleep(1200); while (PeekMessageW(&m, NULL, 0, 0, PM_REMOVE)) DispatchMessageW(&m); CHECK(g_stubCalls == c); } /* the timer is off */
+
TrayRemove();
DestroyWindow(g_hMain);
return pbtest_done("test_main_ui");
diff --git a/Windows/tests/test_service.c b/Windows/tests/test_service.c
index 0ed689b..a4f01ed 100644
--- a/Windows/tests/test_service.c
+++ b/Windows/tests/test_service.c
@@ -35,6 +35,21 @@ 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; }
+static UINT32 g_flowsAsked = 0, g_flowsHave = 0;
+static UINT32 SGetFlows(PBFlow* out, UINT32 max)
+{
+ g_flowsAsked = max;
+ UINT32 n = g_flowsHave < max ? g_flowsHave : max;
+ for (UINT32 i = 0; i < n; i++)
+ {
+ ZeroMemory(&out[i], sizeof out[i]);
+ out[i].id = 0x100000002ull + i; out[i].pid = 4000 + i; out[i].proxy_config_id = 7; out[i].rule_id = 40 + i; out[i].age_ms = i ? 0xFFFFFFFFu : 1500;
+ out[i].sent = 0x500000001ull; out[i].received = 99; out[i].port = 443; out[i].is_udp = (UINT8)(i & 1); out[i].is_ipv6 = (UINT8)((i >> 1) & 1);
+ strcpy_s(out[i].name, sizeof out[i].name, "chrome.exe"); strcpy_s(out[i].host, sizeof out[i].host, "example.com");
+ }
+ if (n) memset(out[n - 1].name, 'x', sizeof out[n - 1].name); /* an unterminated name must not run past the field */
+ return n;
+}
/* ---- request helpers ---- */
static BYTE rq[PB_MSG_MAX], rs[PB_MSG_MAX];
@@ -49,11 +64,11 @@ int main(void)
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;
+ g_api.Start = SStart; g_api.Stop = SStop; g_api.TestProxyConfigEx = NULL; g_api.GetFlows = SGetFlows;
UINT32 ret;
/* ================= request handler ================= */
- begin(PBOP_HELLO); CHECK(run(&ret) && ret == PB_PROTO_VERSION && PB_PROTO_VERSION >= 4);
+ begin(PBOP_HELLO); CHECK(run(&ret) && ret == PB_PROTO_VERSION && PB_PROTO_VERSION >= 5);
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);
@@ -96,6 +111,30 @@ int main(void)
begin(PBOP_START); CHECK(run(&ret) && ret == 1 && g_started == 1);
begin(PBOP_STOP); CHECK(run(&ret) && ret == 0 && g_stopped == 1);
+ /* live connections */
+ g_flowsHave = 3;
+ begin(PBOP_GET_FLOWS); PbW_U32(&W, 10);
+ { PbW resp; PbW_Init(&resp, rs, sizeof rs); CHECK(Dispatch(rq, W.len, &resp) && resp.ok);
+ PbR r; PbR_Init(&r, rs, resp.len);
+ CHECK(PbR_U32(&r) == 3 && g_flowsAsked == 10);
+ for (int i = 0; i < 3; i++)
+ {
+ UINT32 lo = PbR_U32(&r), hi = PbR_U32(&r); UINT32 pid = PbR_U32(&r), flags = PbR_U32(&r), port = PbR_U32(&r), cfg = PbR_U32(&r), rid = PbR_U32(&r), age = PbR_U32(&r);
+ UINT32 sl = PbR_U32(&r), sh = PbR_U32(&r), rl = PbR_U32(&r), rh = PbR_U32(&r);
+ char name[64], host[64]; PbR_Str(&r, name, sizeof name, NULL); PbR_Str(&r, host, sizeof host, NULL);
+ CHECK(r.ok && lo == 2u + i && hi == 1 && pid == 4000u + i && port == 443 && cfg == 7 && rid == 40u + i && sl == 1 && sh == 5 && rl == 99 && rh == 0);
+ CHECK(flags == (UINT32)(((i & 1) ? 1 : 0) | (((i >> 1) & 1) ? 2 : 0)) && age == (i ? 0xFFFFFFFFu : 1500u) && !strcmp(host, "example.com"));
+ if (i == 2) CHECK(strlen(name) == 39); /* the unterminated name was cut at the field size */
+ else CHECK(!strcmp(name, "chrome.exe"));
+ }
+ CHECK(r.pos == r.len); } /* nothing left over */
+ begin(PBOP_GET_FLOWS); PbW_U32(&W, 0xFFFFFFFFu); CHECK(run(&ret) && ret == 3 && g_flowsAsked == PB_FLOWS_MAX_GUI); /* a huge request is capped */
+ g_flowsHave = 0; begin(PBOP_GET_FLOWS); PbW_U32(&W, 5); CHECK(run(&ret) && ret == 0);
+ g_flowsHave = 1000; begin(PBOP_GET_FLOWS); PbW_U32(&W, 400); /* the biggest possible answer still fits one message */
+ { PbW resp; PbW_Init(&resp, rs, sizeof rs); CHECK(Dispatch(rq, W.len, &resp) && resp.ok && resp.len <= PB_MSG_MAX); PbR r; PbR_Init(&r, rs, resp.len); CHECK(PbR_U32(&r) == 400); }
+ begin(PBOP_GET_FLOWS); CHECK(!run(&ret)); /* missing argument */
+ g_flowsHave = 0;
+
/* unknown operations and garbage are rejected without touching the engine */
begin(0); CHECK(!run(&ret));
begin(9999); CHECK(!run(&ret));
@@ -105,7 +144,7 @@ int main(void)
{
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); }
+ if (n >= 4 && it % 2) { UINT32 op = 1 + rand() % (PBOP_GET_FLOWS + 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);