Skip to content

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

test(linux): fault, UDP, differential rule, lifecycle, exemption, logging, checker, CLI and GUI automation tests; coverage tooling

anof-cybere33b1e867f88
diff --git a/Linux/README.md b/Linux/README.md
index b785863..0744687 100644
--- a/Linux/README.md
+++ b/Linux/README.md
@@ -89,7 +89,7 @@ sudo ProxyBridgeGUI
The GTK3-based GUI provides:
- Proxy configuration (SOCKS5/HTTP with authentication)
- Visual rule management with process selection
-- Real-time connection monitoring
+- Real-time connection monitoring, a **Live Connections** tab (every proxied TCP connection and UDP flow with its process, destination, proxy, age and bytes), and *Log Every Connection* / *Enable ProxyBridge* switches in the Proxy menu
- Profiles: create, switch, duplicate, rename, delete, **import and export** `.pbprofile` files (the Windows/macOS format, see [Profiles](#profiles))
- Import/Export rules (JSON format compatible with Windows/macOS)
- DNS via Proxy toggle
@@ -203,6 +203,13 @@ OPTIONS:
combined with --proxy and --rule. Disabled rules are skipped.
--list-profiles List the profiles saved by the GUI and exit
+ --test-proxy <host[:port]> Check every configured proxy against that target (reach it, open a tunnel and log in,
+ load a page, time tunnels, probe UDP), print the steps and exit 0 only if all work.
+ Needs no root. Example: --proxy socks5://127.0.0.1:1080 --test-proxy example.com:80
+
+ --log-every-connection <bool> Show every new connection in the connection log (--verbose 2/3) instead of one
+ line per application, destination and action (default false; a profile can set it)
+
--dns-via-proxy <bool> Route DNS queries through the proxy (true/false/1/0, default true)
--verbose <level> 0 none (default), 1 logs, 2 connections, 3 both
@@ -308,7 +315,7 @@ sudo ProxyBridge --profile work --rule "curl:*:*:TCP:DIRECT" # profile first,
- Rules point at proxies by `ProxyConfigId`; `0` means the default proxy (`DefaultProxyId`, otherwise the first proxy). A rule that names a proxy that is not in the file makes the profile invalid, rather than silently routing somewhere else.
- Linux keeps domain names in the host list. On export they are written to `TargetDomains` (as the Windows app does) and merged back on import.
-- Fields this version has no use for (`LogFilters`, ...) are ignored on import. `DnsViaProxy` and `DefaultProxyId` are Linux additions that other apps ignore. `Name` (proxies and rules), `SendDomainToProxy` (per proxy, default `true`) and `LocalhostViaProxy` (per rule, default `false`) mean the same as in the Windows app; a top-level `LocalhostViaProxy` from older profiles is the default for rules that have none of their own. The CLI takes DNS-via-proxy from the profile unless `--dns-via-proxy` is given, and uses `--verbose` instead of the logging flag.
+- Fields this version has no use for (`LogFilters`, ...) are ignored on import. `DnsViaProxy` and `DefaultProxyId` are Linux additions that other apps ignore. `LogEveryConnection` is the same per-profile setting as in the Windows app. `Name` (proxies and rules), `SendDomainToProxy` (per proxy, default `true`) and `LocalhostViaProxy` (per rule, default `false`) mean the same as in the Windows app; a top-level `LocalhostViaProxy` from older profiles is the default for rules that have none of their own. The CLI takes DNS-via-proxy from the profile unless `--dns-via-proxy` is given, and uses `--verbose` instead of the logging flag.
- Disabled rules (`"IsEnabled": false`) are kept in the GUI and skipped by the CLI.
- **GUI storage:** `/etc/proxybridge/profiles/<name>.pbprofile` (one file per profile) and `/etc/proxybridge/settings.json`, which holds only the name of the active profile. Everything else, including the *Enable Traffic Logging* and *DNS via Proxy* switches, is saved inside the profile, so switching profiles switches those too. The directory is `0700` and the files `0600`, because they hold proxy passwords; exported files are `0600` as well, and the CLI warns when a profile with credentials is readable by others. The `config.ini` of earlier versions is converted on the first start and kept as `config.ini.bak`.
- Files are limited to 4 MiB, 256 proxies and 4096 rules; malformed files are rejected with the reason, never partly applied.
@@ -336,6 +343,29 @@ Cost: DNS from covered processes takes one extra loopback hop (about +90 µs per
- **DNS via proxy, per proxy** (*SendDomainToProxy*, on by default, like Windows and macOS). When a connection goes to an address whose name the application resolved, the proxy is asked for the *name* (SOCKS5 domain address, or `CONNECT host:port`), so the proxy does the resolving. Off sends the IP address (`?dns=local` on the command line). The name comes from the application's own unencrypted DNS answers (the DNS tap that already powers domain rules; DoH/DoT bypass it), the most recent lookup for that address wins, and without a known name the IP is sent. UDP datagrams always carry the IP. Names are checked before they reach a proxy, so a hostile DNS answer cannot inject anything into a request. This is separate from the menu switch **DNS via Proxy**, which decides whether DNS queries themselves are routed through the rules.
- **Also proxy localhost traffic, per rule** (*LocalhostViaProxy*, off by default, PROXY rules only). Without it a PROXY rule leaves connections to this computer (`127.0.0.0/8`, `::1`) direct, as on Windows, which is usually what you want. With it, matching loopback TCP and UDP connections go to the proxy, for example to inspect a local application in an intercepting proxy. First match still wins: a PROXY rule without the option stops the walk and the connection stays local. Differences from Windows: BLOCK and DIRECT rules never touch loopback, and DNS to a local resolver (port 53, e.g. `127.0.0.53`) is never proxied, so a broad rule cannot break name resolution.
+## Connection log, live connections and the main switch
+
+- **Connection log.** By default a connection is listed once per application, destination, port, protocol and action, so a program that opens 50 connections to one server gets one line. *Log Every Connection* (`--log-every-connection true`, saved per profile) lists every new TCP connection and every new UDP flow instead; a UDP flow is listed again after 30 seconds of silence. Each decision appears exactly once, whether the kernel or the relay made it.
+- **Live Connections** (GUI tab, `ProxyBridge_GetFlows()` in the library): the TCP connections and UDP flows being relayed through a proxy right now, newest first, with process, PID, destination (the name the application resolved when known), proxy, age and payload bytes in each direction. Direct and blocked traffic never reaches the relay and is not listed.
+- **Enable ProxyBridge** (Proxy menu, `ProxyBridge_SetEnabled()`): the main switch. Off pauses every rule for *new* connections; connections already relayed keep running.
+- **Testing a proxy.** The Test button in the proxy settings and `--test-proxy host[:port]` run the same five steps: reach the proxy, open a tunnel and log in, load a page (port 80), time three more tunnels, and probe UDP ASSOCIATE. Only the first two decide success; a page, latency or UDP problem is a warning. The exit code is 0 only when every configured proxy works.
+
+## Compared with the Windows app (4.3.0)
+
+| Feature | Linux |
+|---|---|
+| Multiple proxies, per-rule proxy, default proxy | yes |
+| TCP and UDP (SOCKS5 UDP ASSOCIATE), IPv4 and IPv6 destinations | yes (UDP: IPv4, or connected IPv6 sockets; unconnected IPv6 UDP fails closed) |
+| Rules by process, address, CIDR, range, wildcard, port, protocol, domain | yes |
+| Rule names, proxy names, enable/disable, reorder, import/export | yes |
+| Per-proxy *DNS via proxy* (`SendDomainToProxy`) | yes |
+| Per-rule *Also proxy localhost traffic* (`LocalhostViaProxy`) | yes (BLOCK/DIRECT never touch loopback) |
+| Profiles in the `.pbprofile` format, CLI `--profile` | yes |
+| Detailed proxy check (reach, login, page, latency, UDP) | yes (GUI Test button, `--test-proxy`) |
+| Live connections | yes (GUI tab, `ProxyBridge_GetFlows`) |
+| Log Every Connection, main on/off switch | yes |
+| Hide/Show log filters (`LogFilters`), auto-clear logs, font zoom, language, close to tray, start with the OS, update check on start-up | not implemented (a `LogFilters` list in an imported profile is ignored) |
+
## Multiple proxies
Add as many `--proxy` entries (CLI) or proxies (GUI) as you need; each rule chooses its own with `PROXY=name`. Proxy hosts may be IP addresses or **host names** (resolved with a 5 s deadline and a cache, so a slow resolver cannot stall traffic). A rule that references a proxy that no longer exists blocks instead of leaking.
@@ -372,10 +402,12 @@ Add as many `--proxy` entries (CLI) or proxies (GUI) as you need; each rule choo
## Things to Note
+- **Stalled proxies do not hold everything up.** Connections that need a handshake with their proxy are served by a pool of workers that starts with 8 and grows to 64 while handshakes queue up (extra workers leave after 20 idle seconds). No single proxy may occupy more than 48 workers at once, so a proxy that accepts connections and then never answers (up to the 10 s handshake timeout each) cannot delay connections that use another proxy.
+
- **DNS Traffic Handling**: with `--dns-via-proxy true` (default) DNS (port 53) follows your rules like any other traffic; with `false`, DNS always uses a direct connection regardless of rules.
- **Automatic Direct Routing**: Certain IP addresses and ports automatically use direct connection regardless of proxy rules:
- - **Loopback** (127.0.0.0/8, ::1) and **0.0.0.0/8**
+ - **Loopback** (127.0.0.0/8, ::1) and **0.0.0.0/8**, unless a PROXY rule has *Also proxy localhost traffic* (then only that rule's matches are proxied, and never port 53 or the relay itself)
- **Multicast / broadcast / reserved** (224.0.0.0 and above, ff00::/8) and IPv6 link-local (fe80::/10)
- **DHCP ports** (UDP 67, 68) - Dynamic Host Configuration Protocol
@@ -583,6 +615,13 @@ cd ../../tests && sudo ./e2e.sh # end-to-end with real kernel
sudo ./e2e_domains.sh # domain rules with a real resolver client (root, needs dig)
sudo ./e2e_rules.sh # every rule form + every proxy type, incl. HTTP auth and UDP rules (root)
sudo ./e2e_profile.sh # `ProxyBridge --profile`: Windows-format profiles on the live datapath (root)
+sudo ./e2e_faults.sh # misbehaving SOCKS5/HTTP proxies: every failure code, stalls, early closes, 255-byte logins, 4 MiB integrity, a dead proxy cannot starve a healthy one (root)
+sudo ./e2e_udp.sh # UDP through SOCKS5 UDP ASSOCIATE: normal and malformed proxies, sizes, many sockets, BLOCK/DIRECT/HTTP, IPv6 (root)
+sudo ./e2e_rules_diff.sh # random rule sets vs an independent reference: kernel fast path and slow path, TCP and UDP (root)
+sudo ./e2e_logging.sh # connection log: de-duplication, log-every-connection, one line per decision (root)
+./e2e_checker.sh # `--test-proxy` against working and broken proxies (no root)
+sudo ./gui_ui.sh # drives the real windows and dialogs: proxies, rules, profiles, file choosers, menus, engine (root, needs broadwayd)
+sudo ./coverage.sh # line coverage of everything above plus the unit tests; `./coverage.sh unit` needs no root
sudo ./e2e_parity.sh # per-proxy host-name sending and per-rule localhost, incl. a hostile DNS name (root, needs dig)
sudo ./api_live.sh # library API: edit/move/disable/delete rules and proxies on the live datapath (root)
sudo BPFTOOL=$(command -v bpftool) ./e2e_security.sh # relay hand-off cannot be hijacked from another loopback address (root)
diff --git a/Linux/gui/tests/run_tests.sh b/Linux/gui/tests/run_tests.sh
index 2a9179b..3ccad92 100755
--- a/Linux/gui/tests/run_tests.sh
+++ b/Linux/gui/tests/run_tests.sh
@@ -17,5 +17,10 @@ gcc -O2 -Wall -Wextra -I. tests/events_test.c gui_events.c -o "$OUT/events_plain
time "$OUT/events_plain"
gcc -g -Wall -Wextra -fsanitize=address,undefined -I. tests/events_test.c gui_events.c -o "$OUT/events_asan" -pthread
ASAN_OPTIONS=detect_leaks=1 "$OUT/events_asan"
-gcc -g -O1 -Wall -Wextra -fsanitize=thread -I. tests/events_test.c gui_events.c -o "$OUT/events_tsan" -pthread
-setarch "$(uname -m)" -R "$OUT/events_tsan"
+# TSan needs ASLR switched off (setarch -R), which some containers forbid
+if setarch "$(uname -m)" -R true 2>/dev/null; then
+ gcc -g -O1 -Wall -Wextra -fsanitize=thread -I. tests/events_test.c gui_events.c -o "$OUT/events_tsan" -pthread
+ setarch "$(uname -m)" -R "$OUT/events_tsan"
+else
+ echo "skipping the ThreadSanitizer run: setarch -R is not permitted here"
+fi
diff --git a/Linux/gui/tests/ui_test.c b/Linux/gui/tests/ui_test.c
new file mode 100644
index 0000000..ee98085
--- /dev/null
+++ b/Linux/gui/tests/ui_test.c
@@ -0,0 +1,724 @@
+// Drives the real ProxyBridge window and its dialogs (GTK Broadway backend, needs root like the GUI itself).
+// The program under test is main.c compiled with -Dmain=pb_gui_main; pb_gui_ready_hook hands control to this test once the window
+// exists. Dialogs run modal loops, so every dialog the test expects is "armed" first: an independent timer source finds it by
+// widget name, fills it in and answers it. Results are checked in the widgets, in the model and in the profile file on disk.
+#include "gui.h"
+#include "pb_profile.h"
+
+extern void (*pb_gui_ready_hook)(void);
+extern int pb_gui_main(int argc, char *argv[]);
+
+static int checks, fails;
+#define STEP(msg) do { printf(" . %s\n", msg); fflush(stdout); } while (0)
+#define CHECK(c) do { checks++; if (!(c)) { fails++; printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); } } while (0)
+#define CHECK_STR(got, want) do { const char *g_ = (got), *w_ = (want); checks++; \
+ if (!g_ || strcmp(g_, w_) != 0) { fails++; printf("FAIL %s:%d got '%s', wanted '%s'\n", __FILE__, __LINE__, g_ ? g_ : "(null)", w_); } } while (0)
+#define CHECK_HAS(got, want) do { const char *g_ = (got), *w_ = (want); checks++; \
+ if (!g_ || !strstr(g_, w_)) { fails++; printf("FAIL %s:%d '%s' lacks '%s'\n", __FILE__, __LINE__, g_ ? g_ : "(null)", w_); } } while (0)
+
+static void pump(int ms) {
+ gint64 end = g_get_monotonic_time() + (gint64)ms * 1000;
+ while (g_get_monotonic_time() < end) {
+ while (gtk_events_pending()) gtk_main_iteration();
+ g_usleep(2000);
+ }
+}
+
+// ---- finding widgets ------------------------------------------------------------------------------------------------------
+typedef struct { const char *key; GtkWidget *found; bool by_label; } Find;
+
+static void find_cb(GtkWidget *w, gpointer p) {
+ Find *f = p;
+ if (f->found) return;
+ if (f->by_label) {
+ if (GTK_IS_MENU_ITEM(w)) {
+ const char *l = gtk_menu_item_get_label(GTK_MENU_ITEM(w));
+ if (l && strcmp(l, f->key) == 0) { f->found = w; return; }
+ }
+ } else {
+ const char *n = gtk_widget_get_name(w);
+ if (n && strcmp(n, f->key) == 0) { f->found = w; return; }
+ }
+ if (GTK_IS_MENU_ITEM(w)) {
+ GtkWidget *sub = gtk_menu_item_get_submenu(GTK_MENU_ITEM(w));
+ if (sub) find_cb(sub, p);
+ }
+ if (GTK_IS_CONTAINER(w)) gtk_container_foreach(GTK_CONTAINER(w), find_cb, p);
+}
+
+static GtkWidget *find_in(GtkWidget *root, const char *name) {
+ Find f = { name, NULL, false };
+ find_cb(root, &f);
+ return f.found;
+}
+
+static GtkWidget *find_named(const char *name) {
+ GList *tops = gtk_window_list_toplevels();
+ Find f = { name, NULL, false };
+ for (GList *l = tops; l && !f.found; l = l->next) find_cb(l->data, &f);
+ g_list_free(tops);
+ return f.found;
+}
+
+static GtkWidget *menu_item(const char *label) {
+ Find f = { label, NULL, true };
+ find_cb(window, &f);
+ return f.found;
+}
+
+static void click(const char *name) {
+ GtkWidget *w = find_named(name);
+ CHECK(w != NULL);
+ if (w) gtk_button_clicked(GTK_BUTTON(w));
+}
+
+static void activate(const char *label) {
+ GtkWidget *w = menu_item(label);
+ CHECK(w != NULL);
+ if (w) gtk_menu_item_activate(GTK_MENU_ITEM(w));
+}
+
+// ---- answering dialogs ----------------------------------------------------------------------------------------------------
+typedef void (*FillFn)(GtkWidget *, gpointer);
+typedef struct { const char *name; FillFn fill; gpointer arg; int response; int ticks; int line; } Armed;
+
+static GtkWidget *visible_dialog(const char *name) {
+ GList *tops = gtk_window_list_toplevels();
+ GtkWidget *found = NULL;
+ for (GList *l = tops; l; l = l->next) {
+ GtkWidget *w = l->data;
+ if (!GTK_IS_DIALOG(w) || !gtk_widget_get_visible(w)) continue;
+ bool match = strcmp(name, "msg") == 0 ? GTK_IS_MESSAGE_DIALOG(w)
+ : strcmp(name, "chooser") == 0 ? GTK_IS_FILE_CHOOSER_DIALOG(w)
+ : strcmp(gtk_widget_get_name(w), name) == 0;
+ if (match) found = w;
+ }
+ g_list_free(tops);
+ return found;
+}
+
+static gboolean armed_poll(gpointer p) {
+ Armed *a = p;
+ GtkWidget *d = visible_dialog(a->name);
+ if (!d) {
+ if (++a->ticks > 500) {
+ CHECK(!"an expected dialog never appeared");
+ printf(" (armed at line %d, waiting for '%s')\n", a->line, a->name);
+ g_free(a);
+ return G_SOURCE_REMOVE;
+ }
+ return G_SOURCE_CONTINUE;
+ }
+ FillFn fill = a->fill;
+ gpointer arg = a->arg;
+ int response = a->response;
+ g_free(a); // before filling: a fill may arm the next dialog
+ if (fill) fill(d, arg);
+ if (response) gtk_dialog_response(GTK_DIALOG(d), response);
+ return G_SOURCE_REMOVE;
+}
+
+static void arm_at(int line, const char *name, FillFn fill, gpointer arg, int response) {
+ Armed *a = g_malloc0(sizeof *a);
+ a->name = name; a->fill = fill; a->arg = arg; a->response = response; a->line = line;
+ g_timeout_add(30, armed_poll, a);
+}
+
+static char *last_msg;
+static void remember_msg(GtkWidget *d, gpointer arg) {
+ (void)arg;
+ g_free(last_msg);
+ g_object_get(d, "text", &last_msg, NULL);
+}
+#define arm(name, fill, arg, response) arm_at(__LINE__, name, fill, arg, response)
+#define arm_msg(response) arm_at(__LINE__, "msg", remember_msg, NULL, response)
+
+// ---- widget helpers -------------------------------------------------------------------------------------------------------
+static void set_text(GtkWidget *dlg, const char *name, const char *text) {
+ GtkWidget *w = find_in(dlg, name);
+ CHECK(w != NULL);
+ if (!w) return;
+ if (GTK_IS_TEXT_VIEW(w)) gtk_text_buffer_set_text(gtk_text_view_get_buffer(GTK_TEXT_VIEW(w)), text, -1);
+ else gtk_entry_set_text(GTK_ENTRY(w), text);
+}
+
+static char *get_text(GtkWidget *dlg, const char *name) {
+ GtkWidget *w = find_in(dlg, name);
+ if (!w) return g_strdup("");
+ if (GTK_IS_TEXT_VIEW(w)) {
+ GtkTextBuffer *b = gtk_text_view_get_buffer(GTK_TEXT_VIEW(w));
+ GtkTextIter s, e;
+ gtk_text_buffer_get_bounds(b, &s, &e);
+ return gtk_text_buffer_get_text(b, &s, &e, FALSE);
+ }
+ if (GTK_IS_LABEL(w)) return g_strdup(gtk_label_get_text(GTK_LABEL(w)));
+ return g_strdup(gtk_entry_get_text(GTK_ENTRY(w)));
+}
+
+static void set_combo(GtkWidget *dlg, const char *name, int idx) {
+ GtkWidget *w = find_in(dlg, name);
+ CHECK(w != NULL);
+ if (w) gtk_combo_box_set_active(GTK_COMBO_BOX(w), idx);
+}
+
+static int get_combo(GtkWidget *dlg, const char *name) {
+ GtkWidget *w = find_in(dlg, name);
+ return w ? gtk_combo_box_get_active(GTK_COMBO_BOX(w)) : -2;
+}
+
+static void set_check(GtkWidget *dlg, const char *name, bool on) {
+ GtkWidget *w = find_in(dlg, name);
+ CHECK(w != NULL);
+ if (w) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), on);
+}
+
+static bool get_check(GtkWidget *dlg, const char *name) {
+ GtkWidget *w = find_in(dlg, name);
+ return w && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(w));
+}
+
+static bool is_sensitive(GtkWidget *root, const char *name) {
+ GtkWidget *w = find_in(root, name);
+ return w && gtk_widget_get_sensitive(w);
+}
+
+static void select_row(const char *tree_name, int idx) {
+ GtkWidget *t = find_named(tree_name);
+ CHECK(t != NULL);
+ if (!t) return;
+ GtkTreePath *p = gtk_tree_path_new_from_indices(idx, -1);
+ gtk_tree_selection_select_path(gtk_tree_view_get_selection(GTK_TREE_VIEW(t)), p);
+ gtk_tree_path_free(p);
+}
+
+static void unselect_all(const char *tree_name) {
+ GtkWidget *t = find_named(tree_name);
+ if (t) gtk_tree_selection_unselect_all(gtk_tree_view_get_selection(GTK_TREE_VIEW(t)));
+}
+
+static int model_rows(const char *tree_name) {
+ GtkWidget *t = find_named(tree_name);
+ return t ? gtk_tree_model_iter_n_children(gtk_tree_view_get_model(GTK_TREE_VIEW(t)), NULL) : -1;
+}
+
+static bool select_by_first_column(const char *tree_name, const char *text) {
+ GtkWidget *t = find_named(tree_name);
+ if (!t) return false;
+ GtkTreeModel *m = gtk_tree_view_get_model(GTK_TREE_VIEW(t));
+ GtkTreeIter it;
+ bool ok = gtk_tree_model_get_iter_first(m, &it);
+ while (ok) {
+ char *v = NULL;
+ gtk_tree_model_get(m, &it, 0, &v, -1);
+ bool hit = v && strcmp(v, text) == 0;
+ g_free(v);
+ if (hit) { gtk_tree_selection_select_iter(gtk_tree_view_get_selection(GTK_TREE_VIEW(t)), &it); return true; }
+ ok = gtk_tree_model_iter_next(m, &it);
+ }
+ return false;
+}
+
+static void show_profiles(const char *when) {
+ printf(" profiles %s:", when);
+ for (GList *l = g_profiles; l; l = l->next) printf(" [%s]", ((Profile *)l->data)->name);
+ printf(" active=%s\n", g_active_profile);
+ fflush(stdout);
+}
+
+// ---- the profile file on disk ---------------------------------------------------------------------------------------------
+static bool load_disk(const char *profile, struct pbp_profile *p) {
+ char *file = pbp_filename_for(profile);
+ char *path = g_strdup_printf("%s/profiles/%s", pbp_config_dir(), file);
+ char err[200];
+ bool ok = pbp_load_file(path, p, err, sizeof err) == 0;
+ free(file);
+ g_free(path);
+ return ok;
+}
+
+static char *tmp_path(const char *name) { return g_strdup_printf("%s/%s", pbp_config_dir(), name); }
+
+static void choose_file(GtkWidget *d, gpointer arg) {
+ const char *path = arg;
+ if (gtk_file_chooser_get_action(GTK_FILE_CHOOSER(d)) == GTK_FILE_CHOOSER_ACTION_SAVE) {
+ char *dir = g_path_get_dirname(path), *base = g_path_get_basename(path);
+ gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(d), dir);
+ gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(d), base);
+ g_free(dir); g_free(base);
+ } else {
+ gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(d), path);
+ }
+ pump(400); // the chooser loads its folder asynchronously; answering at once can be vetoed by its response handler
+}
+
+// ================================================================================================================================
+// Proxy Settings
+// ================================================================================================================================
+typedef struct { const char *name, *host, *port, *user, *pass; int type; bool dns; const char *error; } PxForm;
+
+static void fill_px(GtkWidget *d, gpointer arg) {
+ PxForm *f = arg;
+ set_text(d, "px_name", f->name); set_text(d, "px_host", f->host); set_text(d, "px_port", f->port);
+ set_text(d, "px_user", f->user); set_text(d, "px_pass", f->pass);
+ set_combo(d, "px_type", f->type);
+ set_check(d, "px_dns", f->dns);
+}
+
+static PxForm *px(const char *name, int type, const char *host, const char *port, const char *user, const char *pass, bool dns) {
+ PxForm *f = g_malloc0(sizeof *f);
+ f->name = name; f->type = type; f->host = host; f->port = port; f->user = user; f->pass = pass; f->dns = dns;
+ return f;
+}
+
+static char *seen_error;
+static void see_error_then_cancel(GtkWidget *d, gpointer arg) { (void)arg; g_free(seen_error); seen_error = get_text(d, "px_error"); }
+// first pass: submit the bad form (the dialog stays open and shows why); the second pass is armed from here, after the answer
+static void submit_bad_px(GtkWidget *d, gpointer arg) {
+ fill_px(d, arg);
+ arm("dlg_proxy", see_error_then_cancel, NULL, GTK_RESPONSE_CANCEL);
+}
+
+static ProxyData *proxy_named(const char *name) { return find_proxy_by_name(name); }
+
+static void proxies_body(GtkWidget *dlg, gpointer arg) {
+ (void)arg;
+ STEP("proxy dialog open");
+ CHECK(model_rows("proxy_tree") == 0);
+
+ arm("dlg_proxy", fill_px, px("p1", 1, "127.0.0.1", "19080", "", "", false), GTK_RESPONSE_ACCEPT);
+ click("px_add");
+ ProxyData *p1 = proxy_named("p1");
+ CHECK(p1 && p1->type == PROXY_TYPE_SOCKS5 && p1->port == 19080 && !p1->send_domain && p1->id != 0);
+ CHECK_STR(g_default_proxy, "p1");
+ CHECK(model_rows("proxy_tree") == 1);
+
+ STEP("p1 added; validation cases");
+ struct { PxForm *bad; const char *error; } cases[] = {
+ { px("", 1, "h", "1", "", "", true), "Name cannot be empty." },
+ { px("p1", 1, "h", "1", "", "", true), "A proxy with this name already exists." },
+ { px("x", 1, "", "1", "", "", true), "Host (IP/Domain) cannot be empty." },
+ { px("x", 1, "h", "0", "", "", true), "Port must be a number between 1 and 65535." },
+ { px("x", 1, "h", "70000", "", "", true), "Port must be a number between 1 and 65535." },
+ { px("x", 1, "h", "80x", "", "", true), "Port must be a number between 1 and 65535." },
+ };
+ for (size_t i = 0; i < sizeof cases / sizeof *cases; i++) {
+ g_free(seen_error); seen_error = NULL;
+ arm("dlg_proxy", submit_bad_px, cases[i].bad, GTK_RESPONSE_ACCEPT);
+ click("px_add");
+ CHECK_STR(seen_error, cases[i].error);
+ CHECK(g_list_length(g_proxies_list) == 1);
+ }
+
+ STEP("validation done; adding p2");
+ arm("dlg_proxy", fill_px, px("p2", 0, "10.9.9.9", "8080", "bob", "pw", true), GTK_RESPONSE_ACCEPT);
+ click("px_add");
+ ProxyData *p2 = proxy_named("p2");
+ CHECK(p2 && p2->type == PROXY_TYPE_HTTP && p2->send_domain && strcmp(p2->username, "bob") == 0 && strcmp(p2->password, "pw") == 0);
+ CHECK(model_rows("proxy_tree") == 2);
+
+ STEP("editing p1");
+ // edit shows the stored values first; renaming keeps the default pointing at the proxy
+ select_row("proxy_tree", 0);
+ arm("dlg_proxy", fill_px, px("p1x", 1, "127.0.0.1", "19080", "", "", true), GTK_RESPONSE_ACCEPT);
+ click("px_edit");
+ CHECK(proxy_named("p1") == NULL && proxy_named("p1x") && proxy_named("p1x")->send_domain);
+ CHECK_STR(g_default_proxy, "p1x");
+
+ select_row("proxy_tree", 1);
+ click("px_default");
+ CHECK_STR(g_default_proxy, "p2");
+ select_row("proxy_tree", 1);
+ arm_msg(GTK_RESPONSE_NO);
+ click("px_delete");
+ CHECK_HAS(last_msg, "Delete proxy 'p2'");
+ CHECK(proxy_named("p2") != NULL); // "No" keeps it
+ arm_msg(GTK_RESPONSE_YES);
+ click("px_delete");
+ CHECK(proxy_named("p2") == NULL && g_list_length(g_proxies_list) == 1);
+ CHECK_STR(g_default_proxy, "p1x");
+
+ STEP("deleting / empty selection");
+ unselect_all("proxy_tree");
+ arm_msg(GTK_RESPONSE_OK); click("px_edit"); CHECK_HAS(last_msg, "Select a proxy first");
+ arm_msg(GTK_RESPONSE_OK); click("px_delete"); CHECK_HAS(last_msg, "Select a proxy first");
+ arm_msg(GTK_RESPONSE_OK); click("px_default"); CHECK_HAS(last_msg, "Select a proxy first");
+ click("px_test");
+ char *out = get_text(dlg, "px_test_output");
+ CHECK_HAS(out, "Select a proxy to test");
+ g_free(out);
+
+ STEP("connection test");
+ // the connection test runs on a worker thread and re-enables the button when it is done
+ select_row("proxy_tree", 0);
+ set_text(dlg, "px_test_host", "203.0.113.5");
+ set_text(dlg, "px_test_port", "80");
+ click("px_test");
+ CHECK(!is_sensitive(dlg, "px_test"));
+ for (int i = 0; i < 150 && !is_sensitive(dlg, "px_test"); i++) pump(100);
+ CHECK(is_sensitive(dlg, "px_test"));
+ out = get_text(dlg, "px_test_output");
+ CHECK_HAS(out, "[1/5] Connecting to the proxy"); // the steps stream into the window
+ CHECK_HAS(out, "Result: PASSED");
+ g_free(out);
+
+ gtk_dialog_response(GTK_DIALOG(dlg), GTK_RESPONSE_CLOSE);
+}
+
+// ================================================================================================================================
+// Rules
+// ================================================================================================================================
+typedef struct { const char *name, *proc, *hosts, *ports; int proto, action, proxy_idx; bool localhost; } RuleForm;
+
+static RuleForm *rf(const char *name, const char *proc, const char *hosts, const char *ports, int proto, int action, int proxy_idx, bool lo) {
+ RuleForm *f = g_malloc0(sizeof *f);
+ f->name = name; f->proc = proc; f->hosts = hosts; f->ports = ports; f->proto = proto; f->action = action; f->proxy_idx = proxy_idx; f->localhost = lo;
+ return f;
+}
+
+static void fill_rule(GtkWidget *d, gpointer arg) {
+ RuleForm *f = arg;
+ set_text(d, "rule_name", f->name); set_text(d, "rule_process", f->proc); set_text(d, "rule_hosts", f->hosts);
+ set_text(d, "rule_ports", f->ports);
+ set_combo(d, "rule_proto", f->proto); set_combo(d, "rule_proxy", f->proxy_idx);
+ set_check(d, "rule_localhost", f->localhost);
+ set_combo(d, "rule_action", f->action); // last: the localhost option follows the action
+}
+
+static char *rule_error;
+static void see_rule_error(GtkWidget *d, gpointer arg) { (void)arg; g_free(rule_error); rule_error = get_text(d, "rule_error"); }
+static void submit_bad_rule(GtkWidget *d, gpointer arg) {
+ fill_rule(d, arg);
+ arm("dlg_rule", see_rule_error, NULL, GTK_RESPONSE_CANCEL);
+}
+
+static RuleData *rule_at(int i) { return g_list_nth_data(g_rules_list, i); }
+
+static void check_dialog_shows_web(GtkWidget *d, gpointer arg) {
+ (void)arg;
+ char *name = get_text(d, "rule_name"), *proc = get_text(d, "rule_process"), *ports = get_text(d, "rule_ports");
+ CHECK_STR(name, "Web"); CHECK_STR(proc, "curl"); CHECK_STR(ports, "80;443");
+ CHECK(get_check(d, "rule_localhost") && is_sensitive(d, "rule_localhost"));
+ CHECK(get_combo(d, "rule_proto") == RULE_PROTOCOL_TCP && get_combo(d, "rule_action") == RULE_ACTION_PROXY && get_combo(d, "rule_proxy") == 1);
+ g_free(name); g_free(proc); g_free(ports);
+ set_text(d, "rule_name", "Web2");
+ set_check(d, "rule_localhost", false);
+}
+
+static void check_localhost_follows_action(GtkWidget *d, gpointer arg) {
+ RuleForm *f = arg;
+ set_combo(d, "rule_action", RULE_ACTION_PROXY);
+ CHECK(is_sensitive(d, "rule_localhost") && is_sensitive(d, "rule_proxy"));
+ set_combo(d, "rule_action", RULE_ACTION_DIRECT);
+ CHECK(!is_sensitive(d, "rule_localhost") && !is_sensitive(d, "rule_proxy"));
+ set_combo(d, "rule_action", RULE_ACTION_BLOCK);
+ CHECK(!is_sensitive(d, "rule_localhost"));
+ fill_rule(d, f);
+}
+
+static void rules_scenario(void) {
+ GtkWidget *win = find_named("win_rules");
+ CHECK(win != NULL);
+ STEP("rules window: add r1");
+
+ arm("dlg_rule", fill_rule, rf("Web", "curl", "10.0.0.0/8;\nexample.com", "80;443", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, 1, true), GTK_RESPONSE_ACCEPT);
+ click("rules_add");
+ RuleData *r1 = rule_at(0);
+ CHECK(g_list_length(g_rules_list) == 1 && r1 && r1->id != 0);
+ CHECK(r1 && strcmp(r1->name, "Web") == 0 && strcmp(r1->process_name, "curl") == 0 && r1->localhost && r1->enabled);
+ CHECK_STR(r1 ? r1->proxy_name : NULL, "p1x");
+ CHECK_HAS(r1 ? r1->target_hosts : NULL, "example.com");
+ CHECK(r1 && strchr(r1->target_hosts, '\n') == NULL); // line breaks in the editor are only for reading
+
+ STEP("rule validation");
+ // a rule the engine rejects: the dialog stays open and shows the reason
+ g_free(rule_error); rule_error = NULL;
+ arm("dlg_rule", submit_bad_rule, rf("Bad", "curl", "bad host!", "80", RULE_PROTOCOL_TCP, RULE_ACTION_DIRECT, 0, false), GTK_RESPONSE_ACCEPT);
+ click("rules_add");
+ CHECK(rule_error && strlen(rule_error) > 0);
+ CHECK(g_list_length(g_rules_list) == 1);
+ g_free(rule_error); rule_error = NULL;
+ arm("dlg_rule", submit_bad_rule, rf("Bad", "curl", "*", "99999", RULE_PROTOCOL_TCP, RULE_ACTION_DIRECT, 0, false), GTK_RESPONSE_ACCEPT);
+ click("rules_add");
+ CHECK(rule_error && strlen(rule_error) > 0 && g_list_length(g_rules_list) == 1);
+
+ // "Also proxy localhost traffic" only exists for PROXY rules; a DIRECT rule never keeps it
+ RuleForm *direct = rf("Local", "wget", "192.168.0.0/16", "*", RULE_PROTOCOL_UDP, RULE_ACTION_DIRECT, 0, true);
+ arm("dlg_rule", check_localhost_follows_action, direct, GTK_RESPONSE_ACCEPT);
+ click("rules_add");
+ RuleData *r2 = rule_at(1);
+ CHECK(r2 && r2->action == RULE_ACTION_DIRECT && r2->protocol == RULE_PROTOCOL_UDP && !r2->localhost);
+
+ arm("dlg_rule", fill_rule, rf("", "*", "*", "53", RULE_PROTOCOL_UDP, RULE_ACTION_BLOCK, 0, false), GTK_RESPONSE_ACCEPT);
+ click("rules_add");
+ RuleData *r3 = rule_at(2);
+ CHECK(r3 && r3->action == RULE_ACTION_BLOCK && strcmp(r3->name, "") == 0);
+
+ STEP("enable/disable and reorder");
+ // enable/disable, reorder
+ GtkWidget *en2 = find_named("rule_enable_2");
+ CHECK(en2 != NULL);
+ if (en2) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(en2), FALSE);
+ CHECK(!r2->enabled);
+ CHECK(!is_sensitive(win, "rule_up_1") && is_sensitive(win, "rule_up_3") && !is_sensitive(win, "rule_down_3"));
+ click("rule_up_3");
+ CHECK(rule_at(0) == r1 && rule_at(1) == r3 && rule_at(2) == r2);
+ click("rule_down_2");
+ CHECK(rule_at(1) == r2 && rule_at(2) == r3);
+
+ // edit shows the stored values
+ arm("dlg_rule", check_dialog_shows_web, NULL, GTK_RESPONSE_ACCEPT);
+ click("rule_edit_1");
+ CHECK_STR(r1->name, "Web2");
+ CHECK(!r1->localhost && r1->id != 0);
+ struct pbp_profile disk;
+ CHECK(load_disk("Default", &disk));
+ CHECK(disk.nrules == 3 && strcmp(disk.rules[0].name, "Web2") == 0 && !disk.rules[0].localhost && !disk.rules[1].enabled);
+ CHECK(disk.rules[0].proxy_id != 0 && strcmp(disk.rules[0].hosts, "10.0.0.0/8;example.com") == 0);
+ pbp_free(&disk);
+
+ STEP("export / import");
+ // export two rules, delete them, import them back
+ char *file = tmp_path("rules_export.json");
+ unlink(file);
+ arm_msg(GTK_RESPONSE_OK);
+ click("rules_export"); // nothing selected yet
+ CHECK_HAS(last_msg, "select at least one rule");
+ GtkWidget *s1 = find_named("rule_select_1"), *s3 = find_named("rule_select_3");
+ CHECK(s1 && s3);
+ if (s1) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(s1), TRUE);
+ s3 = find_named("rule_select_3");
+ if (s3) gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(s3), TRUE);
+ arm("chooser", choose_file, file, GTK_RESPONSE_ACCEPT);
+ arm_msg(GTK_RESPONSE_OK);
+ click("rules_export");
+ CHECK_HAS(last_msg, "exported");
+ char *json = NULL;
+ CHECK(g_file_get_contents(file, &json, NULL, NULL));
+ CHECK_HAS(json, "Web2"); CHECK_HAS(json, "\"localhostViaProxy\"");
+ g_free(json);
+
+ click("rules_delete_selected");
+ CHECK(g_list_length(g_rules_list) == 1 && rule_at(0) == r2);
+ arm("chooser", choose_file, file, GTK_RESPONSE_ACCEPT);
+ arm_msg(GTK_RESPONSE_OK);
+ click("rules_import");
+ CHECK_HAS(last_msg, "Imported 2 rules");
+ CHECK(g_list_length(g_rules_list) == 3);
+ CHECK_STR(rule_at(1)->name, "Web2");
+
+ char *bad = tmp_path("not_rules.json");
+ g_file_set_contents(bad, "this is not json", -1, NULL);
+ arm("chooser", choose_file, bad, GTK_RESPONSE_ACCEPT);
+ arm_msg(GTK_RESPONSE_OK);
+ click("rules_import");
+ CHECK_HAS(last_msg, "No rules found");
+ CHECK(g_list_length(g_rules_list) == 3);
+
+ click("rule_delete_1");
+ CHECK(g_list_length(g_rules_list) == 2);
+ click("rules_select_all");
+ click("rules_delete_selected");
+ CHECK(g_rules_list == NULL);
+ g_free(file); g_free(bad);
+
+ STEP("rules done");
+ // leave one rule behind for the profile scenario
+ arm("dlg_rule", fill_rule, rf("Keep", "firefox", "*", "443", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, 0, false), GTK_RESPONSE_ACCEPT);
+ click("rules_add");
+ CHECK(g_list_length(g_rules_list) == 1);
+ gtk_widget_destroy(win);
+ pump(50);
+ CHECK(find_named("win_rules") == NULL);
+}
+
+// ================================================================================================================================
+// Profiles
+// ================================================================================================================================
+static void fill_name(GtkWidget *d, gpointer arg) { set_text(d, "profile_name_entry", arg); }
+static void cancel_name_dialog(GtkWidget *d, gpointer arg) { (void)d; (void)arg; }
+
+// submit a name the dialog refuses, read the message, then cancel (the cancel is armed after the message so it cannot answer early)
+static const char *refused_name;
+static void msg_then_arm_cancel(GtkWidget *d, gpointer arg) {
+ remember_msg(d, arg);
+ arm("dlg_profile_name", cancel_name_dialog, NULL, GTK_RESPONSE_CANCEL);
+}
+static void submit_refused(GtkWidget *d, gpointer arg) {
+ (void)arg;
+ set_text(d, "profile_name_entry", refused_name);
+ arm("msg", msg_then_arm_cancel, NULL, GTK_RESPONSE_OK);
+}
+
+static void profiles_body(GtkWidget *dlg, gpointer arg) {
+ (void)arg;
+ STEP("profiles dialog open");
+ CHECK(model_rows("profile_tree") == 1);
+
+ arm("dlg_profile_name", fill_name, (gpointer)"Work", GTK_RESPONSE_ACCEPT);
+ click("pf_new");
+ CHECK(profile_find("Work") && model_rows("profile_tree") == 2);
+ struct pbp_profile disk;
+ CHECK(load_disk("Work", &disk) && disk.nrules == 0 && disk.nproxies == 0);
+ pbp_free(&disk);
+
+ refused_name = "";
+ arm("dlg_profile_name", submit_refused, NULL, GTK_RESPONSE_ACCEPT);
+ click("pf_new");
+ CHECK_HAS(last_msg, "cannot be empty");
+ refused_name = "Work";
+ arm("dlg_profile_name", submit_refused, NULL, GTK_RESPONSE_ACCEPT);
+ click("pf_new");
+ CHECK_HAS(last_msg, "already exists");
+ CHECK(model_rows("profile_tree") == 2);
+
+ STEP("duplicate");
+ // duplicate copies proxies, rules and switches
+ CHECK(select_by_first_column("profile_tree", "Default"));
+ arm("dlg_profile_name", fill_name, (gpointer)"Home", GTK_RESPONSE_ACCEPT);
+ click("pf_duplicate");
+ Profile *home = profile_find("Home");
+ CHECK(home && g_list_length(home->proxies) == 1 && g_list_length(home->rules) == 1);
+
+ // rename
+ CHECK(select_by_first_column("profile_tree", "Home"));
+ arm("dlg_profile_name", fill_name, (gpointer)"Office", GTK_RESPONSE_ACCEPT);
+ click("pf_rename");
+ CHECK(profile_find("Home") == NULL && profile_find("Office"));
+ struct pbp_profile d2;
+ CHECK(load_disk("Office", &d2));
+ pbp_free(&d2);
+ CHECK(!load_disk("Home", &d2)); // the old file is gone
+
+ STEP("switch");
+ // switch: the window title, the engine's rules and the profile's own switches follow
+ GtkWidget *log_item = menu_item("Enable Traffic Logging"), *dns_item = menu_item("DNS via Proxy");
+ CHECK(log_item && dns_item);
+ gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(log_item), FALSE); // Default: logging off
+ CHECK(!g_chk_logging);
+ CHECK(select_by_first_column("profile_tree", "Work"));
+ click("pf_switch");
+ CHECK_STR(g_active_profile, "Work");
+ CHECK_HAS(gtk_window_get_title(GTK_WINDOW(window)), "ProxyBridge - Work");
+ CHECK(g_chk_logging && gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(log_item))); // Work has its own, default-on switches
+ gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(dns_item), FALSE); // Work: DNS off
+ CHECK(select_by_first_column("profile_tree", "Default"));
+ click("pf_switch");
+ CHECK_STR(g_active_profile, "Default");
+ CHECK(!gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(log_item)) && gtk_check_menu_item_get_active(GTK_CHECK_MENU_ITEM(dns_item)));
+ CHECK(load_disk("Work", &d2) && !d2.dns_via_proxy && d2.logging);
+ pbp_free(&d2);
+
+ STEP("profile export / import");
+ // export and import through the file chooser
+ char *file = tmp_path("exported.pbprofile");
+ unlink(file);
+ CHECK(select_by_first_column("profile_tree", "Office"));
+ arm("chooser", choose_file, file, GTK_RESPONSE_ACCEPT);
+ arm_msg(GTK_RESPONSE_OK);
+ click("pf_export");
+ CHECK_HAS(last_msg, "exported");
+ struct stat st;
+ CHECK(stat(file, &st) == 0 && (st.st_mode & 0777) == 0600);
+ arm("chooser", choose_file, file, GTK_RESPONSE_ACCEPT);
+ arm_msg(GTK_RESPONSE_OK);
+ click("pf_import");
+ CHECK_HAS(last_msg, "Imported as profile");
+ CHECK(profile_find("Office (2)") != NULL);
+ char *junk = tmp_path("junk.pbprofile");
+ g_file_set_contents(junk, "{ nope", -1, NULL);
+ arm("chooser", choose_file, junk, GTK_RESPONSE_ACCEPT);
+ arm_msg(GTK_RESPONSE_OK);
+ click("pf_import");
+ CHECK_HAS(last_msg, "Import failed");
+ g_free(file); g_free(junk);
+
+ STEP("profile delete");
+ // delete: asks first; the last profile stays
+ CHECK(select_by_first_column("profile_tree", "Office (2)"));
+ show_profiles("before deleting");
+ arm_msg(GTK_RESPONSE_NO);
+ click("pf_delete");
+ CHECK(profile_find("Office (2)") != NULL);
+ arm_msg(GTK_RESPONSE_YES);
+ click("pf_delete");
+ CHECK(profile_find("Office (2)") == NULL);
+ CHECK(select_by_first_column("profile_tree", "Office"));
+ arm_msg(GTK_RESPONSE_YES);
+ click("pf_delete");
+ show_profiles("after deleting Office");
+ CHECK(select_by_first_column("profile_tree", "Work"));
+ arm_msg(GTK_RESPONSE_YES);
+ click("pf_delete");
+ show_profiles("after deleting Work");
+ CHECK(g_list_length(g_profiles) == 1);
+ CHECK(select_by_first_column("profile_tree", "Default"));
+ arm_msg(GTK_RESPONSE_OK);
+ click("pf_delete");
+ CHECK_HAS(last_msg, "last profile");
+ CHECK(profile_find("Default") != NULL);
+ gtk_dialog_response(GTK_DIALOG(dlg), GTK_RESPONSE_CLOSE);
+}
+
+// ================================================================================================================================
+static void ui_main(void) {
+ pump(300);
+ CHECK_HAS(gtk_window_get_title(GTK_WINDOW(window)), "ProxyBridge - Default");
+ CHECK(menu_item("Proxy Settings...") && menu_item("Proxy Rules...") && menu_item("Profiles..."));
+
+ printf("== proxy settings\n");
+ arm("dlg_proxies", proxies_body, NULL, 0);
+ activate("Proxy Settings...");
+ struct pbp_profile disk;
+ CHECK(load_disk("Default", &disk));
+ CHECK(disk.nproxies == 1 && strcmp(disk.proxies[0].name, "p1x") == 0 && disk.proxies[0].send_domain);
+ pbp_free(&disk);
+
+ printf("== rules\n");
+ activate("Proxy Rules...");
+ pump(100);
+ rules_scenario();
+
+ printf("== profiles\n");
+ arm("dlg_profiles", profiles_body, NULL, 0);
+ activate("Profiles...");
+
+ printf("== menus and engine\n");
+ GtkWidget *start = menu_item("Start Engine"), *stop = menu_item("Stop Engine");
+ CHECK(start && stop);
+ for (int i = 0; i < 40 && !gtk_widget_get_sensitive(stop); i++) pump(100);
+ CHECK(gtk_widget_get_sensitive(stop) && !gtk_widget_get_sensitive(start));
+ activate("Stop Engine");
+ for (int i = 0; i < 40 && !gtk_widget_get_sensitive(start); i++) pump(100);
+ CHECK(gtk_widget_get_sensitive(start) && !gtk_widget_get_sensitive(stop));
+ activate("Start Engine");
+ for (int i = 0; i < 40 && !gtk_widget_get_sensitive(stop); i++) pump(100);
+ CHECK(gtk_widget_get_sensitive(stop));
+ arm("dlg_about", NULL, NULL, GTK_RESPONSE_OK);
+ activate("About");
+ pump(100);
+
+ // what is on screen and in the files is what a restart would load
+ config_free_all();
+ load_config();
+ CHECK_STR(g_active_profile, "Default");
+ CHECK(g_list_length(g_profiles) == 1 && g_list_length(g_proxies_list) == 1 && g_list_length(g_rules_list) == 1);
+ CHECK(strcmp(((RuleData *)g_rules_list->data)->name, "Keep") == 0);
+
+ printf("ui_test: %d checks, %d failed\n", checks, fails);
+}
+
+static void watchdog(int sig) {
+ (void)sig;
+ printf("FAIL the UI test hung (watchdog)\n");
+ fflush(stdout);
+ _exit(2);
+}
+
+int main(int argc, char *argv[]) {
+ setvbuf(stdout, NULL, _IOLBF, 0);
+ pb_gui_ready_hook = ui_main;
+ signal(SIGALRM, watchdog);
+ alarm(280);
+ int rc = pb_gui_main(argc, argv);
+ return rc ? rc : (fails ? 1 : 0);
+}
diff --git a/Linux/profile/tests/profile_test.c b/Linux/profile/tests/profile_test.c
index 1f13df8..fdc240e 100644
--- a/Linux/profile/tests/profile_test.c
+++ b/Linux/profile/tests/profile_test.c
@@ -74,6 +74,17 @@ static void test_parity_fields(void)
free(json);
pbp_free(&p);
pbp_free(&q);
+
+ // LogEveryConnection: off unless the file says so, and it survives a round trip
+ CHECK(parse("{}", &p, err) == 0 && !p.log_every);
+ pbp_free(&p);
+ CHECK(parse("{ \"LogEveryConnection\": true }", &p, err) == 0 && p.log_every);
+ json = pbp_serialize(&p);
+ CHECK(json && strstr(json, "\"LogEveryConnection\": true"));
+ CHECK(pbp_parse(json, strlen(json), &q, err, sizeof err) == 0 && q.log_every);
+ free(json);
+ pbp_free(&p);
+ pbp_free(&q);
}
static void test_roundtrip(void)
diff --git a/Linux/src/tests/proc_test.c b/Linux/src/tests/proc_test.c
new file mode 100644
index 0000000..11e75fe
--- /dev/null
+++ b/Linux/src/tests/proc_test.c
@@ -0,0 +1,95 @@
+// Unit test of pb_proc.c: which processes listen on a TCP port, and which addresses are local. Needs no root (own sockets only).
+#include "../pb_proc.h"
+#include <arpa/inet.h>
+#include <ifaddrs.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+static int checks, fails;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; printf("FAIL line %d: %s\n", __LINE__, #c); } } while (0)
+
+static int listener(const char *ip, uint16_t *port)
+{
+ int s = socket(AF_INET, SOCK_STREAM, 0);
+ int one = 1;
+ setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
+ struct sockaddr_in a = { .sin_family = AF_INET };
+ inet_pton(AF_INET, ip, &a.sin_addr);
+ if (bind(s, (struct sockaddr *)&a, sizeof a) != 0 || listen(s, 8) != 0) { close(s); return -1; }
+ socklen_t l = sizeof a;
+ getsockname(s, (struct sockaddr *)&a, &l);
+ *port = ntohs(a.sin_port);
+ return s;
+}
+
+static uint32_t be(const char *ip) { struct in_addr a; inet_pton(AF_INET, ip, &a); return a.s_addr; }
+
+int main(void)
+{
+ uint32_t t[8];
+ uint16_t port = 0;
+
+ int s = listener("127.0.0.1", &port);
+ CHECK(s >= 0);
+ CHECK(pb_proc_listeners(be("127.0.0.1"), port, t, 8) == 1 && t[0] == (uint32_t)getpid());
+ CHECK(pb_proc_listeners(be("127.0.0.2"), port, t, 8) == 0); // bound to another address
+ CHECK(pb_proc_listeners(be("127.0.0.1"), (uint16_t)(port + 1), t, 8) == 0); // nothing on that port
+ CHECK(pb_proc_listeners(be("127.0.0.1"), 0, t, 8) == 0);
+ CHECK(pb_proc_listeners(be("127.0.0.1"), port, t, 0) == 0); // no room
+
+ // a connected (not listening) socket on the same port is not a listener
+ int c = socket(AF_INET, SOCK_STREAM, 0);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(port) };
+ a.sin_addr.s_addr = be("127.0.0.1");
+ CHECK(connect(c, (struct sockaddr *)&a, sizeof a) == 0);
+ CHECK(pb_proc_listeners(be("127.0.0.1"), port, t, 8) == 1);
+
+ // a wildcard listener answers for every local address
+ uint16_t wport = 0;
+ int w = listener("0.0.0.0", &wport);
+ CHECK(w >= 0 && pb_proc_listeners(be("127.0.0.1"), wport, t, 8) == 1 && t[0] == (uint32_t)getpid());
+ CHECK(pb_proc_listeners(be("127.0.0.5"), wport, t, 8) == 1);
+
+ // a child that inherits the socket is a listener too; both are reported, max limits the answer
+ pid_t kid = fork();
+ if (kid == 0) { sleep(5); _exit(0); }
+ usleep(100000);
+ size_t n = pb_proc_listeners(be("127.0.0.1"), port, t, 8);
+ CHECK(n == 2);
+ bool me = false, child = false;
+ for (size_t i = 0; i < n; i++) { me |= t[i] == (uint32_t)getpid(); child |= t[i] == (uint32_t)kid; }
+ CHECK(me && child);
+ CHECK(pb_proc_listeners(be("127.0.0.1"), port, t, 1) == 1);
+
+ // only the child holds it once we close our copy
+ close(s);
+ CHECK(pb_proc_listeners(be("127.0.0.1"), port, t, 8) == 1 && t[0] == (uint32_t)kid);
+ kill(kid, SIGKILL);
+ waitpid(kid, NULL, 0);
+ CHECK(pb_proc_listeners(be("127.0.0.1"), port, t, 8) == 0); // gone with the process
+
+ close(c);
+ close(w);
+
+ // local addresses
+ CHECK(pb_proc_is_local_ip(be("127.0.0.1")) && pb_proc_is_local_ip(be("127.200.3.4")));
+ CHECK(!pb_proc_is_local_ip(be("192.0.2.1")) && !pb_proc_is_local_ip(be("198.51.100.7")) && !pb_proc_is_local_ip(be("8.8.8.8")));
+ struct ifaddrs *list, *i;
+ int found = 0, ok = 0;
+ if (getifaddrs(&list) == 0) {
+ for (i = list; i; i = i->ifa_next)
+ if (i->ifa_addr && i->ifa_addr->sa_family == AF_INET) {
+ found++;
+ ok += pb_proc_is_local_ip(((struct sockaddr_in *)i->ifa_addr)->sin_addr.s_addr);
+ }
+ freeifaddrs(list);
+ }
+ CHECK(found > 0 && ok == found); // every configured address is local
+
+ printf("proc_test: %d checks, %d failed\n", checks, fails);
+ return fails != 0;
+}
diff --git a/Linux/src/tests/relay_test.c b/Linux/src/tests/relay_test.c
index 4304599..8a553c7 100644
--- a/Linux/src/tests/relay_test.c
+++ b/Linux/src/tests/relay_test.c
@@ -42,6 +42,7 @@ static bool g_px_used[16];
static uint32_t g_default_px = 1;
static struct pb_decision g_decision = { PB_ACT_DIRECT, 0 };
static atomic_int g_ev, g_ev_proxy, g_ev_direct, g_ev_block, g_decide_calls;
+static atomic_int g_loop_pid; // tests: non-zero = every flow counts as made by the proxy process itself
static char g_log[64][512];
static int g_log_n;
@@ -121,6 +122,12 @@ static uint32_t fnv(const uint8_t *p, size_t n)
while (n--) { h ^= *p++; h *= 16777619u; }
return h;
}
+int pb_core_is_proxy_process(uint32_t pid, uint32_t proxy_id)
+{
+ (void)pid; (void)proxy_id;
+ return atomic_load(&g_loop_pid) != 0;
+}
+
int pb_core_name_for(const struct pb_orig *o, char *out, size_t n)
{
(void)o; (void)out; (void)n;
@@ -259,7 +266,7 @@ struct srvcfg { bool auth; char user[64], pass[64]; bool leftover; bool silent;
struct srv { int lfd; uint16_t port; void (*h)(int, const struct srvcfg *); struct srvcfg cfg; };
struct hctx { int fd; struct srv *s; };
-static atomic_int g_assoc_count, g_s5_udp_dgrams;
+static atomic_int g_assoc_count, g_s5_udp_dgrams, g_socks_conns;
static int rd_full(int fd, void *b, size_t n)
{
@@ -359,6 +366,7 @@ static void socks_udp_assoc(int tfd)
static void socks_handler(int fd, const struct srvcfg *c)
{
+ atomic_fetch_add(&g_socks_conns, 1);
if (c->silent) { char b[16]; while (recv(fd, b, sizeof b, 0) > 0) {} return; }
uint8_t h[2], m[256];
if (rd_full(fd, h, 2) || h[0] != 5 || rd_full(fd, m, h[1])) return;
@@ -1296,6 +1304,112 @@ static void test_udp(void)
close(c);
}
+
+static int flows_of(struct pb_flow_info *out, int max, int udp)
+{
+ int n = pb_relay_flows(out, max), k = 0;
+ for (int i = 0; i < n; i++) if (out[i].udp == udp) out[k++] = out[i];
+ return k;
+}
+
+static bool wait_flow_count(int want, int udp, int ms)
+{
+ struct pb_flow_info f[64];
+ for (int t = 0; t < ms; t += 50) {
+ if (flows_of(f, 64, udp) == want) return true;
+ usleep(50000);
+ }
+ return false;
+}
+
+static void test_flows(void)
+{
+ struct pb_flow_info f[64];
+ CHECK(flows_of(f, 64, 0) == 0, "no flows listed before any connection");
+
+ int fds[3];
+ for (int i = 0; i < 3; i++) {
+ uint16_t src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_PROXY, 1);
+ fds[i] = relay_connect(src);
+ usleep(30000);
+ }
+ CHECK(wait_flow_count(3, 0, 3000), "three proxied TCP connections are listed");
+ int n = flows_of(f, 64, 0);
+ bool fields = n == 3;
+ for (int i = 0; i < n; i++) fields &= f[i].proxy_id == 1 && f[i].port == g_echo->port && f[i].family == AF_INET && f[i].id != 0;
+ CHECK(fields, "each flow has its proxy, destination port and id");
+ CHECK(n == 3 && f[0].age_ms <= f[1].age_ms && f[1].age_ms <= f[2].age_ms, "newest first");
+ CHECK(n == 3 && f[0].id != f[1].id && f[1].id != f[2].id, "ids are unique");
+
+ char buf[4096];
+ memset(buf, 'a', sizeof buf);
+ bool ok = fds[0] >= 0 && send(fds[0], buf, sizeof buf, MSG_NOSIGNAL) == (ssize_t)sizeof buf && rd_full(fds[0], buf, sizeof buf) == 0;
+ CHECK(ok, "data goes through the first connection");
+ usleep(100000);
+ n = flows_of(f, 64, 0);
+ uint64_t best_sent = 0, best_recv = 0;
+ for (int i = 0; i < n; i++) { if (f[i].sent > best_sent) best_sent = f[i].sent; if (f[i].recv > best_recv) best_recv = f[i].recv; }
+ CHECK(best_sent >= sizeof buf && best_recv >= sizeof buf, "byte counters follow the traffic (sent %llu, received %llu)",
+ (unsigned long long)best_sent, (unsigned long long)best_recv);
+
+ uint16_t src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_DIRECT, 0);
+ int direct = relay_connect(src);
+ usleep(100000);
+ CHECK(flows_of(f, 64, 0) == 3, "a direct connection is not a proxied flow");
+ if (direct >= 0) close(direct);
+
+ close(fds[1]);
+ CHECK(wait_flow_count(2, 0, 3000), "a closed connection leaves the list");
+ close(fds[0]); close(fds[2]);
+ CHECK(wait_flow_count(0, 0, 3000), "all closed: the list is empty");
+
+ // UDP flows are published once a second; earlier tests left flows behind, so start from a clean relay
+ pb_relay_stop();
+ CHECK(relay_up(300, 60, 0, 5) == 0, "relay restarted for the UDP part");
+ int c = udp_client();
+ set_flow("127.1.6.1", "127.0.0.1", g_uecho1, PB_ACT_PROXY, 1);
+ CHECK(udp_echo_ok(c, "127.1.6.1", "flow-one") && udp_echo_ok(c, "127.1.6.1", "flow-two"), "UDP traffic through the proxy");
+ CHECK(wait_flow_count(1, 1, 3000), "the UDP flow is listed");
+ n = flows_of(f, 64, 1);
+ CHECK(n == 1 && f[0].sent >= 16 && f[0].recv >= 16 && f[0].proxy_id == 1 && f[0].port == g_uecho1,
+ "UDP counters and destination (sent %llu, received %llu)", n ? (unsigned long long)f[0].sent : 0ULL, n ? (unsigned long long)f[0].recv : 0ULL);
+ set_flow("127.1.6.2", "127.0.0.1", g_uecho2, PB_ACT_DIRECT, 0);
+ int c2 = udp_client();
+ CHECK(udp_echo_ok(c2, "127.1.6.2", "direct"), "a direct UDP flow to the other echo server");
+ sleep(2);
+ n = flows_of(f, 64, 1);
+ bool direct_listed = false;
+ for (int i = 0; i < n; i++) direct_listed |= f[i].port == g_uecho2;
+ CHECK(!direct_listed, "direct UDP is never listed (%d UDP flows listed)", n);
+ close(c2);
+ close(c);
+
+ CHECK(pb_relay_flows(f, 0) == 0 && pb_relay_flows(NULL, 5) == 0, "degenerate arguments");
+}
+
+
+static void test_proxy_process_loop(void)
+{
+ // the process that serves the proxy must never be sent through it: the relay connects such flows directly
+ int before = g_socks_conns;
+ atomic_store(&g_loop_pid, 1);
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 1, 20000, false) == 20000, "TCP of the proxy's own process still works");
+ CHECK(g_socks_conns == before, "...without touching the proxy (%d new proxy connections)", (int)g_socks_conns - before);
+ set_decision((struct pb_decision){ PB_ACT_PROXY, 1 });
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_DECIDE, 0, 5000, false) == 5000 && g_socks_conns == before,
+ "also when the relay itself decided to use the proxy");
+ int a0 = g_assoc_count;
+ int c = udp_client();
+ set_flow("127.1.7.1", "127.0.0.1", g_uecho1, PB_ACT_PROXY, 1);
+ CHECK(udp_echo_ok(c, "127.1.7.1", "own-process") && g_assoc_count == a0, "UDP of the proxy's own process goes direct, no association (%d)", (int)g_assoc_count - a0);
+ close(c);
+ atomic_store(&g_loop_pid, 0);
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 1, 20000, false) == 20000 && g_socks_conns > before,
+ "any other process still goes through the proxy");
+}
+
static void test_udp_idle(void)
{
pb_relay_stop();
@@ -1786,6 +1900,8 @@ int main(void)
RUN(test_tcp_bad_proxy);
RUN(test_tcp_halfclose);
RUN(test_udp);
+ RUN(test_flows);
+ RUN(test_proxy_process_loop);
RUN(test_proxy_helper);
RUN(test_udp_odd);
RUN(test_hostname);
diff --git a/Linux/tests/api_live_test.c b/Linux/tests/api_live_test.c
index fb980b1..9664721 100644
--- a/Linux/tests/api_live_test.c
+++ b/Linux/tests/api_live_test.c
@@ -2,6 +2,7 @@
// Needs root and the fake proxies running (tests/api_live.sh starts them).
#define _GNU_SOURCE
#include <stdio.h>
+#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
@@ -96,6 +97,67 @@ int main(void)
sleep(1);
expect("rules and proxies survived Stop/Start", "192.0.2.5", "hello-from-C");
+ printf("== main switch and per-object options\n");
+ ProxyBridge_SetEnabled(false);
+ expect("paused: new connections are not redirected", "192.0.2.5", NULL);
+ ProxyBridge_SetEnabled(true);
+ expect("enabled again", "192.0.2.5", "hello-from-C");
+ check("SetProxySendDomain on a known proxy", ProxyBridge_SetProxySendDomain(pa2, false) && ProxyBridge_SetProxySendDomain(pa2, true));
+ check("SetRuleLocalhost on a known rule", ProxyBridge_SetRuleLocalhost(r1, true) && ProxyBridge_SetRuleLocalhost(r1, false));
+ expect("traffic still flows after changing the options", "192.0.2.5", "hello-from-C");
+ ProxyBridge_ClearConnectionLogs();
+ ProxyBridge_SetLogEveryConnection(true);
+ ProxyBridge_SetLogEveryConnection(false);
+
+ printf("== live connections\n");
+ {
+ FILE *f = fopen("/tmp/pb_api_live_hold.py", "w");
+ if (f) {
+ fputs("import socket, time\n"
+ "a = socket.socket(); a.connect(('192.0.2.30', 8888)); a.sendall(b'x' * 1000)\n"
+ "b = socket.socket(); b.connect(('192.0.2.31', 8888))\n"
+ "u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); u.connect(('192.0.2.32', 5300)); u.send(b'hello'); u.send(b'again')\n"
+ "print('ready', flush=True)\n"
+ "time.sleep(6)\n", f);
+ fclose(f);
+ }
+ uint32_t fr1 = ProxyBridge_AddRule("python3*", "192.0.2.30-192.0.2.31", "8888", RULE_PROTOCOL_TCP, RULE_ACTION_PROXY, pb2, err, sizeof err);
+ uint32_t fr2 = ProxyBridge_AddRule("python3*", "192.0.2.32", "5300", RULE_PROTOCOL_UDP, RULE_ACTION_PROXY, pb2, err, sizeof err);
+ check("rules for the holder process", fr1 && fr2);
+ FILE *kid = popen("python3 /tmp/pb_api_live_hold.py", "r");
+ char line[64] = "";
+ check("holder process started", kid && fgets(line, sizeof line, kid) && strncmp(line, "ready", 5) == 0);
+ sleep(2); /* UDP flows are published once a second */
+ ProxyBridgeFlow fl[PB_FLOWS_MAX];
+ uint32_t n = ProxyBridge_GetFlows(fl, PB_FLOWS_MAX);
+ int tcp = 0, udp = 0;
+ bool good = true;
+ uint64_t sent_max = 0;
+ for (uint32_t i = 0; i < n; i++) {
+ if (strncmp(fl[i].name, "python3", 7) != 0) continue;
+ good &= fl[i].proxy_id == pb2 && fl[i].age_ms < 10000 && fl[i].id != 0 && !fl[i].is_ipv6;
+ if (fl[i].is_udp) { udp++; good &= fl[i].port == 5300 && strcmp(fl[i].host, "192.0.2.32") == 0 && fl[i].sent >= 10; }
+ else { tcp++; good &= fl[i].port == 8888 && strncmp(fl[i].host, "192.0.2.3", 9) == 0; if (fl[i].sent > sent_max) sent_max = fl[i].sent; }
+ }
+ check("GetFlows lists the two held TCP connections and the UDP flow", tcp == 2 && udp == 1);
+ check("...with proxy, destination, process name and age", good);
+ check("...and the payload counters (sent >= 1000)", sent_max >= 1000);
+ check("GetFlows with max 1 returns one entry", ProxyBridge_GetFlows(fl, 1) == 1);
+ check("GetFlows with no buffer returns 0", ProxyBridge_GetFlows(NULL, 10) == 0 && ProxyBridge_GetFlows(fl, 0) == 0);
+ if (kid) pclose(kid); /* the holder exits: its connections close */
+ int left = 99;
+ for (int i = 0; i < 40 && left; i++) {
+ usleep(100000);
+ n = ProxyBridge_GetFlows(fl, PB_FLOWS_MAX);
+ left = 0;
+ for (uint32_t k = 0; k < n; k++) if (!fl[k].is_udp && strncmp(fl[k].name, "python3", 7) == 0) left++;
+ }
+ check("closed connections leave the list", left == 0);
+ ProxyBridge_DeleteRule(fr1);
+ ProxyBridge_DeleteRule(fr2);
+ unlink("/tmp/pb_api_live_hold.py");
+ }
+
printf("== proxy test helper\n");
char buf[512] = "";
check("TestProxy through a SOCKS5 proxy works", ProxyBridge_TestProxy(pb2, "192.0.2.77", 80, buf, sizeof buf) == 0);
diff --git a/Linux/tests/coverage.sh b/Linux/tests/coverage.sh
new file mode 100755
index 0000000..2b819c2
--- /dev/null
+++ b/Linux/tests/coverage.sh
@@ -0,0 +1,65 @@
+#!/bin/bash
+# Line coverage of the library, CLI, profile reader and GUI under the whole test suite (end-to-end suites + unit tests).
+# sudo Linux/tests/coverage.sh build instrumented copies, run everything, print the table
+# COV_MIN=88 sudo Linux/tests/coverage.sh also exit 1 if the library's line coverage is below 88 %
+# Linux/tests/coverage.sh unit only the root-free unit tests (no root, no kernel)
+# Linux/tests/coverage.sh report only print the table for the data already collected
+# Everything lives in $COV_DIR (default /tmp/pb-coverage), the list of lines nobody executed is in $COV_DIR/uncovered.txt.
+# The eBPF program runs in the kernel and cannot be measured; its behaviour is covered by the end-to-end suites.
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(dirname "$HERE")"
+COV_DIR="${COV_DIR:-/tmp/pb-coverage}"
+BUILD="$COV_DIR/build"; OUT="$COV_DIR/out"; UNIT="$COV_DIR/unit"
+BPFTOOL="${BPFTOOL:-bpftool}"; export BPFTOOL
+
+report() {
+ python3 -I "$HERE/coverage_report.py" --uncovered "$COV_DIR/uncovered.txt" ${COV_MIN:+--min-library "$COV_MIN"} "$COV_DIR"
+}
+
+unit_tests() {
+ rm -rf "$UNIT"; mkdir -p "$UNIT"
+ local cf="--coverage -O0 -g -D_GNU_SOURCE -std=gnu11 -w"
+ local gtk; gtk="$(pkg-config --cflags --libs gtk+-3.0 2> /dev/null)"
+ echo "== unit tests (instrumented)"
+ ( cd "$ROOT/src" &&
+ gcc $cf tests/rules_test.c pb_rules.c -o "$UNIT/rules_test" && "$UNIT/rules_test" &&
+ gcc $cf tests/dns_test.c pb_dns.c -o "$UNIT/dns_test" && "$UNIT/dns_test" &&
+ gcc $cf tests/proc_test.c pb_proc.c -o "$UNIT/proc_test" && "$UNIT/proc_test" &&
+ gcc $cf -I. tests/relay_test.c pb_relay.c -o "$UNIT/relay_test" -lpthread && "$UNIT/relay_test" ) 2>&1 | grep -E "FAIL|passed|RESULT" || true
+ ( cd "$ROOT/profile/tests" && gcc $cf profile_test.c ../pb_profile.c -o "$UNIT/profile_test" && "$UNIT/profile_test" ) 2>&1 | tail -1
+ if [ -n "$gtk" ]; then
+ ( cd "$ROOT/gui" &&
+ gcc $cf -I../src -I../profile -I. tests/config_test.c gui_config.c ../profile/pb_profile.c -o "$UNIT/config_test" $gtk && "$UNIT/config_test" &&
+ gcc $cf -I../src -I. tests/json_test.c gui_json.c -o "$UNIT/json_test" $gtk && "$UNIT/json_test" &&
+ gcc $cf -I. tests/events_test.c gui_events.c -o "$UNIT/events_test" -pthread && "$UNIT/events_test" ) 2>&1 | grep -E "FAIL|passed" || true
+ fi
+}
+
+case "${1:-}" in
+ report) report; exit $? ;;
+ unit) unit_tests; echo; report; exit $? ;;
+esac
+[ "$(id -u)" = 0 ] || { echo "run as root (or use: coverage.sh unit)"; exit 1; }
+
+rm -rf "$COV_DIR"; mkdir -p "$COV_DIR"
+PB_BUILD_DIR="$BUILD" AUDIT=0 OUTPUT_DIR="$OUT" EXTRA_CFLAGS="--coverage -O0 -g" EXTRA_LDFLAGS="--coverage" LTO=0 STRIP_FLAG= OPT=-O0 \
+ "$ROOT/build.sh" > "$COV_DIR/build.log" 2>&1 || { tail -20 "$COV_DIR/build.log"; exit 1; }
+
+export PB_DIR="$OUT"
+for t in e2e e2e_rules e2e_domains e2e_security e2e_profile e2e_parity e2e_faults e2e_udp e2e_rules_diff e2e_logging e2e_checker e2e_cli e2e_exempt e2e_lifecycle api_live e2e_openssh; do
+ [ -f "$HERE/$t.sh" ] || continue
+ echo "== $t"
+ timeout 900 bash "$HERE/$t.sh" 2>&1 | grep -E "FAIL|passed=" || true
+done
+echo "== churn"; timeout 300 bash "$HERE/churn.sh" 1500 2>&1 | grep -E "PASS|FAIL" || true
+if [ -x "$OUT/ProxyBridgeGUI" ] && command -v broadwayd > /dev/null; then
+ echo "== gui_headless"; timeout 300 bash "$HERE/gui_headless.sh" "$OUT/ProxyBridgeGUI" "$OUT" 2>&1 | grep -E "FAIL|passed=" || true
+fi
+if command -v broadwayd > /dev/null; then
+ echo "== gui_ui"
+ UI_BUILD_DIR="$COV_DIR/uibuild" EXTRA_CFLAGS="--coverage -O0" EXTRA_LDFLAGS="--coverage" timeout 600 bash "$HERE/gui_ui.sh" "$OUT" 2>&1 | grep -E "FAIL|checks" || true
+fi
+unit_tests
+echo
+report
diff --git a/Linux/tests/coverage_report.py b/Linux/tests/coverage_report.py
new file mode 100755
index 0000000..2c700a0
--- /dev/null
+++ b/Linux/tests/coverage_report.py
@@ -0,0 +1,75 @@
+#!/usr/bin/env python3
+"""Merges gcov data from several instrumented runs (end-to-end suites, unit tests) into one line-coverage table.
+
+usage: coverage_report.py [--uncovered FILE] [--min-library PCT] DIR [DIR...]
+Every *.gcda below the given directories is read with `gcov --json-format`; a line counts as covered when any run executed it.
+"""
+import json, os, subprocess, sys
+
+def main():
+ args = sys.argv[1:]
+ uncovered_out = min_lib = None
+ while args and args[0].startswith("--"):
+ if args[0] == "--uncovered": uncovered_out = args[1]; args = args[2:]
+ elif args[0] == "--min-library": min_lib = float(args[1]); args = args[2:]
+ else: sys.exit("unknown option " + args[0])
+ if not args: sys.exit(__doc__)
+
+ root = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
+ wanted = [os.path.join(root, d) + os.sep for d in ("src", "cli", "gui", "profile")]
+ lines = {} # path -> {line: covered}
+ funcs = {} # path -> {name: executed}
+ for top in args:
+ for dirpath, _, names in os.walk(top):
+ for n in names:
+ if not n.endswith(".gcda"): continue
+ gcda = os.path.join(dirpath, n)
+ p = subprocess.run(["gcov", "--json-format", "--stdout", "-o", dirpath, gcda], capture_output=True, text=True)
+ if p.returncode != 0 or not p.stdout.strip(): continue
+ for doc in p.stdout.splitlines():
+ if not doc.startswith("{"): continue
+ d = json.loads(doc)
+ cwd = d.get("current_working_directory", "")
+ for f in d["files"]:
+ path = os.path.realpath(os.path.join(cwd, f["file"]))
+ if not any(path.startswith(w) for w in wanted) or "/tests/" in path or path.endswith(".skel.h"): continue
+ L = lines.setdefault(path, {})
+ for ln in f["lines"]:
+ L[ln["line_number"]] = L.get(ln["line_number"], False) or ln["count"] > 0
+ F = funcs.setdefault(path, {})
+ for fn in f["functions"]:
+ F[fn["name"]] = F.get(fn["name"], False) or fn["execution_count"] > 0
+
+ rows, tot, cov, ltot, lcov = [], 0, 0, 0, 0
+ missing = []
+ for path in sorted(lines):
+ L = lines[path]
+ n, c = len(L), sum(1 for v in L.values() if v)
+ rel = os.path.relpath(path, root)
+ fn_n, fn_c = len(funcs[path]), sum(1 for v in funcs[path].values() if v)
+ rows.append((rel, n, c, fn_n, fn_c))
+ tot += n; cov += c
+ if rel.startswith(("src/", "profile/")): ltot += n; lcov += c
+ miss = sorted(k for k, v in L.items() if not v)
+ if miss: missing.append((rel, miss))
+ print("%-28s %8s %8s %7s %12s" % ("file", "lines", "covered", "%", "functions"))
+ for rel, n, c, fn_n, fn_c in rows:
+ print("%-28s %8d %8d %6.1f%% %7d/%-4d" % (rel, n, c, 100.0 * c / n if n else 100, fn_c, fn_n))
+ print("%-28s %8d %8d %6.1f%%" % ("TOTAL", tot, cov, 100.0 * cov / tot if tot else 0))
+ lib = 100.0 * lcov / ltot if ltot else 0
+ print("%-28s %8d %8d %6.1f%% (library + profile reader)" % ("LIBRARY", ltot, lcov, lib))
+
+ if uncovered_out:
+ with open(uncovered_out, "w") as out:
+ for rel, miss in missing:
+ ranges, start, prev = [], None, None
+ for k in miss + [None]:
+ if start is None: start = prev = k
+ elif k is not None and k == prev + 1: prev = k
+ else:
+ ranges.append(str(start) if start == prev else "%d-%d" % (start, prev)); start = prev = k
+ out.write("%s: %s\n" % (rel, ", ".join(ranges)))
+ if min_lib is not None and lib < min_lib:
+ print("library coverage %.1f%% is below the required %.1f%%" % (lib, min_lib)); sys.exit(1)
+
+main()
diff --git a/Linux/tests/e2e_checker.sh b/Linux/tests/e2e_checker.sh
new file mode 100755
index 0000000..1d89f49
--- /dev/null
+++ b/Linux/tests/e2e_checker.sh
@@ -0,0 +1,65 @@
+#!/bin/bash
+# `ProxyBridge --test-proxy host[:port]`: the multi-step proxy check, against working and broken proxies. Needs python3 (no root).
+# Linux/tests/e2e_checker.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+WORK="$(mktemp -d)"; PASS=0; FAIL=0
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+cleanup() { kill $F1 $F2 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+export LD_LIBRARY_PATH="$PB_DIR"
+python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & F1=$!
+python3 "$HERE/fault_proxies.py" "$WORK/fault.log" > /dev/null 2>&1 & F2=$!
+sleep 1.5
+
+# check <name> <expected exit> <needle>... -- <ProxyBridge args>
+check() {
+ local name="$1" want_rc="$2"; shift 2
+ local needles=()
+ while [ "$1" != "--" ]; do needles+=("$1"); shift; done; shift
+ local out; out=$(timeout 60 "$PB_DIR/ProxyBridge" "$@" 2>&1); local rc=$?
+ if [ "$rc" != "$want_rc" ]; then bad "$name (exit $rc, wanted $want_rc: ${out:0:300})"; return; fi
+ for n in "${needles[@]}"; do
+ if [[ "$out" != *"$n"* ]]; then bad "$name (output lacks '$n': ${out:0:400})"; return; fi
+ done
+ ok "$name"
+}
+
+echo "== working proxies"
+check "SOCKS5, every step passes" 0 "[1/5]" "OK: connected to 127.0.0.1" "OK: SOCKS5 tunnel established" "OK: HTTP/1.0 200 OK" \
+ "OK: min/avg/max" "OK: UDP ASSOCIATE accepted" "Result: PASSED" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy example.test:80
+check "SOCKS5 with a login" 0 "(login accepted)" "Result: PASSED" -- --proxy b=socks5://bob:[email protected]:19081 --test-proxy example.test:80
+check "HTTP CONNECT" 0 "OK: HTTP CONNECT tunnel established" "HTTP proxies cannot carry UDP" "Result: PASSED" -- --proxy c=http://127.0.0.1:19082 --test-proxy example.test:80
+check "HTTP CONNECT with a login" 0 "(login accepted)" "Result: PASSED" -- --proxy d=http://bob:[email protected]:19083 --test-proxy example.test:80
+check "another port skips the page load" 0 "skipped: only port 80" "Result: PASSED" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy example.test:8443
+check "default port is 80" 0 "Target: example.test:80" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy example.test
+check "IPv6 literal target" 0 "Target: ::1:80" "Result: PASSED" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy "[::1]:80"
+check "IPv4 target" 0 "Target: 198.51.100.7:80" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy 198.51.100.7:80
+check "every proxy is checked" 0 "Proxy: a" "Proxy: c" "Result: PASSED" -- --proxy a=socks5://127.0.0.1:19080 --proxy c=http://127.0.0.1:19082 --test-proxy example.test:80
+
+echo "== broken proxies are explained"
+check "wrong SOCKS5 password" 1 "FAILED: SOCKS5 authentication failed" "refused the tunnel or the login" -- --proxy b=socks5://bob:[email protected]:19081 --test-proxy example.test:80
+check "SOCKS5 login required but none given" 1 "rejected all auth methods" -- --proxy b=socks5://127.0.0.1:19081 --test-proxy example.test:80
+check "wrong HTTP password" 1 "authentication required (407)" -- --proxy d=http://bob:[email protected]:19083 --test-proxy example.test:80
+check "nothing is listening" 1 "FAILED:" "cannot be reached" -- --proxy dead=socks5://127.0.0.1:19999 --test-proxy example.test:80
+check "proxy host that does not resolve" 1 "cannot resolve" -- --proxy dead=socks5://no-such-host.invalid:1080 --test-proxy example.test:80
+check "tunnel refused by the proxy" 1 "connection refused by target" -- --proxy f=socks5://127.0.0.1:19100 --test-proxy 203.0.113.1:9005
+check "proxy that sends garbage" 1 "bad SOCKS5 reply version" -- --proxy f=socks5://127.0.0.1:19100 --test-proxy 203.0.113.1:9015
+check "proxy that never answers" 1 "timed out" -- --proxy f=socks5://127.0.0.1:19100 --test-proxy 203.0.113.1:9014
+check "HTTP proxy that refuses with 403" 1 "forbids this connection (403)" -- --proxy h=http://127.0.0.1:19110 --test-proxy 203.0.113.1:9021
+check "UDP refused is a warning, not a failure" 0 "WARNING: UDP ASSOCIATE refused" "command not supported" "Result: PASSED" -- --proxy n=socks5://127.0.0.1:19106 --test-proxy 203.0.113.1:80
+check "page load through a proxy that answers nothing is a warning" 0 "Result: PASSED" -- --proxy f=socks5://127.0.0.1:19100 --test-proxy 203.0.113.1:9016
+check "one bad proxy among good ones fails the run" 1 "Result: PASSED" "Result: FAILED" -- --proxy a=socks5://127.0.0.1:19080 --proxy dead=socks5://127.0.0.1:19999 --test-proxy example.test:80
+
+echo "== bad arguments"
+check "empty host" 2 "Invalid target" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy :80
+check "port out of range" 2 "Invalid target" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy example.test:99999
+check "port that is not a number" 2 "Invalid target" -- --proxy a=socks5://127.0.0.1:19080 --test-proxy example.test:http
+echo '{ "ProxyConfigs": [ { "Id": 1, "Name": "p1", "Type": "socks5", "Host": "127.0.0.1", "Port": "19080" } ] }' > "$WORK/p.pbprofile"; chmod 600 "$WORK/p.pbprofile"
+check "profile proxies are checked too (again, file present)" 0 "Proxy: p1" "Result: PASSED" -- --profile "$WORK/p.pbprofile" --test-proxy example.test:80
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ]
diff --git a/Linux/tests/e2e_cli.sh b/Linux/tests/e2e_cli.sh
new file mode 100755
index 0000000..cb7b0a1
--- /dev/null
+++ b/Linux/tests/e2e_cli.sh
@@ -0,0 +1,118 @@
+#!/bin/bash
+# Command line: every way to get the arguments wrong, and the ways to get them right, without ever starting the engine.
+# Works as any user (valid specs are checked through --test-proxy, which needs no root). Linux/tests/e2e_cli.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+WORK="$(mktemp -d)"; PASS=0; FAIL=0
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+trap 'rm -rf "$WORK"' EXIT
+export LD_LIBRARY_PATH="$PB_DIR"
+export PROXYBRIDGE_CONFIG_DIR="$WORK/cfg"
+
+# t <name> <exit code> <text the output must contain or '-'> -- args...
+t() {
+ local name="$1" want="$2" needle="$3"; shift 4
+ local out; out=$(timeout 30 "$PB_DIR/ProxyBridge" "$@" 2>&1); local rc=$?
+ if [ "$rc" != "$want" ]; then bad "$name (exit $rc, wanted $want: ${out:0:240})"; return; fi
+ if [ "$needle" != "-" ] && [[ "$out" != *"$needle"* ]]; then bad "$name (output lacks '$needle': ${out:0:240})"; return; fi
+ ok "$name"
+}
+# a proxy spec that parses is reported by --test-proxy ("Proxy: ..."); one that does not is an error before that
+parses() { t "$1" 1 "Proxy:" -- --proxy "$2" --test-proxy 127.0.0.1:9; }
+rejects() { t "$1" 1 "$3" -- --proxy "$2" --test-proxy 127.0.0.1:9; }
+
+echo "== help, version, small commands"
+t "--help" 0 "--proxy" -- --help
+t "-h" 0 "--rule" -- -h
+t "help documents the new options" 0 "--test-proxy" -- --help
+t "help documents profiles" 0 "--profile" -- --help
+t "--cleanup is a harmless no-op" 0 "Nothing to clean up" -- --cleanup
+t "--list-profiles without a profiles directory" 1 "No profiles directory" -- --list-profiles
+mkdir -p "$WORK/cfg/profiles"
+t "--list-profiles with an empty directory" 0 "No profiles" -- --list-profiles
+echo '{}' > "$WORK/cfg/profiles/A b.pbprofile"; echo '{}' > "$WORK/cfg/profiles/plain.pbprofile"; echo x > "$WORK/cfg/profiles/ignored.txt"
+out=$("$PB_DIR/ProxyBridge" --list-profiles 2>&1)
+[[ "$out" == *"A b"* && "$out" == *"plain"* && "$out" != *"ignored"* ]] && ok "--list-profiles lists exactly the .pbprofile files" || bad "list: $out"
+
+echo "== unknown and incomplete options"
+t "unknown option" 1 "Unknown option '--bogus'" -- --bogus
+t "stray argument" 1 "Unknown option 'stray'" -- stray
+t "--proxy without a value" 1 "Unknown option '--proxy'" -- --proxy
+t "--rule without a value" 1 "Unknown option '--rule'" -- --rule
+t "--profile without a value" 1 "Unknown option '--profile'" -- --profile
+t "--test-proxy without a value" 1 "Unknown option '--test-proxy'" -- --test-proxy
+t "--verbose without a value" 1 "Unknown option '--verbose'" -- --verbose
+t "--verbose out of range" 1 "Verbose level must be 0-3" -- --verbose 9
+t "--verbose negative" 1 "Verbose level must be 0-3" -- --verbose -1
+t "--dns-via-proxy with a bad value" 1 "Invalid value for --dns-via-proxy" -- --dns-via-proxy maybe
+t "--log-every-connection with a bad value" 1 "Invalid value for --log-every-connection" -- --log-every-connection 2
+
+echo "== proxy specs that are accepted"
+parses "socks5" "socks5://127.0.0.1:1"
+parses "http" "http://127.0.0.1:1"
+parses "uppercase scheme" "SOCKS5://127.0.0.1:1"
+parses "named" "work=socks5://127.0.0.1:1"
+parses "user and password" "socks5://bob:[email protected]:1"
+parses "password with a colon and an at sign" "socks5://bob:p:w@[email protected]:1"
+parses "legacy host:port:user:pass" "socks5://127.0.0.1:1:bob:pw"
+parses "IPv6 proxy address" "socks5://[::1]:1"
+parses "host name" "socks5://localhost:1"
+parses "dns=local" "socks5://127.0.0.1:1?dns=local"
+parses "dns=proxy" "socks5://127.0.0.1:1?dns=proxy"
+parses "port 65535" "socks5://127.0.0.1:65535"
+t "credentials are reported as present, never shown" 1 "with credentials" -- --proxy "a=socks5://bob:[email protected]:1" --test-proxy 127.0.0.1:9
+out=$("$PB_DIR/ProxyBridge" --proxy "a=socks5://bob:[email protected]:1" --test-proxy 127.0.0.1:9 2>&1)
+[[ "$out" != *topsecret* ]] && ok "the password never appears in the output" || bad "password printed"
+
+echo "== proxy specs that are refused"
+rejects "no scheme" "127.0.0.1:1080" "Expected [name=]type://host:port"
+rejects "unknown scheme" "ftp://127.0.0.1:1" "Invalid proxy type"
+rejects "missing port" "socks5://127.0.0.1" "missing port"
+rejects "port zero" "socks5://127.0.0.1:0" "Invalid proxy port"
+rejects "port too large" "socks5://127.0.0.1:65536" "Invalid proxy port"
+rejects "port not a number" "socks5://127.0.0.1:abc" "Invalid proxy port"
+rejects "empty host" "socks5://:1080" "host is empty"
+rejects "IPv6 without closing bracket" "socks5://[::1:1080" "Invalid IPv6 proxy host"
+rejects "unknown option after ?" "socks5://127.0.0.1:1?dns=maybe" "Unknown proxy option"
+t "too many proxies" 1 "Maximum 64 proxies" -- $(for i in $(seq 65); do printf -- '--proxy socks5://127.0.0.1:%d ' $((1000 + i)); done)
+
+echo "== rule specs that are refused"
+r() { t "$1" 1 "$3" -- --rule "$2"; }
+r "no colons at all" "curl" "Invalid rule format"
+r "too few fields" "curl:*:*:TCP" "Invalid rule format"
+r "bad protocol" "curl:*:*:ICMP:PROXY" "Invalid protocol"
+r "bad action" "curl:*:*:TCP:ALLOW" "Invalid action"
+r "empty protocol" "::::PROXY" "Invalid protocol"
+r "proxy on DIRECT" "curl:*:*:TCP:DIRECT=a" "only valid with PROXY"
+r "+localhost on BLOCK" "curl:*:*:TCP:BLOCK+localhost" "only valid with PROXY"
+r "+localhost on DIRECT" "curl:*:*:TCP:DIRECT+localhost" "only valid with PROXY"
+t "too many rules" 1 "Maximum 1024 rules" -- $(for i in $(seq 1025); do printf -- '--rule curl:*:*:TCP:DIRECT '; done)
+
+echo "== rule specs that parse (--test-proxy stops before the engine)"
+for spec in "curl:*:*:TCP:PROXY" "curl:10.0.0.0/8:80;443:UDP:DIRECT" "curl;wget:*:*:BOTH:BLOCK" "*:*.github.com:443:TCP:PROXY=a" \
+ "curl:2001:db8::1:80:TCP:PROXY" "curl:[::1]:80:TCP:PROXY" "curl:*:*:tcp:proxy" "curl:*:*:TCP:PROXY=a+localhost" "curl:*:*:TCP:PROXY+LOCALHOST"; do
+ out=$("$PB_DIR/ProxyBridge" --proxy a=socks5://127.0.0.1:1 --rule "$spec" --test-proxy 127.0.0.1:9 2>&1)
+ [[ "$out" == *"Proxy:"* && "$out" != *"Invalid"* ]] && ok "rule accepted: $spec" || bad "rule '$spec': ${out:0:200}"
+done
+
+echo "== target of --test-proxy"
+for tg in "example.test" "example.test:80" "198.51.100.1:8080" "[2001:db8::1]:443" "[2001:db8::1]"; do
+ out=$("$PB_DIR/ProxyBridge" --proxy a=socks5://127.0.0.1:1 --test-proxy "$tg" 2>&1)
+ [[ "$out" == *"Target:"* ]] && ok "target accepted: $tg" || bad "target '$tg': ${out:0:200}"
+done
+for tg in ":80" "host:0" "host:70000" "host:x" "[::1" "" ; do
+ out=$("$PB_DIR/ProxyBridge" --proxy a=socks5://127.0.0.1:1 --test-proxy "$tg" 2>&1); rc=$?
+ [ $rc = 2 ] && ok "target refused: '$tg'" || bad "target '$tg' (exit $rc: ${out:0:160})"
+done
+
+if [ "$(id -u)" != 0 ]; then
+ echo "== not root"
+ t "the engine needs root" 1 "requires root privileges" -- --proxy socks5://127.0.0.1:1
+ t "...even with rules" 1 "requires root privileges" -- --proxy socks5://127.0.0.1:1 --rule "curl:*:*:TCP:PROXY"
+fi
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ]
diff --git a/Linux/tests/e2e_exempt.sh b/Linux/tests/e2e_exempt.sh
new file mode 100755
index 0000000..8c44b96
--- /dev/null
+++ b/Linux/tests/e2e_exempt.sh
@@ -0,0 +1,68 @@
+#!/bin/bash
+# A rule such as "*:...:PROXY" also matches the proxy's own outbound connections. ProxyBridge exempts the processes that listen on a
+# configured local proxy address, so they cannot loop back through themselves. Needs root, python3, curl.
+# sudo Linux/tests/e2e_exempt.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+WORK="$(mktemp -d)"; PASS=0; FAIL=0; PB=""; FWD=""; WWW=""
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+cleanup() { kill $PB $FWD $WWW 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+export LD_LIBRARY_PATH="$PB_DIR"
+MYIP=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p' | head -1)
+[ -n "$MYIP" ] || { echo "no non-loopback address: skipped"; exit 0; }
+mkdir -p "$WORK/www"; echo "origin-ok" > "$WORK/www/index.html"
+python3 -m http.server 18399 --bind "$MYIP" --directory "$WORK/www" > /dev/null 2>&1 & WWW=$!
+sleep 1
+start_pb() { # proxy spec
+ stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 --proxy "fwd=$1" --rule "*:$MYIP:18399:TCP:PROXY=fwd" > "$WORK/pb.out" 2>&1 & PB=$!
+ for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; sleep 0.25; done; return 1
+}
+stop_pb() { kill -INT $PB 2>/dev/null; wait $PB 2>/dev/null; PB=""; }
+start_fwd() { : > "$WORK/fwd.log"; python3 "$HERE/fwd_socks5.py" "$1" "$2" "$WORK/fwd.log" > /dev/null 2>&1 & FWD=$!; sleep 1; }
+stop_fwd() { kill $FWD 2>/dev/null; wait $FWD 2>/dev/null; FWD=""; }
+fetch() { curl -s -m 4 "http://$MYIP:18399/"; }
+
+echo "== proxy on 127.0.0.1 running first"
+start_fwd 127.0.0.1 19090
+start_pb socks5://127.0.0.1:19090 || bad "start"
+out=$(fetch); [[ "$out" == *origin-ok* ]] && ok "request reaches the origin through the forwarding proxy" || bad "no answer (${out:0:100}): $(tail -3 "$WORK/fwd.log")"
+n=$(grep -c "FWD $MYIP:18399" "$WORK/fwd.log")
+[ "$n" = 1 ] && ok "the proxy was asked exactly once: its own connection to the origin was not looped back" || bad "proxy saw $n requests"
+grep -q "FAIL" "$WORK/fwd.log" && bad "forwarding failed: $(grep FAIL "$WORK/fwd.log")"
+stop_pb; stop_fwd
+
+echo "== proxy configured by host name"
+start_fwd 127.0.0.1 19090
+start_pb socks5://localhost:19090 || bad "start"
+out=$(fetch); [[ "$out" == *origin-ok* ]] && ok "proxy given as 'localhost'" || bad "localhost proxy: ${out:0:100}"
+stop_pb; stop_fwd
+
+echo "== proxy listening on the machine's own LAN address"
+start_fwd "$MYIP" 19091
+start_pb "socks5://$MYIP:19091" || bad "start"
+out=$(fetch); [[ "$out" == *origin-ok* ]] && ok "proxy bound to $MYIP is recognised as local" || bad "LAN proxy: ${out:0:100} $(tail -2 "$WORK/fwd.log")"
+stop_pb; stop_fwd
+
+echo "== proxy that starts after ProxyBridge"
+start_pb socks5://127.0.0.1:19090 || bad "start"
+out=$(fetch); [[ "$out" != *origin-ok* ]] && ok "nothing listens yet: the request fails (and does not hang)" || bad "unexpected success"
+start_fwd 127.0.0.1 19090
+good=no
+for _ in $(seq 40); do out=$(fetch); if [[ "$out" == *origin-ok* ]]; then good=yes; break; fi; sleep 0.5; done
+[ $good = yes ] && ok "once the proxy is up it is exempted and the request works" || bad "never worked after the proxy started"
+n=$(grep -c "FWD $MYIP:18399" "$WORK/fwd.log")
+[ "$n" -ge 1 ] && [ "$n" -le 2 ] && ok "no request storm from a loop ($n requests)" || bad "proxy saw $n requests"
+stop_pb; stop_fwd
+
+echo "== a proxy that is NOT local is not exempted"
+start_pb socks5://198.51.100.55:1080 || bad "start"
+out=$(fetch); [[ "$out" != *origin-ok* ]] && ok "traffic for the rule goes to the remote proxy (unreachable here), not around it" || bad "bypassed the rule"
+stop_pb
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ]
diff --git a/Linux/tests/e2e_faults.sh b/Linux/tests/e2e_faults.sh
new file mode 100755
index 0000000..cf77bbb
--- /dev/null
+++ b/Linux/tests/e2e_faults.sh
@@ -0,0 +1,113 @@
+#!/bin/bash
+# Fault tests: what a misbehaving SOCKS5 or HTTP proxy does to a connection, and what ProxyBridge reports.
+# Every case ends with the client seeing a clean close (never a hang) and a readable reason in the log. Needs root, python3.
+# sudo Linux/tests/e2e_faults.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+WORK="$(mktemp -d)"; FLOG="$WORK/fault.log"; : > "$FLOG"
+PASS=0; FAIL=0; DST=203.0.113.10
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+PB_PID=""
+cleanup() { [ -n "$PB_PID" ] && kill "$PB_PID" 2>/dev/null; kill $FAKE $FAKE2 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+export LD_LIBRARY_PATH="$PB_DIR"
+python3 "$HERE/fault_proxies.py" "$FLOG" > /dev/null 2>&1 & FAKE=$!
+python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & FAKE2=$!
+sleep 1
+
+start_pb() {
+ stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+ for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; kill -0 "$PB_PID" 2>/dev/null || return 1; sleep 0.25; done; return 1
+}
+stop_pb() { kill -INT "$PB_PID" 2>/dev/null; wait "$PB_PID" 2>/dev/null; PB_PID=""; }
+
+# case_ <name> <port> <mode> <result prefix> <log substring, client:<text the client must see>, or -> [timeout]
+case_() {
+ local name="$1" port="$2" mode="$3" want="$4" log="${5:--}" t="${6:-15}"
+ local before; before=$(wc -l < "$WORK/pb.out")
+ local res; res=$(timeout 40 python3 "$HERE/tcp_probe.py" $DST "$port" "$mode" "$t" 2>&1 | tail -1)
+ sleep 0.2
+ local newlog; newlog=$(tail -n +$((before + 1)) "$WORK/pb.out")
+ if [[ "$res" != "RESULT $want"* ]]; then bad "$name (client: $res)"; return; fi
+ if [[ "$log" == client:* ]]; then
+ [[ "$res" == *"${log#client:}"* ]] || { bad "$name (client lacks '${log#client:}': $res)"; return; }
+ elif [ "$log" != "-" ] && [[ "$newlog" != *"$log"* ]]; then bad "$name (log lacks '$log': ${newlog:0:240})"; return; fi
+ ok "$name"
+}
+
+echo "== SOCKS5 proxy: every failure code is reported, the client is closed cleanly"
+start_pb --proxy s=socks5://127.0.0.1:19100 --rule "python3*:$DST:9001-9032:TCP:PROXY=s" || { bad "start"; cat "$WORK/pb.out"; }
+case_ "REP 1 general failure" 9001 get CLOSED "general SOCKS server failure"
+case_ "REP 2 not allowed" 9002 get CLOSED "connection not allowed by ruleset"
+case_ "REP 3 network unreachable" 9003 get CLOSED "network unreachable"
+case_ "REP 4 host unreachable" 9004 get CLOSED "host unreachable"
+case_ "REP 5 connection refused" 9005 get CLOSED "connection refused by target"
+case_ "REP 6 TTL expired" 9006 get CLOSED "TTL expired"
+case_ "REP 7 command not supported" 9007 get CLOSED "command not supported"
+case_ "REP 8 address type" 9008 get CLOSED "address type not supported"
+case_ "BND is a domain name" 9010 get DATA "-"
+case_ "BND is IPv6" 9011 get DATA "-"
+case_ "BND of an unknown type" 9012 get CLOSED "unknown address type"
+case_ "proxy closes after request" 9013 get CLOSED "connection closed by peer during handshake"
+case_ "proxy closes after greeting" 9019 get CLOSED "connection closed by peer during handshake"
+case_ "SOCKS4-style reply" 9015 get CLOSED "bad SOCKS5 reply version"
+case_ "data then close" 9016 get DATA "-"
+case_ "4 MiB from the proxy arrive intact" 9017 pattern "PATTERN ok 4194304"
+case_ "2 MiB echoed both ways arrive intact" 9018 echo "ECHO ok 2097152"
+case_ "proxy that never answers times out" 9014 get CLOSED "timed out" 30
+echo "== the relay still works after all that"
+case_ "healthy connection afterwards" 9018 echo "ECHO ok 2097152"
+stop_pb
+
+echo "== SOCKS5 greeting and login variants"
+for spec in "19101:gssapi:unsupported auth method 0x01" "19102:none:rejected all auth methods"; do
+ IFS=: read -r p n want <<< "$spec"
+ start_pb --proxy "g=socks5://bob:[email protected]:$p" --rule "python3*:$DST:9018:TCP:PROXY=g" || bad "start"
+ case_ "$n" 9018 get CLOSED "$want"; stop_pb
+done
+start_pb --proxy g=socks5://bob:[email protected]:19103 --rule "python3*:$DST:9018:TCP:PROXY=g" || bad "start"
+case_ "login rejected" 9018 get CLOSED "authentication failed (wrong username or password)"; stop_pb
+start_pb --proxy g=socks5://127.0.0.1:19104 --rule "python3*:$DST:9018:TCP:PROXY=g" || bad "start"
+case_ "proxy wants a login, none configured" 9018 get CLOSED "requires username/password but none configured"; stop_pb
+LONGU=$(python3 -c "print('u'*255)"); LONGP=$(python3 -c "print('p'*255)")
+start_pb --proxy "g=socks5://$LONGU:[email protected]:19105" --rule "python3*:$DST:9018:TCP:PROXY=g" || bad "start"
+case_ "255-byte user and password are sent intact" 9018 echo "ECHO ok"; stop_pb
+grep -q "userlen 255 passlen 255" "$FLOG" && ok "the proxy received 255+255 bytes of credentials" || bad "credential lengths: $(grep AUTH "$FLOG" | tail -2)"
+
+echo "== HTTP CONNECT proxy: every refusal is reported"
+start_pb --proxy h=http://127.0.0.1:19110 --rule "python3*:$DST:9021-9032:TCP:PROXY=h" || { bad "start"; cat "$WORK/pb.out"; }
+case_ "403" 9021 get CLOSED "forbids this connection (403)"
+case_ "407 without credentials" 9022 get CLOSED "authentication required (407)"
+case_ "502" 9023 get CLOSED "upstream error (502)"
+case_ "503" 9024 get CLOSED "upstream error (503)"
+case_ "301" 9025 get CLOSED "refused CONNECT (301)"
+case_ "early data after the headers is delivered" 9026 get DATA "client:EARLY-DATA"
+case_ "reply that is not HTTP" 9027 get CLOSED "invalid HTTP proxy response"
+case_ "proxy closes without replying" 9028 get CLOSED "connection closed by peer during handshake"
+case_ "200 then close" 9030 get CLOSED "-"
+case_ "headers arriving in two segments" 9031 get DATA "client:echo:"
+case_ "oversized header block" 9032 get CLOSED "headers too large"
+case_ "proxy that never answers times out" 9029 get CLOSED "timed out" 30
+case_ "healthy connection afterwards" 9031 get DATA "client:echo:"
+stop_pb
+
+echo "== a stalled upstream cannot starve connections that use another one"
+start_pb --proxy s=socks5://127.0.0.1:19100 --proxy a=socks5://127.0.0.1:19080 \
+ --rule "python3*:$DST:9014:TCP:PROXY=s" --rule "python3*:203.0.113.11:80:TCP:PROXY=a" || { bad "start"; cat "$WORK/pb.out"; }
+HUNG=()
+for i in $(seq 60); do python3 "$HERE/tcp_probe.py" $DST 9014 get 14 > /dev/null 2>&1 & HUNG+=($!); done
+sleep 1.5
+t0=$(date +%s.%N)
+res=$(timeout 20 python3 "$HERE/tcp_probe.py" 203.0.113.11 80 get 10 2>&1 | tail -1)
+dt=$(awk -v a="$t0" -v b="$(date +%s.%N)" 'BEGIN{printf "%.1f", b - a}')
+if [[ "$res" == *"hello-from-A"* ]] && awk -v d="$dt" 'BEGIN{exit !(d < 3)}'; then ok "healthy proxy answered in ${dt}s while 60 connections waited on a stalled one"
+else bad "healthy connection was held up (${dt}s): $res"; fi
+wait "${HUNG[@]}" 2>/dev/null
+stop_pb
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ]
diff --git a/Linux/tests/e2e_lifecycle.sh b/Linux/tests/e2e_lifecycle.sh
new file mode 100755
index 0000000..453ee75
--- /dev/null
+++ b/Linux/tests/e2e_lifecycle.sh
@@ -0,0 +1,100 @@
+#!/bin/bash
+# Process lifecycle: however ProxyBridge ends, the machine's networking goes back to normal; relay ports already taken, rapid
+# restarts, two instances at once. Needs root, python3, bpftool. sudo Linux/tests/e2e_lifecycle.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+BPFTOOL="${BPFTOOL:-bpftool}"
+[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+WORK="$(mktemp -d)"; PASS=0; FAIL=0; PB=""; PB2=""; HOLD_T=""; HOLD_U=""; FAKE=""
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+cleanup() { kill -9 $PB $PB2 $FAKE $HOLD_T $HOLD_U 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+export LD_LIBRARY_PATH="$PB_DIR"
+python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & FAKE=$!
+sleep 1
+progs() { "$BPFTOOL" prog show 2>/dev/null | grep -c "pb_connect4"; }
+RULE="python3*:192.0.2.0/24:80:TCP:PROXY=a"
+start() { # outfile args... ; sets PB
+ local out="$1"; shift
+ stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 --proxy a=socks5://127.0.0.1:19080 --rule "$RULE" "$@" > "$out" 2>&1 & PB=$!
+ for _ in $(seq 40); do grep -q "ProxyBridge started" "$out" && return 0; kill -0 $PB 2>/dev/null || return 1; sleep 0.25; done; return 1
+}
+get() { python3 - "$1" <<'PY'
+import socket, sys
+s = socket.socket(); s.settimeout(3)
+try:
+ s.connect((sys.argv[1], 80)); s.sendall(b"GET / HTTP/1.0\r\n\r\n"); d = s.recv(500)
+ print("DATA" if b"hello-from" in d else "OTHER")
+except socket.timeout: print("TIMEOUT")
+except OSError as e: print("ERROR", e.errno)
+PY
+}
+
+echo "== however it ends, the datapath is gone"
+for sig in KILL TERM INT HUP; do
+ start "$WORK/pb.out" || { bad "SIG$sig: start"; continue; }
+ [ "$(progs)" -ge 1 ] && [ "$(get 192.0.2.7)" = DATA ] && ok "SIG$sig: running and redirecting" || bad "SIG$sig: not running properly ($(progs) programs)"
+ kill -$sig $PB 2>/dev/null; wait $PB 2>/dev/null; rc=$?
+ sleep 0.5
+ [ "$(progs)" = 0 ] && ok "SIG$sig: no BPF program is left" || bad "SIG$sig: $(progs) programs left behind"
+ [ "$(get 192.0.2.7)" != DATA ] && ok "SIG$sig: new connections are no longer redirected" || bad "SIG$sig: still redirected"
+ case $sig in INT|TERM) [ $rc = 0 ] && ok "SIG$sig: clean exit code" || bad "SIG$sig: exit code $rc";; esac
+done
+PB=""
+
+echo "== relay ports that are already taken"
+python3 - > /dev/null 2>&1 <<'PY' & HOLD_T=$!
+import socket, time
+t = socket.socket(); t.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); t.bind(("127.0.0.1", 24010)); t.listen(1)
+u = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); u.bind(("127.0.0.1", 24013))
+time.sleep(600)
+PY
+sleep 0.5
+start "$WORK/pb.out" || bad "start with busy ports"
+grep -q "relay tcp:24014 udp:24015" "$WORK/pb.out" && ok "the relay moved to free ports (24014/24015)" || bad "ports: $(grep 'relay tcp' "$WORK/pb.out")"
+[ "$(get 192.0.2.7)" = DATA ] && ok "traffic is relayed through the alternative ports" || bad "no traffic on alternative ports"
+kill -INT $PB; wait $PB 2>/dev/null; PB=""; kill $HOLD_T 2>/dev/null
+
+echo "== 20 quick restarts"
+good=0
+for i in $(seq 20); do
+ start "$WORK/pb.out" || continue
+ [ "$(get 192.0.2.7)" = DATA ] && good=$((good+1))
+ kill -INT $PB; wait $PB 2>/dev/null; PB=""
+done
+[ $good = 20 ] && ok "20 of 20 start/serve/stop cycles worked" || bad "only $good of 20 cycles worked"
+[ "$(progs)" = 0 ] && ok "nothing left behind" || bad "$(progs) programs left behind"
+
+echo "== two instances at once"
+start "$WORK/a.out" || bad "first instance"
+PA=$PB
+stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 --proxy a=socks5://127.0.0.1:19080 --rule "python3*:192.0.2.0/24:81:TCP:PROXY=a" > "$WORK/b.out" 2>&1 & PB2=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/b.out" && break; sleep 0.25; done
+grep -q "ProxyBridge started" "$WORK/b.out" && ok "a second instance starts next to the first" || bad "second instance: $(tail -3 "$WORK/b.out")"
+[ "$(get 192.0.2.7)" = DATA ] && ok "the first instance's rule still works" || bad "first instance broken by the second"
+kill -INT $PB2; wait $PB2 2>/dev/null; PB2=""
+sleep 0.5
+[ "$(get 192.0.2.7)" = DATA ] && ok "...and after the second one exits" || bad "first instance broken after the second exited"
+kill -INT $PA; wait $PA 2>/dev/null; PB=""
+[ "$(progs)" = 0 ] && ok "both gone: no programs left" || bad "$(progs) programs left"
+
+echo "== a program that is already running keeps its sockets"
+python3 - "$WORK" > "$WORK/long.out" 2>&1 <<'PY' & HOLD_U=$!
+import socket, sys, time
+s = socket.socket(); s.settimeout(30); s.connect(("127.0.0.1", 19080)) ; print("connected", flush=True)
+time.sleep(5)
+try:
+ s.sendall(b"\x05\x01\x00"); print("still usable", flush=True)
+except OSError as e:
+ print("broken", e, flush=True)
+PY
+sleep 1
+start "$WORK/pb.out"; kill -INT $PB; wait $PB 2>/dev/null; PB=""
+sleep 5
+grep -q "still usable" "$WORK/long.out" && ok "an existing connection survives ProxyBridge starting and stopping" || bad "existing connection: $(cat "$WORK/long.out")"
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ]
diff --git a/Linux/tests/e2e_logging.sh b/Linux/tests/e2e_logging.sh
new file mode 100755
index 0000000..a1bb5f2
--- /dev/null
+++ b/Linux/tests/e2e_logging.sh
@@ -0,0 +1,96 @@
+#!/bin/bash
+# Connection log: one line per (application, destination, action) by default, every connection with --log-every-connection,
+# and exactly one line per decision (the kernel and the relay used to report proxied flows twice). Needs root, python3.
+# sudo Linux/tests/e2e_logging.sh (PB_SLOW=1 also waits out the 30 s UDP re-log window)
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+WORK="$(mktemp -d)"; PASS=0; FAIL=0; PB_PID=""
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+cleanup() { [ -n "$PB_PID" ] && kill "$PB_PID" 2>/dev/null; kill $FAKE 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+export LD_LIBRARY_PATH="$PB_DIR"
+python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & FAKE=$!
+sleep 1
+
+start_pb() {
+ stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 2 --proxy a=socks5://127.0.0.1:19080 "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+ for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; sleep 0.25; done; return 1
+}
+stop_pb() { kill -INT "$PB_PID" 2>/dev/null; wait "$PB_PID" 2>/dev/null; PB_PID=""; }
+lines() { grep -c -- "$1" "$WORK/pb.out"; }
+connects() { python3 - "$@" <<'PY'
+import socket, sys
+ip, port, n = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
+for _ in range(n):
+ s = socket.socket(); s.setblocking(False); s.connect_ex((ip, port)); s.close()
+PY
+}
+udp_sends() { python3 - "$@" <<'PY'
+import socket, sys, time
+ip, port, n = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
+s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+for _ in range(n):
+ s.sendto(b"x", (ip, port)); time.sleep(0.05)
+PY
+}
+
+RULES=(--rule "python3*:198.51.100.50:80:TCP:PROXY=a" --rule "python3*:198.51.100.51:80:TCP:BLOCK" --rule "python3*:198.51.100.52:80:TCP:DIRECT"
+ --rule "python3*:198.51.100.60-198.51.100.63;198.51.100.70;198.51.100.71;198.51.100.72;198.51.100.73;198.51.100.74;198.51.100.75:80:TCP:PROXY=a"
+ --rule "python3*:198.51.100.80:5300:UDP:PROXY=a")
+
+echo "== default: repeats are collapsed"
+start_pb "${RULES[@]}" || bad "start"
+connects 198.51.100.50 80 6; connects 198.51.100.51 80 4; connects 198.51.100.52 80 4; sleep 1
+[ "$(lines '198.51.100.50:80 via SOCKS5')" = 1 ] && ok "6 proxied connections: one line (not two per connection)" || bad "proxied: $(lines '198.51.100.50:80 via')"
+[ "$(lines '198.51.100.51:80 via BLOCK')" = 1 ] && ok "4 blocked connections: one line" || bad "blocked: $(lines '198.51.100.51:80 via')"
+[ "$(lines '198.51.100.52:80 via DIRECT')" = 1 ] && ok "4 direct connections: one line" || bad "direct: $(lines '198.51.100.52:80 via')"
+connects 198.51.100.61 80 5; sleep 1.5
+[ "$(lines '198.51.100.61:80 via')" = 1 ] && ok "decided by the relay (long host list): one line" || bad "slow path: $(grep '198.51.100.61' "$WORK/pb.out")"
+udp_sends 198.51.100.80 5300 8; sleep 1
+[ "$(lines '198.51.100.80:5300 via')" = 1 ] && ok "a UDP flow of 8 datagrams: one line" || bad "udp: $(lines '198.51.100.80:5300 via')"
+stop_pb
+
+echo "== --log-every-connection true"
+start_pb --log-every-connection true "${RULES[@]}" || bad "start"
+connects 198.51.100.50 80 6; connects 198.51.100.51 80 4; connects 198.51.100.52 80 4; sleep 1
+[ "$(lines '198.51.100.50:80 via SOCKS5')" = 6 ] && ok "every proxied connection is listed, each exactly once" || bad "proxied: $(lines '198.51.100.50:80 via')"
+[ "$(lines '198.51.100.51:80 via BLOCK')" = 4 ] && ok "every blocked connection is listed" || bad "blocked: $(lines '198.51.100.51:80 via')"
+[ "$(lines '198.51.100.52:80 via DIRECT')" = 4 ] && ok "every direct connection is listed" || bad "direct: $(lines '198.51.100.52:80 via')"
+connects 198.51.100.61 80 5; sleep 2
+[ "$(lines '198.51.100.61:80 via')" = 5 ] && ok "decided by the relay: every connection, once" || bad "slow path: $(lines '198.51.100.61:80 via')"
+udp_sends 198.51.100.80 5300 8; sleep 1
+[ "$(lines '198.51.100.80:5300 via')" = 1 ] && ok "a busy UDP flow is still one line" || bad "udp: $(lines '198.51.100.80:5300 via')"
+if [ "${PB_SLOW:-0}" = 1 ]; then
+ sleep 31; udp_sends 198.51.100.80 5300 1; sleep 1
+ [ "$(lines '198.51.100.80:5300 via')" = 2 ] && ok "after 30 s of silence the UDP flow is listed again" || bad "udp relog: $(lines '198.51.100.80:5300 via')"
+fi
+stop_pb
+
+echo "== a profile can switch it on"
+cat > "$WORK/le.pbprofile" <<'JSON'
+{ "Version": "1.0", "LogEveryConnection": true,
+ "ProxyConfigs": [ { "Id": 1, "Name": "a", "Type": "socks5", "Host": "127.0.0.1", "Port": "19080" } ],
+ "ProxyRules": [ { "ProcessName": "python3*", "TargetHosts": "198.51.100.50", "TargetPorts": "80", "Protocol": "TCP", "Action": "PROXY", "ProxyConfigId": 1 } ] }
+JSON
+chmod 600 "$WORK/le.pbprofile"
+stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 2 --profile "$WORK/le.pbprofile" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
+connects 198.51.100.50 80 3; sleep 1
+[ "$(lines '198.51.100.50:80 via SOCKS5')" = 3 ] && ok "LogEveryConnection from the profile" || bad "profile: $(lines '198.51.100.50:80 via')"
+stop_pb
+start_pb --log-every-connection false "${RULES[@]}" || bad "start"
+stop_pb
+stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 2 --profile "$WORK/le.pbprofile" --log-every-connection false > "$WORK/pb.out" 2>&1 & PB_PID=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
+connects 198.51.100.50 80 3; sleep 1
+[ "$(lines '198.51.100.50:80 via SOCKS5')" = 1 ] && ok "the command line overrides the profile" || bad "override: $(lines '198.51.100.50:80 via')"
+stop_pb
+out=$("$PB_DIR/ProxyBridge" --log-every-connection maybe 2>&1); rc=$?
+[ $rc -ne 0 ] && [[ "$out" == *"Invalid value for --log-every-connection"* ]] && ok "bad value is refused" || bad "bad value (rc=$rc)"
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ]
diff --git a/Linux/tests/e2e_rules_diff.sh b/Linux/tests/e2e_rules_diff.sh
new file mode 100755
index 0000000..d353a42
--- /dev/null
+++ b/Linux/tests/e2e_rules_diff.sh
@@ -0,0 +1,14 @@
+#!/bin/bash
+# Differential rule test: random rule sets, random destinations, kernel fast path + slow path vs an independent reference.
+# sudo Linux/tests/e2e_rules_diff.sh [seeds] [probes per protocol]
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+[ -x "$PB_DIR/ProxyBridge" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+WORK="$(mktemp -d)"
+ip route add unreachable 198.18.0.0/15 2>/dev/null; ROUTE=$?
+trap 'kill $FAKE 2>/dev/null; wait 2>/dev/null; [ "$ROUTE" = 0 ] && ip route del unreachable 198.18.0.0/15 2>/dev/null; rm -rf "$WORK"' EXIT
+python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & FAKE=$!
+sleep 1
+python3 "$HERE/rules_diff.py" "$PB_DIR" "${1:-8}" "${2:-300}"
diff --git a/Linux/tests/e2e_udp.sh b/Linux/tests/e2e_udp.sh
new file mode 100755
index 0000000..e0168ba
--- /dev/null
+++ b/Linux/tests/e2e_udp.sh
@@ -0,0 +1,91 @@
+#!/bin/bash
+# UDP through SOCKS5 UDP ASSOCIATE: a normal proxy, a pile of misbehaving ones, and every rule outcome (proxy, direct, block, HTTP proxy).
+# Needs root, python3. sudo Linux/tests/e2e_udp.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+WORK="$(mktemp -d)"; : > "$WORK/fault.log"; : > "$WORK/proxy.log"
+PASS=0; FAIL=0
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+PB_PID=""; ECHO_PID=""
+cleanup() { [ -n "$PB_PID" ] && kill "$PB_PID" 2>/dev/null; kill $F1 $F2 $ECHO_PID 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+export LD_LIBRARY_PATH="$PB_DIR"
+python3 "$HERE/fault_proxies.py" "$WORK/fault.log" > /dev/null 2>&1 & F1=$!
+python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & F2=$!
+MYIP=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p' | head -1); MYIP=${MYIP:-127.0.0.1}
+python3 - "$MYIP" > /dev/null 2>&1 <<'PY' & ECHO_PID=$!
+import socket, sys
+s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.bind((sys.argv[1], 5301))
+while True:
+ d, a = s.recvfrom(65535); s.sendto(b"DIRECT-ECHO " + d, a)
+PY
+sleep 1.5
+
+probe() { timeout 60 python3 "$HERE/udp_probe.py" "$@" 2>&1; }
+want() { # name, output, expected substring
+ if [[ "$2" == *"$3"* ]]; then ok "$1"; else bad "$1 (got: ${2:0:300})"; fi; }
+nowant() { if [[ "$2" != *"$3"* ]]; then ok "$1"; else bad "$1 (got: ${2:0:300})"; fi; }
+logged() { grep -q "$2" "$WORK/pb.out" && ok "$1" || bad "$1 (log lacks '$2')"; }
+
+stdbuf -oL "$PB_DIR/ProxyBridge" --verbose 1 \
+ --proxy a=socks5://127.0.0.1:19080 --proxy c=http://127.0.0.1:19082 \
+ --proxy u0=socks5://127.0.0.1:19120 --proxy u1=socks5://127.0.0.1:19121 --proxy u2=socks5://127.0.0.1:19122 --proxy u3=socks5://127.0.0.1:19123 \
+ --proxy u4=socks5://127.0.0.1:19124 --proxy u5=socks5://127.0.0.1:19125 --proxy u6=socks5://127.0.0.1:19126 --proxy u7=socks5://127.0.0.1:19127 \
+ --rule "python3*:198.51.100.20:5300:UDP:PROXY=u0" --rule "python3*:198.51.100.21:5300:UDP:PROXY=u1" \
+ --rule "python3*:198.51.100.22:5300:UDP:PROXY=u2" --rule "python3*:198.51.100.23:5300:UDP:PROXY=u3" \
+ --rule "python3*:198.51.100.24:5300:UDP:PROXY=u4" --rule "python3*:198.51.100.25:5300:UDP:PROXY=u5" \
+ --rule "python3*:198.51.100.26:5300:UDP:PROXY=u6" --rule "python3*:198.51.100.27:5300:UDP:PROXY=u7" \
+ --rule "python3*:198.51.100.100:5300:UDP:BLOCK" --rule "python3*:198.51.100.110:5300:UDP:PROXY=c" \
+ --rule "python3*:$MYIP:5301:UDP:DIRECT" --rule "python3*:198.51.100.30-198.51.100.99:5300:UDP:PROXY=a" \
+ --rule "python3*:2001:db8::/32:*:UDP:PROXY=a" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && break; sleep 0.25; done
+grep -q "ProxyBridge started" "$WORK/pb.out" || { echo "ProxyBridge failed to start"; cat "$WORK/pb.out"; exit 1; }
+sleep 1
+
+echo "== a normal SOCKS5 proxy"
+out=$(probe echo 198.51.100.31 5300 hello); want "unconnected socket: reply comes from the destination" "$out" "RESULT REPLY 198.51.100.31:5300 UDP-A 198.51.100.31:5300 hello"
+out=$(probe multi 198.51.100.40 5 5300); want "one socket, five destinations" "$out" "RESULT ok every destination answered from its own address"
+nowant "...with the right replies" "$out" "RESULT BAD"
+out=$(probe connected 198.51.100.41 5300); want "connected socket" "$out" "RESULT ok connected socket gets both replies"
+want "getpeername reports the real destination" "$out" "RESULT ok getpeername shows the real destination"
+out=$(probe many 198.51.100.42 5300 150); want "150 sockets at once" "$out" "RESULT ok 150 sockets, each got its own reply"
+out=$(probe sizes 198.51.100.43 5300); want "datagram sizes 1..60000" "$out" "RESULT ok payloads of 1..60000 bytes survive the round trip"
+out=$(probe boundport 198.51.100.44 5300); want "reply returns to the bound local port" "$out" "RESULT ok reply arrives on the bound port"
+out=$(probe v6connected 2001:db8::7 5300); want "connected IPv6 destination through the proxy" "$out" "RESULT ok connected IPv6 UDP goes through the proxy"
+out=$(probe v6unconnected 2001:db8::8 5300); want "unconnected IPv6 sendto fails closed" "$out" "RESULT ok unconnected IPv6 sendto fails closed"
+nowant "...and nothing was sent in the clear or through the proxy" "$(cat "$WORK/proxy.log")" "2001:db8::8"
+
+echo "== rule outcomes"
+out=$(probe blocked 198.51.100.100 5300); want "BLOCK" "$out" "RESULT ok BLOCK refuses sendto"
+out=$(probe echo $MYIP 5301 direct); want "DIRECT bypasses every proxy" "$out" "DIRECT-ECHO direct"
+out=$(probe echo 198.51.100.110 5300 http 2); want "UDP through an HTTP proxy gets no reply" "$out" "RESULT NOREPLY"
+logged "...and the log says why" "cannot carry UDP"
+
+echo "== misbehaving SOCKS5 UDP proxies"
+out=$(probe echo 198.51.100.20 5300 hello); want "BND.ADDR 0.0.0.0: the proxy's own address is used" "$out" "UDP-U 198.51.100.20:5300 hello"
+out=$(probe echo 198.51.100.21 5300 hello 2); want "BND is a domain name: refused, no hang" "$out" "RESULT NOREPLY"
+logged "...with a readable reason" "UDP relay address is a domain name"
+out=$(probe echo 198.51.100.22 5300 hello); want "BND is an IPv6 address" "$out" "UDP-U 198.51.100.22:5300 hello"
+out=$(probe echo 198.51.100.23 5300 SPOOF-1 2); want "reply from a stranger is dropped" "$out" "RESULT NOREPLY"
+out=$(probe echo 198.51.100.23 5300 plain); want "...and the proxy's own replies still work" "$out" "UDP-U 198.51.100.23:5300 plain"
+out=$(probe echo 198.51.100.24 5300 FRAG 2); want "fragmented reply (FRAG != 0) is dropped" "$out" "RESULT NOREPLY"
+out=$(probe echo 198.51.100.24 5300 SHORT 2); want "truncated reply is dropped" "$out" "RESULT NOREPLY"
+out=$(probe echo 198.51.100.24 5300 DOM); want "reply with a domain address is mapped to its flow" "$out" "RESULT REPLY 198.51.100.24:5300 UDP-U 198.51.100.24:5300 DOM"
+out=$(probe echo 198.51.100.24 5300 ZERO); want "empty datagram is delivered" "$out" "RESULT REPLY 198.51.100.24:5300 "
+out=$(probe echo 198.51.100.24 5300 OK); want "relay is healthy after malformed replies" "$out" "UDP-U 198.51.100.24:5300 OK"
+out=$(probe echo 198.51.100.25 5300 hello 2); want "association refused: no reply, no hang" "$out" "RESULT NOREPLY"
+logged "...with the proxy's reason" "command not supported"
+out=$(probe echo 198.51.100.27 5300 hello 2); want "proxy that swallows datagrams: no reply, no hang" "$out" "RESULT NOREPLY"
+out=$(probe seq 198.51.100.26 5300 one two three)
+want "control connection dropped by the proxy: a new association is made" "$out" "UDP-U 198.51.100.26:5300 three"
+nowant "...every datagram was answered" "$out" "NOREPLY"
+logged "...and logged" "control connection closed"
+out=$(probe echo 198.51.100.31 5300 after); want "the relay is still healthy at the end" "$out" "UDP-A 198.51.100.31:5300 after"
+
+kill -INT "$PB_PID" 2>/dev/null; wait "$PB_PID" 2>/dev/null; PB_PID=""
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ]
diff --git a/Linux/tests/fault_proxies.py b/Linux/tests/fault_proxies.py
new file mode 100755
index 0000000..7a008a9
--- /dev/null
+++ b/Linux/tests/fault_proxies.py
@@ -0,0 +1,262 @@
+#!/usr/bin/env python3
+"""Misbehaving upstream proxies for ProxyBridge's fault tests (never use these for anything else).
+
+usage: fault_proxies.py <logfile> listens on 127.0.0.1; the behaviour is chosen by the port that is asked for.
+
+SOCKS5 19100 - by the requested destination port:
+ 9001-9008 reply code 1-8 9010 BND is a domain name 9011 BND is IPv6 9012 BND of unknown type
+ 9013 close after the request 9014 never answers (stall) 9015 SOCKS4-style reply 9016 data, then close
+ 9017 sends 4 MiB of a known pattern 9018 echo server 9019 close right after the greeting
+SOCKS5 greeting variants: 19101 method 0x01 (GSSAPI) 19102 no acceptable method 19103 asks for a login and rejects every one
+ 19104 asks for a login (clients without credentials) 19105 accepts any login, then works as 19100
+ 19106 works for CONNECT but refuses UDP ASSOCIATE
+HTTP CONNECT 19110 - by the requested destination port:
+ 9021 403 9022 407 9023 502 9024 503 9025 301 9026 200 plus early data 9027 not HTTP 9028 close, no reply
+ 9029 stall 9030 200 then close 9031 headers in two segments 9032 oversized header block
+SOCKS5 UDP ASSOCIATE 19120-19127 (control ports, each relays echoes "UDP-U <dst> <payload>"):
+ 19120 BND.ADDR 0.0.0.0 19121 BND is a domain 19122 BND is ::1 19123 SPOOF* replies come from a stranger
+ 19124 malformed replies by payload prefix (FRAG, DOM, SHORT, ZERO, OK) 19125 refuses the association
+ 19126 closes the control connection after the first datagram 19127 swallows datagrams
+"""
+import asyncio, socket, struct, sys
+
+LOG = open(sys.argv[1], "a", buffering=1)
+PATTERN = bytes((i * 7 + 3) & 0xFF for i in range(65536))
+PATTERN_TOTAL = 4 << 20
+
+
+def log(*a):
+ LOG.write(" ".join(str(x) for x in a) + "\n")
+
+
+async def read_addr(reader):
+ atyp = (await reader.readexactly(1))[0]
+ if atyp == 1:
+ raw = await reader.readexactly(4)
+ elif atyp == 4:
+ raw = await reader.readexactly(16)
+ else:
+ n = (await reader.readexactly(1))[0]
+ raw = await reader.readexactly(n)
+ return atyp, raw, struct.unpack("!H", await reader.readexactly(2))[0]
+
+
+def reply(rep, atyp=1, addr=b"\0\0\0\0", port=0):
+ if atyp == 3:
+ return bytes([5, rep, 0, 3, len(addr)]) + addr + struct.pack("!H", port)
+ return bytes([5, rep, 0, atyp]) + addr + struct.pack("!H", port)
+
+
+async def serve_socks(reader, writer, greeting):
+ try:
+ ver, n = await reader.readexactly(2)
+ methods = await reader.readexactly(n)
+ if greeting == "gssapi":
+ writer.write(b"\x05\x01"); await writer.drain(); return
+ if greeting == "none":
+ writer.write(b"\x05\xff"); await writer.drain(); return
+ if greeting in ("reject", "login", "any"):
+ writer.write(b"\x05\x02"); await writer.drain()
+ v, ul = await reader.readexactly(2)
+ await reader.readexactly(ul)
+ pl = (await reader.readexactly(1))[0]
+ await reader.readexactly(pl)
+ ok = greeting == "any"
+ writer.write(b"\x01" + (b"\x00" if ok else b"\x01")); await writer.drain()
+ log("AUTH", greeting, "accepted" if ok else "rejected", "userlen", ul, "passlen", pl)
+ if not ok:
+ return
+ else:
+ writer.write(b"\x05\x00"); await writer.drain()
+ try:
+ _v, cmd, _r = await reader.readexactly(3)
+ except asyncio.IncompleteReadError:
+ return # 9019: the client gave up or we are meant to close here
+ atyp, raw, port = await read_addr(reader)
+ log("TCP" if cmd == 1 else "CMD%d" % cmd, port, "atyp", atyp)
+ if greeting == "noudp" and cmd != 1:
+ writer.write(reply(7)); await writer.drain(); return
+ if port == 9019:
+ return
+ if 9001 <= port <= 9008:
+ writer.write(reply(port - 9000)); await writer.drain(); return
+ if port == 9013:
+ return
+ if port == 9014:
+ await asyncio.sleep(60); return
+ if port == 9015:
+ writer.write(b"\x04\x5a\0\0\0\0\0\0"); await writer.drain(); return
+ if port == 9010:
+ writer.write(reply(0, 3, b"bnd.example.test", 1080))
+ elif port == 9011:
+ writer.write(reply(0, 4, b"\0" * 15 + b"\x01", 1080))
+ elif port == 9012:
+ writer.write(b"\x05\x00\x00\x09junkjunk"); await writer.drain(); return
+ else:
+ writer.write(reply(0, 1, b"\x7f\0\0\x01", 0))
+ await writer.drain()
+ if port == 9016:
+ writer.write(b"partial"); await writer.drain(); return
+ if port == 9017:
+ sent = 0
+ while sent < PATTERN_TOTAL:
+ writer.write(PATTERN); sent += len(PATTERN)
+ await writer.drain()
+ return
+ if port == 9018:
+ while True:
+ d = await reader.read(65536)
+ if not d:
+ return
+ writer.write(d); await writer.drain()
+ data = await reader.read(65536)
+ writer.write(b"HTTP/1.0 200 OK\r\nContent-Length: 3\r\n\r\nok\n" if data.startswith(b"GET") else b"echo:" + data)
+ await writer.drain()
+ except Exception as e:
+ log("ERR", repr(e))
+ finally:
+ writer.close()
+
+
+async def serve_http(reader, writer):
+ try:
+ head = await reader.readuntil(b"\r\n\r\n")
+ first = head.split(b"\r\n")[0].decode()
+ port = int(first.split()[1].rsplit(":", 1)[1])
+ log("HTTP", port)
+ statuses = {9021: b"403 Forbidden", 9022: b"407 Proxy Authentication Required", 9023: b"502 Bad Gateway",
+ 9024: b"503 Service Unavailable", 9025: b"301 Moved Permanently"}
+ if port in statuses:
+ writer.write(b"HTTP/1.1 " + statuses[port] + b"\r\nContent-Length: 4\r\n\r\nnope"); await writer.drain(); return
+ if port == 9027:
+ writer.write(b"NOTHTTP garbage\r\n\r\n"); await writer.drain(); return
+ if port == 9028:
+ return
+ if port == 9029:
+ await asyncio.sleep(60); return
+ if port == 9030:
+ writer.write(b"HTTP/1.1 200 OK\r\n\r\n"); await writer.drain(); return
+ if port == 9031:
+ writer.write(b"HTTP/1.1 200 Connection"); await writer.drain()
+ await asyncio.sleep(0.3)
+ writer.write(b" established\r\n\r\n"); await writer.drain()
+ elif port == 9032:
+ writer.write(b"HTTP/1.1 200 OK\r\n" + b"X-Pad: " + b"a" * 20000 + b"\r\n\r\n"); await writer.drain(); return
+ elif port == 9026:
+ writer.write(b"HTTP/1.1 200 OK\r\n\r\nEARLY-DATA"); await writer.drain()
+ else:
+ writer.write(b"HTTP/1.1 200 OK\r\n\r\n"); await writer.drain()
+ data = await asyncio.wait_for(reader.read(65536), 5)
+ writer.write(b"echo:" + data); await writer.drain()
+ except Exception as e:
+ log("ERR", repr(e))
+ finally:
+ writer.close()
+
+
+class UdpRelay(asyncio.DatagramProtocol):
+ def __init__(self, mode):
+ self.mode = mode
+
+ def connection_made(self, transport):
+ self.t = transport
+ self.stranger = None
+
+ def datagram_received(self, data, addr):
+ if len(data) < 10 or data[2] != 0:
+ return
+ atyp = data[3]
+ if atyp == 1:
+ raw, off = data[4:8], 8
+ elif atyp == 4:
+ raw, off = data[4:20], 20
+ else:
+ n = data[4]; raw, off = data[5:5 + n], 5 + n
+ port = struct.unpack("!H", data[off:off + 2])[0]
+ payload = data[off + 2:]
+ if atyp == 1:
+ dst = socket.inet_ntoa(raw) + ":" + str(port)
+ elif atyp == 4:
+ dst = socket.inet_ntop(socket.AF_INET6, raw) + ":" + str(port)
+ else:
+ dst = raw.decode() + ":" + str(port)
+ log("UDP", self.mode, dst, len(payload))
+ if self.mode == "swallow":
+ return
+ head = data[:off + 2]
+ echo = f"UDP-U {dst} ".encode() + payload
+ if self.mode == "spoof" and payload.startswith(b"SPOOF"):
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ s.bind(("127.0.0.1", 0)); s.sendto(head + echo, addr); s.close()
+ return
+ if self.mode == "malformed":
+ if payload.startswith(b"FRAG"):
+ self.t.sendto(b"\0\0\x01" + head[3:] + echo, addr); return
+ if payload.startswith(b"DOM"):
+ name = b"host.example"
+ self.t.sendto(b"\0\0\0\x03" + bytes([len(name)]) + name + struct.pack("!H", port) + echo, addr); return
+ if payload.startswith(b"SHORT"):
+ self.t.sendto(b"\0\0\0", addr); return
+ if payload.startswith(b"ZERO"):
+ self.t.sendto(head, addr); return
+ self.t.sendto(head + echo, addr)
+ if self.mode == "dropctl":
+ asyncio.get_running_loop().call_later(0.3, self.close_control)
+
+ close_control = lambda self: None
+
+
+def udp_control(mode, bind_ip="127.0.0.1"):
+ async def handle(reader, writer):
+ try:
+ ver, n = await reader.readexactly(2)
+ await reader.readexactly(n)
+ writer.write(b"\x05\x00"); await writer.drain()
+ _v, cmd, _r = await reader.readexactly(3)
+ await read_addr(reader)
+ if mode == "refuse" or cmd != 3:
+ writer.write(reply(7)); await writer.drain(); return
+ loop = asyncio.get_running_loop()
+ relay_mode = {"dropctl": "dropctl", "spoof": "spoof", "malformed": "malformed", "swallow": "swallow"}.get(mode, "echo")
+ fam = socket.AF_INET6 if mode == "ipv6" else socket.AF_INET
+ sock = socket.socket(fam, socket.SOCK_DGRAM)
+ sock.bind(("::1" if mode == "ipv6" else "127.0.0.1", 0))
+ transport, proto = await loop.create_datagram_endpoint(lambda: UdpRelay(relay_mode), sock=sock)
+ port = sock.getsockname()[1]
+ if mode == "dropctl":
+ proto.close_control = lambda: writer.close()
+ if mode == "unspec":
+ writer.write(reply(0, 1, b"\0\0\0\0", port))
+ elif mode == "domain":
+ writer.write(reply(0, 3, b"relay.example.test", port))
+ elif mode == "ipv6":
+ writer.write(reply(0, 4, b"\0" * 15 + b"\x01", port))
+ else:
+ writer.write(reply(0, 1, b"\x7f\0\0\x01", port))
+ await writer.drain()
+ log("ASSOC", mode)
+ try:
+ while await reader.read(1024):
+ pass
+ finally:
+ transport.close()
+ except Exception as e:
+ log("ERR", repr(e))
+ finally:
+ writer.close()
+ return handle
+
+
+async def main():
+ def socks(greeting):
+ return lambda r, w: serve_socks(r, w, greeting)
+ for port, g in ((19100, "ok"), (19101, "gssapi"), (19102, "none"), (19103, "reject"), (19104, "login"), (19105, "any"), (19106, "noudp")):
+ await asyncio.start_server(socks(g), "127.0.0.1", port)
+ await asyncio.start_server(serve_http, "127.0.0.1", 19110)
+ for port, mode in ((19120, "unspec"), (19121, "domain"), (19122, "ipv6"), (19123, "spoof"), (19124, "malformed"),
+ (19125, "refuse"), (19126, "dropctl"), (19127, "swallow")):
+ await asyncio.start_server(udp_control(mode), "127.0.0.1", port)
+ print("fault proxies up", flush=True)
+ await asyncio.Event().wait()
+
+asyncio.run(main())
diff --git a/Linux/tests/fwd_socks5.py b/Linux/tests/fwd_socks5.py
new file mode 100755
index 0000000..863ae90
--- /dev/null
+++ b/Linux/tests/fwd_socks5.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python3
+"""A real (forwarding) SOCKS5 CONNECT proxy for the exemption tests: it opens the connection the client asks for.
+usage: fwd_socks5.py <bind-ip> <port> <logfile>"""
+import asyncio, ipaddress, struct, sys
+
+LOG = open(sys.argv[3], "a", buffering=1)
+
+
+async def pipe(r, w):
+ try:
+ while True:
+ d = await r.read(65536)
+ if not d:
+ break
+ w.write(d)
+ await w.drain()
+ except Exception:
+ pass
+ try:
+ w.close()
+ except Exception:
+ pass
+
+
+async def handle(r, w):
+ try:
+ _v, n = await r.readexactly(2)
+ await r.readexactly(n)
+ w.write(b"\x05\x00")
+ _v, cmd, _r, atyp = await r.readexactly(4)
+ if atyp == 1:
+ host = str(ipaddress.IPv4Address(await r.readexactly(4)))
+ elif atyp == 4:
+ host = str(ipaddress.IPv6Address(await r.readexactly(16)))
+ else:
+ host = (await r.readexactly((await r.readexactly(1))[0])).decode()
+ port = struct.unpack("!H", await r.readexactly(2))[0]
+ LOG.write(f"FWD {host}:{port}\n")
+ try:
+ ur, uw = await asyncio.wait_for(asyncio.open_connection(host, port), 5)
+ except Exception as e:
+ LOG.write(f"FAIL {host}:{port} {e!r}\n")
+ w.write(b"\x05\x05\x00\x01\0\0\0\0\0\0"); await w.drain(); w.close(); return
+ w.write(b"\x05\x00\x00\x01\x7f\x00\x00\x01\x00\x00"); await w.drain()
+ await asyncio.gather(pipe(r, uw), pipe(ur, w))
+ except Exception:
+ pass
+ finally:
+ w.close()
+
+
+async def main():
+ srv = await asyncio.start_server(handle, sys.argv[1], int(sys.argv[2]))
+ await srv.serve_forever()
+
+asyncio.run(main())
diff --git a/Linux/tests/gui_ui.sh b/Linux/tests/gui_ui.sh
new file mode 100755
index 0000000..1746656
--- /dev/null
+++ b/Linux/tests/gui_ui.sh
@@ -0,0 +1,30 @@
+#!/bin/bash
+# Drives the real GUI's windows and dialogs (gui/tests/ui_test.c) under the GTK Broadway backend. Needs root, broadwayd, python3.
+# sudo Linux/tests/gui_ui.sh [libdir] libdir: directory with libproxybridge.so (default Linux/output)
+# The test binary is compiled here from the GUI sources (main.c as pb_gui_main) in a temporary directory.
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; ROOT="$(dirname "$HERE")"
+LIBDIR="${1:-${PB_DIR:-$ROOT/output}}"
+[ -f "$LIBDIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or pass the directory with libproxybridge.so"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+WORK="$(mktemp -d)"
+BUILD="${UI_BUILD_DIR:-$WORK}" # coverage runs keep the objects (and their .gcno files) here
+mkdir -p "$BUILD"
+cleanup() { kill $FAKE $BW 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+
+G="$ROOT/gui"
+SRC=$(ls "$G"/*.c | grep -v "/main.c$")
+gcc -O1 -g -w -D_GNU_SOURCE ${EXTRA_CFLAGS:-} -I"$ROOT/src" -I"$ROOT/profile" -I"$G" $(pkg-config --cflags gtk+-3.0) \
+ -Dmain=pb_gui_main -c "$G/main.c" -o "$BUILD/gui_main.o" || exit 1
+gcc -O1 -g -w -D_GNU_SOURCE ${EXTRA_CFLAGS:-} -I"$ROOT/src" -I"$ROOT/profile" -I"$G" $(pkg-config --cflags gtk+-3.0) \
+ -o "$BUILD/ui_test" "$G/tests/ui_test.c" "$BUILD/gui_main.o" $SRC "$ROOT/profile/pb_profile.c" \
+ -L"$LIBDIR" -Wl,-rpath,"$LIBDIR" -lproxybridge -lpthread $(pkg-config --libs gtk+-3.0) ${EXTRA_LDFLAGS:-} || exit 1
+
+python3 "$HERE/fake_proxies.py" "$WORK/proxy.log" > /dev/null 2>&1 & FAKE=$!
+broadwayd :8 > /dev/null 2>&1 & BW=$!
+sleep 1.5
+mkdir -p "$WORK/cfg"
+GDK_BACKEND=broadway BROADWAY_DISPLAY=:8 PROXYBRIDGE_CONFIG_DIR="$WORK/cfg" LD_LIBRARY_PATH="$LIBDIR" \
+ timeout 300 "$BUILD/ui_test" 2>&1 | grep -v "^$\|Gtk-WARNING\|GLib-GIO\|dconf"
+exit "${PIPESTATUS[0]}"
diff --git a/Linux/tests/rules_diff.py b/Linux/tests/rules_diff.py
new file mode 100755
index 0000000..5c9d43c
--- /dev/null
+++ b/Linux/tests/rules_diff.py
@@ -0,0 +1,193 @@
+#!/usr/bin/env python3
+"""Differential test of the rule engine against the live datapath.
+
+For several seeds: generate a random rule set (single IPs, CIDR, ranges, octet wildcards, long host lists, port lists and many port
+ranges, TCP/UDP/BOTH, PROXY/DIRECT/BLOCK, matching and non-matching process names), start ProxyBridge with it, make this process
+connect() to hundreds of random destinations over TCP and UDP, and compare the decision ProxyBridge reports for each one with an
+independent reference evaluation written here. The kernel fast path and the user-space slow path (long lists and many ranges
+cannot be decided in the kernel) are both exercised. Needs root.
+
+usage: rules_diff.py <PB_DIR> [seeds] [probes_per_proto]
+"""
+import ipaddress, os, random, re, signal, socket, subprocess, sys, time
+
+PB_DIR = sys.argv[1]
+SEEDS = int(sys.argv[2]) if len(sys.argv) > 2 else 8
+PROBES = int(sys.argv[3]) if len(sys.argv) > 3 else 300
+PROXY = "a=socks5://127.0.0.1:19080"
+
+# 198.18.0.0/15 is the benchmarking range; the wrapper script routes it to "unreachable" so direct connects fail at once
+OCT = {1: [18, 19], 2: [0, 1, 2, 3], 3: [0, 1, 2, 5, 100, 254, 255]}
+PORTS = [1, 22, 80, 81, 443, 1000, 1500, 2000, 5000, 8080, 9000, 65535, 20, 25, 110, 143]
+
+
+def rand_ip(rng):
+ return "198.%d.%d.%d" % (rng.choice(OCT[1]), rng.choice(OCT[2]), rng.choice(OCT[3]))
+
+
+def ip_int(s):
+ return int(ipaddress.IPv4Address(s))
+
+
+class Host:
+ """One host pattern: text for the CLI and a predicate for the reference."""
+ def __init__(self, rng):
+ kind = rng.choice(["any", "ip", "ip", "cidr", "cidr", "range", "wild", "wild2"])
+ a = rand_ip(rng)
+ if kind == "any":
+ self.text, self.fn = "*", lambda ip: True
+ elif kind == "ip":
+ self.text, self.fn = a, lambda ip, v=ip_int(a): ip == v
+ elif kind == "cidr":
+ net = ipaddress.ip_network("%s/%d" % (a, rng.choice([15, 16, 20, 24, 28, 32])), strict=False)
+ self.text, self.fn = str(net), lambda ip, n=net: ipaddress.IPv4Address(ip) in n
+ elif kind == "range":
+ b = rand_ip(rng)
+ lo, hi = sorted((ip_int(a), ip_int(b)))
+ self.text = "%s-%s" % (ipaddress.IPv4Address(lo), ipaddress.IPv4Address(hi))
+ self.fn = lambda ip, lo=lo, hi=hi: lo <= ip <= hi
+ elif kind == "wild":
+ o = a.split(".")
+ k = rng.choice([1, 2, 3])
+ self.text = ".".join(o[:4 - k] + ["*"] * k)
+ self.fn = lambda ip, o=o, k=k: [(ip >> s) & 255 for s in (24, 16, 8, 0)][:4 - k] == [int(x) for x in o[:4 - k]]
+ else: # per-octet range such as 10.1-2.*.5
+ o = a.split(".")
+ lo = 18; hi = rng.choice([18, 19])
+ self.text = "%s.%d-%d.*.%s" % (o[0], lo, hi, o[3])
+ self.fn = lambda ip, o=o, lo=lo, hi=hi: (ip >> 24) == int(o[0]) and lo <= ((ip >> 16) & 255) <= hi and (ip & 255) == int(o[3])
+
+
+class Rule:
+ def __init__(self, rng):
+ n = rng.choice([1, 1, 1, 2, 3, 6, 7]) # more than 4 address ranges do not fit in the kernel: slow path
+ self.hosts = [Host(rng) for _ in range(n)]
+ pk = rng.choice(["any", "one", "list", "range", "many"])
+ if pk == "any":
+ self.ports_text, self.ports = "*", None
+ elif pk == "one":
+ p = rng.choice(PORTS); self.ports_text, self.ports = str(p), [(p, p)]
+ elif pk == "list":
+ ps = rng.sample(PORTS, rng.choice([2, 3, 4])); self.ports_text, self.ports = ";".join(map(str, ps)), [(p, p) for p in ps]
+ elif pk == "range":
+ lo = rng.choice([1, 20, 1000, 5000]); hi = lo + rng.choice([0, 100, 5000, 60000]); hi = min(hi, 65535)
+ self.ports_text, self.ports = "%d-%d" % (lo, hi), [(lo, hi)]
+ else: # more port ranges than the kernel stores
+ rs = []; t = 1
+ for _ in range(rng.choice([5, 6])):
+ lo = t + rng.choice([0, 3]); hi = lo + rng.choice([0, 10, 400]); rs.append((lo, hi)); t = hi + 40
+ self.ports_text, self.ports = ";".join("%d-%d" % r for r in rs), rs
+ self.proto = rng.choice(["TCP", "UDP", "BOTH", "BOTH"])
+ self.proc = rng.choice(["python3*", "python3*", "python3*", "*", "nomatch*"])
+ self.action = rng.choices(["PROXY", "DIRECT", "BLOCK"], [45, 25, 30])[0]
+
+ def cli(self):
+ return "%s:%s:%s:%s:%s" % (self.proc, ";".join(h.text for h in self.hosts), self.ports_text, self.proto,
+ "PROXY=a" if self.action == "PROXY" else self.action)
+
+ def matches(self, ip, port, proto):
+ if self.proc == "nomatch*" or self.proto not in (proto, "BOTH"):
+ return False
+ if self.ports is not None and not any(lo <= port <= hi for lo, hi in self.ports):
+ return False
+ return any(h.fn(ip) for h in self.hosts)
+
+
+def expected(rules, ip, port, proto):
+ for r in rules:
+ if r.matches(ip_int(ip), port, proto):
+ return r.action
+ return "DIRECT"
+
+
+def probes(rng, n):
+ seen, out = set(), []
+ while len(out) < n:
+ k = (rand_ip(rng), rng.choice(PORTS + [rng.randint(1024, 65000)]))
+ if k not in seen:
+ seen.add(k); out.append(k)
+ return out
+
+
+def connect(proto, ip, port):
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM if proto == "TCP" else socket.SOCK_DGRAM)
+ try:
+ if proto == "TCP":
+ s.setblocking(False)
+ err = s.connect_ex((ip, port))
+ return None if err in (0, 115) else err
+ s.connect((ip, port))
+ try:
+ s.send(b"x") # a decision the kernel cannot make alone is reported when the relay sees the first datagram
+ except OSError:
+ pass # unreachable destinations: the send fails after the decision was made
+ except OSError as e:
+ return e.errno
+ finally:
+ s.close()
+ return None
+
+
+def run_seed(seed):
+ rng = random.Random(seed)
+ rules = [Rule(rng) for _ in range(rng.choice([8, 12, 16, 24]))]
+ env = dict(os.environ, LD_LIBRARY_PATH=PB_DIR)
+ args = ["stdbuf", "-oL", os.path.join(PB_DIR, "ProxyBridge"), "--verbose", "2", "--proxy", PROXY]
+ for r in rules:
+ args += ["--rule", r.cli()]
+ out = open("/tmp/rules_diff.%d.out" % os.getpid(), "w+")
+ pb = subprocess.Popen(args, stdout=out, stderr=subprocess.STDOUT, env=env)
+ try:
+ for _ in range(80):
+ out.seek(0)
+ if "ProxyBridge started" in out.read(): break
+ if pb.poll() is not None: break
+ time.sleep(0.25)
+ out.seek(0)
+ text = out.read()
+ if "ProxyBridge started" not in text:
+ print("seed %d: ProxyBridge did not start:\n%s" % (seed, text[-1500:])); return 0, 1
+ time.sleep(0.5)
+ bad = total = 0
+ for proto in ("TCP", "UDP"):
+ batch = probes(rng, PROBES)
+ out.seek(0, 2); start = out.tell()
+ errs = {}
+ for ip, port in batch:
+ errs[(ip, port)] = connect(proto, ip, port)
+ time.sleep(1.0)
+ out.seek(start)
+ seen = {}
+ for line in out:
+ m = re.search(r"\[CONN\] .*\(PID:%d\) -> ([0-9.]+):(\d+) via (.*)" % os.getpid(), line)
+ if not m: continue
+ info = m.group(3).strip()
+ act = "BLOCK" if info == "BLOCK" else "DIRECT" if info == "DIRECT" else "PROXY"
+ seen.setdefault((m.group(1), int(m.group(2))), set()).add(act)
+ for ip, port in batch:
+ total += 1
+ want = expected(rules, ip, port, proto)
+ got = seen.get((ip, port), set())
+ ok = got == {want} # a BLOCK decided in the slow path closes the connection after connect(), so errno is not compared
+ if not ok:
+ bad += 1
+ if bad <= 5:
+ print("seed %d MISMATCH %s %s:%d want %s got %s errno %s" % (seed, proto, ip, port, want, sorted(got), errs[(ip, port)]))
+ if bad:
+ print("seed %d rule set:" % seed)
+ for i, r in enumerate(rules): print(" %2d %s" % (i + 1, r.cli()))
+ return total, bad
+ finally:
+ pb.send_signal(signal.SIGINT)
+ try: pb.wait(10)
+ except subprocess.TimeoutExpired: pb.kill()
+ out.close(); os.unlink(out.name)
+
+
+tot = bad = 0
+for seed in range(int(os.environ.get("SEED_START", 1)), int(os.environ.get("SEED_START", 1)) + SEEDS):
+ t, b = run_seed(seed)
+ tot += t; bad += b
+ print("seed %d: %d decisions, %d mismatches" % (seed, t, b), flush=True)
+print("RESULT %d decisions compared, %d mismatches" % (tot, bad))
+sys.exit(1 if bad else 0)
diff --git a/Linux/tests/tcp_probe.py b/Linux/tests/tcp_probe.py
new file mode 100755
index 0000000..361371c
--- /dev/null
+++ b/Linux/tests/tcp_probe.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+"""Client for the fault tests: connects to <ip>:<port> (ProxyBridge redirects it) and prints one RESULT line.
+
+usage: tcp_probe.py <ip> <port> <mode> [timeout_s]
+ get send a GET, read until the end RESULT DATA <n> <first bytes> | CLOSED | ERROR <errno> | TIMEOUT
+ pattern read until the end, compare with the 4 MiB pattern of fault_proxies.py RESULT PATTERN ok|bad <n>
+ echo send 2 MiB while reading the echo back, compare RESULT ECHO ok|bad <n>
+"""
+import os, random, socket, sys, threading
+
+ip, port, mode = sys.argv[1], int(sys.argv[2]), sys.argv[3]
+timeout = float(sys.argv[4]) if len(sys.argv) > 4 else 15.0
+PATTERN = bytes((i * 7 + 3) & 0xFF for i in range(65536))
+
+s = socket.socket()
+s.settimeout(timeout)
+try:
+ s.connect((ip, port))
+except socket.timeout:
+ print("RESULT TIMEOUT connect"); sys.exit(0)
+except OSError as e:
+ print("RESULT ERROR", e.errno, "connect"); sys.exit(0)
+
+def read_all():
+ got = b""
+ try:
+ while True:
+ d = s.recv(1 << 16)
+ if not d:
+ return got, "eof"
+ got += d
+ except socket.timeout:
+ return got, "timeout"
+ except OSError as e:
+ return got, "error%d" % e.errno
+
+if mode == "get":
+ try:
+ s.sendall(b"GET / HTTP/1.0\r\n\r\n")
+ except OSError:
+ pass
+ got, end = read_all()
+ if got:
+ print("RESULT DATA", len(got), got[:140].replace(b"\r", b"").replace(b"\n", b"|").decode("latin1"))
+ elif end == "timeout":
+ print("RESULT TIMEOUT read")
+ else:
+ print("RESULT CLOSED", end)
+elif mode == "pattern":
+ got, end = read_all()
+ expect = (PATTERN * 64)[: 4 << 20]
+ print("RESULT PATTERN", "ok" if got == expect else "bad", len(got), end)
+elif mode == "echo":
+ data = random.Random(7).randbytes(2 << 20)
+ def writer():
+ try:
+ for i in range(0, len(data), 65536):
+ s.sendall(data[i:i + 65536])
+ except OSError:
+ pass
+ t = threading.Thread(target=writer); t.start()
+ got = b""
+ try:
+ while len(got) < len(data):
+ d = s.recv(1 << 16)
+ if not d:
+ break
+ got += d
+ except OSError:
+ pass
+ t.join(timeout)
+ print("RESULT ECHO", "ok" if got == data else "bad", len(got))
diff --git a/Linux/tests/udp_probe.py b/Linux/tests/udp_probe.py
new file mode 100755
index 0000000..400fe45
--- /dev/null
+++ b/Linux/tests/udp_probe.py
@@ -0,0 +1,123 @@
+#!/usr/bin/env python3
+"""Client side of the UDP tests (ProxyBridge redirects these sockets). One scenario per run, one RESULT line per check.
+
+usage: udp_probe.py <scenario> [args]
+ echo <ip> <port> <payload> [wait_s] one datagram, prints RESULT REPLY <peer> <text> | RESULT NOREPLY
+ seq <ip> <port> <p1> <p2> ... datagrams one after the other (new association after the proxy dropped one), 1 s apart
+ multi <base-ip> <n> <port> ONE unconnected socket talks to n destinations; replies must come from the right peers
+ connected <ip> <port> connect()ed socket: send/recv without addresses
+ many <ip> <port> <n> n sockets at once, all must get their own reply
+ sizes <ip> <port> payloads from 1 byte to 60000 bytes
+ boundport <ip> <port> socket bound to a chosen local port; the reply must come back to it
+ v6connected <ip6> <port> connect()ed IPv6 socket
+ v6unconnected <ip6> <port> sendto() on an IPv6 socket: the kernel cannot redirect it, ProxyBridge fails it closed
+ blocked <ip> <port> sendto() that a BLOCK rule must refuse
+"""
+import errno, random, select, socket, sys, time
+
+def check(name, ok, detail=""):
+ print("RESULT", "ok" if ok else "BAD", name, detail, flush=True)
+
+def udp(family=socket.AF_INET):
+ s = socket.socket(family, socket.SOCK_DGRAM)
+ s.settimeout(4)
+ return s
+
+sc = sys.argv[1]
+a = sys.argv[2:]
+
+if sc == "echo":
+ s = udp(); wait = float(a[3]) if len(a) > 3 else 3
+ s.settimeout(wait)
+ try:
+ s.sendto(a[2].encode(), (a[0], int(a[1])))
+ d, peer = s.recvfrom(70000)
+ print("RESULT REPLY %s:%d %s" % (peer[0], peer[1], d.decode("latin1")))
+ except socket.timeout:
+ print("RESULT NOREPLY")
+ except OSError as e:
+ print("RESULT ERROR", e.errno)
+elif sc == "seq":
+ s = udp(); s.settimeout(2.5)
+ for p in a[2:]:
+ try:
+ s.sendto(p.encode(), (a[0], int(a[1])))
+ d, peer = s.recvfrom(70000)
+ print("RESULT REPLY %s:%d %s" % (peer[0], peer[1], d.decode("latin1")), flush=True)
+ except socket.timeout:
+ print("RESULT NOREPLY", flush=True)
+ time.sleep(1)
+elif sc == "multi":
+ base, n, port = a[0], int(a[1]), int(a[2])
+ s = udp()
+ prefix = base.rsplit(".", 1)[0]; first = int(base.rsplit(".", 1)[1])
+ dsts = ["%s.%d" % (prefix, first + i) for i in range(n)]
+ for d in dsts:
+ s.sendto(("to-" + d).encode(), (d, port))
+ got = {}
+ for _ in dsts:
+ data, peer = s.recvfrom(2048)
+ got[peer[0]] = data.decode()
+ check("every destination answered from its own address", sorted(got) == sorted(dsts), str(sorted(got)))
+ check("replies match their requests", all(got[d].endswith("to-" + d) and (" %s:%d " % (d, port)) in got[d] for d in dsts if d in got))
+elif sc == "connected":
+ s = udp(); s.connect((a[0], int(a[1])))
+ s.send(b"conn-1"); d1 = s.recv(2048)
+ s.send(b"conn-2"); d2 = s.recv(2048)
+ check("connected socket gets both replies", d1.endswith(b"conn-1") and d2.endswith(b"conn-2"), d2.decode())
+ check("getpeername shows the real destination", s.getpeername() == (a[0], int(a[1])), str(s.getpeername()))
+elif sc == "many":
+ n = int(a[2])
+ socks = []
+ for i in range(n):
+ s = udp(); s.settimeout(8)
+ s.sendto(b"s%d" % i, (a[0], int(a[1])))
+ socks.append(s)
+ good = 0
+ for i, s in enumerate(socks):
+ try:
+ d, _ = s.recvfrom(2048)
+ good += d.endswith(b"s%d" % i)
+ except socket.timeout:
+ pass
+ check("%d sockets, each got its own reply" % n, good == n, "%d/%d" % (good, n))
+elif sc == "sizes":
+ s = udp(); s.settimeout(6)
+ bad = []
+ for size in (1, 100, 512, 1400, 1472, 4000, 9000, 30000, 60000):
+ payload = bytes(random.Random(size).randrange(33, 126) for _ in range(size))
+ try:
+ s.sendto(payload, (a[0], int(a[1])))
+ d, _ = s.recvfrom(70000)
+ if not d.endswith(payload):
+ bad.append(size)
+ except (socket.timeout, OSError):
+ bad.append(size)
+ check("payloads of 1..60000 bytes survive the round trip", not bad, "failed sizes: %s" % bad)
+elif sc == "boundport":
+ s = udp(); s.bind(("0.0.0.0", 0)); port = s.getsockname()[1]
+ s.sendto(b"bound", (a[0], int(a[1])))
+ d, _ = s.recvfrom(2048)
+ check("reply arrives on the bound port", d.endswith(b"bound") and s.getsockname()[1] == port, "port %d" % port)
+elif sc == "v6connected":
+ s = udp(socket.AF_INET6); s.connect((a[0], int(a[1])))
+ s.send(b"six")
+ d = s.recv(2048)
+ check("connected IPv6 UDP goes through the proxy", d.endswith(b"six") and a[0].encode() in d, d.decode())
+elif sc == "v6unconnected":
+ s = udp(socket.AF_INET6)
+ try:
+ s.sendto(b"six", (a[0], int(a[1])))
+ check("unconnected IPv6 sendto fails closed", False, "it was sent")
+ except OSError as e:
+ # EPERM from ProxyBridge's hook, or ENETUNREACH when the host has no IPv6 route and the kernel refuses first
+ check("unconnected IPv6 sendto fails closed", e.errno in (errno.EPERM, errno.EACCES, errno.ENETUNREACH), "errno %s" % e.errno)
+elif sc == "blocked":
+ s = udp()
+ try:
+ s.sendto(b"x", (a[0], int(a[1])))
+ check("BLOCK refuses sendto", False, "it was sent")
+ except OSError as e:
+ check("BLOCK refuses sendto", e.errno in (errno.EPERM, errno.EACCES), "errno %s" % e.errno)
+else:
+ sys.exit(__doc__)