Skip to content

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

feat(linux): live connections, proxy check, connection log options, main switch; fix local-proxy exemption

anof-cyber23b7665beb7a
diff --git a/Linux/build.sh b/Linux/build.sh
index 0eb334b..b787a4f 100755
--- a/Linux/build.sh
+++ b/Linux/build.sh
@@ -7,12 +7,17 @@
# OUTPUT_DIR=/some/dir ./build.sh
# WERROR=1 ./build.sh warnings are errors (CI) LTO=0 ./build.sh no link-time optimisation
# AUDIT=0 ./build.sh skip the binary audit STATIC_LIBBPF=0 ./build.sh use the system libbpf
+# PB_BUILD_DIR=/dir ./build.sh keep the intermediate files there (used by tests/coverage.sh)
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
OUTPUT_DIR="${OUTPUT_DIR:-$SCRIPT_DIR/output}"
-BUILD_DIR="$(mktemp -d "${TMPDIR:-/tmp}/proxybridge-build.XXXXXX")"
-trap 'rm -rf "$BUILD_DIR"' EXIT
+if [ -n "${PB_BUILD_DIR:-}" ]; then # keep the intermediate files (coverage builds need the .gcno files)
+ BUILD_DIR="$PB_BUILD_DIR"; mkdir -p "$BUILD_DIR"
+else
+ BUILD_DIR="$(mktemp -d "${TMPDIR:-/tmp}/proxybridge-build.XXXXXX")"
+ trap 'rm -rf "$BUILD_DIR"' EXIT
+fi
JOBS="$(nproc 2>/dev/null || echo 2)"
export WERROR LTO OPT
diff --git a/Linux/cli/main.c b/Linux/cli/main.c
index 0acf85b..4cce495 100644
--- a/Linux/cli/main.c
+++ b/Linux/cli/main.c
@@ -123,6 +123,13 @@ static void show_help(const char* prog)
printf(" --dns-via-proxy <bool> Route DNS queries through the proxy (true/false/1/0, default true)\n\n");
+ printf(" --log-every-connection <bool> Show every new connection in the connection log (--verbose 2/3) instead of one\n");
+ printf(" line per application, destination and action (default false; a profile can set it)\n\n");
+
+ printf(" --test-proxy <host[:port]> Check every configured proxy against that target (reach it, open a tunnel and log in,\n");
+ printf(" load a page, time tunnels, probe UDP), print the steps and exit 0 only if all work.\n");
+ printf(" Needs no root. Example: --proxy socks5://127.0.0.1:1080 --test-proxy example.com:80\n\n");
+
printf(" --verbose <level> 0 none (default), 1 logs, 2 connections, 3 both\n\n");
printf(" --cleanup No-op, kept for compatibility: the eBPF programs detach automatically\n\n");
@@ -358,7 +365,7 @@ static const char* profile_default_ref = NULL;
static char profile_default_name[64];
/* Appends the proxies and rules of a .pbprofile (a path, or the name of a profile saved by the GUI). */
-static bool load_profile(const char* arg, ProxyEntry* proxies, int* num_proxies, ProxyRule* rules, int* num_rules, bool* dns)
+static bool load_profile(const char* arg, ProxyEntry* proxies, int* num_proxies, ProxyRule* rules, int* num_rules, bool* dns, bool* log_every)
{
char* path = pbp_resolve(pbp_config_dir(), arg);
char err[256];
@@ -436,6 +443,7 @@ static bool load_profile(const char* arg, ProxyEntry* proxies, int* num_proxies,
}
}
*dns = prof.dns_via_proxy;
+ *log_every = prof.log_every;
pbp_free(&prof);
return ok;
}
@@ -468,6 +476,60 @@ static int list_profiles(void)
return 0;
}
+static void check_line(const char* line, void* user)
+{
+ (void)user;
+ printf("%s\n", line);
+ fflush(stdout);
+}
+
+/* --test-proxy host[:port]: runs the multi-step check against every configured proxy; no root needed. */
+static int run_proxy_checks(ProxyEntry* proxies, int num_proxies, const char* target)
+{
+ char host[256];
+ unsigned long port = 80;
+ snprintf(host, sizeof(host), "%s", target);
+ char* colon = strrchr(host, ':');
+ if (host[0] == '[')
+ {
+ char* close = strchr(host, ']');
+ if (!close) { fprintf(stderr, "ERROR: Invalid target '%s'\n", target); return 2; }
+ *close = '\0';
+ memmove(host, host + 1, strlen(host));
+ colon = (close[1] == ':') ? close + 1 : NULL;
+ if (colon) { char* e = NULL; port = strtoul(colon + 1, &e, 10); if (!colon[1] || *e) port = 0; }
+ }
+ else if (colon && strchr(host, ':') == colon)
+ {
+ char* e = NULL;
+ port = strtoul(colon + 1, &e, 10);
+ if (!colon[1] || *e) port = 0;
+ *colon = '\0';
+ }
+ if (!host[0] || port < 1 || port > 65535)
+ {
+ fprintf(stderr, "ERROR: Invalid target '%s'. Expected host[:port]\n", target);
+ return 2;
+ }
+ int failed = 0;
+ char err[256];
+ for (int i = 0; i < num_proxies; i++)
+ {
+ ProxyEntry* p = &proxies[i];
+ p->id = ProxyBridge_AddProxy(p->name, p->type, p->host, p->port, p->username, p->password, err, sizeof(err));
+ if (!p->id)
+ {
+ fprintf(stderr, "ERROR: Proxy %d (%s:%u): %s\n", i + 1, p->host, p->port, err);
+ return 2;
+ }
+ if (i)
+ printf("\n");
+ if (ProxyBridge_TestProxyEx(p->id, host, (uint16_t)port, check_line, NULL) != 0)
+ failed++;
+ }
+ return failed ? 1 : 0;
+}
+
static bool is_root(void)
{
return getuid() == 0;
@@ -481,6 +543,8 @@ int main(int argc, char *argv[])
int num_rules = 0;
bool dns_via_proxy = true;
bool dns_explicit = false;
+ bool log_every = false, log_every_explicit = false;
+ const char* test_target = NULL;
for (int i = 1; i < argc; i++)
{
@@ -518,11 +582,13 @@ int main(int argc, char *argv[])
}
else if (strcmp(argv[i], "--profile") == 0 && i + 1 < argc)
{
- bool dns = dns_via_proxy;
- if (!load_profile(argv[++i], proxies, &num_proxies, rules, &num_rules, &dns))
+ bool dns = dns_via_proxy, every = log_every;
+ if (!load_profile(argv[++i], proxies, &num_proxies, rules, &num_rules, &dns, &every))
return 1;
if (!dns_explicit)
dns_via_proxy = dns;
+ if (!log_every_explicit)
+ log_every = every;
}
else if (strcmp(argv[i], "--rule") == 0 && i + 1 < argc)
{
@@ -549,6 +615,24 @@ int main(int argc, char *argv[])
return 1;
}
}
+ else if (strcmp(argv[i], "--log-every-connection") == 0 && i + 1 < argc)
+ {
+ char* value = argv[++i];
+ log_every_explicit = true;
+ if (strcmp(value, "true") == 0 || strcmp(value, "1") == 0)
+ log_every = true;
+ else if (strcmp(value, "false") == 0 || strcmp(value, "0") == 0)
+ log_every = false;
+ else
+ {
+ fprintf(stderr, "ERROR: Invalid value for --log-every-connection. Use: true, false, 1, or 0\n");
+ return 1;
+ }
+ }
+ else if (strcmp(argv[i], "--test-proxy") == 0 && i + 1 < argc)
+ {
+ test_target = argv[++i];
+ }
else if (strcmp(argv[i], "--verbose") == 0 && i + 1 < argc)
{
verbose_level = atoi(argv[++i]);
@@ -573,6 +657,9 @@ int main(int argc, char *argv[])
num_proxies = 1;
}
+ if (test_target)
+ return run_proxy_checks(proxies, num_proxies, test_target);
+
show_banner();
if (!is_root())
@@ -594,6 +681,7 @@ int main(int argc, char *argv[])
ProxyBridge_SetTrafficLoggingEnabled(verbose_level > 0);
ProxyBridge_SetDnsViaProxy(dns_via_proxy);
+ ProxyBridge_SetLogEveryConnection(log_every);
char err[256];
printf("Proxies: %d\n", num_proxies);
diff --git a/Linux/gui/gui.h b/Linux/gui/gui.h
index e8ab865..37a6642 100644
--- a/Linux/gui/gui.h
+++ b/Linux/gui/gui.h
@@ -42,7 +42,7 @@ typedef struct {
GList *proxies;
char *default_proxy;
GList *rules;
- bool logging, dns; // traffic logging and DNS via proxy, stored in the profile like the Windows app does
+ bool logging, dns, log_every; // traffic logging, DNS via proxy and "log every connection", stored in the profile like the Windows app does
char *saved; // what is on disk, to skip rewriting unchanged profiles
} Profile;
@@ -66,6 +66,7 @@ extern char *g_default_proxy;
extern GList *g_rules_list;
extern bool g_chk_logging;
extern bool g_chk_dns;
+extern bool g_chk_log_every;
void show_message(GtkWindow *parent, GtkMessageType type, const char *format, ...);
GtkWidget *combo_new(const char *first, ...) G_GNUC_NULL_TERMINATED;
@@ -81,7 +82,8 @@ char *extract_sub_json_str(const char *json, const char *key);
int rules_from_json(const char *json, RuleImportCb cb, void *ud);
char *rules_to_json(GList *rules, bool only_selected);
-void gui_sync_switches(); // pushes the active profile's logging/DNS switches to the engine and the menu
+void gui_sync_switches();
+void gui_refresh_flows(); // refreshes the Live Connections tab from the engine // pushes the active profile's logging/DNS switches to the engine and the menu
void save_config();
void load_config();
void config_free_all();
diff --git a/Linux/gui/gui_config.c b/Linux/gui/gui_config.c
index aa38715..6062dfc 100644
--- a/Linux/gui/gui_config.c
+++ b/Linux/gui/gui_config.c
@@ -59,6 +59,7 @@ static void profile_sync_active() {
p->default_proxy = g_default_proxy;
p->logging = g_chk_logging;
p->dns = g_chk_dns;
+ p->log_every = g_chk_log_every;
}
static void load_globals_from(Profile *p) {
@@ -67,6 +68,7 @@ static void load_globals_from(Profile *p) {
g_default_proxy = p->default_proxy;
g_chk_logging = p->logging;
g_chk_dns = p->dns;
+ g_chk_log_every = p->log_every;
}
void config_free_all() {
@@ -124,6 +126,7 @@ Profile *profile_create(const char *name, bool copy_active) {
p->default_proxy = g_strdup(src->default_proxy);
p->logging = src->logging;
p->dns = src->dns;
+ p->log_every = src->log_every;
}
return p;
}
@@ -182,6 +185,7 @@ static void profile_to_pbp(const Profile *prof, struct pbp_profile *out) {
out->name = prof->name;
out->logging = prof->logging;
out->dns_via_proxy = prof->dns;
+ out->log_every = prof->log_every;
out->nproxies = g_list_length(prof->proxies);
out->nrules = g_list_length(prof->rules);
out->proxies = g_new0(struct pbp_proxy, out->nproxies + 1);
@@ -257,6 +261,7 @@ static void fill_profile_from_pbp(Profile *p, const struct pbp_profile *src) {
p->default_proxy = d ? g_strdup(d->name) : NULL;
p->logging = src->logging;
p->dns = src->dns_via_proxy;
+ p->log_every = src->log_every;
}
bool profile_export(const Profile *prof, const char *path, char *err, size_t errlen) {
diff --git a/Linux/gui/gui_rules.c b/Linux/gui/gui_rules.c
index 027fd95..85bbd7b 100644
--- a/Linux/gui/gui_rules.c
+++ b/Linux/gui/gui_rules.c
@@ -148,6 +148,7 @@ static void open_rule_dialog(RuleData *rule) {
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
"Cancel", GTK_RESPONSE_CANCEL, "Save", GTK_RESPONSE_ACCEPT, NULL);
gtk_window_set_default_size(GTK_WINDOW(dialog), 500, 400);
+ gtk_widget_set_name(dialog, "dlg_rule");
GtkWidget *grid = gtk_grid_new();
gtk_grid_set_row_spacing(GTK_GRID(grid), 8);
gtk_grid_set_column_spacing(GTK_GRID(grid), 10);
@@ -203,6 +204,10 @@ static void open_rule_dialog(RuleData *rule) {
g_signal_connect(action_combo, "changed", G_CALLBACK(on_action_changed), localhost_check);
GtkWidget *err_label = hint_label("");
+ // names let the UI test find the widgets
+ gtk_widget_set_name(name_entry, "rule_name"); gtk_widget_set_name(proc_entry, "rule_process"); gtk_widget_set_name(host_view, "rule_hosts");
+ gtk_widget_set_name(port_entry, "rule_ports"); gtk_widget_set_name(proto_combo, "rule_proto"); gtk_widget_set_name(action_combo, "rule_action");
+ gtk_widget_set_name(proxy_combo, "rule_proxy"); gtk_widget_set_name(localhost_check, "rule_localhost"); gtk_widget_set_name(err_label, "rule_error");
grid_row(grid, 0, "Name:", name_entry);
grid_row(grid, 1, "Process Name:", proc_box);
gtk_grid_attach(GTK_GRID(grid), hint_label("Example: firefox; chrome; /usr/bin/wget"), 1, 2, 1, 1);
@@ -441,15 +446,23 @@ static void refresh_rules_ui() {
int row = 2, sr = 1;
for (GList *l = g_rules_list; l != NULL; l = l->next, row += 2) {
RuleData *r = (RuleData *)l->data;
- check_cell(grid, row, 0, r->selected, G_CALLBACK(on_rule_select_toggle), r);
- check_cell(grid, row, 1, r->enabled, G_CALLBACK(on_rule_toggle), r);
+ char nm[48];
+ snprintf(nm, sizeof nm, "rule_select_%d", sr);
+ gtk_widget_set_name(check_cell(grid, row, 0, r->selected, G_CALLBACK(on_rule_select_toggle), r), nm);
+ snprintf(nm, sizeof nm, "rule_enable_%d", sr);
+ gtk_widget_set_name(check_cell(grid, row, 1, r->enabled, G_CALLBACK(on_rule_toggle), r), nm);
// list position is the priority, first match wins
GtkWidget *act_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);
- small_button(act_box, "Edit", NULL, true, G_CALLBACK(on_rule_edit), r);
- small_button(act_box, "Delete", NULL, true, G_CALLBACK(on_rule_delete), r);
- small_button(act_box, "▲", "Move up (higher priority)", l->prev != NULL, G_CALLBACK(on_rule_move_up), r);
- small_button(act_box, "▼", "Move down (lower priority)", l->next != NULL, G_CALLBACK(on_rule_move_down), r);
+ char bn[48];
+ snprintf(bn, sizeof bn, "rule_edit_%d", sr);
+ gtk_widget_set_name(small_button(act_box, "Edit", NULL, true, G_CALLBACK(on_rule_edit), r), bn);
+ snprintf(bn, sizeof bn, "rule_delete_%d", sr);
+ gtk_widget_set_name(small_button(act_box, "Delete", NULL, true, G_CALLBACK(on_rule_delete), r), bn);
+ snprintf(bn, sizeof bn, "rule_up_%d", sr);
+ gtk_widget_set_name(small_button(act_box, "▲", "Move up (higher priority)", l->prev != NULL, G_CALLBACK(on_rule_move_up), r), bn);
+ snprintf(bn, sizeof bn, "rule_down_%d", sr);
+ gtk_widget_set_name(small_button(act_box, "▼", "Move down (lower priority)", l->next != NULL, G_CALLBACK(on_rule_move_down), r), bn);
gtk_grid_attach(GTK_GRID(grid), act_box, 2, row, 1, 1);
char sr_str[16];
@@ -492,6 +505,7 @@ void on_proxy_rules_clicked(GtkWidget *widget, gpointer data) {
return;
}
rules_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
+ gtk_widget_set_name(rules_window, "win_rules");
g_signal_connect(rules_window, "destroy", G_CALLBACK(on_rules_window_destroy), NULL);
gtk_window_set_title(GTK_WINDOW(rules_window), "Process Rules");
gtk_window_set_default_size(GTK_WINDOW(rules_window), 1000, 500);
@@ -512,6 +526,8 @@ void on_proxy_rules_clicked(GtkWidget *widget, gpointer data) {
GtkWidget *del_btn = gtk_button_new_with_label("Delete Selected");
GtkWidget *import_btn = gtk_button_new_with_label("Import");
GtkWidget *export_btn = gtk_button_new_with_label("Export");
+ gtk_widget_set_name(add_btn, "rules_add"); gtk_widget_set_name(btn_select_all_header, "rules_select_all"); gtk_widget_set_name(del_btn, "rules_delete_selected");
+ gtk_widget_set_name(import_btn, "rules_import"); gtk_widget_set_name(export_btn, "rules_export");
g_signal_connect(add_btn, "clicked", G_CALLBACK(on_rule_add_clicked), NULL);
g_signal_connect(btn_select_all_header, "clicked", G_CALLBACK(on_select_all_clicked), NULL);
g_signal_connect(del_btn, "clicked", G_CALLBACK(on_bulk_delete_clicked), NULL);
@@ -523,6 +539,7 @@ void on_proxy_rules_clicked(GtkWidget *widget, gpointer data) {
GtkWidget *scrolled = gtk_scrolled_window_new(NULL, NULL);
rules_list_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
+ gtk_widget_set_name(rules_list_box, "rules_list");
gtk_container_add(GTK_CONTAINER(scrolled), rules_list_box);
gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 0);
diff --git a/Linux/gui/gui_settings.c b/Linux/gui/gui_settings.c
index bc1cf46..320ccb4 100644
--- a/Linux/gui/gui_settings.c
+++ b/Linux/gui/gui_settings.c
@@ -22,9 +22,11 @@ typedef struct {
uint16_t port;
GtkTextBuffer *buffer;
GtkWidget *btn;
- char result[4096];
+ int result;
} TestJob;
+typedef struct { GtkTextBuffer *buffer; char *line; } TestLine;
+
void free_proxy_data(ProxyData *p) {
if (!p) return;
g_free(p->name);
@@ -83,12 +85,24 @@ static bool port_text_valid(const char *text, int *port_out) {
return true;
}
+// the first line replaces the "Testing..." placeholder, later lines are appended
+static gboolean on_test_line(gpointer user_data) {
+ TestLine *tl = (TestLine *)user_data;
+ char *text = g_utf8_make_valid(tl->line, -1);
+ GtkTextIter end;
+ gtk_text_buffer_get_end_iter(tl->buffer, &end);
+ gtk_text_buffer_insert(tl->buffer, &end, text, -1);
+ gtk_text_buffer_insert(tl->buffer, &end, "\n", 1);
+ g_free(text);
+ g_object_unref(tl->buffer);
+ g_free(tl->line);
+ g_free(tl);
+ return FALSE;
+}
+
static gboolean on_test_done(gpointer user_data) {
TestJob *job = (TestJob *)user_data;
- char *text = g_utf8_make_valid(job->result, -1);
- gtk_text_buffer_set_text(job->buffer, text, -1);
gtk_widget_set_sensitive(job->btn, TRUE);
- g_free(text);
g_object_unref(job->buffer);
g_object_unref(job->btn);
g_free(job->host);
@@ -96,10 +110,17 @@ static gboolean on_test_done(gpointer user_data) {
return FALSE;
}
+static void test_progress(const char *line, void *user) {
+ TestJob *job = (TestJob *)user;
+ TestLine *tl = g_malloc0(sizeof *tl);
+ tl->buffer = g_object_ref(job->buffer);
+ tl->line = g_strdup(line);
+ g_idle_add(on_test_line, tl);
+}
+
static gpointer run_test_thread(gpointer user_data) {
TestJob *job = (TestJob *)user_data;
- ProxyBridge_TestProxy(job->proxy_id, job->host, job->port, job->result, sizeof(job->result));
- job->result[sizeof(job->result) - 1] = '\0';
+ job->result = ProxyBridge_TestProxyEx(job->proxy_id, job->host, job->port, test_progress, job);
g_idle_add(on_test_done, job);
return NULL;
}
@@ -127,7 +148,7 @@ static void on_start_test_clicked(GtkWidget *widget, gpointer data) {
int t_port = (int)parse_long(gtk_entry_get_text(GTK_ENTRY(info->test_port)));
if (t_port <= 0 || t_port > 65535) t_port = 80;
- gtk_text_buffer_set_text(info->output_buffer, "Testing connection... Please wait...", -1);
+ gtk_text_buffer_set_text(info->output_buffer, "", -1);
gtk_widget_set_sensitive(info->test_btn, FALSE);
TestJob *job = g_malloc0(sizeof(TestJob));
@@ -193,6 +214,7 @@ static ProxyData *proxy_edit_dialog(GtkWindow *parent, ProxyData *existing) {
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
"Cancel", GTK_RESPONSE_CANCEL, "Save", GTK_RESPONSE_ACCEPT, NULL);
gtk_window_set_default_size(GTK_WINDOW(dialog), 420, -1);
+ gtk_widget_set_name(dialog, "dlg_proxy");
GtkWidget *grid = gtk_grid_new();
gtk_grid_set_row_spacing(GTK_GRID(grid), 5);
gtk_grid_set_column_spacing(GTK_GRID(grid), 10);
@@ -217,6 +239,9 @@ static ProxyData *proxy_edit_dialog(GtkWindow *parent, ProxyData *existing) {
gtk_grid_attach(GTK_GRID(grid), dns_check, 1, 6, 1, 1);
gtk_grid_attach(GTK_GRID(grid), hint_label("On: connections to a name the application resolved are sent to the proxy by name. Off: the IP address is sent. UDP always uses the IP."), 1, 7, 1, 1);
GtkWidget *err_label = hint_label("");
+ gtk_widget_set_name(name_entry, "px_name"); gtk_widget_set_name(type_combo, "px_type"); gtk_widget_set_name(ip_entry, "px_host");
+ gtk_widget_set_name(port_entry, "px_port"); gtk_widget_set_name(user_entry, "px_user"); gtk_widget_set_name(pass_entry, "px_pass");
+ gtk_widget_set_name(dns_check, "px_dns"); gtk_widget_set_name(err_label, "px_error");
gtk_grid_attach(GTK_GRID(grid), err_label, 0, 8, 2, 1);
gtk_combo_box_set_active(GTK_COMBO_BOX(type_combo), 1);
@@ -371,6 +396,7 @@ void on_proxy_configure(GtkWidget *widget, gpointer data) {
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
"Close", GTK_RESPONSE_CLOSE, NULL);
gtk_window_set_default_size(GTK_WINDOW(info.dialog), 650, 560);
+ gtk_widget_set_name(info.dialog, "dlg_proxies");
GtkWidget *grid = gtk_grid_new();
gtk_grid_set_row_spacing(GTK_GRID(grid), 5);
@@ -388,6 +414,7 @@ void on_proxy_configure(GtkWidget *widget, gpointer data) {
gtk_tree_view_column_set_expand(c, i == 2);
gtk_tree_view_append_column(GTK_TREE_VIEW(info.tree), c);
}
+ gtk_widget_set_name(info.tree, "proxy_tree");
g_signal_connect(info.tree, "row-activated", G_CALLBACK(on_proxy_row_activated), &info);
GtkWidget *tree_scroll = gtk_scrolled_window_new(NULL, NULL);
gtk_widget_set_size_request(tree_scroll, -1, 180);
@@ -399,8 +426,10 @@ void on_proxy_configure(GtkWidget *widget, gpointer data) {
GtkWidget *btn_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
const char *labels[] = {"Add", "Edit", "Delete", "Set Default"};
void (*cbs[])(GtkWidget *, gpointer) = {on_proxy_add, on_proxy_edit, on_proxy_delete, on_proxy_set_default};
+ const char *bnames[] = {"px_add", "px_edit", "px_delete", "px_default"};
for (int i = 0; i < 4; i++) {
GtkWidget *b = gtk_button_new_with_label(labels[i]);
+ gtk_widget_set_name(b, bnames[i]);
g_signal_connect(b, "clicked", G_CALLBACK(cbs[i]), &info);
gtk_box_pack_start(GTK_BOX(btn_box), b, FALSE, FALSE, 0);
}
@@ -423,13 +452,16 @@ void on_proxy_configure(GtkWidget *widget, gpointer data) {
gtk_widget_set_size_request(info.test_port, 80, -1);
gtk_grid_attach(GTK_GRID(grid), info.test_port, 3, 4, 1, 1);
+ gtk_widget_set_name(info.test_host, "px_test_host"); gtk_widget_set_name(info.test_port, "px_test_port");
info.test_btn = gtk_button_new_with_label("Start Test");
+ gtk_widget_set_name(info.test_btn, "px_test");
g_signal_connect(info.test_btn, "clicked", G_CALLBACK(on_start_test_clicked), &info);
gtk_grid_attach(GTK_GRID(grid), info.test_btn, 0, 5, 4, 1);
GtkWidget *out_scroll = gtk_scrolled_window_new(NULL, NULL);
gtk_widget_set_size_request(out_scroll, -1, 150);
GtkWidget *out_view = gtk_text_view_new();
+ gtk_widget_set_name(out_view, "px_test_output");
gtk_text_view_set_editable(GTK_TEXT_VIEW(out_view), FALSE);
gtk_text_view_set_monospace(GTK_TEXT_VIEW(out_view), TRUE);
info.output_buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(out_view));
@@ -495,9 +527,11 @@ static char *selected_profile_name(ProfilesInfo *pi) {
static char *ask_profile_name(GtkWindow *parent, const char *title, const char *initial) {
GtkWidget *d = gtk_dialog_new_with_buttons(title, parent, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
"Cancel", GTK_RESPONSE_CANCEL, "OK", GTK_RESPONSE_ACCEPT, NULL);
+ gtk_widget_set_name(d, "dlg_profile_name");
GtkWidget *box = gtk_dialog_get_content_area(GTK_DIALOG(d));
gtk_container_set_border_width(GTK_CONTAINER(box), 10);
GtkWidget *entry = gtk_entry_new();
+ gtk_widget_set_name(entry, "profile_name_entry");
gtk_entry_set_activates_default(GTK_ENTRY(entry), TRUE);
gtk_entry_set_text(GTK_ENTRY(entry), initial);
gtk_box_pack_start(GTK_BOX(box), gtk_label_new("Profile name:"), FALSE, FALSE, 0);
@@ -646,6 +680,7 @@ void on_profiles_clicked(GtkWidget *widget, gpointer data) {
pi.dialog = gtk_dialog_new_with_buttons("Profiles", GTK_WINDOW(window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
"Close", GTK_RESPONSE_CLOSE, NULL);
gtk_window_set_default_size(GTK_WINDOW(pi.dialog), 560, 360);
+ gtk_widget_set_name(pi.dialog, "dlg_profiles");
GtkWidget *box = gtk_dialog_get_content_area(GTK_DIALOG(pi.dialog));
gtk_container_set_border_width(GTK_CONTAINER(box), 10);
@@ -658,6 +693,7 @@ void on_profiles_clicked(GtkWidget *widget, gpointer data) {
gtk_tree_view_column_set_expand(c, i == 0);
gtk_tree_view_append_column(GTK_TREE_VIEW(pi.tree), c);
}
+ gtk_widget_set_name(pi.tree, "profile_tree");
g_signal_connect(pi.tree, "row-activated", G_CALLBACK(on_profile_row_activated), &pi);
GtkWidget *scroll = gtk_scrolled_window_new(NULL, NULL);
gtk_container_add(GTK_CONTAINER(scroll), pi.tree);
@@ -667,8 +703,10 @@ void on_profiles_clicked(GtkWidget *widget, gpointer data) {
const char *labels[] = {"Switch", "New", "Duplicate", "Rename", "Delete", "Import...", "Export..."};
void (*cbs[])(GtkWidget *, gpointer) = {on_profile_switch, on_profile_new, on_profile_duplicate, on_profile_rename, on_profile_delete,
on_profile_import, on_profile_export};
+ const char *bnames[] = {"pf_switch", "pf_new", "pf_duplicate", "pf_rename", "pf_delete", "pf_import", "pf_export"};
for (int i = 0; i < 7; i++) {
GtkWidget *b = gtk_button_new_with_label(labels[i]);
+ gtk_widget_set_name(b, bnames[i]);
g_signal_connect(b, "clicked", G_CALLBACK(cbs[i]), &pi);
gtk_box_pack_start(GTK_BOX(btns), b, FALSE, FALSE, 0);
}
diff --git a/Linux/gui/main.c b/Linux/gui/main.c
index a447872..9ad0957 100644
--- a/Linux/gui/main.c
+++ b/Linux/gui/main.c
@@ -11,7 +11,8 @@ guint status_context_id;
GList *g_rules_list = NULL;
bool g_chk_logging = true;
bool g_chk_dns = true;
-static GtkWidget *log_item, *dns_item;
+bool g_chk_log_every = false;
+static GtkWidget *log_item, *dns_item, *every_item, *enable_item;
static void on_log_traffic_toggled(GtkCheckMenuItem *item, gpointer data) {
bool active = gtk_check_menu_item_get_active(item);
@@ -20,6 +21,19 @@ static void on_log_traffic_toggled(GtkCheckMenuItem *item, gpointer data) {
save_config();
}
+static void on_log_every_toggled(GtkCheckMenuItem *item, gpointer data) {
+ bool active = gtk_check_menu_item_get_active(item);
+ ProxyBridge_SetLogEveryConnection(active);
+ g_chk_log_every = active;
+ save_config();
+}
+
+// main switch: pauses the rules for new connections; it is not part of a profile
+static void on_enable_toggled(GtkCheckMenuItem *item, gpointer data) {
+ ProxyBridge_SetEnabled(gtk_check_menu_item_get_active(item));
+ gui_log("ProxyBridge %s", gtk_check_menu_item_get_active(item) ? "enabled" : "paused: new connections are not redirected");
+}
+
static void on_dns_proxy_toggled(GtkCheckMenuItem *item, gpointer data) {
bool active = gtk_check_menu_item_get_active(item);
ProxyBridge_SetDnsViaProxy(active);
@@ -31,6 +45,8 @@ static void on_dns_proxy_toggled(GtkCheckMenuItem *item, gpointer data) {
void gui_sync_switches() {
ProxyBridge_SetTrafficLoggingEnabled(g_chk_logging);
ProxyBridge_SetDnsViaProxy(g_chk_dns);
+ ProxyBridge_SetLogEveryConnection(g_chk_log_every);
+ if (every_item) gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(every_item), g_chk_log_every);
if (log_item) gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(log_item), g_chk_logging);
if (dns_item) gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(dns_item), g_chk_dns);
}
@@ -197,6 +213,7 @@ static void on_check_update(GtkWidget *widget, gpointer data) {
static void on_about(GtkWidget *widget, gpointer data) {
GtkWidget *dialog = gtk_dialog_new_with_buttons("About ProxyBridge", GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL, "OK", GTK_RESPONSE_OK, NULL);
gtk_window_set_default_size(GTK_WINDOW(dialog), 400, 300);
+ gtk_widget_set_name(dialog, "dlg_about");
GtkWidget *content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog));
gtk_container_set_border_width(GTK_CONTAINER(content_area), 20);
char *markup = g_strdup_printf(
@@ -377,6 +394,63 @@ static GtkTextBuffer *add_text_tab(GtkWidget *notebook, const char *title, const
return buffer;
}
+// set only by the UI test: it drives the finished window instead of the user and returns when it is done
+void (*pb_gui_ready_hook)(void) = NULL;
+
+// ---- Live Connections tab ----
+static GtkListStore *flows_store;
+static GtkWidget *flows_tree, *flows_page;
+
+static char *human_bytes(uint64_t b) {
+ if (b < 1024) return g_strdup_printf("%llu B", (unsigned long long)b);
+ if (b < 1024 * 1024) return g_strdup_printf("%.1f KB", b / 1024.0);
+ if (b < 1024ULL * 1024 * 1024) return g_strdup_printf("%.1f MB", b / (1024.0 * 1024));
+ return g_strdup_printf("%.2f GB", b / (1024.0 * 1024 * 1024));
+}
+
+void gui_refresh_flows() {
+ if (!flows_store) return;
+ static ProxyBridgeFlow flows[PB_FLOWS_MAX];
+ uint32_t n = ProxyBridge_GetFlows(flows, PB_FLOWS_MAX);
+ gtk_list_store_clear(flows_store);
+ for (uint32_t i = 0; i < n; i++) {
+ const ProxyBridgeFlow *f = &flows[i];
+ const char *proxy = "?";
+ for (GList *l = g_proxies_list; l != NULL; l = l->next)
+ if (((ProxyData *)l->data)->id == f->proxy_id) proxy = ((ProxyData *)l->data)->name;
+ char *dest = f->is_ipv6 ? g_strdup_printf("[%s]:%u", f->host, f->port) : g_strdup_printf("%s:%u", f->host, f->port);
+ char *age = g_strdup_printf("%u s", f->age_ms / 1000);
+ char *sent = human_bytes(f->sent), *recv = human_bytes(f->received);
+ GtkTreeIter it;
+ gtk_list_store_append(flows_store, &it);
+ gtk_list_store_set(flows_store, &it, 0, f->name, 1, (guint)f->pid, 2, dest, 3, f->is_udp ? "UDP" : "TCP", 4, proxy, 5, age, 6, sent, 7, recv, -1);
+ g_free(dest); g_free(age); g_free(sent); g_free(recv);
+ }
+}
+
+static gboolean flows_tick(gpointer data) {
+ if (flows_page && gtk_widget_get_mapped(flows_page)) gui_refresh_flows();
+ return G_SOURCE_CONTINUE;
+}
+
+static GtkWidget *add_flows_tab(GtkWidget *notebook) {
+ flows_store = gtk_list_store_new(8, G_TYPE_STRING, G_TYPE_UINT, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING);
+ flows_tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(flows_store));
+ gtk_widget_set_name(flows_tree, "flows_tree");
+ g_object_unref(flows_store);
+ const char *titles[] = {"Process", "PID", "Destination", "Proto", "Proxy", "Age", "Sent", "Received"};
+ for (int i = 0; i < 8; i++) {
+ GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes(titles[i], gtk_cell_renderer_text_new(), "text", i, NULL);
+ gtk_tree_view_column_set_resizable(c, TRUE);
+ gtk_tree_view_column_set_expand(c, i == 2);
+ gtk_tree_view_append_column(GTK_TREE_VIEW(flows_tree), c);
+ }
+ flows_page = gtk_scrolled_window_new(NULL, NULL);
+ gtk_container_add(GTK_CONTAINER(flows_page), flows_tree);
+ gtk_notebook_append_page(GTK_NOTEBOOK(notebook), flows_page, gtk_label_new("Live Connections"));
+ return flows_page;
+}
+
int main(int argc, char *argv[]) {
if (getuid() != 0) {
gtk_init(&argc, &argv);
@@ -408,6 +482,8 @@ int main(int argc, char *argv[]) {
add_separator(proxy_menu);
log_item = add_check_item(proxy_menu, "Enable Traffic Logging", g_chk_logging, G_CALLBACK(on_log_traffic_toggled));
dns_item = add_check_item(proxy_menu, "DNS via Proxy", g_chk_dns, G_CALLBACK(on_dns_proxy_toggled));
+ every_item = add_check_item(proxy_menu, "Log Every Connection", g_chk_log_every, G_CALLBACK(on_log_every_toggled));
+ enable_item = add_check_item(proxy_menu, "Enable ProxyBridge", true, G_CALLBACK(on_enable_toggled));
add_separator(proxy_menu);
start_item = add_menu_item(proxy_menu, "Start Engine", G_CALLBACK(on_start_engine));
stop_item = add_menu_item(proxy_menu, "Stop Engine", G_CALLBACK(on_stop_engine));
@@ -421,6 +497,8 @@ int main(int argc, char *argv[]) {
gtk_box_pack_start(GTK_BOX(vbox), notebook, TRUE, TRUE, 0);
conn_buffer = add_text_tab(notebook, "Connections", "Search connections...", G_CALLBACK(on_search_conn_changed), G_CALLBACK(on_clear_conn_clicked), G_CALLBACK(on_pause_conn_toggled));
log_buffer = add_text_tab(notebook, "Activity Logs", "Search logs...", G_CALLBACK(on_search_log_changed), G_CALLBACK(on_clear_log_clicked), NULL);
+ add_flows_tab(notebook);
+ g_timeout_add_seconds(1, flows_tick, NULL);
GtkWidget *status_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
status_bar = gtk_statusbar_new();
@@ -436,6 +514,7 @@ int main(int argc, char *argv[]) {
ProxyBridge_SetConnectionCallback(lib_connection_callback);
ProxyBridge_SetTrafficLoggingEnabled(g_chk_logging);
ProxyBridge_SetDnsViaProxy(g_chk_dns);
+ ProxyBridge_SetLogEveryConnection(g_chk_log_every);
apply_proxies_to_lib();
apply_rules_to_lib();
@@ -446,7 +525,8 @@ int main(int argc, char *argv[]) {
update_status_info();
status_source = g_timeout_add_seconds(1, status_tick, NULL);
engine_request(true);
- gtk_main();
+ if (pb_gui_ready_hook) pb_gui_ready_hook();
+ else gtk_main();
shutdown_engine();
gui_logs_free();
diff --git a/Linux/profile/pb_profile.c b/Linux/profile/pb_profile.c
index f6871e9..3ea3a40 100644
--- a/Linux/profile/pb_profile.c
+++ b/Linux/profile/pb_profile.c
@@ -498,6 +498,7 @@ int pbp_parse(const char *json, size_t len, struct pbp_profile *out, char *err,
out->name = jtext(&root, "Name");
out->logging = jbool(&root, "IsTrafficLoggingEnabled", true);
out->dns_via_proxy = jbool(&root, "DnsViaProxy", true);
+ out->log_every = jbool(&root, "LogEveryConnection", false);
long dp = jnum(&root, "DefaultProxyId", 0);
out->default_proxy_id = dp > 0 ? (uint32_t)dp : 0;
if (cfgs && cfgs->nk) out->proxies = calloc(cfgs->nk, sizeof *out->proxies);
@@ -591,6 +592,7 @@ char *pbp_serialize(const struct pbp_profile *p)
sb_kv(&b, " ", "Name", p->name ? p->name : "", ",\n");
sb_puts(&b, p->logging ? " \"IsTrafficLoggingEnabled\": true,\n" : " \"IsTrafficLoggingEnabled\": false,\n");
sb_puts(&b, p->dns_via_proxy ? " \"DnsViaProxy\": true,\n" : " \"DnsViaProxy\": false,\n");
+ sb_puts(&b, p->log_every ? " \"LogEveryConnection\": true,\n" : " \"LogEveryConnection\": false,\n");
sb_fmt(&b, " \"DefaultProxyId\": %u,\n", p->default_proxy_id);
sb_puts(&b, " \"ProxyConfigs\": [");
diff --git a/Linux/profile/pb_profile.h b/Linux/profile/pb_profile.h
index b7f7fcd..c3ece74 100644
--- a/Linux/profile/pb_profile.h
+++ b/Linux/profile/pb_profile.h
@@ -46,6 +46,7 @@ struct pbp_profile {
char *name;
bool logging; // IsTrafficLoggingEnabled
bool dns_via_proxy; // DnsViaProxy (Linux extension)
+ bool log_every; // LogEveryConnection: the connection log is not de-duplicated
uint32_t default_proxy_id; // DefaultProxyId (Linux extension); 0 = first proxy
struct pbp_proxy *proxies; size_t nproxies;
struct pbp_rule *rules; size_t nrules;
diff --git a/Linux/src/Makefile b/Linux/src/Makefile
index ab84111..fc91bcf 100644
--- a/Linux/src/Makefile
+++ b/Linux/src/Makefile
@@ -52,9 +52,10 @@ $(TARGET): $(OBJECTS) exports.map
$(BUILD_DIR)/%.o: %.c pb_internal.h ProxyBridge.h | $(BUILD_DIR)
$(CC) $(CFLAGS) -c $< -o $@
-test-rules: tests/rules_test.c tests/dns_test.c pb_rules.c pb_rules.h pb_dns.c pb_dns.h | $(BUILD_DIR)
+test-rules: tests/rules_test.c tests/dns_test.c tests/proc_test.c pb_rules.c pb_rules.h pb_dns.c pb_dns.h pb_proc.c pb_proc.h | $(BUILD_DIR)
$(CC) -Wall -Wextra -g -fsanitize=address,undefined -D_GNU_SOURCE tests/rules_test.c pb_rules.c -o $(BUILD_DIR)/rules_test && $(BUILD_DIR)/rules_test
$(CC) -Wall -Wextra -g -fsanitize=address,undefined -D_GNU_SOURCE tests/dns_test.c pb_dns.c -o $(BUILD_DIR)/dns_test && $(BUILD_DIR)/dns_test
+ $(CC) -Wall -Wextra -g -fsanitize=address,undefined -D_GNU_SOURCE tests/proc_test.c pb_proc.c -o $(BUILD_DIR)/proc_test && $(BUILD_DIR)/proc_test
# Downloads, verifies and builds libbpf (cached); prints nothing. `make -s libbpf-path` prints the directory to use as LIBBPF_DIR.
libbpf-static: $(LIBBPF_CACHE)/lib/libbpf.a
diff --git a/Linux/src/ProxyBridge.c b/Linux/src/ProxyBridge.c
index aa5d1db..f36ede8 100644
--- a/Linux/src/ProxyBridge.c
+++ b/Linux/src/ProxyBridge.c
@@ -28,7 +28,7 @@ static struct {
struct pb_proxy proxies[MAX_PROXIES]; size_t nproxies;
uint32_t next_rule_id, next_proxy_id, default_proxy;
bool running;
- atomic_bool dns_via_proxy, traffic_logging, need_names, has_localhost;
+ atomic_bool dns_via_proxy, traffic_logging, need_names, has_localhost, paused, log_every;
pthread_t maint;
bool maint_started, maint_stop, maint_kick;
pthread_mutex_t maint_mu;
@@ -81,7 +81,58 @@ static bool exe_path_of_pid(uint32_t pid, char *out, size_t n)
return true;
}
-static void emit_connection(uint32_t pid, const char *comm, int family, const uint8_t addr[16], uint16_t port, int action, uint32_t proxy_id)
+// Connection log history: bounded, so a busy host cannot grow it. Entries are replaced oldest-first within a short probe window.
+#define SEEN_SLOTS 8192
+#define SEEN_PROBES 8
+#define UDP_RELOG_MS 30000
+static struct seen_ent { uint64_t key; int64_t at; } *seen_tab;
+static pthread_mutex_t seen_mu = PTHREAD_MUTEX_INITIALIZER;
+
+static int64_t mono_ms(void)
+{
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+
+static uint64_t conn_key(const char *name, int family, const uint8_t addr[16], uint16_t port, int proto, int action, uint32_t proxy_id)
+{
+ uint64_t h = 1469598103934665603ULL;
+ for (const char *s = name; *s; s++) h = (h ^ (uint8_t)*s) * 1099511628211ULL;
+ const uint8_t extra[] = { (uint8_t)family, (uint8_t)(port >> 8), (uint8_t)port, (uint8_t)proto, (uint8_t)action, (uint8_t)proxy_id, (uint8_t)(proxy_id >> 8) };
+ for (size_t i = 0; i < sizeof extra; i++) h = (h ^ extra[i]) * 1099511628211ULL;
+ for (int i = 0; i < 16; i++) h = (h ^ addr[i]) * 1099511628211ULL;
+ return h ? h : 1;
+}
+
+// Should this connection appear in the log?
+static bool log_wanted(uint64_t key, bool udp)
+{
+ bool every = atomic_load(&G.log_every), want = true;
+ int64_t now = mono_ms();
+ pthread_mutex_lock(&seen_mu);
+ if (!seen_tab) seen_tab = calloc(SEEN_SLOTS, sizeof *seen_tab);
+ if (seen_tab) {
+ struct seen_ent *hit = NULL, *victim = NULL;
+ for (int i = 0; i < SEEN_PROBES && !hit; i++) {
+ struct seen_ent *e = &seen_tab[(key + (uint64_t)i) % SEEN_SLOTS];
+ if (e->key == key) hit = e;
+ else if (e->key == 0) { if (!victim || victim->key) victim = e; }
+ else if (!victim || (victim->key && e->at < victim->at)) victim = e;
+ }
+ if (hit) {
+ want = every && (!udp || now - hit->at >= UDP_RELOG_MS);
+ hit->at = now; // traffic keeps a UDP flow "alive"
+ } else if (victim) {
+ victim->key = key;
+ victim->at = now;
+ }
+ }
+ pthread_mutex_unlock(&seen_mu);
+ return want;
+}
+
+static void emit_connection(uint32_t pid, const char *comm, int family, const uint8_t addr[16], uint16_t port, int proto, int action, uint32_t proxy_id)
{
if (!atomic_load(&G.traffic_logging)) return;
char path[4096], dest[INET6_ADDRSTRLEN + 280], info[400];
@@ -90,6 +141,7 @@ static void emit_connection(uint32_t pid, const char *comm, int family, const ui
const char *base = strrchr(path, '/');
name = base ? base + 1 : path;
}
+ if (!log_wanted(conn_key(name, family, addr, port, proto, action, proxy_id), proto == IPPROTO_UDP)) return;
if (family == AF_INET) {
inet_ntop(AF_INET, addr + 12, dest, sizeof dest);
uint32_t ip = ((uint32_t)addr[12] << 24) | ((uint32_t)addr[13] << 16) | ((uint32_t)addr[14] << 8) | addr[15];
@@ -116,12 +168,14 @@ static void on_bpf_event(const struct pb_event *e)
char comm[17];
memcpy(comm, e->comm, 16);
comm[16] = 0;
- emit_connection(e->pid, comm, e->family, e->addr, e->port, e->action, e->proxy_id);
+ emit_connection(e->pid, comm, e->family, e->addr, e->port, e->proto, e->action, e->proxy_id);
}
+// The kernel already reported every flow it decided itself; the relay only reports the ones it decided.
void pb_core_flow_event(const struct pb_orig *o, int action)
{
- emit_connection(o->pid, NULL, o->family, o->addr, o->port, action, o->proxy_id);
+ if (o->action != PB_ACT_DECIDE) return;
+ emit_connection(o->pid, NULL, o->family, o->addr, o->port, o->proto, action, o->proxy_id);
}
static struct pb_proxy *find_proxy_locked(uint32_t id)
@@ -291,6 +345,7 @@ void pb_core_decide(const struct pb_orig *o, struct pb_decision *out)
out->action = PB_ACT_DIRECT;
out->proxy_id = 0;
+ if (atomic_load(&G.paused)) return;
pthread_rwlock_rdlock(&G.lock);
bool lo = atomic_load(&G.has_localhost) && is_loopback(o) && o->port != 53 &&
o->port != pb_relay_tcp_port() && o->port != pb_relay_udp_port();
@@ -359,6 +414,43 @@ static uint32_t resolve_proxy_ip(const char *host, struct host_cache *cache, siz
return cache[slot].ip_be;
}
+#define LOOP_CACHE 32
+static struct { uint32_t pid, proxy_id; int64_t until; bool hit; } loop_cache[LOOP_CACHE];
+static unsigned loop_next;
+static struct host_cache loop_hosts[4];
+static pthread_mutex_t loop_mu = PTHREAD_MUTEX_INITIALIZER;
+
+int pb_core_is_proxy_process(uint32_t pid, uint32_t proxy_id)
+{
+ int64_t now = mono_ms();
+ pthread_mutex_lock(&loop_mu);
+ for (int i = 0; i < LOOP_CACHE; i++)
+ if (loop_cache[i].pid == pid && loop_cache[i].proxy_id == proxy_id && loop_cache[i].until > now) {
+ int hit = loop_cache[i].hit;
+ pthread_mutex_unlock(&loop_mu);
+ return hit;
+ }
+ pthread_mutex_unlock(&loop_mu);
+
+ struct pb_proxy px;
+ bool hit = false;
+ if (pb_core_get_proxy(proxy_id, &px) == 0) {
+ pthread_mutex_lock(&loop_mu);
+ uint32_t ip = resolve_proxy_ip(px.host, loop_hosts, 4, time(NULL));
+ pthread_mutex_unlock(&loop_mu);
+ hit = ip && pb_proc_is_local_ip(ip) && pb_proc_pid_listens(pid, ip, px.port);
+ }
+ pthread_mutex_lock(&loop_mu);
+ unsigned slot = loop_next++ % LOOP_CACHE;
+ loop_cache[slot].pid = pid; loop_cache[slot].proxy_id = proxy_id; loop_cache[slot].hit = hit; loop_cache[slot].until = now + 3000;
+ pthread_mutex_unlock(&loop_mu);
+ if (hit) {
+ pb_core_log("process %u serves proxy '%s': its own connections are sent direct, not back through the proxy", pid, px.name);
+ maint_kick(); // exempt it in the kernel too, so later connections skip the relay
+ }
+ return hit;
+}
+
static void refresh_exempt(struct host_cache *cache, size_t ncache, uint32_t *last, size_t *nlast)
{
struct { char host[256]; uint16_t port; } targets[MAX_PROXIES];
@@ -694,7 +786,20 @@ void ProxyBridge_SetTrafficLoggingEnabled(bool enable)
pb_bpf_set_flags(enable, atomic_load(&G.dns_via_proxy));
}
-void ProxyBridge_ClearConnectionLogs(void) {}
+void ProxyBridge_ClearConnectionLogs(void)
+{
+ pthread_mutex_lock(&seen_mu);
+ if (seen_tab) memset(seen_tab, 0, SEEN_SLOTS * sizeof *seen_tab);
+ pthread_mutex_unlock(&seen_mu);
+}
+
+void ProxyBridge_SetLogEveryConnection(bool enable) { atomic_store(&G.log_every, enable); }
+
+void ProxyBridge_SetEnabled(bool enable)
+{
+ atomic_store(&G.paused, !enable);
+ pb_bpf_set_paused(!enable);
+}
static bool proxies_missing_locked(void)
{
@@ -737,6 +842,7 @@ bool ProxyBridge_Start(void)
pthread_mutex_unlock(&G.maint_mu);
G.maint_started = pthread_create(&G.maint, NULL, maint_loop, NULL) == 0;
+ pb_bpf_set_paused(atomic_load(&G.paused));
pthread_rwlock_wrlock(&G.lock);
sync_locked();
pthread_rwlock_unlock(&G.lock);
@@ -775,6 +881,51 @@ int ProxyBridge_TestProxy(uint32_t proxy_id, const char *host, uint16_t port, ch
return pb_relay_test_proxy(&p, host, port, buf, n);
}
+uint32_t ProxyBridge_GetFlows(ProxyBridgeFlow *out, uint32_t max)
+{
+ if (!out || !max) return 0;
+ if (max > PB_FLOWS_MAX) max = PB_FLOWS_MAX;
+ struct pb_flow_info *raw = calloc(max, sizeof *raw);
+ if (!raw) return 0;
+ int n = pb_relay_flows(raw, (int)max);
+ for (int i = 0; i < n; i++) {
+ const struct pb_flow_info *f = &raw[i];
+ ProxyBridgeFlow *o = &out[i];
+ memset(o, 0, sizeof *o);
+ o->id = f->id; o->pid = f->pid; o->proxy_id = f->proxy_id; o->age_ms = f->age_ms;
+ o->sent = f->sent; o->received = f->recv; o->port = f->port; o->is_udp = f->udp; o->is_ipv6 = f->family == AF_INET6;
+ memcpy(o->dest, f->addr, 16);
+ char path[4096];
+ if (exe_path_of_pid(f->pid, path, sizeof path)) {
+ const char *base = strrchr(path, '/');
+ snprintf(o->name, sizeof o->name, "%.*s", (int)sizeof o->name - 1, base ? base + 1 : path);
+ } else {
+ snprintf(o->name, sizeof o->name, "pid %u", f->pid);
+ }
+ if (f->family == AF_INET) {
+ uint32_t ip = ((uint32_t)f->addr[12] << 24) | ((uint32_t)f->addr[13] << 16) | ((uint32_t)f->addr[14] << 8) | f->addr[15];
+ char names[PB_DNS_MAX_NAMES][256];
+ int k = pb_dns_lookup(ip, names, PB_DNS_MAX_NAMES);
+ if (k > 0) snprintf(o->host, sizeof o->host, "%s", names[k - 1]);
+ else inet_ntop(AF_INET, f->addr + 12, o->host, sizeof o->host);
+ } else {
+ inet_ntop(AF_INET6, f->addr, o->host, sizeof o->host);
+ }
+ }
+ free(raw);
+ return (uint32_t)n;
+}
+
+int ProxyBridge_TestProxyEx(uint32_t proxy_id, const char *host, uint16_t port, ProxyTestLogCallback cb, void *user)
+{
+ struct pb_proxy p;
+ if (pb_core_get_proxy(proxy_id, &p) != 0) {
+ if (cb) cb("Result: FAILED - no proxy configured", user);
+ return -1;
+ }
+ return pb_relay_check_proxy(&p, host, port, cb, user);
+}
+
int ProxyBridge_TestConnection(const char *host, uint16_t port, char *buf, size_t n)
{
return ProxyBridge_TestProxy(0, host, port, buf, n);
diff --git a/Linux/src/ProxyBridge.h b/Linux/src/ProxyBridge.h
index ccb88b9..baf074f 100644
--- a/Linux/src/ProxyBridge.h
+++ b/Linux/src/ProxyBridge.h
@@ -80,12 +80,42 @@ PB_API bool ProxyBridge_SetProxyConfig(ProxyType type, const char* proxy_ip, uin
/* ---- Runtime --------------------------------------------------------------------------------------------------------- */
PB_API void ProxyBridge_SetDnsViaProxy(bool enable);
+/* Main switch (default true). False pauses every rule for new connections; existing connections are not touched. */
+PB_API void ProxyBridge_SetEnabled(bool enable);
+/* Connection log: by default a connection is reported once per (application, destination, port, protocol, action); true reports
+ * every new TCP connection and every new UDP flow (a UDP flow again after 30 s of silence). ClearConnectionLogs forgets the history. */
+PB_API void ProxyBridge_SetLogEveryConnection(bool enable);
PB_API void ProxyBridge_SetLogCallback(LogCallback callback);
PB_API void ProxyBridge_SetConnectionCallback(ConnectionCallback callback);
PB_API void ProxyBridge_SetTrafficLoggingEnabled(bool enable);
PB_API void ProxyBridge_ClearConnectionLogs(void);
PB_API bool ProxyBridge_Start(void); /* needs root (CAP_BPF/CAP_SYS_ADMIN) and a BTF kernel >= 5.11; returns false and logs why on failure */
PB_API bool ProxyBridge_Stop(void); /* keeps rules and proxies; Start() may be called again */
+/* Live connections: the TCP connections and UDP flows ProxyBridge is relaying through a proxy right now (direct and blocked traffic
+ * is not part of it). Newest first, at most PB_FLOWS_MAX; cheap enough to poll about once a second. UDP flows are refreshed once
+ * a second and stay listed for 30 s after their last datagram. Returns the number of entries written. */
+#define PB_FLOWS_MAX 400
+typedef struct {
+ uint64_t id; /* stable for the life of the flow */
+ uint32_t pid;
+ uint32_t proxy_id;
+ uint32_t age_ms; /* time since the flow started */
+ uint64_t sent; /* payload bytes application -> proxy */
+ uint64_t received; /* payload bytes proxy -> application */
+ uint16_t port; /* destination port */
+ uint8_t is_udp;
+ uint8_t is_ipv6;
+ uint8_t dest[16]; /* destination address (IPv4 as ::ffff:a.b.c.d) */
+ char name[40]; /* process name */
+ char host[64]; /* destination: the DNS name the application resolved if known, otherwise the address */
+} ProxyBridgeFlow;
+PB_API uint32_t ProxyBridge_GetFlows(ProxyBridgeFlow* out, uint32_t max);
+
+/* Multi-step check (reach the proxy, open a tunnel and log in, load a page, measure tunnel set-up, probe UDP). Streams human readable
+ * lines to the callback (called on the calling thread). Returns 0 when the proxy works, -1 when it cannot be reached, -2 when it
+ * refuses the tunnel or the login. Works without ProxyBridge_Start(). */
+typedef void (*ProxyTestLogCallback)(const char* line, void* user);
+PB_API int ProxyBridge_TestProxyEx(uint32_t proxy_id, const char* target_host, uint16_t target_port, ProxyTestLogCallback callback, void* user);
PB_API int ProxyBridge_TestConnection(const char* target_host, uint16_t target_port, char* result_buffer, size_t buffer_size);
PB_API int ProxyBridge_TestProxy(uint32_t proxy_id, const char* target_host, uint16_t target_port, char* result_buffer, size_t buffer_size);
diff --git a/Linux/src/bpf/pb_bpf_shared.h b/Linux/src/bpf/pb_bpf_shared.h
index 8b2432d..5d9d187 100644
--- a/Linux/src/bpf/pb_bpf_shared.h
+++ b/Linux/src/bpf/pb_bpf_shared.h
@@ -28,6 +28,7 @@ typedef uint8_t pb_u8; typedef uint16_t pb_u16; typedef uint32_t pb_u32; typedef
struct pb_cfg {
pb_u32 enabled; // at least one rule is loaded
+ pb_u32 paused; // main switch off: nothing is redirected
pb_u32 self_tgid; // the process hosting the relay is never redirected
pb_u32 log;
pb_u32 dns_via_proxy;
diff --git a/Linux/src/bpf/proxybridge.bpf.c b/Linux/src/bpf/proxybridge.bpf.c
index ea10862..8d225dc 100644
--- a/Linux/src/bpf/proxybridge.bpf.c
+++ b/Linux/src/bpf/proxybridge.bpf.c
@@ -121,7 +121,7 @@ static __always_inline int implicit_direct(const struct pb_orig *o)
// Sets o->proxy_id for ACT_PROXY.
static __always_inline int decide(struct pb_orig *o)
{
- if (!cfg.enabled || o->pid == cfg.self_tgid) return ACT_DIRECT;
+ if (!cfg.enabled || cfg.paused || o->pid == cfg.self_tgid) return ACT_DIRECT;
if (cfg.n_exempt && bpf_map_lookup_elem(&exempt, &o->pid)) return ACT_DIRECT;
int tap = o->port == 53 && cfg.dns_tap;
// Loopback joins the rule walk only when some rule asks for it; the resolver stub (port 53) and the relay itself never do.
diff --git a/Linux/src/pb_bpf.c b/Linux/src/pb_bpf.c
index 18268d6..a46801b 100644
--- a/Linux/src/pb_bpf.c
+++ b/Linux/src/pb_bpf.c
@@ -237,6 +237,13 @@ void pb_bpf_stop(void)
pthread_mutex_unlock(&G.lock);
}
+void pb_bpf_set_paused(bool paused)
+{
+ pthread_mutex_lock(&G.lock);
+ if (G.skel) G.skel->bss->cfg.paused = paused;
+ pthread_mutex_unlock(&G.lock);
+}
+
void pb_bpf_set_flags(bool log, bool dns_via_proxy)
{
pthread_mutex_lock(&G.lock);
diff --git a/Linux/src/pb_bpf.h b/Linux/src/pb_bpf.h
index 6bc582e..f1564b6 100644
--- a/Linux/src/pb_bpf.h
+++ b/Linux/src/pb_bpf.h
@@ -32,6 +32,7 @@ void pb_bpf_detach(void);
void pb_bpf_stop(void);
void pb_bpf_set_flags(bool log, bool dns_via_proxy);
+void pb_bpf_set_paused(bool paused);
// Recompiles the rule set and rescans /proc for running executables. -1 if it does not fit.
int pb_bpf_sync(const struct pb_rule_view *v, size_t n);
// Installs the class of the executable the kernel reported in `o` (slow-path learning); no-op for known binaries.
diff --git a/Linux/src/pb_internal.h b/Linux/src/pb_internal.h
index c060410..9c99d04 100644
--- a/Linux/src/pb_internal.h
+++ b/Linux/src/pb_internal.h
@@ -59,6 +59,10 @@ int pb_core_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out);
// Host name the application most recently resolved to the destination of `o` (IPv4, from the DNS tap); 0 if known.
int pb_core_name_for(const struct pb_orig *o, char *out, size_t n);
+// True when `pid` is the process serving this (local) proxy: its own connections must not be sent through itself. The periodic
+// exemption refresh normally covers this; the relay asks for connections made in the moment before it ran.
+int pb_core_is_proxy_process(uint32_t pid, uint32_t proxy_id);
+
// Full rule evaluation for a PB_ACT_DECIDE flow.
void pb_core_decide(const struct pb_orig *o, struct pb_decision *out);
@@ -95,4 +99,23 @@ uint16_t pb_relay_udp_port(void);
// Blocking test of a proxy: tunnels to target_host:target_port and writes a one-line result (or the error) to buf. 0 on success.
int pb_relay_test_proxy(const struct pb_proxy *proxy, const char *target_host, uint16_t target_port, char *buf, size_t buflen);
+
+// One live proxied flow as the relay knows it (TCP connection or UDP flow).
+struct pb_flow_info {
+ uint64_t id;
+ uint32_t pid;
+ uint16_t proxy_id, port;
+ uint8_t family, udp;
+ uint8_t addr[16];
+ uint32_t age_ms;
+ uint64_t sent, recv; // payload bytes application -> proxy / proxy -> application
+};
+// Fills out with up to max live proxied flows, newest first; returns the count. Safe from any thread.
+int pb_relay_flows(struct pb_flow_info *out, int max);
+
+// Multi-step proxy check for the GUI and CLI: streams human readable lines to cb. 0 = the proxy works (reachable, tunnel and login
+// accepted); -1 = cannot reach it; -2 = the tunnel or login was refused. Page load, latency and UDP findings are warnings only.
+typedef void (*pb_check_cb)(const char *line, void *user);
+int pb_relay_check_proxy(const struct pb_proxy *proxy, const char *target_host, uint16_t target_port, pb_check_cb cb, void *user);
+
#endif
diff --git a/Linux/src/pb_proc.c b/Linux/src/pb_proc.c
index 61b756e..c6a382d 100644
--- a/Linux/src/pb_proc.c
+++ b/Linux/src/pb_proc.c
@@ -15,9 +15,11 @@ static bool parse_number(const char *s, unsigned base, unsigned long long *out,
unsigned long long v = 0;
const char *p = s;
for (;; p++) {
- unsigned d = (unsigned)(*p - '0');
- if (*p >= 'a' && *p <= 'f') d = (unsigned)(*p - 'a') + 10;
+ unsigned d;
+ if (*p >= '0' && *p <= '9') d = (unsigned)(*p - '0');
+ else if (*p >= 'a' && *p <= 'f') d = (unsigned)(*p - 'a') + 10;
else if (*p >= 'A' && *p <= 'F') d = (unsigned)(*p - 'A') + 10;
+ else break;
if (d >= base) break;
v = v * base + d;
}
@@ -102,6 +104,17 @@ size_t pb_proc_listeners(uint32_t ip_be, uint16_t port, uint32_t *tgids, size_t
return n;
}
+bool pb_proc_pid_listens(uint32_t pid, uint32_t ip_be, uint16_t port)
+{
+ uint64_t inodes[MAX_INODES];
+ size_t ni = listen_inodes(ip_be, port, inodes);
+ char name[24];
+ snprintf(name, sizeof name, "%u", pid);
+ for (size_t i = 0; i < ni; i++)
+ if (pid_has_socket(name, inodes[i])) return true;
+ return false;
+}
+
bool pb_proc_is_local_ip(uint32_t ip_be)
{
if ((ntohl(ip_be) >> 24) == 127) return true;
diff --git a/Linux/src/pb_proc.h b/Linux/src/pb_proc.h
index c5e4986..a7c3fc1 100644
--- a/Linux/src/pb_proc.h
+++ b/Linux/src/pb_proc.h
@@ -9,6 +9,9 @@
// tgids of processes with a TCP socket in LISTEN state on `port` bound to `ip_be` or to 0.0.0.0. Returns the count (<= max).
size_t pb_proc_listeners(uint32_t ip_be, uint16_t port, uint32_t *tgids, size_t max);
+// True if the process `pid` (a tgid) holds a LISTEN socket on `port` bound to `ip_be` or to 0.0.0.0. Looks at that one process only.
+bool pb_proc_pid_listens(uint32_t pid, uint32_t ip_be, uint16_t port);
+
// True for 127.0.0.0/8 and for any IPv4 address configured on a local interface.
bool pb_proc_is_local_ip(uint32_t ip_be);
diff --git a/Linux/src/pb_relay.c b/Linux/src/pb_relay.c
index 3e2409f..cd51797 100644
--- a/Linux/src/pb_relay.c
+++ b/Linux/src/pb_relay.c
@@ -27,7 +27,10 @@
#define SCRATCH_SZ 65536
#define HDR_MAX 8192
-#define NWORKERS 16
+#define WORKERS_MIN 8 // handshake workers: a few always, more while handshakes pile up, extras leave after a pause
+#define WORKERS_MAX 64
+#define WORKER_IDLE_S 20
+#define UPSTREAM_CAP 48 // handshakes in flight per upstream, so a dead proxy cannot take every worker
#define MAX_DATA 8
#define PIPE_SZ (1 << 20)
#define JOBQ_MAX 4096 // handshake queue; excess accepts are shed with a log
@@ -39,6 +42,8 @@
#define UDP_BATCH 16
#define FLOW_TTL_MS 1000
#define DC_SIZE 1024
+#define UFLOWS_MAX 200
+#define UDP_LIVE_MS 30000
#define SESS_BUCKETS 256
#define DIRECT_ID 0xFFFFFFFFu
@@ -526,6 +531,12 @@ struct conn {
uint32_t mask[2];
bool eof[2], shut[2], dead;
int64_t last;
+ // what GetFlows reports
+ uint64_t id, bytes[2];
+ int64_t t0;
+ uint32_t pid;
+ uint16_t port, proxy_id;
+ uint8_t family, addr[16];
};
static void conn_bufs_free(struct conn *c)
@@ -553,6 +564,7 @@ struct sess;
struct job {
struct job *next;
int kind;
+ unsigned key; // upstream the handshake talks to (0 = not known before the decision)
int fd;
struct pb_orig o;
struct sess *s;
@@ -594,8 +606,8 @@ struct dce {
uint32_t flow_be, pid;
struct pb_orig o;
int action, fidx;
- int64_t looked, last;
- uint64_t sid;
+ int64_t looked, last, t0;
+ uint64_t sid, id, sent, recv;
};
static struct {
@@ -606,10 +618,13 @@ static struct {
atomic_bool stopping;
atomic_int nconn;
atomic_uint rr;
+ atomic_ullong flow_id;
uint16_t tcp_port, udp_port;
pthread_t acceptor; bool acc_started;
- pthread_t workers[NWORKERS]; int nworkers;
+ int nworkers, nidle;
+ int busy[256]; // handshakes in flight per upstream key
+ pthread_cond_t wdone;
struct dthread data[MAX_DATA];
int ndata;
pthread_t udpth; bool udp_started;
@@ -627,6 +642,8 @@ static struct {
int nsess;
struct sess *sgrave;
struct dce *dc;
+ pthread_mutex_t fmu; // guards uflows, the UDP side of GetFlows (published by the UDP thread once a second)
+ struct pb_flow_info uflows[UFLOWS_MAX]; int nuflows;
uint8_t *rxbuf;
int64_t drop_count, drop_logged;
uint64_t next_sid;
@@ -634,20 +651,37 @@ static struct {
struct iovec *mmiov;
struct sockaddr_in *mmname;
char (*mmctl)[CMSG_SPACE(sizeof(struct in_pktinfo))];
-} R = { .life = PTHREAD_MUTEX_INITIALIZER, .jmu = PTHREAD_MUTEX_INITIALIZER, .jcv = PTHREAD_COND_INITIALIZER,
- .dmu = PTHREAD_MUTEX_INITIALIZER, .lfd = -1, .ufd = -1, .stopfd = -1, .tmfd = -1, .uep = -1, .uwake = -1 };
+} R = { .life = PTHREAD_MUTEX_INITIALIZER, .jmu = PTHREAD_MUTEX_INITIALIZER, .jcv = PTHREAD_COND_INITIALIZER, .wdone = PTHREAD_COND_INITIALIZER,
+ .dmu = PTHREAD_MUTEX_INITIALIZER, .fmu = PTHREAD_MUTEX_INITIALIZER, .lfd = -1, .ufd = -1, .stopfd = -1, .tmfd = -1, .uep = -1, .uwake = -1 };
static void proxy_desc(const struct pb_proxy *p, char *out, size_t n)
{
snprintf(out, n, "%s %s:%u", p->type == PROXY_TYPE_SOCKS5 ? "SOCKS5" : "HTTP", p->host, p->port);
}
+static void *worker_main(void *arg);
+
+// Caller holds R.jmu.
+static void worker_spawn_locked(void)
+{
+ pthread_attr_t at;
+ pthread_t th;
+ pthread_attr_init(&at);
+ pthread_attr_setstacksize(&at, 512 * 1024);
+ pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
+ R.nworkers++;
+ if (pthread_create(&th, &at, worker_main, NULL) != 0) R.nworkers--;
+ pthread_attr_destroy(&at);
+}
+
static int job_push(int kind, int fd, const struct pb_orig *o, struct sess *s)
{
struct job *j = calloc(1, sizeof *j);
if (!j) return -1;
j->kind = kind; j->fd = fd; j->s = s;
if (o) j->o = *o;
+ if (kind == J_TCP && o && o->action == PB_ACT_PROXY) j->key = 1 + o->proxy_id % 255u;
+ else if (kind != J_TCP && s) j->key = 1 + s->proxy.id % 255u;
pthread_mutex_lock(&R.jmu);
if (R.jcount >= JOBQ_MAX || atomic_load(&R.stopping)) {
pthread_mutex_unlock(&R.jmu);
@@ -657,17 +691,22 @@ static int job_push(int kind, int fd, const struct pb_orig *o, struct sess *s)
if (R.jtail) R.jtail->next = j; else R.jhead = j;
R.jtail = j;
R.jcount++;
+ if (R.jcount > R.nidle && R.nworkers < WORKERS_MAX && R.busy[j->key] < UPSTREAM_CAP) worker_spawn_locked();
pthread_cond_signal(&R.jcv);
pthread_mutex_unlock(&R.jmu);
return 0;
}
-static void conn_handoff(int cfd, int ufd, const uint8_t *left, size_t leftn, bool dns)
+static void conn_handoff(int cfd, int ufd, const uint8_t *left, size_t leftn, bool dns, const struct pb_orig *o, uint32_t proxy_id)
{
struct conn *c = calloc(1, sizeof *c);
if (!c) { close(cfd); close(ufd); atomic_fetch_sub(&R.nconn, 1); return; }
c->fd[0] = cfd; c->fd[1] = ufd;
c->dns = dns;
+ c->id = atomic_fetch_add(&R.flow_id, 1) + 1;
+ c->t0 = now_ms();
+ c->pid = o->pid; c->port = o->port; c->proxy_id = (uint16_t)proxy_id; c->family = o->family;
+ memcpy(c->addr, o->addr, 16);
if (leftn) {
uint8_t *m = malloc(leftn);
if (!m) { close(cfd); close(ufd); free(c); atomic_fetch_sub(&R.nconn, 1); return; }
@@ -712,6 +751,7 @@ static void tcp_job_run(struct job *j)
pb_core_decide(o, &d);
action = d.action; pid = d.proxy_id;
}
+ if (action == PB_ACT_PROXY && pb_core_is_proxy_process(o->pid, pid)) action = PB_ACT_DIRECT; // a local proxy must not loop through itself
if (action == PB_ACT_DIRECT) {
pb_core_flow_event(o, PB_ACT_DIRECT);
struct sockaddr_storage ss;
@@ -765,7 +805,7 @@ static void tcp_job_run(struct job *j)
atomic_fetch_sub(&R.nconn, 1);
return;
}
- conn_handoff(cfd, up, left, leftn, o->port == 53);
+ conn_handoff(cfd, up, left, leftn, o->port == 53, o, action == PB_ACT_PROXY ? pid : 0);
}
static void udp_job_run(struct sess *s)
@@ -823,18 +863,37 @@ out:
static void *worker_main(void *arg)
{
(void)arg;
- for (;;) {
- pthread_mutex_lock(&R.jmu);
- while (!R.jhead && !atomic_load(&R.stopping)) pthread_cond_wait(&R.jcv, &R.jmu);
- if (atomic_load(&R.stopping)) { pthread_mutex_unlock(&R.jmu); return NULL; }
- struct job *j = R.jhead;
- R.jhead = j->next;
- if (!R.jhead) R.jtail = NULL;
- R.jcount--;
- pthread_mutex_unlock(&R.jmu);
- if (j->kind == J_TCP) tcp_job_run(j); else udp_job_run(j->s);
- free(j);
- }
+ pthread_mutex_lock(&R.jmu);
+ while (!atomic_load(&R.stopping)) {
+ struct job *prev = NULL, *j;
+ for (j = R.jhead; j; prev = j, j = j->next)
+ if (R.busy[j->key] < UPSTREAM_CAP) break;
+ if (j) {
+ if (prev) prev->next = j->next; else R.jhead = j->next;
+ if (R.jtail == j) R.jtail = prev;
+ R.jcount--;
+ unsigned key = j->key;
+ R.busy[key]++;
+ pthread_mutex_unlock(&R.jmu);
+ if (j->kind == J_TCP) tcp_job_run(j); else udp_job_run(j->s);
+ free(j);
+ pthread_mutex_lock(&R.jmu);
+ R.busy[key]--;
+ pthread_cond_signal(&R.jcv); // a job held back by this upstream's cap may be able to run now
+ continue;
+ }
+ struct timespec ts;
+ clock_gettime(CLOCK_REALTIME, &ts);
+ ts.tv_sec += WORKER_IDLE_S;
+ R.nidle++;
+ int rc = pthread_cond_timedwait(&R.jcv, &R.jmu, &ts);
+ R.nidle--;
+ if (rc == ETIMEDOUT && !R.jhead && R.nworkers > WORKERS_MIN) break;
+ }
+ R.nworkers--;
+ pthread_cond_broadcast(&R.wdone);
+ pthread_mutex_unlock(&R.jmu);
+ return NULL;
}
static void *acceptor_main(void *arg)
@@ -921,6 +980,7 @@ static int pump_splice(struct dthread *t, struct conn *c, int d)
if (errno != EAGAIN && errno != EINTR) { pipe_discard(t->pfd[0]); return -1; }
w = 0;
}
+ c->bytes[d] += (uint64_t)n;
if (w < n && spill_from_pipe(c, d, t->pfd[0], (size_t)(n - w)) != 0) return -1;
return 1;
}
@@ -932,6 +992,7 @@ static int dns_pump_up(struct conn *c, uint8_t *scratch)
ssize_t n = recv(c->fd[1], scratch, SCRATCH_SZ, 0);
if (n < 0 && errno != EAGAIN && errno != EINTR) return -1;
if (n > 0) {
+ c->bytes[1] += (uint64_t)n;
if (c->dhave + (size_t)n > c->dcap) {
size_t nc = c->dhave + (size_t)n;
uint8_t *nb = realloc(c->dbuf, nc);
@@ -1001,6 +1062,7 @@ static int conn_pump(struct dthread *t, struct conn *c)
ssize_t n = recv(c->fd[d], scratch, SCRATCH_SZ, 0);
if (n > 0) {
progress = true;
+ c->bytes[d] += (uint64_t)n;
ssize_t w = send(c->fd[o], scratch, (size_t)n, MSG_NOSIGNAL);
if (w < 0) {
if (errno != EAGAIN && errno != EINTR) return -1;
@@ -1061,8 +1123,10 @@ static void conn_close(struct dthread *t, struct conn *c)
close(c->fd[1]);
c->dead = true;
conn_bufs_free(c);
+ pthread_mutex_lock(&t->mu); // GetFlows walks this list from another thread
if (c->prev) c->prev->next = c->next; else t->conns = c->next;
if (c->next) c->next->prev = c->prev;
+ pthread_mutex_unlock(&t->mu);
c->next = t->grave;
c->prev = NULL;
t->grave = c;
@@ -1085,9 +1149,11 @@ static void dthread_adopt(struct dthread *t)
pthread_mutex_unlock(&t->mu);
while (c) {
struct conn *n = c->next;
+ pthread_mutex_lock(&t->mu);
c->next = t->conns; c->prev = NULL;
if (t->conns) t->conns->prev = c;
t->conns = c;
+ pthread_mutex_unlock(&t->mu);
c->last = now_ms();
if (c->len[1] || c->dhave) conn_service(t, c);
else if (conn_update(t, c) != 0) conn_close(t, c);
@@ -1211,8 +1277,16 @@ static struct sess *sess_new(const struct sockaddr_in *cli, uint32_t id, uint32_
return s;
}
+static struct dce *dce_slot(const struct sockaddr_in *cli, uint32_t flow_be)
+{
+ uint32_t hv = (cli->sin_addr.s_addr * 2654435761u) ^ (cli->sin_port * 40503u) ^ (flow_be * 2246822519u);
+ return &R.dc[hv % DC_SIZE];
+}
+
static void udp_reply(const struct sockaddr_in *cli, uint32_t flow_be, const uint8_t *data, size_t n)
{
+ struct dce *de = dce_slot(cli, flow_be);
+ if (de->used && de->cli.sin_addr.s_addr == cli->sin_addr.s_addr && de->cli.sin_port == cli->sin_port && de->flow_be == flow_be) de->recv += n;
struct iovec iov = { (void *)data, n };
union { char b[CMSG_SPACE(sizeof(struct in_pktinfo))]; struct cmsghdr a; } cb;
memset(&cb, 0, sizeof cb);
@@ -1266,8 +1340,7 @@ static size_t socks5_header(uint8_t *h, const struct pb_orig *o)
static void udp_dgram(const struct sockaddr_in *cli, uint32_t flow_be, const uint8_t *pl, size_t n, int64_t now)
{
- uint32_t hv = (cli->sin_addr.s_addr * 2654435761u) ^ (cli->sin_port * 40503u) ^ (flow_be * 2246822519u);
- struct dce *e = &R.dc[hv % DC_SIZE];
+ struct dce *e = dce_slot(cli, flow_be);
bool same = e->used && e->cli.sin_addr.s_addr == cli->sin_addr.s_addr && e->cli.sin_port == cli->sin_port && e->flow_be == flow_be;
if (!same || now - e->looked >= FLOW_TTL_MS) {
struct pb_orig o;
@@ -1289,6 +1362,7 @@ static void udp_dgram(const struct sockaddr_in *cli, uint32_t flow_be, const uin
act = PB_ACT_BLOCK;
} else {
pid = px.id;
+ if (pb_core_is_proxy_process(o.pid, pid)) act = PB_ACT_DIRECT;
}
} else if (act != PB_ACT_DIRECT) {
act = PB_ACT_BLOCK;
@@ -1297,6 +1371,8 @@ static void udp_dgram(const struct sockaddr_in *cli, uint32_t flow_be, const uin
e->action = act;
e->pid = pid;
e->sid = 0;
+ e->t0 = now; e->sent = e->recv = 0;
+ e->id = atomic_fetch_add(&R.flow_id, 1) + 1;
}
e->used = true;
e->cli = *cli;
@@ -1305,6 +1381,7 @@ static void udp_dgram(const struct sockaddr_in *cli, uint32_t flow_be, const uin
e->looked = now;
}
e->last = now;
+ e->sent += n;
if (e->action == PB_ACT_BLOCK) return;
const struct pb_orig *o = &e->o;
@@ -1503,6 +1580,24 @@ static void udp_ctl_event(struct sess *s)
sess_destroy(s);
}
+// The UDP thread owns the flow table; GetFlows reads this copy, refreshed once a second.
+static void udp_publish_flows(void)
+{
+ int64_t now = now_ms();
+ pthread_mutex_lock(&R.fmu);
+ int n = 0;
+ for (int i = 0; i < DC_SIZE && n < UFLOWS_MAX; i++) {
+ const struct dce *e = &R.dc[i];
+ if (!e->used || e->action != PB_ACT_PROXY || now - e->last > UDP_LIVE_MS) continue;
+ struct pb_flow_info *f = &R.uflows[n++];
+ f->id = e->id; f->pid = e->o.pid; f->proxy_id = (uint16_t)e->pid; f->port = e->o.port;
+ f->family = e->o.family; f->udp = 1; memcpy(f->addr, e->o.addr, 16);
+ f->age_ms = (uint32_t)(now - e->t0); f->sent = e->sent; f->recv = e->recv;
+ }
+ R.nuflows = n;
+ pthread_mutex_unlock(&R.fmu);
+}
+
static void udp_sweep(void)
{
int64_t now = now_ms(), lim = (int64_t)R.cfg.udp_idle_timeout_s * 1000;
@@ -1525,7 +1620,7 @@ static void *udp_main(void *arg)
if (p == &TAG_STOP) return NULL;
if (p == &TAG_UDP) udp_recv_client();
else if (p == &TAG_WAKE) { eventfd_t v; eventfd_read(R.uwake, &v); udp_setup_done(); }
- else if (p == &TAG_TIMER) { uint64_t v; if (read(R.tmfd, &v, sizeof v) > 0) udp_sweep(); }
+ else if (p == &TAG_TIMER) { uint64_t v; if (read(R.tmfd, &v, sizeof v) > 0) { udp_sweep(); udp_publish_flows(); } }
else {
struct ref *r = p;
struct sess *s = r->s;
@@ -1541,16 +1636,20 @@ static void *udp_main(void *arg)
static void teardown(void)
{
atomic_store(&R.stopping, true);
+ pthread_mutex_lock(&R.fmu);
+ R.nuflows = 0;
+ pthread_mutex_unlock(&R.fmu);
if (R.stopfd >= 0) eventfd_write(R.stopfd, 1);
pthread_mutex_lock(&R.jmu);
pthread_cond_broadcast(&R.jcv);
pthread_mutex_unlock(&R.jmu);
if (R.acc_started) pthread_join(R.acceptor, NULL);
- for (int i = 0; i < R.nworkers; i++) pthread_join(R.workers[i], NULL);
+ pthread_mutex_lock(&R.jmu);
+ while (R.nworkers > 0) pthread_cond_wait(&R.wdone, &R.jmu);
+ pthread_mutex_unlock(&R.jmu);
for (int i = 0; i < R.ndata; i++) if (R.data[i].started) pthread_join(R.data[i].th, NULL);
if (R.udp_started) pthread_join(R.udpth, NULL);
R.acc_started = R.udp_started = false;
- R.nworkers = 0;
while (R.jhead) {
struct job *j = R.jhead;
@@ -1684,10 +1783,11 @@ int pb_relay_start(const struct pb_relay_cfg *cfg)
ok = pthread_create(&R.data[i].th, &at, data_main, &R.data[i]) == 0;
R.data[i].started = ok;
}
- for (int i = 0; i < NWORKERS && ok; i++) {
- ok = pthread_create(&R.workers[i], &at, worker_main, NULL) == 0;
- if (ok) R.nworkers++;
- }
+ pthread_mutex_lock(&R.jmu);
+ memset(R.busy, 0, sizeof R.busy);
+ for (int i = 0; i < WORKERS_MIN; i++) worker_spawn_locked();
+ ok = R.nworkers == WORKERS_MIN;
+ pthread_mutex_unlock(&R.jmu);
if (ok) { ok = pthread_create(&R.udpth, &at, udp_main, NULL) == 0; R.udp_started = ok; }
if (ok) { ok = pthread_create(&R.acceptor, &at, acceptor_main, NULL) == 0; R.acc_started = ok; }
pthread_attr_destroy(&at);
@@ -1765,3 +1865,195 @@ int pb_relay_test_proxy(const struct pb_proxy *proxy, const char *host, uint16_t
snprintf(buf, buflen, "%s", resp);
return 0;
}
+
+// ---- detailed proxy check -----------------------------------------------------------------------------------------------------
+
+static void chk(pb_check_cb cb, void *user, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
+static void chk(pb_check_cb cb, void *user, const char *fmt, ...)
+{
+ if (!cb) return;
+ char line[512];
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(line, sizeof line, fmt, ap);
+ va_end(ap);
+ cb(line, user);
+}
+
+static void s5dst_from_host(struct s5dst *d, const char *host, uint16_t port)
+{
+ memset(d, 0, sizeof *d);
+ d->port = port;
+ struct in_addr a4; struct in6_addr a6;
+ if (inet_pton(AF_INET, host, &a4) == 1) { d->atyp = 1; memcpy(d->addr, &a4, 4); }
+ else if (inet_pton(AF_INET6, host, &a6) == 1) { d->atyp = 4; memcpy(d->addr, &a6, 16); }
+ else { d->atyp = 3; snprintf(d->host, sizeof d->host, "%s", host); }
+}
+
+// Connects to the proxy and opens a tunnel to host:port. Returns the socket or -1 with the reason in err; *ms is the setup time.
+static int check_open_tunnel(const struct pb_proxy *proxy, const char *host, uint16_t port, uint8_t *left, size_t *leftn,
+ char *err, size_t errn, int *stage, int64_t *ms)
+{
+ int64_t t0 = now_ms(), dl = t0 + 10000;
+ char cerr[200];
+ *stage = 1;
+ int fd = connect_host(proxy->host, proxy->port, dl, -1, cerr, sizeof cerr);
+ if (fd < 0) { snprintf(err, errn, "%s", cerr); return -1; }
+ *stage = 2;
+ struct io x = { .fd = fd, .dl = dl, .stopfd = -1 };
+ int rc;
+ *leftn = 0;
+ if (proxy->type == PROXY_TYPE_SOCKS5) {
+ struct s5dst d;
+ s5dst_from_host(&d, host, port);
+ rc = socks5_request(&x, proxy, 1, &d, NULL);
+ } else {
+ rc = http_connect(&x, proxy, host, port, left, leftn);
+ }
+ if (rc) { snprintf(err, errn, "%s", x.err); close(fd); return -1; }
+ *ms = now_ms() - t0;
+ return fd;
+}
+
+int pb_relay_check_proxy(const struct pb_proxy *proxy, const char *host, uint16_t port, pb_check_cb cb, void *user)
+{
+ char desc[300], err[256] = "";
+ proxy_desc(proxy, desc, sizeof desc);
+ chk(cb, user, "Proxy: %s (%s)%s", proxy->name, desc, proxy->user[0] ? ", with credentials" : ", no credentials");
+ chk(cb, user, "Target: %s:%u", host, port);
+
+ chk(cb, user, "[1/5] Connecting to the proxy ...");
+ int64_t t0 = now_ms();
+ char cerr[200];
+ int probe = connect_host(proxy->host, proxy->port, t0 + 10000, -1, cerr, sizeof cerr);
+ if (probe < 0) {
+ chk(cb, user, " FAILED: %s", cerr);
+ chk(cb, user, "Result: FAILED - the proxy cannot be reached");
+ return -1;
+ }
+ struct sockaddr_storage ss;
+ socklen_t sl = sizeof ss;
+ char peer[INET6_ADDRSTRLEN] = "?";
+ if (getpeername(probe, (struct sockaddr *)&ss, &sl) == 0)
+ inet_ntop(ss.ss_family, ss.ss_family == AF_INET ? (void *)&((struct sockaddr_in *)&ss)->sin_addr : (void *)&((struct sockaddr_in6 *)&ss)->sin6_addr, peer, sizeof peer);
+ close(probe);
+ chk(cb, user, " OK: connected to %s in %lld ms", peer, (long long)(now_ms() - t0));
+
+ chk(cb, user, "[2/5] Opening a tunnel to the target ...");
+ uint8_t left[HDR_MAX];
+ size_t leftn = 0;
+ int stage = 0;
+ int64_t ms = 0;
+ int fd = check_open_tunnel(proxy, host, port, left, &leftn, err, sizeof err, &stage, &ms);
+ if (fd < 0) {
+ chk(cb, user, " FAILED: %s", err);
+ chk(cb, user, "Result: FAILED - the proxy refused the tunnel or the login");
+ return -2;
+ }
+ chk(cb, user, " OK: %s tunnel established in %lld ms%s", proxy->type == PROXY_TYPE_SOCKS5 ? "SOCKS5" : "HTTP CONNECT", (long long)ms,
+ proxy->user[0] ? " (login accepted)" : "");
+
+ chk(cb, user, "[3/5] Loading a page through the tunnel ...");
+ if (port != 80) {
+ chk(cb, user, " skipped: only port 80 is probed with a plain HTTP request");
+ } else {
+ struct io x = { .fd = fd, .dl = now_ms() + 8000, .stopfd = -1 };
+ char req[600];
+ int n = snprintf(req, sizeof req, "HEAD / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\nUser-Agent: ProxyBridge-check\r\n\r\n", host);
+ char resp[1024];
+ size_t got = leftn < sizeof resp - 1 ? leftn : sizeof resp - 1;
+ memcpy(resp, left, got);
+ int64_t t1 = now_ms();
+ if (io_send(&x, req, (size_t)n) == 0) {
+ while (!memchr(resp, '\n', got) && got < sizeof resp - 1) {
+ ssize_t r = io_recv(&x, resp + got, sizeof resp - 1 - got);
+ if (r < 0) break;
+ got += (size_t)r;
+ }
+ }
+ resp[got] = 0;
+ char *nl = strpbrk(resp, "\r\n");
+ if (nl) *nl = 0;
+ if (resp[0]) chk(cb, user, " OK: %.120s (first byte after %lld ms)", resp, (long long)(now_ms() - t1));
+ else chk(cb, user, " WARNING: no HTTP answer through the tunnel (%s)", x.err[0] ? x.err : "empty reply");
+ }
+ close(fd);
+
+ chk(cb, user, "[4/5] Measuring tunnel set-up time (3 tunnels) ...");
+ int64_t lo = INT64_MAX, hi = 0, sum = 0;
+ int okn = 0;
+ for (int i = 0; i < 3; i++) {
+ int fd2 = check_open_tunnel(proxy, host, port, left, &leftn, err, sizeof err, &stage, &ms);
+ if (fd2 < 0) continue;
+ close(fd2);
+ okn++; sum += ms;
+ if (ms < lo) lo = ms;
+ if (ms > hi) hi = ms;
+ }
+ if (okn == 3) chk(cb, user, " OK: min/avg/max = %lld/%lld/%lld ms", (long long)lo, (long long)(sum / 3), (long long)hi);
+ else if (okn > 0) chk(cb, user, " WARNING: only %d of 3 tunnels opened (min/avg/max = %lld/%lld/%lld ms)", okn, (long long)lo, (long long)(sum / okn), (long long)hi);
+ else chk(cb, user, " WARNING: none of the repeat tunnels opened: %s", err);
+
+ chk(cb, user, "[5/5] UDP support ...");
+ if (proxy->type != PROXY_TYPE_SOCKS5) {
+ chk(cb, user, " HTTP proxies cannot carry UDP: rules that send UDP here go direct");
+ } else {
+ int64_t dl = now_ms() + 8000;
+ int cfd = connect_host(proxy->host, proxy->port, dl, -1, cerr, sizeof cerr);
+ if (cfd < 0) {
+ chk(cb, user, " WARNING: %s", cerr);
+ } else {
+ struct io x = { .fd = cfd, .dl = dl, .stopfd = -1 };
+ struct s5dst d;
+ struct s5bnd b;
+ memset(&d, 0, sizeof d);
+ d.atyp = 1;
+ if (socks5_request(&x, proxy, 3, &d, &b) == 0) {
+ char a[INET6_ADDRSTRLEN] = "?";
+ if (b.atyp == 1) inet_ntop(AF_INET, b.addr, a, sizeof a);
+ else if (b.atyp == 4) inet_ntop(AF_INET6, b.addr, a, sizeof a);
+ else snprintf(a, sizeof a, "(host name)");
+ chk(cb, user, " OK: UDP ASSOCIATE accepted, the proxy relays UDP at %s:%u", a, b.port);
+ } else {
+ chk(cb, user, " WARNING: UDP ASSOCIATE refused: %s (UDP rules for this proxy will not work)", x.err);
+ }
+ close(cfd);
+ }
+ }
+ chk(cb, user, "Result: PASSED");
+ return 0;
+}
+
+// ---- live flows ---------------------------------------------------------------------------------------------------------------
+
+static int flow_newest_first(const void *a, const void *b)
+{
+ const struct pb_flow_info *x = a, *y = b;
+ return x->age_ms < y->age_ms ? -1 : x->age_ms > y->age_ms;
+}
+
+int pb_relay_flows(struct pb_flow_info *out, int max)
+{
+ int n = 0;
+ if (!out || max <= 0 || !R.running || atomic_load(&R.stopping)) return 0;
+ int64_t now = now_ms();
+ for (int i = 0; i < R.ndata && n < max; i++) {
+ struct dthread *t = &R.data[i];
+ pthread_mutex_lock(&t->mu);
+ for (struct conn *c = t->conns; c && n < max; c = c->next) {
+ if (!c->proxy_id) continue; // direct flows are not the engine's business
+ struct pb_flow_info *f = &out[n++];
+ f->id = c->id; f->pid = c->pid; f->proxy_id = c->proxy_id; f->port = c->port; f->family = c->family; f->udp = 0;
+ memcpy(f->addr, c->addr, 16);
+ f->age_ms = (uint32_t)(now - c->t0);
+ f->sent = __atomic_load_n(&c->bytes[0], __ATOMIC_RELAXED);
+ f->recv = __atomic_load_n(&c->bytes[1], __ATOMIC_RELAXED);
+ }
+ pthread_mutex_unlock(&t->mu);
+ }
+ pthread_mutex_lock(&R.fmu);
+ for (int i = 0; i < R.nuflows && n < max; i++) out[n++] = R.uflows[i];
+ pthread_mutex_unlock(&R.fmu);
+ qsort(out, (size_t)n, sizeof *out, flow_newest_first);
+ return n;
+}