Skip to content

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

feat(linux): replace iptables/NFQUEUE with an eBPF cgroup datapath

anof-cyberbbf26e417cbf
diff --git a/Linux/src/Makefile b/Linux/src/Makefile
index 29effb0..677f8b8 100644
--- a/Linux/src/Makefile
+++ b/Linux/src/Makefile
@@ -1,5 +1,9 @@
-CC = gcc
-CFLAGS = -Wall -Wextra -O3 -fPIC -D_GNU_SOURCE \
+CC ?= gcc
+CLANG ?= clang
+BPFTOOL ?= bpftool
+MULTIARCH := $(shell $(CC) -print-multiarch)
+
+CFLAGS = -Wall -Wextra -O2 -fPIC -D_GNU_SOURCE \
-fstack-protector-strong \
-D_FORTIFY_SOURCE=2 \
-fPIE \
@@ -9,27 +13,39 @@ CFLAGS = -Wall -Wextra -O3 -fPIC -D_GNU_SOURCE \
-fno-delete-null-pointer-checks \
-fwrapv
LDFLAGS = -shared -Wl,-z,relro,-z,now -Wl,-z,noexecstack -s
-LIBS = -lpthread -lnetfilter_queue -lnfnetlink
+LIBS = -lpthread -lbpf
TARGET = libproxybridge.so
-SOURCES = ProxyBridge.c
+SOURCES = ProxyBridge.c pb_rules.c pb_dns.c pb_bpf.c pb_relay.c
OBJECTS = $(SOURCES:.c=.o)
+BPF_OBJ = bpf/proxybridge.bpf.o
+SKEL = proxybridge.skel.h
all: $(TARGET)
+$(BPF_OBJ): bpf/proxybridge.bpf.c bpf/pb_bpf_shared.h
+ $(CLANG) -O2 -g -target bpf -D__BPF__ -I/usr/include/$(MULTIARCH) -c $< -o $@
+
+$(SKEL): $(BPF_OBJ)
+ $(BPFTOOL) gen skeleton $< > $@
+
+pb_bpf.o: $(SKEL)
+
$(TARGET): $(OBJECTS)
$(CC) $(LDFLAGS) -o $@ $^ $(LIBS)
- @echo "Stripping debug symbols..."
- strip --strip-unneeded $@
-%.o: %.c
+%.o: %.c pb_internal.h ProxyBridge.h
$(CC) $(CFLAGS) -c $< -o $@
+test-rules: tests/rules_test.c tests/dns_test.c pb_rules.c pb_rules.h pb_dns.c pb_dns.h
+ $(CC) -Wall -Wextra -g -fsanitize=address,undefined -D_GNU_SOURCE tests/rules_test.c pb_rules.c -o tests/rules_test && tests/rules_test
+ $(CC) -Wall -Wextra -g -fsanitize=address,undefined -D_GNU_SOURCE tests/dns_test.c pb_dns.c -o tests/dns_test && tests/dns_test
+
clean:
- rm -f $(OBJECTS) $(TARGET)
+ rm -f $(OBJECTS) $(TARGET) $(BPF_OBJ) $(SKEL) tests/rules_test tests/dns_test
install: $(TARGET)
install -m 0755 $(TARGET) /usr/local/lib/
ldconfig
-.PHONY: all clean install
+.PHONY: all clean install test-rules
diff --git a/Linux/src/ProxyBridge.c b/Linux/src/ProxyBridge.c
index 6a008c2..2cbb5a9 100644
--- a/Linux/src/ProxyBridge.c
+++ b/Linux/src/ProxyBridge.c
@@ -1,3166 +1,546 @@
+#include <arpa/inet.h>
+#include <ctype.h>
+#include <errno.h>
+#include <pthread.h>
+#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <stdarg.h>
#include <unistd.h>
-#include <pthread.h>
-#include <errno.h>
-#include <ctype.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <signal.h>
-#include <sys/stat.h>
-#include <sys/socket.h>
-#include <sys/epoll.h>
-#include <poll.h>
-#include <netinet/in.h>
-#include <netinet/ip.h>
-#include <netinet/tcp.h>
-#include <netinet/udp.h>
-#include <arpa/inet.h>
-#include <linux/netfilter.h>
-#include <libnetfilter_queue/libnetfilter_queue.h>
-#include <linux/netlink.h>
-#include <linux/sock_diag.h>
-#include <linux/inet_diag.h>
-#include <netdb.h>
-#include <sys/wait.h>
#include "ProxyBridge.h"
+#include <stdatomic.h>
+#include "pb_bpf.h"
+#include "pb_dns.h"
+#include "pb_internal.h"
+#include "pb_rules.h"
-#define LOCAL_PROXY_PORT 34010
-#define LOCAL_UDP_RELAY_PORT 34011
-#define MAX_PROCESS_NAME 256
-#define PID_CACHE_SIZE 1024
-#define PID_CACHE_TTL_MS 1000
-#define NUM_PACKET_THREADS 4
-#define CONNECTION_HASH_SIZE 256
-#define SOCKS5_BUFFER_SIZE 1024
-#define HTTP_BUFFER_SIZE 1024
-#define LOG_BUFFER_SIZE 1024
+#define MAX_PROXIES 255
-// safe way to run commands without shell injection issues
-static int run_command_v(const char *cmd_path, char *const argv[]) {
- pid_t pid = fork();
- if (pid == -1) {
- return -1;
- } else if (pid == 0) {
- // child process
- // send output to /dev/null so it doesnt clutter
- int fd = open("/dev/null", O_WRONLY);
- if (fd >= 0) {
- dup2(fd, STDOUT_FILENO);
- dup2(fd, STDERR_FILENO);
- close(fd);
- }
- execvp(cmd_path, argv);
- _exit(127); // command not found or no perms
- } else {
- // parent waits for child
- int status;
- waitpid(pid, &status, 0);
- if (WIFEXITED(status)) {
- return WEXITSTATUS(status);
- }
- return -1;
- }
-}
+static struct {
+ pthread_rwlock_t lock;
+ struct pb_rule *rules; size_t nrules, caprules;
+ struct pb_proxy proxies[MAX_PROXIES]; size_t nproxies;
+ uint32_t next_rule_id, next_proxy_id, default_proxy;
+ bool dns_via_proxy, traffic_logging, running;
+ atomic_bool has_domain_rules;
+ LogCallback log_cb;
+ ConnectionCallback conn_cb;
+} G = { .lock = PTHREAD_RWLOCK_INITIALIZER, .next_rule_id = 1, .next_proxy_id = 1, .dns_via_proxy = true };
-// run iptables commands easier
-static int run_iptables_cmd(const char *arg1, const char *arg2, const char *arg3, const char *arg4, const char *arg5, const char *arg6, const char *arg7, const char *arg8, const char *arg9, const char *arg10, const char *arg11, const char *arg12, const char *arg13, const char *arg14) {
- // build argv array skipping null args
- const char *argv[17];
- int i = 0;
- argv[i++] = "iptables";
- if (arg1) argv[i++] = arg1;
- if (arg2) argv[i++] = arg2;
- if (arg3) argv[i++] = arg3;
- if (arg4) argv[i++] = arg4;
- if (arg5) argv[i++] = arg5;
- if (arg6) argv[i++] = arg6;
- if (arg7) argv[i++] = arg7;
- if (arg8) argv[i++] = arg8;
- if (arg9) argv[i++] = arg9;
- if (arg10) argv[i++] = arg10;
- if (arg11) argv[i++] = arg11;
- if (arg12) argv[i++] = arg12;
- if (arg13) argv[i++] = arg13;
- if (arg14) argv[i++] = arg14;
- argv[i] = NULL;
+static pthread_mutex_t cb_lock = PTHREAD_MUTEX_INITIALIZER; // serialises user callbacks
- return run_command_v("iptables", (char **)argv);
+static void set_err(char *err, size_t n, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
+static void set_err(char *err, size_t n, const char *fmt, ...)
+{
+ if (!err || !n) return;
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(err, n, fmt, ap);
+ va_end(ap);
}
-// convert string to int safely
-static int safe_atoi(const char *str) {
- if (!str) return 0;
- char *endptr;
- long val = strtol(str, &endptr, 10);
- if (endptr == str) return 0;
- return (int)val;
+// ---- logging -----------------------------------------------------------------------------------------------------------
+void pb_core_log(const char *fmt, ...)
+{
+ char buf[1024];
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(buf, sizeof buf, fmt, ap);
+ va_end(ap);
+ pthread_mutex_lock(&cb_lock);
+ LogCallback cb = G.log_cb;
+ if (cb) cb(buf);
+ pthread_mutex_unlock(&cb_lock);
}
+static const char *proxy_type_name(ProxyType t) { return t == PROXY_TYPE_SOCKS5 ? "SOCKS5" : "HTTP"; }
-typedef struct PROCESS_RULE {
- uint32_t rule_id;
- char process_name[MAX_PROCESS_NAME];
- char *target_hosts;
- char *target_ports;
- RuleProtocol protocol;
- RuleAction action;
- bool enabled;
- struct PROCESS_RULE *next;
-} PROCESS_RULE;
-
-#define SOCKS5_VERSION 0x05
-#define SOCKS5_CMD_CONNECT 0x01
-#define SOCKS5_CMD_UDP_ASSOCIATE 0x03
-#define SOCKS5_ATYP_IPV4 0x01
-#define SOCKS5_AUTH_NONE 0x00
-
-typedef struct CONNECTION_INFO {
- uint16_t src_port;
- bool is_udp; // protocol - a TCP and a UDP flow may share a local port
- uint32_t src_ip;
- uint32_t orig_dest_ip;
- uint16_t orig_dest_port;
- bool is_tracked;
- uint64_t last_activity;
- struct CONNECTION_INFO *next;
-} CONNECTION_INFO;
-
-typedef struct LOGGED_CONNECTION {
- uint32_t pid;
- uint32_t dest_ip;
- uint16_t dest_port;
- RuleAction action;
- struct LOGGED_CONNECTION *next;
-} LOGGED_CONNECTION;
-
-typedef struct PID_CACHE_ENTRY {
- uint32_t src_ip;
- uint16_t src_port;
- uint32_t pid;
- uint64_t timestamp;
- bool is_udp;
- struct PID_CACHE_ENTRY *next;
-} PID_CACHE_ENTRY;
-
-static CONNECTION_INFO *connection_hash_table[CONNECTION_HASH_SIZE] = {NULL};
-static LOGGED_CONNECTION *logged_connections = NULL;
-static PROCESS_RULE *rules_list = NULL;
-static uint32_t g_next_rule_id = 1;
-static pthread_rwlock_t conn_lock = PTHREAD_RWLOCK_INITIALIZER; // read-heavy connection hash
-static pthread_rwlock_t rules_lock = PTHREAD_RWLOCK_INITIALIZER; // read-heavy rules list
-static pthread_mutex_t pid_cache_lock = PTHREAD_MUTEX_INITIALIZER; // PID cache only
-static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER; // logged connections only
-
-typedef struct {
- int client_socket;
- uint32_t orig_dest_ip;
- uint16_t orig_dest_port;
-} connection_config_t;
-
-typedef struct {
- int from_socket;
- int to_socket;
-} transfer_config_t;
-
-static struct nfq_handle *nfq_h = NULL;
-static struct nfq_q_handle *nfq_qh = NULL;
-static pthread_t packet_thread[NUM_PACKET_THREADS] = {0};
-static pthread_t proxy_thread = 0;
-static pthread_t udp_relay_thread = 0;
-static pthread_t cleanup_thread = 0;
-static PID_CACHE_ENTRY *pid_cache[PID_CACHE_SIZE] = {NULL};
-static bool g_has_active_rules = false;
-static bool running = false;
-static uint32_t g_current_process_id = 0;
-
-// udp relay stuff
-static int udp_relay_socket = -1;
-static int socks5_udp_control_socket = -1;
-static int socks5_udp_send_socket = -1;
-static struct sockaddr_in socks5_udp_relay_addr;
-static bool udp_associate_connected = false;
-static uint64_t last_udp_connect_attempt = 0;
-
-static bool g_traffic_logging_enabled = true;
-
-static char g_proxy_host[256] = "";
-static uint16_t g_proxy_port = 0;
-static uint16_t g_local_relay_port = LOCAL_PROXY_PORT;
-static ProxyType g_proxy_type = PROXY_TYPE_SOCKS5;
-static char g_proxy_username[256] = "";
-static char g_proxy_password[256] = "";
-static bool g_dns_via_proxy = true;
-static uint32_t g_proxy_ip_cached = 0; // Cached resolved proxy IP
-static LogCallback g_log_callback = NULL;
-static ConnectionCallback g_connection_callback = NULL;
-
-static void log_message(const char *msg, ...)
+static void proc_name_of(uint32_t pid, const char *comm, char *out, size_t n)
{
- if (g_log_callback == NULL) return;
- char buffer[LOG_BUFFER_SIZE];
- va_list args;
- va_start(args, msg);
- vsnprintf(buffer, sizeof(buffer), msg, args);
- va_end(args);
- g_log_callback(buffer);
+ char lnk[64], path[512];
+ snprintf(lnk, sizeof lnk, "/proc/%u/exe", pid);
+ ssize_t r = readlink(lnk, path, sizeof path - 1);
+ if (r > 0) {
+ path[r] = 0;
+ const char *b = strrchr(path, '/');
+ snprintf(out, n, "%s", b ? b + 1 : path);
+ size_t l = strlen(out);
+ if (l > 10 && !strcmp(out + l - 10, " (deleted)")) out[l - 10] = 0;
+ return;
+ }
+ snprintf(out, n, "%s", comm && *comm ? comm : "unknown");
}
-static const char* extract_filename(const char* path)
+static void emit_connection(uint32_t pid, const char *comm, int family, const uint8_t addr[16], uint16_t port, int action, uint32_t proxy_id)
{
- if (!path) return "";
- const char* last_slash = strrchr(path, '/');
- return last_slash ? (last_slash + 1) : path;
+ if (!G.traffic_logging) return;
+ char name[512], ip[INET6_ADDRSTRLEN + 280], info[400];
+ proc_name_of(pid, comm, name, sizeof name);
+ if (family == AF_INET) {
+ inet_ntop(AF_INET, addr + 12, ip, sizeof ip);
+ uint32_t h = ((uint32_t)addr[12] << 24) | ((uint32_t)addr[13] << 16) | ((uint32_t)addr[14] << 8) | addr[15];
+ char nm[1][256];
+ if (pb_dns_lookup(h, nm, 1) == 1) { // show the domain the application asked for, when we know it
+ size_t l = strlen(ip);
+ snprintf(ip + l, sizeof ip - l, " (%.*s)", (int)(sizeof ip - l - 4), nm[0]);
+ }
+ } else inet_ntop(AF_INET6, addr, ip, sizeof ip);
+ if (action == PB_ACT_PROXY) {
+ struct pb_proxy p;
+ if (pb_core_get_proxy(proxy_id, &p) == 0) snprintf(info, sizeof info, "%s %s:%u", proxy_type_name(p.type), p.host, p.port);
+ else snprintf(info, sizeof info, "PROXY");
+ } else snprintf(info, sizeof info, "%s", action == PB_ACT_BLOCK ? "BLOCK" : "DIRECT");
+ pthread_mutex_lock(&cb_lock);
+ ConnectionCallback cb = G.conn_cb;
+ if (cb) cb(name, pid, ip, port, info);
+ pthread_mutex_unlock(&cb_lock);
}
-static inline char* skip_whitespace(char *str)
+static void on_bpf_event(const struct pb_event *e)
{
- while (*str == ' ' || *str == '\t')
- str++;
- return str;
+ char comm[17];
+ memcpy(comm, e->comm, 16); comm[16] = 0;
+ emit_connection(e->pid, comm, e->family, e->addr, e->port, e->action, e->proxy_id);
}
-static void format_ip_address(uint32_t ip, char *buffer, size_t size)
+void pb_core_flow_event(const struct pb_orig *o, int action, const char *proxy_desc)
{
- snprintf(buffer, size, "%d.%d.%d.%d",
- (ip >> 0) & 0xFF, (ip >> 8) & 0xFF,
- (ip >> 16) & 0xFF, (ip >> 24) & 0xFF);
+ (void)proxy_desc;
+ emit_connection(o->pid, NULL, o->family, o->addr, o->port, action, o->proxy_id);
}
-typedef bool (*token_match_func)(const char *token, const void *data);
+bool pb_core_dns_via_proxy(void) { return G.dns_via_proxy; }
-static bool parse_token_list(const char *list, const char *delimiters, token_match_func match_func, const void *match_data)
+// ---- proxies -------------------------------------------------------------------------------------------------------------
+static struct pb_proxy *find_proxy_locked(uint32_t id)
{
- if (list == NULL || list[0] == '\0' || strcmp(list, "*") == 0)
- return true;
-
- size_t len = strlen(list) + 1;
- char *list_copy = malloc(len);
- if (list_copy == NULL)
- return false;
-
- memcpy(list_copy, list, len); // copy including null terminator
- bool matched = false;
- char *saveptr = NULL;
- char *token = strtok_r(list_copy, delimiters, &saveptr);
- while (token != NULL)
- {
- token = skip_whitespace(token);
-
- // remove spaces at end
- size_t tlen = strlen(token);
- while (tlen > 0 && (token[tlen - 1] == ' ' || token[tlen - 1] == '\t' || token[tlen-1] == '\r' || token[tlen-1] == '\n'))
- {
- token[tlen - 1] = '\0';
- tlen--;
- }
-
- if (tlen > 0 && match_func(token, match_data))
- {
- matched = true;
- break;
- }
- token = strtok_r(NULL, delimiters, &saveptr);
- }
- free(list_copy);
- return matched;
+ for (size_t i = 0; i < G.nproxies; i++) if (G.proxies[i].id == id) return &G.proxies[i];
+ return NULL;
}
-static void configure_tcp_socket(int sock, int bufsize, int timeout_ms)
+static struct pb_proxy *default_proxy_locked(void)
{
- int nodelay = 1;
- setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay));
- setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize));
- setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
- struct timeval timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
- setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
- setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
+ struct pb_proxy *p = G.default_proxy ? find_proxy_locked(G.default_proxy) : NULL;
+ return p ? p : (G.nproxies ? &G.proxies[0] : NULL);
}
-static void configure_udp_socket(int sock, int bufsize, int timeout_ms)
+int pb_core_get_proxy(uint32_t id, struct pb_proxy *out)
{
- setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize));
- setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize));
- struct timeval timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
- setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
- setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
+ int rc = -1;
+ pthread_rwlock_rdlock(&G.lock);
+ struct pb_proxy *p = id ? find_proxy_locked(id) : NULL;
+ if (!p) p = default_proxy_locked();
+ if (p) { *out = *p; rc = 0; }
+ pthread_rwlock_unlock(&G.lock);
+ return rc;
}
-static ssize_t send_all(int sock, const char *buf, size_t len)
+static bool valid_proxy(const char *host, uint16_t port, char *err, size_t en)
{
- size_t sent = 0;
- while (sent < len) {
- ssize_t n = send(sock, buf + sent, len - sent, MSG_NOSIGNAL);
- if (n < 0) return -1;
- sent += n;
- }
- return sent;
+ if (!host || !*host) { set_err(err, en, "proxy host is empty"); return false; }
+ if (strlen(host) > 253) { set_err(err, en, "proxy host too long"); return false; }
+ for (const char *c = host; *c; c++)
+ if (isspace((unsigned char)*c) || *c == '/' || *c == '@') { set_err(err, en, "proxy host contains invalid characters"); return false; }
+ if (!port) { set_err(err, en, "proxy port must be 1-65535"); return false; }
+ return true;
}
-static uint64_t get_monotonic_ms(void)
+static void fill_proxy(struct pb_proxy *p, const char *name, ProxyType type, const char *host, uint16_t port, const char *user, const char *pass)
{
- struct timespec ts;
- clock_gettime(CLOCK_MONOTONIC, &ts);
- return (uint64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+ snprintf(p->name, sizeof p->name, "%s", name && *name ? name : host);
+ p->type = type == PROXY_TYPE_HTTP ? PROXY_TYPE_HTTP : PROXY_TYPE_SOCKS5;
+ snprintf(p->host, sizeof p->host, "%s", host);
+ p->port = port;
+ snprintf(p->user, sizeof p->user, "%s", user ? user : "");
+ snprintf(p->pass, sizeof p->pass, "%s", pass ? pass : "");
}
-static uint32_t parse_ipv4(const char *ip);
-static uint32_t resolve_hostname(const char *hostname);
-static int socks5_connect(int s, uint32_t dest_ip, uint16_t dest_port);
-static bool match_ip_pattern(const char *pattern, uint32_t ip);
-static bool match_port_pattern(const char *pattern, uint16_t port);
-static bool match_ip_list(const char *ip_list, uint32_t ip);
-static bool match_port_list(const char *port_list, uint16_t port);
-static bool match_process_pattern(const char *pattern, const char *process_name);
-static bool match_process_list(const char *process_list, const char *process_name);
-static int http_connect(int s, uint32_t dest_ip, uint16_t dest_port);
-static void* local_proxy_server(void *arg);
-static void* connection_handler(void *arg);
-static void* transfer_handler(void *arg);
-static void* packet_processor(void *arg);
-static uint32_t get_process_id_from_connection(uint32_t src_ip, uint16_t src_port, bool is_udp);
-static bool get_process_name_from_pid(uint32_t pid, char *name, size_t name_size);
-static RuleAction match_rule(const char *process_name, uint32_t dest_ip, uint16_t dest_port, bool is_udp);
-static RuleAction check_process_rule(uint32_t src_ip, uint16_t src_port, uint32_t dest_ip, uint16_t dest_port, bool is_udp, uint32_t *out_pid);
-static void add_connection(uint16_t src_port, bool is_udp, uint32_t src_ip, uint32_t dest_ip, uint16_t dest_port);
-static bool get_connection(uint16_t src_port, bool is_udp, uint32_t *dest_ip, uint16_t *dest_port);
-static bool is_connection_tracked(uint16_t src_port, bool is_udp);
-static void cleanup_stale_connections(void);
-static bool is_connection_already_logged(uint32_t pid, uint32_t dest_ip, uint16_t dest_port, RuleAction action);
-static void add_logged_connection(uint32_t pid, uint32_t dest_ip, uint16_t dest_port, RuleAction action);
-static void clear_logged_connections(void);
-static bool is_broadcast_or_multicast(uint32_t ip);
-static uint32_t get_cached_pid(uint32_t src_ip, uint16_t src_port, bool is_udp);
-static void cache_pid(uint32_t src_ip, uint16_t src_port, uint32_t pid, bool is_udp);
-static void clear_pid_cache(void);
-static void update_has_active_rules(void);
-
-// find which process owns a socket by checking /proc
-// uses uid hint to skip processes we dont need to check
-static uint32_t find_pid_from_inode(unsigned long target_inode, uint32_t uid_hint)
+// ---- DNS tap: arm kernel rules for addresses whose names match domain rules ---------------------------------------------------
+// Caller holds G.lock (read or write).
+static void arm_ip_locked(uint32_t ip, const char *const *names, int nnames)
{
- // build the socket string we're looking for
- char expected[64];
- int expected_len = snprintf(expected, sizeof(expected), "socket:[%lu]", target_inode);
-
- DIR *proc_dir = opendir("/proc");
- if (!proc_dir)
- return 0;
-
- uint32_t pid = 0;
- struct dirent *proc_entry;
-
- while ((proc_entry = readdir(proc_dir)) != NULL) {
- // skip stuff that aint a pid folder
- if (proc_entry->d_type != DT_DIR || !isdigit(proc_entry->d_name[0]))
- continue;
-
- // if we know the user id, skip other users processes
- // makes this way faster cuz less folders to check
- if (uid_hint != (uint32_t)-1) {
- struct stat proc_stat;
- char proc_path[280];
- snprintf(proc_path, sizeof(proc_path), "/proc/%s", proc_entry->d_name);
- if (stat(proc_path, &proc_stat) == 0 && proc_stat.st_uid != uid_hint)
- continue;
- }
-
- char fd_path[280];
- snprintf(fd_path, sizeof(fd_path), "/proc/%s/fd", proc_entry->d_name);
- DIR *fd_dir = opendir(fd_path);
- if (!fd_dir)
- continue;
-
- struct dirent *fd_entry;
- while ((fd_entry = readdir(fd_dir)) != NULL) {
- if (fd_entry->d_name[0] == '.')
- continue;
-
- char link_path[560];
- snprintf(link_path, sizeof(link_path), "/proc/%s/fd/%s",
- proc_entry->d_name, fd_entry->d_name);
-
- char link_target[64];
- ssize_t link_len = readlink(link_path, link_target, sizeof(link_target) - 1);
- if (link_len == expected_len) {
- link_target[link_len] = '\0';
- if (memcmp(link_target, expected, expected_len) == 0) {
- pid = (uint32_t)safe_atoi(proc_entry->d_name);
- closedir(fd_dir);
- closedir(proc_dir);
- return pid;
- }
- }
+ for (size_t i = 0; i < G.nrules; i++) {
+ const struct pb_rule *r = &G.rules[i];
+ if (!r->enabled || !r->ndomains) continue;
+ for (int d = 0; d < r->ndomains; d++) {
+ bool hit = false;
+ for (int k = 0; k < nnames && !hit; k++) hit = pb_domain_match(r->domains[d], names[k]);
+ if (hit) { pb_bpf_dom_set((uint32_t)i, ip); break; }
}
- closedir(fd_dir);
}
- closedir(proc_dir);
- return pid;
}
-// fast pid lookup using netlink
-// tcp uses exact query, udp needs dump
-static uint32_t get_process_id_from_connection(uint32_t src_ip, uint16_t src_port, bool is_udp)
+static void arm_cb(uint32_t ip, const char *const *names, int n, void *ctx)
{
- uint32_t cached_pid = get_cached_pid(src_ip, src_port, is_udp);
- if (cached_pid != 0)
- return cached_pid;
-
- int fd = socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_SOCK_DIAG);
- if (fd < 0)
- return 0;
-
- // short timeout so we dont block packet flow
- struct timeval tv = {0, 100000}; // 100ms
- setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
-
- struct {
- struct nlmsghdr nlh;
- struct inet_diag_req_v2 r;
- } req;
-
- memset(&req, 0, sizeof(req));
- req.nlh.nlmsg_len = sizeof(req);
- req.nlh.nlmsg_type = SOCK_DIAG_BY_FAMILY;
- req.r.sdiag_family = AF_INET;
- req.r.sdiag_protocol = is_udp ? IPPROTO_UDP : IPPROTO_TCP;
-
- // udp needs dump cuz no connection state to match on
- // tcp can filter to only syn_sent and established states
- req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;
- if (!is_udp)
- req.r.idiag_states = (1 << 2) | (1 << 3); // SYN_SENT(2) + ESTABLISHED(3) only
- else
- req.r.idiag_states = (uint32_t)-1; // All states for UDP
- req.r.idiag_ext = 0;
-
- struct sockaddr_nl sa;
- memset(&sa, 0, sizeof(sa));
- sa.nl_family = AF_NETLINK;
-
- if (sendto(fd, &req, sizeof(req), 0, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
- close(fd);
- return 0;
- }
-
- uint32_t pid = 0;
- unsigned long target_inode = 0;
- uint32_t target_uid = (uint32_t)-1;
- bool found = false;
- char buf[16384];
- struct iovec iov = {buf, sizeof(buf)};
- struct msghdr msg = {&sa, sizeof(sa), &iov, 1, NULL, 0, 0};
-
- while (1) {
- ssize_t len = recvmsg(fd, &msg, 0);
- if (len <= 0)
- break;
-
- struct nlmsghdr *h = (struct nlmsghdr *)buf;
- while (NLMSG_OK(h, (size_t)len)) {
- if (h->nlmsg_type == NLMSG_DONE || h->nlmsg_type == NLMSG_ERROR)
- goto nl_done;
-
- if (h->nlmsg_type == SOCK_DIAG_BY_FAMILY) {
- struct inet_diag_msg *r = NLMSG_DATA(h);
-
- // check if this is our socket
- if (r->id.idiag_src[0] == src_ip && ntohs(r->id.idiag_sport) == src_port) {
- target_inode = r->idiag_inode;
- target_uid = r->idiag_uid; // UID to narrow /proc scan
- found = true;
- goto nl_done;
- }
- }
- h = NLMSG_NEXT(h, len);
- }
- }
-
-nl_done:
- close(fd);
-
- // if netlink found it, now find pid from inode
- // no need to scan /proc/net/tcp since we got inode already
- if (found && target_inode != 0) {
- pid = find_pid_from_inode(target_inode, target_uid);
- }
-
- // fallback for udp if netlink didnt find it
- // happens when app uses sendto without connecting socket first
- if (!found && is_udp) {
- const char* udp_files[] = {"/proc/net/udp", "/proc/net/udp6"};
- for (int file_idx = 0; file_idx < 2 && pid == 0; file_idx++) {
- FILE *fp = fopen(udp_files[file_idx], "r");
- if (!fp)
- continue;
-
- char line[512];
- if (!fgets(line, sizeof(line), fp)) { // skip header
- fclose(fp);
- continue;
- }
- while (fgets(line, sizeof(line), fp)) {
- unsigned int local_addr, local_port;
- unsigned long inode;
- int uid_val;
-
- if (sscanf(line, "%*d: %X:%X %*X:%*X %*X %*X:%*X %*X:%*X %*X %d %*d %lu",
- &local_addr, &local_port, &uid_val, &inode) == 4) {
- if (local_port == src_port && inode != 0) {
- pid = find_pid_from_inode(inode, (uint32_t)uid_val);
- break;
- }
- }
- }
- fclose(fp);
- }
- }
-
- if (pid != 0)
- cache_pid(src_ip, src_port, pid, is_udp);
- return pid;
+ (void)ctx;
+ arm_ip_locked(ip, names, n);
}
-static bool get_process_name_from_pid(uint32_t pid, char *name, size_t name_size)
+static void rearm_all_locked(void)
{
- if (pid == 0)
- return false;
-
- // pid 1 is always init/systemd
- // kinda like windows pid 4 for system stuff
- if (pid == 1)
- {
- snprintf(name, name_size, "systemd");
- return true;
- }
-
- char path[64];
- snprintf(path, sizeof(path), "/proc/%u/exe", pid);
-
- ssize_t len = readlink(path, name, name_size - 1);
- if (len < 0)
- return false;
-
- name[len] = '\0';
- return true;
+ pb_bpf_dom_clear();
+ if (atomic_load(&G.has_domain_rules)) pb_dns_for_each(arm_cb, NULL);
}
-static bool match_ip_pattern(const char *pattern, uint32_t ip)
+void pb_core_dns_observe(const uint8_t *msg, size_t len)
{
- if (pattern == NULL || strcmp(pattern, "*") == 0)
- return true;
-
- unsigned char ip_octets[4];
- ip_octets[0] = (ip >> 0) & 0xFF;
- ip_octets[1] = (ip >> 8) & 0xFF;
- ip_octets[2] = (ip >> 16) & 0xFF;
- ip_octets[3] = (ip >> 24) & 0xFF;
-
- char pattern_copy[256];
- strncpy(pattern_copy, pattern, sizeof(pattern_copy) - 1);
- pattern_copy[sizeof(pattern_copy) - 1] = '\0';
-
- char pattern_octets[4][16];
- int octet_count = 0;
- int char_idx = 0;
-
- for (size_t i = 0; i <= strlen(pattern_copy) && octet_count < 4; i++)
- {
- if (pattern_copy[i] == '.' || pattern_copy[i] == '\0')
- {
- pattern_octets[octet_count][char_idx] = '\0';
- octet_count++;
- char_idx = 0;
- if (pattern_copy[i] == '\0')
- break;
- }
- else
- {
- if (char_idx < 15)
- pattern_octets[octet_count][char_idx++] = pattern_copy[i];
- }
- }
-
- if (octet_count != 4)
- return false;
-
- for (int i = 0; i < 4; i++)
- {
- if (strcmp(pattern_octets[i], "*") == 0)
- continue;
-
- char *dash = strchr(pattern_octets[i], '-');
- if (dash != NULL)
- {
- int start = safe_atoi(pattern_octets[i]);
- int end = safe_atoi(dash + 1);
- if (ip_octets[i] < start || ip_octets[i] > end)
- return false;
- }
- else
- {
- int pattern_val = safe_atoi(pattern_octets[i]);
- if (pattern_val != ip_octets[i])
- return false;
- }
+ if (!atomic_load(&G.has_domain_rules)) return;
+ struct pb_dns_result res;
+ if (pb_dns_observe(msg, len, &res) <= 0) return;
+ pthread_rwlock_rdlock(&G.lock);
+ for (int i = 0; i < res.nips; i++) {
+ char names[PB_DNS_MAX_NAMES][256];
+ const char *ptrs[PB_DNS_MAX_NAMES];
+ int n = pb_dns_lookup(res.ips[i], names, PB_DNS_MAX_NAMES);
+ for (int k = 0; k < n; k++) ptrs[k] = names[k];
+ arm_ip_locked(res.ips[i], ptrs, n);
}
- return true;
+ pthread_rwlock_unlock(&G.lock);
}
-static bool match_port_pattern(const char *pattern, uint16_t port)
+// ---- rule -> BPF sync ------------------------------------------------------------------------------------------------------
+static struct pb_rule_view *build_views_locked(size_t *n)
{
- if (pattern == NULL || strcmp(pattern, "*") == 0)
- return true;
-
- char *dash = strchr(pattern, '-');
- if (dash != NULL)
- {
- int start_port = safe_atoi(pattern);
- int end_port = safe_atoi(dash + 1);
- return (port >= start_port && port <= end_port);
+ struct pb_rule_view *v = calloc(G.nrules ? G.nrules : 1, sizeof *v);
+ if (!v) return NULL;
+ for (size_t i = 0; i < G.nrules; i++) {
+ const struct pb_rule *r = &G.rules[i];
+ v[i].rule = r;
+ v[i].action = r->action;
+ if (r->action == RULE_ACTION_PROXY) {
+ struct pb_proxy *p = r->proxy_id ? find_proxy_locked(r->proxy_id) : NULL;
+ if (!p) p = default_proxy_locked();
+ if (!p) v[i].action = RULE_ACTION_BLOCK; // no usable proxy: fail closed
+ else { v[i].proxy_id = (uint16_t)p->id; v[i].udp_direct = p->type == PROXY_TYPE_HTTP; }
+ }
}
-
- return (port == safe_atoi(pattern));
+ *n = G.nrules;
+ return v;
}
-static bool ip_match_wrapper(const char *token, const void *data)
+static void sync_locked(void)
{
- return match_ip_pattern(token, *(const uint32_t*)data);
+ if (!G.running) return;
+ size_t n;
+ struct pb_rule_view *v = build_views_locked(&n);
+ bool dom = false;
+ for (size_t i = 0; i < G.nrules; i++) dom |= G.rules[i].enabled && G.rules[i].ndomains > 0;
+ atomic_store(&G.has_domain_rules, dom);
+ if (v && pb_bpf_sync(v, n) != 0) pb_core_log("failed to apply rules to the kernel datapath");
+ free(v);
+ rearm_all_locked();
+ pb_bpf_set_flags(G.traffic_logging, G.dns_via_proxy);
}
-static bool match_ip_list(const char *ip_list, uint32_t ip)
+// ---- slow path -------------------------------------------------------------------------------------------------------------
+static bool exe_path_of_pid(uint32_t pid, char *out, size_t n)
{
- return parse_token_list(ip_list, ";", ip_match_wrapper, &ip);
+ char lnk[64];
+ snprintf(lnk, sizeof lnk, "/proc/%u/exe", pid);
+ ssize_t r = readlink(lnk, out, n - 1);
+ if (r <= 0) { out[0] = 0; return false; }
+ out[r] = 0;
+ size_t l = strlen(out);
+ if (l > 10 && !strcmp(out + l - 10, " (deleted)")) out[l - 10] = 0;
+ return true;
}
-static bool port_match_wrapper(const char *token, const void *data)
-{
- return match_port_pattern(token, *(const uint16_t*)data);
+void pb_core_decide(const struct pb_orig *o, struct pb_decision *out)
+{
+ char path[512];
+ exe_path_of_pid(o->pid, path, sizeof path); // may be empty if the process is already gone
+ out->action = PB_ACT_DIRECT; out->proxy_id = 0;
+
+ pthread_rwlock_rdlock(&G.lock);
+ if (!pb_implicit_direct(o->family, o->addr, o->port, o->proto, G.dns_via_proxy)) {
+ char nbuf[PB_DNS_MAX_NAMES][256];
+ const char *nptr[PB_DNS_MAX_NAMES];
+ int nn = 0;
+ if (o->family == AF_INET && atomic_load(&G.has_domain_rules)) {
+ uint32_t h = ((uint32_t)o->addr[12] << 24) | ((uint32_t)o->addr[13] << 16) | ((uint32_t)o->addr[14] << 8) | o->addr[15];
+ nn = pb_dns_lookup(h, nbuf, PB_DNS_MAX_NAMES);
+ for (int k = 0; k < nn; k++) nptr[k] = nbuf[k];
+ }
+ int idx = pb_rules_eval(G.rules, G.nrules, path, o->family, o->addr, o->port, o->proto, nptr, nn);
+ if (idx >= 0) {
+ const struct pb_rule *r = &G.rules[idx];
+ if (r->action == RULE_ACTION_PROXY) {
+ struct pb_proxy *p = r->proxy_id ? find_proxy_locked(r->proxy_id) : NULL;
+ if (!p) p = default_proxy_locked();
+ if (!p) out->action = PB_ACT_BLOCK;
+ else if (o->proto == IPPROTO_UDP && p->type == PROXY_TYPE_HTTP) out->action = PB_ACT_DIRECT;
+ else { out->action = PB_ACT_PROXY; out->proxy_id = p->id; }
+ } else out->action = r->action == RULE_ACTION_BLOCK ? PB_ACT_BLOCK : PB_ACT_DIRECT;
+ }
+ }
+ if (o->exe_ino && path[0]) { // teach the kernel this binary so the next flow skips the relay
+ size_t n;
+ struct pb_rule_view *v = build_views_locked(&n);
+ if (v) { pb_bpf_learn(o, path, v, n); free(v); }
+ }
+ pthread_rwlock_unlock(&G.lock);
+}
+
+int pb_core_take_tcp_orig(uint16_t client_port, struct pb_orig *out) { return pb_bpf_take_tcp_orig(client_port, out); }
+int pb_core_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out) { return pb_bpf_get_udp_flow(flow_ip_be, out); }
+
+// ---- public API: proxies -----------------------------------------------------------------------------------------------
+uint32_t ProxyBridge_AddProxy(const char *name, ProxyType type, const char *host, uint16_t port, const char *user, const char *pass, char *err, size_t en)
+{
+ if (!valid_proxy(host, port, err, en)) return 0;
+ pthread_rwlock_wrlock(&G.lock);
+ uint32_t id = 0;
+ if (G.nproxies >= MAX_PROXIES) set_err(err, en, "too many proxies (max %d)", MAX_PROXIES);
+ else {
+ struct pb_proxy *p = &G.proxies[G.nproxies++];
+ memset(p, 0, sizeof *p);
+ p->id = id = G.next_proxy_id++;
+ fill_proxy(p, name, type, host, port, user, pass);
+ sync_locked();
+ }
+ pthread_rwlock_unlock(&G.lock);
+ return id;
+}
+
+bool ProxyBridge_EditProxy(uint32_t id, const char *name, ProxyType type, const char *host, uint16_t port, const char *user, const char *pass, char *err, size_t en)
+{
+ if (!valid_proxy(host, port, err, en)) return false;
+ pthread_rwlock_wrlock(&G.lock);
+ struct pb_proxy *p = find_proxy_locked(id);
+ if (p) { fill_proxy(p, name, type, host, port, user, pass); sync_locked(); }
+ else set_err(err, en, "unknown proxy id %u", id);
+ pthread_rwlock_unlock(&G.lock);
+ return p != NULL;
+}
+
+bool ProxyBridge_DeleteProxy(uint32_t id)
+{
+ pthread_rwlock_wrlock(&G.lock);
+ bool ok = false;
+ for (size_t i = 0; i < G.nproxies; i++)
+ if (G.proxies[i].id == id) {
+ memmove(&G.proxies[i], &G.proxies[i + 1], (G.nproxies - i - 1) * sizeof G.proxies[0]);
+ G.nproxies--;
+ if (G.default_proxy == id) G.default_proxy = 0;
+ ok = true;
+ break;
+ }
+ if (ok) sync_locked();
+ pthread_rwlock_unlock(&G.lock);
+ return ok;
}
-static bool match_port_list(const char *port_list, uint16_t port)
+void ProxyBridge_ClearProxies(void)
{
- return parse_token_list(port_list, ",;", port_match_wrapper, &port);
+ pthread_rwlock_wrlock(&G.lock);
+ G.nproxies = 0; G.default_proxy = 0;
+ sync_locked();
+ pthread_rwlock_unlock(&G.lock);
}
-static bool match_process_pattern(const char *pattern, const char *process_full_path)
+void ProxyBridge_SetDefaultProxy(uint32_t id)
{
- if (pattern == NULL || strcmp(pattern, "*") == 0)
- return true;
-
- const char *filename = strrchr(process_full_path, '/');
- if (filename != NULL)
- filename++;
- else
- filename = process_full_path;
-
- size_t pattern_len = strlen(pattern);
- size_t name_len = strlen(filename);
- size_t full_path_len = strlen(process_full_path);
-
- bool is_full_path_pattern = (strchr(pattern, '/') != NULL);
- const char *match_target = is_full_path_pattern ? process_full_path : filename;
- size_t target_len = is_full_path_pattern ? full_path_len : name_len;
-
- if (pattern_len > 0 && pattern[pattern_len - 1] == '*')
- {
- return strncasecmp(pattern, match_target, pattern_len - 1) == 0;
- }
-
- if (pattern_len > 1 && pattern[0] == '*')
- {
- const char *pattern_suffix = pattern + 1;
- size_t suffix_len = pattern_len - 1;
- if (target_len >= suffix_len)
- {
- return strcasecmp(match_target + target_len - suffix_len, pattern_suffix) == 0;
- }
- return false;
- }
-
- return strcasecmp(pattern, match_target) == 0;
+ pthread_rwlock_wrlock(&G.lock);
+ G.default_proxy = id;
+ sync_locked();
+ pthread_rwlock_unlock(&G.lock);
}
-typedef struct {
- const char *process_name;
-} process_match_data;
-
-static bool process_match_wrapper(const char *token, const void *data)
+bool ProxyBridge_SetProxyConfig(ProxyType type, const char *host, uint16_t port, const char *user, const char *pass)
{
- const process_match_data *pdata = data;
- return match_process_pattern(token, pdata->process_name);
+ char err[256];
+ pthread_rwlock_rdlock(&G.lock);
+ struct pb_proxy *d = default_proxy_locked();
+ uint32_t id = d ? d->id : 0;
+ pthread_rwlock_unlock(&G.lock);
+ if (id) return ProxyBridge_EditProxy(id, NULL, type, host, port, user, pass, err, sizeof err);
+ return ProxyBridge_AddProxy("default", type, host, port, user, pass, err, sizeof err) != 0;
}
-static bool match_process_list(const char *process_list, const char *process_name)
+// ---- public API: rules ---------------------------------------------------------------------------------------------------
+bool ProxyBridge_ValidateRule(const char *process, const char *hosts, const char *ports, char *err, size_t en)
{
- process_match_data data = {process_name};
- return parse_token_list(process_list, ";", process_match_wrapper, &data);
+ struct pb_rule r;
+ if (!pb_rule_parse(&r, process, hosts, ports, err, en)) return false;
+ pb_rule_free(&r);
+ return true;
}
-static uint32_t parse_ipv4(const char *ip)
+static struct pb_rule *find_rule_locked(uint32_t id, size_t *idx)
{
- unsigned int a, b, c, d;
- if (sscanf(ip, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
- return 0;
- if (a > 255 || b > 255 || c > 255 || d > 255)
- return 0;
- return (a << 0) | (b << 8) | (c << 16) | (d << 24);
+ for (size_t i = 0; i < G.nrules; i++) if (G.rules[i].id == id) { if (idx) *idx = i; return &G.rules[i]; }
+ return NULL;
}
-static uint32_t resolve_hostname(const char *hostname)
-{
- if (hostname == NULL || hostname[0] == '\0')
- return 0;
-
- uint32_t ip = parse_ipv4(hostname);
- if (ip != 0)
- return ip;
-
- struct addrinfo hints, *result = NULL;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_INET;
- hints.ai_socktype = SOCK_STREAM;
-
- if (getaddrinfo(hostname, NULL, &hints, &result) != 0)
- {
- log_message("failed to resolve hostname: %s", hostname);
- return 0;
- }
-
- if (result == NULL || result->ai_family != AF_INET)
- {
- if (result != NULL)
- freeaddrinfo(result);
- log_message("no ipv4 address found for hostname: %s", hostname);
- return 0;
- }
-
- struct sockaddr_in *addr = (struct sockaddr_in *)result->ai_addr;
- uint32_t resolved_ip = addr->sin_addr.s_addr;
- freeaddrinfo(result);
-
- return resolved_ip;
+uint32_t ProxyBridge_AddRule(const char *proc, const char *hosts, const char *ports, RuleProtocol protocol, RuleAction action, uint32_t proxy_id, char *err, size_t en)
+{
+ struct pb_rule r;
+ if (!pb_rule_parse(&r, proc, hosts, ports, err, en)) return 0;
+ r.enabled = true; r.protocol = protocol; r.action = action; r.proxy_id = proxy_id;
+ pthread_rwlock_wrlock(&G.lock);
+ uint32_t id = 0;
+ if (G.nrules >= PB_MAX_RULES) { set_err(err, en, "too many rules (max %d)", PB_MAX_RULES); pb_rule_free(&r); }
+ else {
+ if (G.nrules == G.caprules) {
+ size_t nc = G.caprules ? G.caprules * 2 : 32;
+ struct pb_rule *nr = realloc(G.rules, nc * sizeof *nr);
+ if (!nr) { pb_rule_free(&r); set_err(err, en, "out of memory"); pthread_rwlock_unlock(&G.lock); return 0; }
+ G.rules = nr; G.caprules = nc;
+ }
+ r.id = id = G.next_rule_id++;
+ G.rules[G.nrules++] = r;
+ sync_locked();
+ }
+ pthread_rwlock_unlock(&G.lock);
+ return id;
+}
+
+bool ProxyBridge_EditRule(uint32_t id, const char *proc, const char *hosts, const char *ports, RuleProtocol protocol, RuleAction action, uint32_t proxy_id, char *err, size_t en)
+{
+ struct pb_rule r;
+ if (!pb_rule_parse(&r, proc, hosts, ports, err, en)) return false;
+ pthread_rwlock_wrlock(&G.lock);
+ struct pb_rule *old = find_rule_locked(id, NULL);
+ if (!old) { set_err(err, en, "unknown rule id %u", id); pb_rule_free(&r); pthread_rwlock_unlock(&G.lock); return false; }
+ r.id = id; r.enabled = old->enabled; r.protocol = protocol; r.action = action; r.proxy_id = proxy_id;
+ pb_rule_free(old);
+ *old = r;
+ sync_locked();
+ pthread_rwlock_unlock(&G.lock);
+ return true;
}
-static bool is_broadcast_or_multicast(uint32_t ip)
+static bool set_enabled(uint32_t id, bool on)
{
- // localhost
- uint8_t first_octet = (ip >> 0) & 0xFF;
- if (first_octet == 127)
- return true;
-
- // link-local apipa stuff
- uint8_t second_octet = (ip >> 8) & 0xFF;
- if (first_octet == 169 && second_octet == 254)
- return true;
-
- // broadcast
- if (ip == 0xFFFFFFFF)
- return true;
-
- // subnet broadcast
- if ((ip & 0xFF000000) == 0xFF000000)
- return true;
-
- // multicast range
- if (first_octet >= 224 && first_octet <= 239)
- return true;
-
- return false;
+ pthread_rwlock_wrlock(&G.lock);
+ struct pb_rule *r = find_rule_locked(id, NULL);
+ if (r) { r->enabled = on; sync_locked(); }
+ pthread_rwlock_unlock(&G.lock);
+ return r != NULL;
}
+bool ProxyBridge_EnableRule(uint32_t id) { return set_enabled(id, true); }
+bool ProxyBridge_DisableRule(uint32_t id) { return set_enabled(id, false); }
-static RuleAction match_rule(const char *process_name, uint32_t dest_ip, uint16_t dest_port, bool is_udp)
+bool ProxyBridge_DeleteRule(uint32_t id)
{
- PROCESS_RULE *rule = rules_list;
- PROCESS_RULE *wildcard_rule = NULL;
-
- while (rule != NULL)
- {
- if (!rule->enabled)
- {
- rule = rule->next;
- continue;
- }
-
- if (rule->protocol != RULE_PROTOCOL_BOTH)
- {
- if (rule->protocol == RULE_PROTOCOL_TCP && is_udp)
- {
- rule = rule->next;
- continue;
- }
- if (rule->protocol == RULE_PROTOCOL_UDP && !is_udp)
- {
- rule = rule->next;
- continue;
- }
- }
-
- bool is_wildcard_process = (strcmp(rule->process_name, "*") == 0 || strcasecmp(rule->process_name, "ANY") == 0);
-
- if (is_wildcard_process)
- {
- bool has_ip_filter = (strcmp(rule->target_hosts, "*") != 0);
- bool has_port_filter = (strcmp(rule->target_ports, "*") != 0);
-
- if (has_ip_filter || has_port_filter)
- {
- if (match_ip_list(rule->target_hosts, dest_ip) &&
- match_port_list(rule->target_ports, dest_port))
- {
- return rule->action;
- }
- rule = rule->next;
- continue;
- }
-
- if (wildcard_rule == NULL)
- {
- wildcard_rule = rule;
- }
- rule = rule->next;
- continue;
- }
-
- if (match_process_list(rule->process_name, process_name))
- {
- if (match_ip_list(rule->target_hosts, dest_ip) &&
- match_port_list(rule->target_ports, dest_port))
- {
- return rule->action;
- }
- }
-
- rule = rule->next;
- }
-
- if (wildcard_rule != NULL)
- {
- return wildcard_rule->action;
+ pthread_rwlock_wrlock(&G.lock);
+ size_t i;
+ struct pb_rule *r = find_rule_locked(id, &i);
+ if (r) {
+ pb_rule_free(r);
+ memmove(&G.rules[i], &G.rules[i + 1], (G.nrules - i - 1) * sizeof *r);
+ G.nrules--;
+ sync_locked();
}
-
- return RULE_ACTION_DIRECT;
+ pthread_rwlock_unlock(&G.lock);
+ return r != NULL;
}
-static RuleAction check_process_rule(uint32_t src_ip, uint16_t src_port, uint32_t dest_ip, uint16_t dest_port, bool is_udp, uint32_t *out_pid)
+bool ProxyBridge_MoveRule(uint32_t id, int new_index)
{
- uint32_t pid;
- char process_name[MAX_PROCESS_NAME];
-
- pid = get_process_id_from_connection(src_ip, src_port, is_udp);
-
- if (out_pid != NULL)
- *out_pid = pid;
-
- if (pid == 0)
- return RULE_ACTION_DIRECT;
-
- if (pid == g_current_process_id)
- return RULE_ACTION_DIRECT;
-
- if (!get_process_name_from_pid(pid, process_name, sizeof(process_name)))
- return RULE_ACTION_DIRECT;
-
- pthread_rwlock_rdlock(&rules_lock);
- RuleAction action = match_rule(process_name, dest_ip, dest_port, is_udp);
- pthread_rwlock_unlock(&rules_lock);
-
- if (action == RULE_ACTION_PROXY && is_udp && g_proxy_type == PROXY_TYPE_HTTP)
- {
- return RULE_ACTION_DIRECT;
+ pthread_rwlock_wrlock(&G.lock);
+ size_t i;
+ struct pb_rule *r = find_rule_locked(id, &i);
+ if (r) {
+ size_t to = new_index < 0 ? 0 : (size_t)new_index >= G.nrules ? G.nrules - 1 : (size_t)new_index;
+ struct pb_rule tmp = *r;
+ if (to < i) memmove(&G.rules[to + 1], &G.rules[to], (i - to) * sizeof tmp);
+ else if (to > i) memmove(&G.rules[i], &G.rules[i + 1], (to - i) * sizeof tmp);
+ G.rules[to] = tmp;
+ sync_locked();
}
- if (action == RULE_ACTION_PROXY && (g_proxy_host[0] == '\0' || g_proxy_port == 0))
- {
- return RULE_ACTION_DIRECT;
- }
-
- return action;
+ pthread_rwlock_unlock(&G.lock);
+ return r != NULL;
}
-// Read exactly n bytes, looping over short reads. SOCKS5/HTTP replies can split
-// across TCP segments (common on high-latency remote proxies), so fixed-length
-// handshake reads must accumulate. Returns n on success, -1 on error/peer close.
-static int recv_n(int s, void *buf, size_t n)
+void ProxyBridge_ClearRules(void)
{
- size_t got = 0;
- while (got < n)
- {
- ssize_t r = recv(s, (char *)buf + got, n - got, 0);
- if (r <= 0) return -1;
- got += (size_t)r;
- }
- return (int)n;
+ pthread_rwlock_wrlock(&G.lock);
+ for (size_t i = 0; i < G.nrules; i++) pb_rule_free(&G.rules[i]);
+ G.nrules = 0;
+ sync_locked();
+ pthread_rwlock_unlock(&G.lock);
}
-// Read and validate a SOCKS5 CONNECT reply (RFC 1928). The proxy chooses the
-// BND.ADDR type in its reply independently of the request's ATYP - many proxies
-// answer with a 4-byte IPv4 0.0.0.0 even for other requests - so parse the 4-byte
-// header (VER REP RSV ATYP) then drain the variable BND.ADDR + BND.PORT by ATYP,
-// instead of assuming a fixed 10-byte reply. *reply gets REP (or -1) for logging.
-static int socks5_read_connect_reply(int s, int *reply)
+// ---- public API: runtime -----------------------------------------------------------------------------------------------------
+void ProxyBridge_SetDnsViaProxy(bool enable)
{
- unsigned char hdr[4];
- if (reply) *reply = -1;
- if (recv_n(s, hdr, 4) != 4) return -1;
- if (reply) *reply = hdr[1];
- if (hdr[0] != SOCKS5_VERSION || hdr[1] != 0x00) return -1;
-
- int drain;
- if (hdr[3] == SOCKS5_ATYP_IPV4) drain = 4 + 2;
- else if (hdr[3] == 0x04 /* IPv6 */) drain = 16 + 2;
- else if (hdr[3] == 0x03 /* domain */)
- {
- unsigned char dlen;
- if (recv_n(s, &dlen, 1) != 1) return -1;
- drain = (int)dlen + 2;
- }
- else return -1; // unknown ATYP
-
- unsigned char scratch[270]; // max drain = 255 + 2 (domain) < 270
- if (drain > 0 && recv_n(s, scratch, (size_t)drain) != drain) return -1;
- return 0;
+ pthread_rwlock_wrlock(&G.lock);
+ G.dns_via_proxy = enable;
+ pb_bpf_set_flags(G.traffic_logging, G.dns_via_proxy);
+ pthread_rwlock_unlock(&G.lock);
}
-static int socks5_connect(int s, uint32_t dest_ip, uint16_t dest_port)
-{
- unsigned char buf[SOCKS5_BUFFER_SIZE];
- bool use_auth = (g_proxy_username[0] != '\0');
-
- buf[0] = SOCKS5_VERSION;
- if (use_auth)
- {
- buf[1] = 0x02;
- buf[2] = SOCKS5_AUTH_NONE;
- buf[3] = 0x02;
- if (send(s, buf, 4, MSG_NOSIGNAL) != 4)
- {
- log_message("socks5 failed to send auth methods");
- return -1;
- }
- }
- else
- {
- buf[1] = 0x01;
- buf[2] = SOCKS5_AUTH_NONE;
- if (send(s, buf, 3, MSG_NOSIGNAL) != 3)
- {
- log_message("socks5 failed to send auth methods");
- return -1;
- }
- }
-
- if (recv_n(s, buf, 2) != 2 || buf[0] != SOCKS5_VERSION)
- {
- log_message("socks5 invalid auth response");
- return -1;
- }
-
- if (buf[1] == 0x02 && use_auth)
- {
- size_t ulen = strlen(g_proxy_username);
- size_t plen = strlen(g_proxy_password);
- if (ulen > 255 || plen > 255) // SOCKS5 username/password fields are length-prefixed by one byte
- {
- log_message("socks5 credentials too long");
- return -1;
- }
- buf[0] = 0x01;
- buf[1] = (unsigned char)ulen;
- memcpy(buf + 2, g_proxy_username, ulen);
- buf[2 + ulen] = (unsigned char)plen;
- memcpy(buf + 3 + ulen, g_proxy_password, plen);
-
- if (send(s, buf, 3 + ulen + plen, MSG_NOSIGNAL) != (ssize_t)(3 + ulen + plen))
- {
- log_message("socks5 failed to send credentials");
- return -1;
- }
-
- if (recv_n(s, buf, 2) != 2 || buf[0] != 0x01 || buf[1] != 0x00)
- {
- log_message("socks5 authentication failed");
- return -1;
- }
- }
- else if (buf[1] != SOCKS5_AUTH_NONE)
- {
- log_message("socks5 unsupported auth method");
- return -1;
- }
+void ProxyBridge_SetLogCallback(LogCallback cb) { pthread_mutex_lock(&cb_lock); G.log_cb = cb; pthread_mutex_unlock(&cb_lock); }
+void ProxyBridge_SetConnectionCallback(ConnectionCallback cb) { pthread_mutex_lock(&cb_lock); G.conn_cb = cb; pthread_mutex_unlock(&cb_lock); }
- buf[0] = SOCKS5_VERSION;
- buf[1] = SOCKS5_CMD_CONNECT;
- buf[2] = 0x00;
- buf[3] = SOCKS5_ATYP_IPV4;
- memcpy(buf + 4, &dest_ip, 4);
- uint16_t port_net = htons(dest_port);
- memcpy(buf + 8, &port_net, 2);
+void ProxyBridge_SetTrafficLoggingEnabled(bool enable)
+{
+ pthread_rwlock_wrlock(&G.lock);
+ G.traffic_logging = enable;
+ pb_bpf_set_flags(G.traffic_logging, G.dns_via_proxy);
+ pthread_rwlock_unlock(&G.lock);
+}
- if (send(s, buf, 10, MSG_NOSIGNAL) != 10)
- {
- log_message("socks5 failed to send connect request");
- return -1;
- }
+void ProxyBridge_ClearConnectionLogs(void) {}
- int reply = -1;
- if (socks5_read_connect_reply(s, &reply) != 0)
- {
- log_message("socks5 connect failed status %d", reply);
- return -1;
+bool ProxyBridge_Start(void)
+{
+ pthread_rwlock_wrlock(&G.lock);
+ if (G.running) { pthread_rwlock_unlock(&G.lock); return true; }
+ for (size_t i = 0; i < G.nrules; i++)
+ if (G.rules[i].enabled && G.rules[i].action == RULE_ACTION_PROXY && !default_proxy_locked() &&
+ !(G.rules[i].proxy_id && find_proxy_locked(G.rules[i].proxy_id))) {
+ pthread_rwlock_unlock(&G.lock);
+ pb_core_log("cannot start: a rule uses a proxy but no proxy is configured");
+ return false;
+ }
+ G.running = true; // pb_core_* callbacks may fire as soon as the relay is up
+ pthread_rwlock_unlock(&G.lock);
+
+ bool started = false;
+ for (uint16_t base = PB_TCP_RELAY_PORT_DEFAULT; base < PB_TCP_RELAY_PORT_DEFAULT + 20 && !started; base += 2) {
+ struct pb_relay_cfg rc = { .tcp_port = base, .udp_port = (uint16_t)(base + 1) };
+ started = pb_relay_start(&rc) == 0;
+ }
+ if (!started) { pthread_rwlock_wrlock(&G.lock); G.running = false; pthread_rwlock_unlock(&G.lock); return false; }
+
+ struct pb_bpf_cfg bc = { .tcp_port = pb_relay_tcp_port(), .udp_port = pb_relay_udp_port(), .self_tgid = (uint32_t)getpid(),
+ .log = G.traffic_logging, .dns_via_proxy = G.dns_via_proxy };
+ if (pb_bpf_start(&bc, on_bpf_event) != 0) {
+ pb_relay_stop();
+ pthread_rwlock_wrlock(&G.lock); G.running = false; pthread_rwlock_unlock(&G.lock);
+ return false;
}
-
- return 0;
+ pb_dns_load_hosts("/etc/hosts", NULL); // static names are known without any DNS traffic
+ pthread_rwlock_wrlock(&G.lock);
+ sync_locked();
+ pthread_rwlock_unlock(&G.lock);
+ pb_core_log("ProxyBridge started (eBPF datapath, relay tcp:%u udp:%u)", pb_relay_tcp_port(), pb_relay_udp_port());
+ return true;
}
-static int http_connect(int s, uint32_t dest_ip, uint16_t dest_port)
+bool ProxyBridge_Stop(void)
{
- char buf[HTTP_BUFFER_SIZE];
- char dest_ip_str[32];
- format_ip_address(dest_ip, dest_ip_str, sizeof(dest_ip_str));
-
- int len = snprintf(buf, sizeof(buf),
- "CONNECT %s:%d HTTP/1.1\r\n"
- "Host: %s:%d\r\n"
- "Proxy-Connection: Keep-Alive\r\n",
- dest_ip_str, dest_port, dest_ip_str, dest_port);
-
- if (g_proxy_username[0] != '\0')
- {
- // encode user:pass in base64
- static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- char auth_raw[512];
- int auth_raw_len = snprintf(auth_raw, sizeof(auth_raw), "%s:%s", g_proxy_username, g_proxy_password);
- char auth_b64[700];
- int j = 0;
- for (int i = 0; i < auth_raw_len; i += 3) {
- unsigned int n = ((unsigned char)auth_raw[i]) << 16;
- if (i + 1 < auth_raw_len) n |= ((unsigned char)auth_raw[i + 1]) << 8;
- if (i + 2 < auth_raw_len) n |= ((unsigned char)auth_raw[i + 2]);
- auth_b64[j++] = b64[(n >> 18) & 0x3F];
- auth_b64[j++] = b64[(n >> 12) & 0x3F];
- auth_b64[j++] = (i + 1 < auth_raw_len) ? b64[(n >> 6) & 0x3F] : '=';
- auth_b64[j++] = (i + 2 < auth_raw_len) ? b64[n & 0x3F] : '=';
- }
- auth_b64[j] = '\0';
- len += snprintf(buf + len, sizeof(buf) - len,
- "Proxy-Authorization: Basic %s\r\n", auth_b64);
- }
-
- len += snprintf(buf + len, sizeof(buf) - len, "\r\n");
-
- if (send_all(s, buf, len) < 0)
- {
- log_message("http failed to send connect");
- return -1;
- }
-
- ssize_t recv_len = recv(s, buf, sizeof(buf) - 1, 0);
- if (recv_len < 12)
- {
- log_message("http invalid response");
- return -1;
- }
-
- buf[recv_len] = '\0';
- if (strncmp(buf, "HTTP/1.", 7) != 0)
- {
- log_message("http invalid response");
- return -1;
- }
-
- int status_code = 0;
- if (sscanf(buf + 9, "%d", &status_code) != 1 || status_code != 200)
- {
- log_message("http connect failed status %d", status_code);
- return -1;
- }
-
- return 0;
+ pthread_rwlock_wrlock(&G.lock);
+ bool was = G.running;
+ G.running = false;
+ pthread_rwlock_unlock(&G.lock);
+ if (!was) return true;
+ pb_bpf_stop(); // detach first: no new flows get redirected
+ pb_relay_stop();
+ pb_core_log("ProxyBridge stopped");
+ return true;
}
-// relay functions for production use
-
-// connection handler like windows - blocks on connect then transfers data
-static void* connection_handler(void *arg)
+int ProxyBridge_TestProxy(uint32_t proxy_id, const char *host, uint16_t port, char *buf, size_t n)
{
- connection_config_t *config = (connection_config_t *)arg;
- int client_sock = config->client_socket;
- uint32_t dest_ip = config->orig_dest_ip;
- uint16_t dest_port = config->orig_dest_port;
- int proxy_sock;
- struct sockaddr_in proxy_addr;
- uint32_t proxy_ip;
-
- free(config);
-
- // use cached proxy ip we resolved earlier
- proxy_ip = g_proxy_ip_cached;
- if (proxy_ip == 0)
- {
- // try resolving again if cache failed
- proxy_ip = resolve_hostname(g_proxy_host);
- if (proxy_ip == 0)
- {
- close(client_sock);
- return NULL;
- }
- g_proxy_ip_cached = proxy_ip;
- }
-
- proxy_sock = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
- if (proxy_sock < 0)
- {
- close(client_sock);
- return NULL;
- }
-
- configure_tcp_socket(proxy_sock, 1048576, 60000);
- configure_tcp_socket(client_sock, 1048576, 60000);
-
- memset(&proxy_addr, 0, sizeof(proxy_addr));
- proxy_addr.sin_family = AF_INET;
- proxy_addr.sin_addr.s_addr = proxy_ip;
- proxy_addr.sin_port = htons(g_proxy_port);
-
- if (connect(proxy_sock, (struct sockaddr *)&proxy_addr, sizeof(proxy_addr)) < 0)
- {
- close(client_sock);
- close(proxy_sock);
- return NULL;
- }
-
- // do handshake blocking
- if (g_proxy_type == PROXY_TYPE_SOCKS5)
- {
- if (socks5_connect(proxy_sock, dest_ip, dest_port) != 0)
- {
- close(client_sock);
- close(proxy_sock);
- return NULL;
- }
- }
- else if (g_proxy_type == PROXY_TYPE_HTTP)
- {
- if (http_connect(proxy_sock, dest_ip, dest_port) != 0)
- {
- close(client_sock);
- close(proxy_sock);
- return NULL;
- }
- }
-
- // Data transfer phase (runs for both SOCKS5 and HTTP once the handshake succeeds).
- // Disable timeout for data transfer phase
- struct timeval zero_timeout = {0, 0};
- setsockopt(proxy_sock, SOL_SOCKET, SO_RCVTIMEO, &zero_timeout, sizeof(zero_timeout));
- setsockopt(proxy_sock, SOL_SOCKET, SO_SNDTIMEO, &zero_timeout, sizeof(zero_timeout));
- setsockopt(client_sock, SOL_SOCKET, SO_RCVTIMEO, &zero_timeout, sizeof(zero_timeout));
- setsockopt(client_sock, SOL_SOCKET, SO_SNDTIMEO, &zero_timeout, sizeof(zero_timeout));
-
- // Enable and configure customized TCP keep-alives
- int keepalive = 1;
- int keepidle = 300; // 5 minutes in seconds
- int keepintvl = 1; // 1 second interval
- int keepcnt = 5; // 5 probes before dropping
- setsockopt(proxy_sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive));
- setsockopt(proxy_sock, SOL_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
- setsockopt(proxy_sock, SOL_TCP, TCP_KEEPINTVL, &keepintvl, sizeof(keepintvl));
- setsockopt(proxy_sock, SOL_TCP, TCP_KEEPCNT, &keepcnt, sizeof(keepcnt));
- setsockopt(client_sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive));
- setsockopt(client_sock, SOL_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
- setsockopt(client_sock, SOL_TCP, TCP_KEEPINTVL, &keepintvl, sizeof(keepintvl));
- setsockopt(client_sock, SOL_TCP, TCP_KEEPCNT, &keepcnt, sizeof(keepcnt));
-
- // setup transfer config
- transfer_config_t *transfer_config = (transfer_config_t *)malloc(sizeof(transfer_config_t));
- if (transfer_config == NULL)
- {
- close(client_sock);
- close(proxy_sock);
- return NULL;
- }
-
- transfer_config->from_socket = client_sock;
- transfer_config->to_socket = proxy_sock;
-
- // transfer data both ways in this thread
- transfer_handler((void*)transfer_config);
-
- return NULL;
+ struct pb_proxy p;
+ if (pb_core_get_proxy(proxy_id, &p) != 0) { snprintf(buf, n, "no proxy configured"); return -1; }
+ return pb_relay_test_proxy(&p, host, port, buf, n);
}
-// relay data both ways using splice for zero-copy
-// data goes kernel to kernel thru pipe, never hits userspace
-// way faster than copying thru userspace buffers
-static void* transfer_handler(void *arg)
+int ProxyBridge_TestConnection(const char *host, uint16_t port, char *buf, size_t n)
{
- transfer_config_t *config = (transfer_config_t *)arg;
- int sock1 = config->from_socket; // client socket
- int sock2 = config->to_socket; // proxy socket
- free(config);
-
- // make 2 pipes for splice
- // pipe_a: proxy to client (download)
- // pipe_b: client to proxy (upload)
- int pipe_a[2] = {-1, -1};
- int pipe_b[2] = {-1, -1};
-
- if (pipe2(pipe_a, O_CLOEXEC | O_NONBLOCK) < 0 ||
- pipe2(pipe_b, O_CLOEXEC | O_NONBLOCK) < 0) {
- // pipe failed, cleanup and fallback
- if (pipe_a[0] >= 0) { close(pipe_a[0]); close(pipe_a[1]); }
- if (pipe_b[0] >= 0) { close(pipe_b[0]); close(pipe_b[1]); }
- goto fallback;
- }
-
- // make pipes bigger for better speed (64kb to 1mb)
- fcntl(pipe_a[0], F_SETPIPE_SZ, 1048576);
- fcntl(pipe_b[0], F_SETPIPE_SZ, 1048576);
-
- // set sockets to nonblocking for splice
- fcntl(sock1, F_SETFL, fcntl(sock1, F_GETFL, 0) | O_NONBLOCK);
- fcntl(sock2, F_SETFL, fcntl(sock2, F_GETFL, 0) | O_NONBLOCK);
-
- {
- struct pollfd fds[2];
- ssize_t pipe_a_bytes = 0; // bytes in download pipe (proxy→client)
- ssize_t pipe_b_bytes = 0; // bytes in upload pipe (client→proxy)
- bool sock1_done = false; // client EOF or error
- bool sock2_done = false; // proxy EOF or error
- bool shut_wr_sock1 = false; // already called shutdown(sock1, SHUT_WR)
- bool shut_wr_sock2 = false; // already called shutdown(sock2, SHUT_WR)
-
- while (1)
- {
- // build poll set, use fd=-1 to skip closed sockets
- // important: poll reports POLLHUP even with events=0
- // so use fd=-1 to actually skip it or we get busy loop
- fds[0].fd = (!sock1_done || pipe_a_bytes > 0 || pipe_b_bytes > 0) ? sock1 : -1;
- fds[1].fd = (!sock2_done || pipe_b_bytes > 0 || pipe_a_bytes > 0) ? sock2 : -1;
- fds[0].events = 0;
- fds[1].events = 0;
- fds[0].revents = 0;
- fds[1].revents = 0;
-
- // download: proxy to client
- if (!sock2_done && pipe_a_bytes == 0)
- fds[1].events |= POLLIN; // read from proxy
- if (pipe_a_bytes > 0)
- fds[0].events |= POLLOUT; // write to client
-
- // upload: client to proxy
- if (!sock1_done && pipe_b_bytes == 0)
- fds[0].events |= POLLIN; // read from client
- if (pipe_b_bytes > 0)
- fds[1].events |= POLLOUT; // write to proxy
-
- // all done
- if (fds[0].fd == -1 && fds[1].fd == -1)
- break;
- if (fds[0].events == 0 && fds[1].events == 0)
- break;
-
- int ready = poll(fds, 2, -1);
- if (ready < 0) {
- if (errno == EINTR) continue;
- break;
- }
-
- // check for errors and hangups
- if (fds[0].revents & POLLERR) break;
- if (fds[1].revents & POLLERR) break;
-
- // pollhup means other side closed
- if ((fds[1].revents & POLLHUP) && !(fds[1].revents & POLLIN))
- sock2_done = true;
- if ((fds[0].revents & POLLHUP) && !(fds[0].revents & POLLIN))
- sock1_done = true;
-
- // download path
-
- if (!sock2_done && pipe_a_bytes == 0 && (fds[1].revents & POLLIN)) {
- ssize_t n = splice(sock2, NULL, pipe_a[1], NULL, 1048576,
- SPLICE_F_MOVE | SPLICE_F_NONBLOCK);
- if (n > 0) {
- pipe_a_bytes = n;
- } else if (n == 0) {
- sock2_done = true;
- } else if (errno != EAGAIN && errno != EWOULDBLOCK) {
- sock2_done = true;
- }
- }
-
- if (pipe_a_bytes > 0 && (fds[0].revents & POLLOUT)) {
- ssize_t n = splice(pipe_a[0], NULL, sock1, NULL, pipe_a_bytes,
- SPLICE_F_MOVE | SPLICE_F_NONBLOCK);
- if (n > 0) {
- pipe_a_bytes -= n;
- } else if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
- break;
- }
- }
-
- // upload path
-
- if (!sock1_done && pipe_b_bytes == 0 && (fds[0].revents & POLLIN)) {
- ssize_t n = splice(sock1, NULL, pipe_b[1], NULL, 1048576,
- SPLICE_F_MOVE | SPLICE_F_NONBLOCK);
- if (n > 0) {
- pipe_b_bytes = n;
- } else if (n == 0) {
- sock1_done = true;
- } else if (errno != EAGAIN && errno != EWOULDBLOCK) {
- sock1_done = true;
- }
- }
-
- if (pipe_b_bytes > 0 && (fds[1].revents & POLLOUT)) {
- ssize_t n = splice(pipe_b[0], NULL, sock2, NULL, pipe_b_bytes,
- SPLICE_F_MOVE | SPLICE_F_NONBLOCK);
- if (n > 0) {
- pipe_b_bytes -= n;
- } else if (n < 0 && errno != EAGAIN && errno != EWOULDBLOCK) {
- break;
- }
- }
-
- // half-close when one side done and pipe empty
- // tell other side with shutdown
- if (sock2_done && pipe_a_bytes == 0 && !shut_wr_sock1) {
- shutdown(sock1, SHUT_WR);
- shut_wr_sock1 = true;
- }
- if (sock1_done && pipe_b_bytes == 0 && !shut_wr_sock2) {
- shutdown(sock2, SHUT_WR);
- shut_wr_sock2 = true;
- }
-
- // both sides finished and pipes empty
- if (sock1_done && sock2_done && pipe_a_bytes == 0 && pipe_b_bytes == 0)
- break;
- }
- }
-
- close(pipe_a[0]); close(pipe_a[1]);
- close(pipe_b[0]); close(pipe_b[1]);
- goto cleanup;
-
-fallback:
- // fallback to normal recv/send if pipes didnt work
- {
- char buf[131072];
- struct pollfd fds[2];
- fds[0].fd = sock1;
- fds[0].events = POLLIN;
- fds[1].fd = sock2;
- fds[1].events = POLLIN;
-
- while (1) {
- int ready = poll(fds, 2, -1);
- if (ready < 0) {
- if (errno == EINTR) continue;
- break;
- }
-
- if (fds[0].revents & POLLERR || fds[1].revents & POLLERR) break;
-
- bool did_work = false;
- if (fds[0].revents & POLLIN) {
- ssize_t n = recv(sock1, buf, sizeof(buf), MSG_NOSIGNAL);
- if (n <= 0) break;
- if (send_all(sock2, buf, n) < 0) break;
- did_work = true;
- }
- if (fds[1].revents & POLLIN) {
- ssize_t n = recv(sock2, buf, sizeof(buf), MSG_NOSIGNAL);
- if (n <= 0) break;
- if (send_all(sock1, buf, n) < 0) break;
- did_work = true;
- }
-
- // pollhup with no data means peer closed
- if (!did_work) break;
- }
- }
-
-cleanup:
- shutdown(sock1, SHUT_RDWR);
- shutdown(sock2, SHUT_RDWR);
- close(sock1);
- close(sock2);
- return NULL;
-}
-
-// proxy server accepts connections and spawns threads
-static void* local_proxy_server(void *arg)
-{
- (void)arg;
- struct sockaddr_in addr;
- int listen_sock;
- int on = 1;
-
- listen_sock = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
- if (listen_sock < 0)
- {
- log_message("Socket creation failed");
- return NULL;
- }
-
- setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
- setsockopt(listen_sock, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
-
- memset(&addr, 0, sizeof(addr));
- addr.sin_family = AF_INET;
- // loopback only, INADDR_ANY was reachable from the lan
- addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- addr.sin_port = htons(g_local_relay_port);
-
- if (bind(listen_sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
- {
- log_message("Bind failed");
- close(listen_sock);
- return NULL;
- }
-
- if (listen(listen_sock, SOMAXCONN) < 0)
- {
- log_message("Listen failed");
- close(listen_sock);
- return NULL;
- }
-
- // create thread attrs with small stack (256kb not 8mb)
- // relay threads dont need big buffers anymore cuz splice
- pthread_attr_t thread_attr;
- pthread_attr_init(&thread_attr);
- pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
- pthread_attr_setstacksize(&thread_attr, 262144); // 256KB stack
-
- struct pollfd pfd;
- pfd.fd = listen_sock;
- pfd.events = POLLIN;
-
- while (running)
- {
- int ready = poll(&pfd, 1, 1000); // 1s timeout
- if (ready <= 0)
- continue;
-
- struct sockaddr_in client_addr;
- socklen_t addr_len = sizeof(client_addr);
- int client_sock = accept4(listen_sock, (struct sockaddr *)&client_addr, &addr_len, SOCK_CLOEXEC);
-
- if (client_sock < 0)
- continue;
-
- connection_config_t *conn_config = (connection_config_t *)malloc(sizeof(connection_config_t));
- if (conn_config == NULL)
- {
- close(client_sock);
- continue;
- }
-
- conn_config->client_socket = client_sock;
-
- uint16_t client_port = ntohs(client_addr.sin_port);
- if (!get_connection(client_port, false, &conn_config->orig_dest_ip, &conn_config->orig_dest_port))
- {
- close(client_sock);
- free(conn_config);
- continue;
- }
-
- pthread_t conn_thread;
- if (pthread_create(&conn_thread, &thread_attr, connection_handler, (void*)conn_config) != 0)
- {
- close(client_sock);
- free(conn_config);
- continue;
- }
- }
-
- pthread_attr_destroy(&thread_attr);
- close(listen_sock);
- return NULL;
-}
-
-// socks5 udp associate
-static int socks5_udp_associate(int s, struct sockaddr_in *relay_addr)
-{
- unsigned char buf[SOCKS5_BUFFER_SIZE]; // must hold 3 + 255 + 255 auth bytes
-
- // auth handshake
- bool use_auth = (g_proxy_username[0] != '\0');
- buf[0] = SOCKS5_VERSION;
- buf[1] = use_auth ? 0x02 : 0x01;
- buf[2] = SOCKS5_AUTH_NONE;
- if (use_auth)
- buf[3] = 0x02; // username/password auth
-
- if (send(s, buf, use_auth ? 4 : 3, MSG_NOSIGNAL) != (use_auth ? 4 : 3))
- return -1;
-
- if (recv_n(s, buf, 2) != 2 || buf[0] != SOCKS5_VERSION)
- return -1;
-
- if (buf[1] == 0x02 && use_auth)
- {
- size_t ulen = strlen(g_proxy_username);
- size_t plen = strlen(g_proxy_password);
- if (ulen > 255 || plen > 255)
- return -1;
- buf[0] = 0x01;
- buf[1] = (unsigned char)ulen;
- memcpy(buf + 2, g_proxy_username, ulen);
- buf[2 + ulen] = (unsigned char)plen;
- memcpy(buf + 3 + ulen, g_proxy_password, plen);
-
- if (send(s, buf, 3 + ulen + plen, MSG_NOSIGNAL) != (ssize_t)(3 + ulen + plen))
- return -1;
-
- if (recv_n(s, buf, 2) != 2 || buf[0] != 0x01 || buf[1] != 0x00)
- return -1;
- }
- else if (buf[1] != SOCKS5_AUTH_NONE)
- return -1;
-
- // udp associate request
- buf[0] = SOCKS5_VERSION;
- buf[1] = SOCKS5_CMD_UDP_ASSOCIATE;
- buf[2] = 0x00;
- buf[3] = SOCKS5_ATYP_IPV4;
- memset(buf + 4, 0, 4); // 0.0.0.0
- memset(buf + 8, 0, 2); // port 0
-
- if (send(s, buf, 10, MSG_NOSIGNAL) != 10)
- return -1;
-
- // Reply: VER REP RSV ATYP BND.ADDR BND.PORT. Parse the header then the bound
- // relay endpoint; we only use IPv4 relay addresses.
- unsigned char rep[4];
- if (recv_n(s, rep, 4) != 4 || rep[0] != SOCKS5_VERSION || rep[1] != 0x00)
- return -1;
- if (rep[3] != SOCKS5_ATYP_IPV4)
- return -1;
- unsigned char ap[6];
- if (recv_n(s, ap, 6) != 6)
- return -1;
-
- memset(relay_addr, 0, sizeof(*relay_addr));
- relay_addr->sin_family = AF_INET;
- memcpy(&relay_addr->sin_addr.s_addr, ap, 4);
- memcpy(&relay_addr->sin_port, ap + 4, 2);
- return 0;
-}
-
-static bool establish_udp_associate(void)
-{
- uint64_t now = get_monotonic_ms();
- if (now - last_udp_connect_attempt < 5000)
- return false;
-
- last_udp_connect_attempt = now;
-
- if (socks5_udp_control_socket >= 0)
- {
- close(socks5_udp_control_socket);
- socks5_udp_control_socket = -1;
- }
- if (socks5_udp_send_socket >= 0)
- {
- close(socks5_udp_send_socket);
- socks5_udp_send_socket = -1;
- }
-
- int tcp_sock = socket(AF_INET, SOCK_STREAM, 0);
- if (tcp_sock < 0)
- return false;
-
- configure_tcp_socket(tcp_sock, 262144, 3000);
-
- uint32_t socks5_ip = resolve_hostname(g_proxy_host);
- if (socks5_ip == 0)
- {
- close(tcp_sock);
- return false;
- }
-
- struct sockaddr_in socks_addr;
- memset(&socks_addr, 0, sizeof(socks_addr));
- socks_addr.sin_family = AF_INET;
- socks_addr.sin_addr.s_addr = socks5_ip;
- socks_addr.sin_port = htons(g_proxy_port);
-
- if (connect(tcp_sock, (struct sockaddr *)&socks_addr, sizeof(socks_addr)) < 0)
- {
- close(tcp_sock);
- return false;
- }
-
- if (socks5_udp_associate(tcp_sock, &socks5_udp_relay_addr) != 0)
- {
- close(tcp_sock);
- return false;
- }
-
- // rfc says if server gives 0.0.0.0 use proxy servers ip instead
- if (socks5_udp_relay_addr.sin_addr.s_addr == INADDR_ANY)
- socks5_udp_relay_addr.sin_addr.s_addr = socks5_ip;
-
- // Handshake done - remove the 3s timeout so the control socket stays open indefinitely.
- struct timeval zero_tv = {0, 0};
- setsockopt(tcp_sock, SOL_SOCKET, SO_RCVTIMEO, &zero_tv, sizeof(zero_tv));
- setsockopt(tcp_sock, SOL_SOCKET, SO_SNDTIMEO, &zero_tv, sizeof(zero_tv));
-
- // Enable TCP keepalives so the SOCKS5 proxy doesn't idle-close the control
- // connection (many proxies terminate it after ~60s of silence, killing UDP ASSOCIATE).
- int ka_on = 1;
- int ka_idle = 10; // start keepalives after 10s idle
- int ka_intvl = 2; // send keepalive every 2s
- int ka_cnt = 5; // drop after 5 missed keepalives
- setsockopt(tcp_sock, SOL_SOCKET, SO_KEEPALIVE, &ka_on, sizeof(ka_on));
- setsockopt(tcp_sock, SOL_TCP, TCP_KEEPIDLE, &ka_idle, sizeof(ka_idle));
- setsockopt(tcp_sock, SOL_TCP, TCP_KEEPINTVL, &ka_intvl, sizeof(ka_intvl));
- setsockopt(tcp_sock, SOL_TCP, TCP_KEEPCNT, &ka_cnt, sizeof(ka_cnt));
-
- socks5_udp_control_socket = tcp_sock;
-
- socks5_udp_send_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- if (socks5_udp_send_socket < 0)
- {
- close(socks5_udp_control_socket);
- socks5_udp_control_socket = -1;
- return false;
- }
-
- configure_udp_socket(socks5_udp_send_socket, 262144, 30000);
-
- udp_associate_connected = true;
- log_message("UDP ASSOCIATE established with SOCKS5 proxy");
- return true;
-}
-
-// teardown udp associate so next packet reconnects
-static void teardown_udp_associate(void)
-{
- udp_associate_connected = false;
- if (socks5_udp_control_socket >= 0)
- {
- close(socks5_udp_control_socket);
- socks5_udp_control_socket = -1;
- }
- if (socks5_udp_send_socket >= 0)
- {
- close(socks5_udp_send_socket);
- socks5_udp_send_socket = -1;
- }
-}
-
-static void* udp_relay_server(void *arg)
-{
- (void)arg;
- struct sockaddr_in local_addr, from_addr;
- unsigned char recv_buf[65536];
- unsigned char send_buf[65536];
- socklen_t from_len;
-
- udp_relay_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
- if (udp_relay_socket < 0)
- return NULL;
-
- int on = 1;
- setsockopt(udp_relay_socket, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
- configure_udp_socket(udp_relay_socket, 262144, 30000);
-
- memset(&local_addr, 0, sizeof(local_addr));
- local_addr.sin_family = AF_INET;
- local_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- local_addr.sin_port = htons(LOCAL_UDP_RELAY_PORT);
-
- if (bind(udp_relay_socket, (struct sockaddr *)&local_addr, sizeof(local_addr)) < 0)
- {
- close(udp_relay_socket);
- udp_relay_socket = -1;
- return NULL;
- }
-
- // try initial connect, not fatal if proxy not up yet
- udp_associate_connected = establish_udp_associate();
-
- while (running)
- {
- struct pollfd fds[3];
- int nfds = 1;
-
- // watch local relay socket for client packets
- fds[0].fd = udp_relay_socket;
- fds[0].events = POLLIN;
- fds[0].revents = 0;
-
- // watch socks5 udp socket for proxy responses
- fds[1].fd = (udp_associate_connected && socks5_udp_send_socket >= 0) ? socks5_udp_send_socket : -1;
- fds[1].events = POLLIN;
- fds[1].revents = 0;
-
- // watch socks5 tcp socket to detect if connection dies
- fds[2].fd = (udp_associate_connected && socks5_udp_control_socket >= 0) ? socks5_udp_control_socket : -1;
- fds[2].events = POLLIN;
- fds[2].revents = 0;
- nfds = 3;
-
- int ready = poll(fds, nfds, 1000); // 1s timeout
- if (ready <= 0)
- {
- // Proactively reconnect so the next client packet is not dropped.
- if (!udp_associate_connected)
- udp_associate_connected = establish_udp_associate();
- continue;
- }
-
- // check if tcp control still alive
- // if it dies the udp associate is dead too
- if (fds[2].fd >= 0 && (fds[2].revents & (POLLIN | POLLHUP | POLLERR)))
- {
- char peek_buf[1];
- ssize_t peek_len = recv(socks5_udp_control_socket, peek_buf, 1, MSG_PEEK | MSG_DONTWAIT);
- if (peek_len == 0 || (peek_len < 0 && errno != EAGAIN && errno != EWOULDBLOCK))
- {
- // tcp died - tear down and reconnect immediately so real-time streams
- // lose as few packets as possible.
- teardown_udp_associate();
- udp_associate_connected = establish_udp_associate();
- continue;
- }
- }
-
- // client sending to proxy
- if (fds[0].revents & POLLIN)
- {
- from_len = sizeof(from_addr);
- ssize_t recv_len = recvfrom(udp_relay_socket, recv_buf, sizeof(recv_buf), 0,
- (struct sockaddr *)&from_addr, &from_len);
- if (recv_len <= 0)
- continue;
-
- // try to connect if not connected yet
- if (!udp_associate_connected)
- {
- if (!establish_udp_associate())
- continue;
- }
-
- uint16_t client_port = ntohs(from_addr.sin_port);
- uint32_t dest_ip;
- uint16_t dest_port;
-
- if (!get_connection(client_port, true, &dest_ip, &dest_port))
- continue;
-
- // make sure data fits with socks5 header
- if (recv_len > (ssize_t)(sizeof(send_buf) - 10))
- continue;
-
- // build socks5 udp packet header
- send_buf[0] = 0x00; // RSV
- send_buf[1] = 0x00; // RSV
- send_buf[2] = 0x00; // FRAG
- send_buf[3] = SOCKS5_ATYP_IPV4;
- memcpy(send_buf + 4, &dest_ip, 4);
- uint16_t port_net = htons(dest_port);
- memcpy(send_buf + 8, &port_net, 2);
- memcpy(send_buf + 10, recv_buf, recv_len);
-
- ssize_t sent = sendto(socks5_udp_send_socket, send_buf, 10 + recv_len, 0,
- (struct sockaddr *)&socks5_udp_relay_addr, sizeof(socks5_udp_relay_addr));
-
- if (sent < 0)
- {
- // sendto failed - proxy likely died. Tear down, reconnect immediately
- // and retry the current packet so real-time streams lose at most one packet.
- teardown_udp_associate();
- if (establish_udp_associate())
- {
- udp_associate_connected = true;
- sendto(socks5_udp_send_socket, send_buf, (size_t)(10 + recv_len), 0,
- (struct sockaddr *)&socks5_udp_relay_addr, sizeof(socks5_udp_relay_addr));
- }
- }
- else if (socks5_udp_send_socket >= 0)
- {
- // After sending (especially on a freshly established association), the proxy
- // may respond within the same poll() cycle before the socket was in fds[].
- // Do a non-blocking check now so we don't add an extra poll() round-trip.
- struct pollfd quick = { socks5_udp_send_socket, POLLIN, 0 };
- if (poll(&quick, 1, 0) > 0)
- fds[1].revents |= POLLIN;
- }
- }
-
- // proxy sending back to client
- if (fds[1].fd >= 0 && (fds[1].revents & POLLIN))
- {
- from_len = sizeof(from_addr);
- ssize_t recv_len = recvfrom(socks5_udp_send_socket, recv_buf, sizeof(recv_buf), 0,
- (struct sockaddr *)&from_addr, &from_len);
-
- // socket error, proxy might be dead
- if (recv_len < 0)
- {
- if (errno != EAGAIN && errno != EWOULDBLOCK)
- teardown_udp_associate();
- continue;
- }
- if (recv_len < 10)
- continue;
-
- // we dont support fragmented packets
- if (recv_buf[2] != 0x00)
- continue;
-
- // parse socks5 udp packet
- if (recv_buf[3] != SOCKS5_ATYP_IPV4)
- continue;
-
- uint32_t src_ip;
- uint16_t src_port;
- memcpy(&src_ip, recv_buf + 4, 4);
- memcpy(&src_port, recv_buf + 8, 2);
- src_port = ntohs(src_port);
-
- // find which client sent packet to this destination
- // loop thru hash table looking for dest match
- pthread_rwlock_rdlock(&conn_lock);
-
- struct sockaddr_in client_addr;
- bool found_client = false;
-
- for (int hash = 0; hash < CONNECTION_HASH_SIZE; hash++)
- {
- CONNECTION_INFO *conn = connection_hash_table[hash];
- while (conn != NULL)
- {
- if (conn->is_udp &&
- conn->orig_dest_ip == src_ip &&
- conn->orig_dest_port == src_port)
- {
- // found it, send response back to original client port
- memset(&client_addr, 0, sizeof(client_addr));
- client_addr.sin_family = AF_INET;
- client_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
- client_addr.sin_port = htons(conn->src_port);
- // Keep session alive while proxy delivers data (benign relaxed write under read lock)
- conn->last_activity = get_monotonic_ms();
- found_client = true;
- break;
- }
- conn = conn->next;
- }
- if (found_client)
- break;
- }
-
- pthread_rwlock_unlock(&conn_lock);
-
- if (found_client)
- {
- // send unwrapped data back to client
- ssize_t data_len = recv_len - 10;
- sendto(udp_relay_socket, recv_buf + 10, data_len, 0,
- (struct sockaddr *)&client_addr, sizeof(client_addr));
- }
- }
-
- // handle errors on udp send socket
- if (fds[1].fd >= 0 && (fds[1].revents & (POLLHUP | POLLERR)))
- {
- teardown_udp_associate();
- }
- }
-
- teardown_udp_associate();
- if (udp_relay_socket >= 0)
- close(udp_relay_socket);
-
- return NULL;
-}
-
-// nfqueue callback for packets
-static int packet_callback(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct nfq_data *nfad, void *data)
-{
- (void)nfmsg;
- (void)data;
-
- struct nfqnl_msg_packet_hdr *ph = nfq_get_msg_packet_hdr(nfad);
- if (!ph) return nfq_set_verdict(qh, 0, NF_ACCEPT, 0, NULL);
-
- uint32_t id = ntohl(ph->packet_id);
-
- unsigned char *payload;
- int payload_len = nfq_get_payload(nfad, &payload);
- if (payload_len < (int)sizeof(struct iphdr))
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
-
- struct iphdr *iph = (struct iphdr *)payload;
-
- // fast path when no rules
- if (!g_has_active_rules && g_connection_callback == NULL)
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
-
- uint32_t src_ip = iph->saddr;
- uint32_t dest_ip = iph->daddr;
- uint16_t src_port = 0;
- uint16_t dest_port = 0;
- RuleAction action = RULE_ACTION_DIRECT;
- uint32_t pid = 0;
-
- if (iph->protocol == IPPROTO_TCP)
- {
- if (payload_len < (int)(iph->ihl * 4 + sizeof(struct tcphdr)))
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
-
- struct tcphdr *tcph = (struct tcphdr *)(payload + iph->ihl * 4);
- src_port = ntohs(tcph->source);
- dest_port = ntohs(tcph->dest);
-
- // skip our own packets from local relay
- if (src_port == g_local_relay_port)
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
-
- if (is_connection_tracked(src_port, false))
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
-
- // only look at syn packets for new connections
- if (!(tcph->syn && !tcph->ack))
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
-
- if (dest_port == 53 && !g_dns_via_proxy)
- action = RULE_ACTION_DIRECT;
- else
- action = check_process_rule(src_ip, src_port, dest_ip, dest_port, false, &pid);
-
- if (action == RULE_ACTION_PROXY && is_broadcast_or_multicast(dest_ip))
- action = RULE_ACTION_DIRECT;
-
- // log it if not from our own process
- if (g_traffic_logging_enabled && g_connection_callback != NULL && (tcph->syn && !tcph->ack) && pid > 0 && pid != g_current_process_id)
- {
- char process_name[MAX_PROCESS_NAME];
- if (get_process_name_from_pid(pid, process_name, sizeof(process_name)))
- {
- if (!is_connection_already_logged(pid, dest_ip, dest_port, action))
- {
- char dest_ip_str[32];
- format_ip_address(dest_ip, dest_ip_str, sizeof(dest_ip_str));
-
- char proxy_info[300];
- if (action == RULE_ACTION_PROXY)
- {
- snprintf(proxy_info, sizeof(proxy_info), "proxy %s://%s:%d tcp",
- g_proxy_type == PROXY_TYPE_HTTP ? "http" : "socks5",
- g_proxy_host, g_proxy_port);
- }
- else if (action == RULE_ACTION_DIRECT)
- {
- snprintf(proxy_info, sizeof(proxy_info), "direct tcp");
- }
- else if (action == RULE_ACTION_BLOCK)
- {
- snprintf(proxy_info, sizeof(proxy_info), "blocked tcp");
- }
-
- const char* display_name = extract_filename(process_name);
- g_connection_callback(display_name, pid, dest_ip_str, dest_port, proxy_info);
-
- add_logged_connection(pid, dest_ip, dest_port, action);
- }
- }
- }
-
- if (action == RULE_ACTION_DIRECT)
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
- else if (action == RULE_ACTION_BLOCK)
- return nfq_set_verdict(qh, id, NF_DROP, 0, NULL);
- else if (action == RULE_ACTION_PROXY)
- {
- // store connection info
- add_connection(src_port, false, src_ip, dest_ip, dest_port);
-
- // mark packet so nat table REDIRECT rule will catch it
- uint32_t mark = 1;
- return nfq_set_verdict2(qh, id, NF_ACCEPT, mark, 0, NULL);
- }
- }
- else if (iph->protocol == IPPROTO_UDP)
- {
- if (payload_len < (int)(iph->ihl * 4 + sizeof(struct udphdr)))
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
-
- struct udphdr *udph = (struct udphdr *)(payload + iph->ihl * 4);
- src_port = ntohs(udph->source);
- dest_port = ntohs(udph->dest);
-
- if (src_port == LOCAL_UDP_RELAY_PORT)
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
-
- if (is_connection_tracked(src_port, true))
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
-
- if (dest_port == 53 && !g_dns_via_proxy)
- action = RULE_ACTION_DIRECT;
- else
- action = check_process_rule(src_ip, src_port, dest_ip, dest_port, true, &pid);
-
- if (action == RULE_ACTION_PROXY && is_broadcast_or_multicast(dest_ip))
- action = RULE_ACTION_DIRECT;
-
- if (action == RULE_ACTION_PROXY && (dest_port == 67 || dest_port == 68))
- action = RULE_ACTION_DIRECT;
-
- // UDP proxy only works with SOCKS5, not HTTP
- if (action == RULE_ACTION_PROXY && g_proxy_type != PROXY_TYPE_SOCKS5)
- action = RULE_ACTION_DIRECT;
-
- // log (skip our own process, log even without PID for ephemeral UDP sockets)
- if (g_traffic_logging_enabled && g_connection_callback != NULL && pid != g_current_process_id)
- {
- char process_name[MAX_PROCESS_NAME];
- uint32_t log_pid = (pid == 0) ? 1 : pid; // Use PID 1 for unknown processes
-
- if (pid > 0 && get_process_name_from_pid(pid, process_name, sizeof(process_name)))
- {
- // Got process name from PID
- }
- else
- {
- // UDP socket not found - ephemeral or timing issue
- snprintf(process_name, sizeof(process_name), "unknown");
- }
-
- if (!is_connection_already_logged(log_pid, dest_ip, dest_port, action))
- {
- char dest_ip_str[32];
- format_ip_address(dest_ip, dest_ip_str, sizeof(dest_ip_str));
-
- char proxy_info[300];
- if (action == RULE_ACTION_PROXY)
- {
- snprintf(proxy_info, sizeof(proxy_info), "proxy socks5://%s:%d udp",
- g_proxy_host, g_proxy_port);
- }
- else if (action == RULE_ACTION_DIRECT)
- {
- snprintf(proxy_info, sizeof(proxy_info), "direct udp");
- }
- else if (action == RULE_ACTION_BLOCK)
- {
- snprintf(proxy_info, sizeof(proxy_info), "blocked udp");
- }
-
- const char* display_name = extract_filename(process_name);
- g_connection_callback(display_name, log_pid, dest_ip_str, dest_port, proxy_info);
-
- add_logged_connection(log_pid, dest_ip, dest_port, action);
- }
- }
-
- if (action == RULE_ACTION_DIRECT)
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
- else if (action == RULE_ACTION_BLOCK)
- return nfq_set_verdict(qh, id, NF_DROP, 0, NULL);
- else if (action == RULE_ACTION_PROXY)
- {
- // UDP proxy via SOCKS5 UDP ASSOCIATE
- add_connection(src_port, true, src_ip, dest_ip, dest_port);
-
- // Mark UDP packet for redirect to local UDP relay (port 34011)
- uint32_t mark = 2; // Use mark=2 for UDP (mark=1 is for TCP)
- return nfq_set_verdict2(qh, id, NF_ACCEPT, mark, 0, NULL);
- }
- }
-
- return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
-}
-
-static void* packet_processor(void *arg)
-{
- (void)arg;
- char buf[4096] __attribute__((aligned));
- int fd = nfq_fd(nfq_h);
- ssize_t rv;
-
- while (running)
- {
- rv = recv(fd, buf, sizeof(buf), 0);
- if (rv >= 0)
- nfq_handle_packet(nfq_h, buf, rv);
- // On error: ENOBUFS = kernel queue full (normal under load),
- // EINTR = signal, other = transient. Always continue -
- // stopping the thread would break all network traffic.
- }
-
- return NULL;
-}
-
-static inline uint32_t connection_hash(uint16_t port)
-{
- return port % CONNECTION_HASH_SIZE;
-}
-
-static void add_connection(uint16_t src_port, bool is_udp, uint32_t src_ip, uint32_t dest_ip, uint16_t dest_port)
-{
- uint32_t hash = connection_hash(src_port);
- pthread_rwlock_wrlock(&conn_lock);
-
- CONNECTION_INFO *conn = connection_hash_table[hash];
- while (conn != NULL)
- {
- if (conn->src_port == src_port && conn->is_udp == is_udp)
- {
- conn->orig_dest_ip = dest_ip;
- conn->orig_dest_port = dest_port;
- conn->src_ip = src_ip;
- conn->is_tracked = true;
- conn->last_activity = get_monotonic_ms();
- pthread_rwlock_unlock(&conn_lock);
- return;
- }
- conn = conn->next;
- }
-
- CONNECTION_INFO *new_conn = malloc(sizeof(CONNECTION_INFO));
- if (new_conn != NULL)
- {
- new_conn->src_port = src_port;
- new_conn->is_udp = is_udp;
- new_conn->src_ip = src_ip;
- new_conn->orig_dest_ip = dest_ip;
- new_conn->orig_dest_port = dest_port;
- new_conn->is_tracked = true;
- new_conn->last_activity = get_monotonic_ms();
- new_conn->next = connection_hash_table[hash];
- connection_hash_table[hash] = new_conn;
- }
-
- pthread_rwlock_unlock(&conn_lock);
-}
-
-static bool get_connection(uint16_t src_port, bool is_udp, uint32_t *dest_ip, uint16_t *dest_port)
-{
- uint32_t hash = connection_hash(src_port);
- pthread_rwlock_rdlock(&conn_lock);
-
- CONNECTION_INFO *conn = connection_hash_table[hash];
- while (conn != NULL)
- {
- if (conn->src_port == src_port && conn->is_udp == is_udp && conn->is_tracked)
- {
- *dest_ip = conn->orig_dest_ip;
- *dest_port = conn->orig_dest_port;
- conn->last_activity = get_monotonic_ms(); // benign race on timestamp
- pthread_rwlock_unlock(&conn_lock);
- return true;
- }
- conn = conn->next;
- }
-
- pthread_rwlock_unlock(&conn_lock);
- return false;
-}
-
-static bool is_connection_tracked(uint16_t src_port, bool is_udp)
-{
- uint32_t hash = connection_hash(src_port);
- pthread_rwlock_rdlock(&conn_lock);
-
- CONNECTION_INFO *conn = connection_hash_table[hash];
- while (conn != NULL)
- {
- if (conn->src_port == src_port && conn->is_udp == is_udp && conn->is_tracked)
- {
- pthread_rwlock_unlock(&conn_lock);
- return true;
- }
- conn = conn->next;
- }
-
- pthread_rwlock_unlock(&conn_lock);
- return false;
-}
-
-static void __attribute__((unused)) remove_connection(uint16_t src_port)
-{
- uint32_t hash = connection_hash(src_port);
- pthread_rwlock_wrlock(&conn_lock);
-
- CONNECTION_INFO **conn_ptr = &connection_hash_table[hash];
- while (*conn_ptr != NULL)
- {
- if ((*conn_ptr)->src_port == src_port)
- {
- CONNECTION_INFO *to_free = *conn_ptr;
- *conn_ptr = (*conn_ptr)->next;
- free(to_free);
- pthread_rwlock_unlock(&conn_lock);
- return;
- }
- conn_ptr = &(*conn_ptr)->next;
- }
-
- pthread_rwlock_unlock(&conn_lock);
-}
-
-static void cleanup_stale_connections(void)
-{
- uint64_t now = get_monotonic_ms();
-
- // Cleanup connection hash table
- for (int i = 0; i < CONNECTION_HASH_SIZE; i++)
- {
- pthread_rwlock_wrlock(&conn_lock);
- CONNECTION_INFO **conn_ptr = &connection_hash_table[i];
-
- while (*conn_ptr != NULL)
- {
- // 30 min idle timeout. Clean closes are removed on FIN/RST already; a short
- // timeout would reap open-but-idle proxied connections (mail IDLE, voice,
- // websocket) mid-session and silently break them until restart.
- if (now - (*conn_ptr)->last_activity > 1800000)
- {
- CONNECTION_INFO *to_free = *conn_ptr;
- *conn_ptr = (*conn_ptr)->next;
- free(to_free);
- }
- else
- {
- conn_ptr = &(*conn_ptr)->next;
- }
- }
- pthread_rwlock_unlock(&conn_lock);
- }
-
- // Cleanup PID cache (separate lock - no contention with connection lookups)
- uint64_t now_cache = get_monotonic_ms();
- for (int i = 0; i < PID_CACHE_SIZE; i++)
- {
- pthread_mutex_lock(&pid_cache_lock);
- PID_CACHE_ENTRY **entry_ptr = &pid_cache[i];
- while (*entry_ptr != NULL)
- {
- if (now_cache - (*entry_ptr)->timestamp > 10000) // 10 sec cache TTL
- {
- PID_CACHE_ENTRY *to_free = *entry_ptr;
- *entry_ptr = (*entry_ptr)->next;
- free(to_free);
- }
- else
- {
- entry_ptr = &(*entry_ptr)->next;
- }
- }
- pthread_mutex_unlock(&pid_cache_lock);
- }
-
- // Keep only last 100 logged connections
- pthread_mutex_lock(&log_lock);
- int logged_count = 0;
- LOGGED_CONNECTION *temp = logged_connections;
- while (temp != NULL)
- {
- logged_count++;
- temp = temp->next;
- }
-
- if (logged_count > 100)
- {
- temp = logged_connections;
- for (int i = 0; i < 99 && temp != NULL; i++)
- {
- temp = temp->next;
- }
- if (temp != NULL && temp->next != NULL)
- {
- LOGGED_CONNECTION *to_free = temp->next;
- temp->next = NULL;
- while (to_free != NULL)
- {
- LOGGED_CONNECTION *next = to_free->next;
- free(to_free);
- to_free = next;
- }
- }
- }
- pthread_mutex_unlock(&log_lock);
-}
-
-static bool is_connection_already_logged(uint32_t pid, uint32_t dest_ip, uint16_t dest_port, RuleAction action)
-{
- pthread_mutex_lock(&log_lock);
-
- LOGGED_CONNECTION *logged = logged_connections;
- while (logged != NULL)
- {
- if (logged->pid == pid && logged->dest_ip == dest_ip &&
- logged->dest_port == dest_port && logged->action == action)
- {
- pthread_mutex_unlock(&log_lock);
- return true;
- }
- logged = logged->next;
- }
-
- pthread_mutex_unlock(&log_lock);
- return false;
-}
-
-static void add_logged_connection(uint32_t pid, uint32_t dest_ip, uint16_t dest_port, RuleAction action)
-{
- pthread_mutex_lock(&log_lock);
-
- // keep only last 100 entries to avoid memory growth
- int count = 0;
- LOGGED_CONNECTION *temp = logged_connections;
- while (temp != NULL && count < 100)
- {
- count++;
- temp = temp->next;
- }
-
- if (count >= 100)
- {
- temp = logged_connections;
- for (int i = 0; i < 98 && temp != NULL; i++)
- {
- temp = temp->next;
- }
-
- if (temp != NULL && temp->next != NULL)
- {
- LOGGED_CONNECTION *to_free_list = temp->next;
- temp->next = NULL;
-
- // Free excess entries (still under log_lock, but this is rare)
- while (to_free_list != NULL)
- {
- LOGGED_CONNECTION *next = to_free_list->next;
- free(to_free_list);
- to_free_list = next;
- }
- }
- }
-
- LOGGED_CONNECTION *logged = malloc(sizeof(LOGGED_CONNECTION));
- if (logged != NULL)
- {
- logged->pid = pid;
- logged->dest_ip = dest_ip;
- logged->dest_port = dest_port;
- logged->action = action;
- logged->next = logged_connections;
- logged_connections = logged;
- }
-
- pthread_mutex_unlock(&log_lock);
-}
-
-static void clear_logged_connections(void)
-{
- pthread_mutex_lock(&log_lock);
-
- while (logged_connections != NULL)
- {
- LOGGED_CONNECTION *to_free = logged_connections;
- logged_connections = logged_connections->next;
- free(to_free);
- }
-
- pthread_mutex_unlock(&log_lock);
-}
-
-static uint32_t pid_cache_hash(uint32_t src_ip, uint16_t src_port, bool is_udp)
-{
- uint32_t hash = src_ip ^ ((uint32_t)src_port << 16) ^ (is_udp ? 0x80000000 : 0);
- return hash % PID_CACHE_SIZE;
-}
-
-static uint32_t get_cached_pid(uint32_t src_ip, uint16_t src_port, bool is_udp)
-{
- uint32_t hash = pid_cache_hash(src_ip, src_port, is_udp);
- uint64_t current_time = get_monotonic_ms();
- uint32_t pid = 0;
-
- pthread_mutex_lock(&pid_cache_lock);
-
- PID_CACHE_ENTRY *entry = pid_cache[hash];
- while (entry != NULL)
- {
- if (entry->src_ip == src_ip &&
- entry->src_port == src_port &&
- entry->is_udp == is_udp)
- {
- if (current_time - entry->timestamp < PID_CACHE_TTL_MS)
- {
- pid = entry->pid;
- break;
- }
- else
- {
- break;
- }
- }
- entry = entry->next;
- }
-
- pthread_mutex_unlock(&pid_cache_lock);
- return pid;
-}
-
-static void cache_pid(uint32_t src_ip, uint16_t src_port, uint32_t pid, bool is_udp)
-{
- uint32_t hash = pid_cache_hash(src_ip, src_port, is_udp);
- uint64_t current_time = get_monotonic_ms();
-
- pthread_mutex_lock(&pid_cache_lock);
-
- PID_CACHE_ENTRY *entry = pid_cache[hash];
- while (entry != NULL)
- {
- if (entry->src_ip == src_ip &&
- entry->src_port == src_port &&
- entry->is_udp == is_udp)
- {
- entry->pid = pid;
- entry->timestamp = current_time;
- pthread_mutex_unlock(&pid_cache_lock);
- return;
- }
- entry = entry->next;
- }
-
- PID_CACHE_ENTRY *new_entry = malloc(sizeof(PID_CACHE_ENTRY));
- if (new_entry != NULL)
- {
- new_entry->src_ip = src_ip;
- new_entry->src_port = src_port;
- new_entry->pid = pid;
- new_entry->timestamp = current_time;
- new_entry->is_udp = is_udp;
- new_entry->next = pid_cache[hash];
- pid_cache[hash] = new_entry;
- }
-
- pthread_mutex_unlock(&pid_cache_lock);
-}
-
-static void clear_pid_cache(void)
-{
- pthread_mutex_lock(&pid_cache_lock);
-
- for (int i = 0; i < PID_CACHE_SIZE; i++)
- {
- while (pid_cache[i] != NULL)
- {
- PID_CACHE_ENTRY *to_free = pid_cache[i];
- pid_cache[i] = pid_cache[i]->next;
- free(to_free);
- }
- }
-
- pthread_mutex_unlock(&pid_cache_lock);
-}
-
-static void* cleanup_worker(void *arg)
-{
- (void)arg;
- while (running)
- {
- sleep(30); // 30 seconds
- if (running)
- {
- cleanup_stale_connections();
- }
- }
- return NULL;
-}
-
-static void update_has_active_rules(void)
-{
- g_has_active_rules = false;
- PROCESS_RULE *rule = rules_list;
- while (rule != NULL)
- {
- if (rule->enabled)
- {
- g_has_active_rules = true;
- break;
- }
- rule = rule->next;
- }
-}
-
-uint32_t ProxyBridge_AddRule(const char* process_name, const char* target_hosts, const char* target_ports, RuleProtocol protocol, RuleAction action)
-{
- if (process_name == NULL || process_name[0] == '\0')
- return 0;
-
- PROCESS_RULE *rule = malloc(sizeof(PROCESS_RULE));
- if (rule == NULL)
- return 0;
-
- rule->rule_id = g_next_rule_id++;
- strncpy(rule->process_name, process_name, MAX_PROCESS_NAME - 1);
- rule->process_name[MAX_PROCESS_NAME - 1] = '\0';
- rule->protocol = protocol;
-
- if (target_hosts != NULL && target_hosts[0] != '\0')
- {
- rule->target_hosts = strdup(target_hosts);
- if (rule->target_hosts == NULL)
- {
- free(rule);
- return 0;
- }
- }
- else
- {
- rule->target_hosts = strdup("*");
- if (rule->target_hosts == NULL)
- {
- free(rule);
- return 0;
- }
- }
-
- if (target_ports != NULL && target_ports[0] != '\0')
- {
- rule->target_ports = strdup(target_ports);
- if (rule->target_ports == NULL)
- {
- free(rule->target_hosts);
- free(rule);
- return 0;
- }
- }
- else
- {
- rule->target_ports = strdup("*");
- if (rule->target_ports == NULL)
- {
- free(rule->target_hosts);
- free(rule);
- return 0;
- }
- }
-
- rule->action = action;
- rule->enabled = true;
-
- pthread_rwlock_wrlock(&rules_lock);
- rule->next = rules_list;
- rules_list = rule;
- update_has_active_rules();
- pthread_rwlock_unlock(&rules_lock);
-
- log_message("added rule id %u for process %s protocol %d action %d", rule->rule_id, process_name, protocol, action);
-
- return rule->rule_id;
-}
-
-bool ProxyBridge_EnableRule(uint32_t rule_id)
-{
- if (rule_id == 0)
- return false;
-
- pthread_rwlock_wrlock(&rules_lock);
- PROCESS_RULE *rule = rules_list;
- while (rule != NULL)
- {
- if (rule->rule_id == rule_id)
- {
- rule->enabled = true;
- update_has_active_rules();
- pthread_rwlock_unlock(&rules_lock);
- log_message("enabled rule id %u", rule_id);
- return true;
- }
- rule = rule->next;
- }
- pthread_rwlock_unlock(&rules_lock);
- return false;
-}
-
-bool ProxyBridge_DisableRule(uint32_t rule_id)
-{
- if (rule_id == 0)
- return false;
-
- pthread_rwlock_wrlock(&rules_lock);
- PROCESS_RULE *rule = rules_list;
- while (rule != NULL)
- {
- if (rule->rule_id == rule_id)
- {
- rule->enabled = false;
- update_has_active_rules();
- pthread_rwlock_unlock(&rules_lock);
- log_message("disabled rule id %u", rule_id);
- return true;
- }
- rule = rule->next;
- }
- pthread_rwlock_unlock(&rules_lock);
- return false;
-}
-
-bool ProxyBridge_DeleteRule(uint32_t rule_id)
-{
- if (rule_id == 0)
- return false;
-
- pthread_rwlock_wrlock(&rules_lock);
- PROCESS_RULE *rule = rules_list;
- PROCESS_RULE *prev = NULL;
-
- while (rule != NULL)
- {
- if (rule->rule_id == rule_id)
- {
- if (prev == NULL)
- rules_list = rule->next;
- else
- prev->next = rule->next;
-
- update_has_active_rules();
- pthread_rwlock_unlock(&rules_lock);
-
- if (rule->target_hosts != NULL)
- free(rule->target_hosts);
- if (rule->target_ports != NULL)
- free(rule->target_ports);
- free(rule);
-
- log_message("deleted rule id %u", rule_id);
- return true;
- }
- prev = rule;
- rule = rule->next;
- }
- pthread_rwlock_unlock(&rules_lock);
- return false;
-}
-
-bool ProxyBridge_EditRule(uint32_t rule_id, const char* process_name, const char* target_hosts, const char* target_ports, RuleProtocol protocol, RuleAction action)
-{
- if (rule_id == 0 || process_name == NULL || target_hosts == NULL || target_ports == NULL)
- return false;
-
- // Pre-allocate new strings before taking lock to minimize hold time
- char *new_hosts = strdup(target_hosts);
- char *new_ports = strdup(target_ports);
- if (new_hosts == NULL || new_ports == NULL)
- {
- free(new_hosts);
- free(new_ports);
- return false;
- }
-
- pthread_rwlock_wrlock(&rules_lock);
- PROCESS_RULE *rule = rules_list;
- while (rule != NULL)
- {
- if (rule->rule_id == rule_id)
- {
- strncpy(rule->process_name, process_name, MAX_PROCESS_NAME - 1);
- rule->process_name[MAX_PROCESS_NAME - 1] = '\0';
-
- free(rule->target_hosts);
- rule->target_hosts = new_hosts;
-
- free(rule->target_ports);
- rule->target_ports = new_ports;
-
- rule->protocol = protocol;
- rule->action = action;
-
- update_has_active_rules();
- pthread_rwlock_unlock(&rules_lock);
- log_message("updated rule id %u", rule_id);
- return true;
- }
- rule = rule->next;
- }
- pthread_rwlock_unlock(&rules_lock);
-
- // Rule not found - free pre-allocated strings
- free(new_hosts);
- free(new_ports);
- return false;
-}
-
-bool ProxyBridge_SetProxyConfig(ProxyType type, const char* proxy_ip, uint16_t proxy_port, const char* username, const char* password)
-{
- if (proxy_ip == NULL || proxy_ip[0] == '\0' || proxy_port == 0)
- return false;
-
- g_proxy_ip_cached = resolve_hostname(proxy_ip);
- if (g_proxy_ip_cached == 0)
- return false;
-
- strncpy(g_proxy_host, proxy_ip, sizeof(g_proxy_host) - 1);
- g_proxy_host[sizeof(g_proxy_host) - 1] = '\0';
- g_proxy_port = proxy_port;
- g_proxy_type = (type == PROXY_TYPE_HTTP) ? PROXY_TYPE_HTTP : PROXY_TYPE_SOCKS5;
-
- if (username != NULL)
- {
- strncpy(g_proxy_username, username, sizeof(g_proxy_username) - 1);
- g_proxy_username[sizeof(g_proxy_username) - 1] = '\0';
- }
- else
- {
- g_proxy_username[0] = '\0';
- }
-
- if (password != NULL)
- {
- strncpy(g_proxy_password, password, sizeof(g_proxy_password) - 1);
- g_proxy_password[sizeof(g_proxy_password) - 1] = '\0';
- }
- else
- {
- g_proxy_password[0] = '\0';
- }
-
- log_message("proxy configured %s %s:%d", type == PROXY_TYPE_HTTP ? "http" : "socks5", proxy_ip, proxy_port);
- return true;
-}
-
-void ProxyBridge_SetDnsViaProxy(bool enable)
-{
- g_dns_via_proxy = enable;
- log_message("dns via proxy %s", enable ? "enabled" : "disabled");
-}
-
-void ProxyBridge_SetLogCallback(LogCallback callback)
-{
- g_log_callback = callback;
-}
-
-void ProxyBridge_SetConnectionCallback(ConnectionCallback callback)
-{
- g_connection_callback = callback;
-}
-
-void ProxyBridge_SetTrafficLoggingEnabled(bool enable)
-{
- g_traffic_logging_enabled = enable;
-}
-
-void ProxyBridge_ClearConnectionLogs(void)
-{
- clear_logged_connections();
-}
-
-bool ProxyBridge_Start(void)
-{
- if (running)
- return false;
-
- running = true;
- g_current_process_id = getpid();
-
- // Ignore SIGPIPE - send() on a closed socket must return EPIPE, not kill the process
- signal(SIGPIPE, SIG_IGN);
-
- // Raise system socket buffer limits for high throughput (requires root)
- // Default rmem_max/wmem_max is usually 208KB, far too small for >100Mbps
- FILE *fp;
- fp = fopen("/proc/sys/net/core/rmem_max", "w");
- if (fp) { fprintf(fp, "4194304"); fclose(fp); } // 4MB
- fp = fopen("/proc/sys/net/core/wmem_max", "w");
- if (fp) { fprintf(fp, "4194304"); fclose(fp); } // 4MB
-
- if (pthread_create(&proxy_thread, NULL, local_proxy_server, NULL) != 0)
- {
- running = false;
- return false;
- }
-
- if (pthread_create(&cleanup_thread, NULL, cleanup_worker, NULL) != 0)
- {
- running = false;
- pthread_cancel(proxy_thread);
- pthread_join(proxy_thread, NULL);
- proxy_thread = 0;
- return false;
- }
-
- // Start UDP relay server if SOCKS5 proxy
- if (g_proxy_type == PROXY_TYPE_SOCKS5)
- {
- if (pthread_create(&udp_relay_thread, NULL, udp_relay_server, NULL) != 0)
- {
- log_message("failed to create UDP relay thread");
- }
- }
-
- nfq_h = nfq_open();
- if (!nfq_h)
- {
- log_message("nfq_open failed");
- goto start_fail;
- }
-
- if (nfq_unbind_pf(nfq_h, AF_INET) < 0)
- {
- log_message("nfq_unbind_pf failed");
- }
-
- if (nfq_bind_pf(nfq_h, AF_INET) < 0)
- {
- log_message("nfq_bind_pf failed");
- nfq_close(nfq_h);
- nfq_h = NULL;
- goto start_fail;
- }
-
- nfq_qh = nfq_create_queue(nfq_h, 0, &packet_callback, NULL);
- if (!nfq_qh)
- {
- log_message("nfq_create_queue failed");
- nfq_close(nfq_h);
- nfq_h = NULL;
- goto start_fail;
- }
-
- if (nfq_set_mode(nfq_qh, NFQNL_COPY_PACKET, 0xffff) < 0)
- {
- log_message("nfq_set_mode failed");
- nfq_destroy_queue(nfq_qh);
- nfq_qh = NULL;
- nfq_close(nfq_h);
- nfq_h = NULL;
- goto start_fail;
- }
-
- // Set larger queue length for better performance (16384 like Windows)
- nfq_set_queue_maxlen(nfq_qh, 16384);
-
- // setup iptables rules for packet interception - USE MANGLE table so it runs BEFORE nat
- log_message("setting up iptables rules");
- // mangle table runs before nat, so we can mark packets there
- int ret1 = run_iptables_cmd("-t", "mangle", "-A", "OUTPUT", "-p", "tcp", "-j", "NFQUEUE", "--queue-num", "0", NULL, NULL, NULL, NULL);
- int ret2 = run_iptables_cmd("-t", "mangle", "-A", "OUTPUT", "-p", "udp", "-j", "NFQUEUE", "--queue-num", "0", NULL, NULL, NULL, NULL);
-
- if (ret1 != 0 || ret2 != 0) {
- log_message("failed to add iptables rules ret1=%d ret2=%d", ret1, ret2);
- } else {
- log_message("iptables nfqueue rules added successfully");
- }
-
- // setup nat redirect for marked packets
- int ret3 = run_iptables_cmd("-t", "nat", "-A", "OUTPUT", "-p", "tcp", "-m", "mark", "--mark", "1", "-j", "REDIRECT", "--to-port", "34010");
- int ret4 = run_iptables_cmd("-t", "nat", "-A", "OUTPUT", "-p", "udp", "-m", "mark", "--mark", "2", "-j", "REDIRECT", "--to-port", "34011");
- if (ret3 != 0 || ret4 != 0) {
- log_message("failed to add nat redirect rules");
- }
-
- (void)ret3;
- (void)ret4;
-
- for (int i = 0; i < NUM_PACKET_THREADS; i++)
- {
- if (pthread_create(&packet_thread[i], NULL, packet_processor, NULL) != 0)
- {
- log_message("failed to create packet thread %d", i);
- }
- }
-
- log_message("proxybridge started");
- return true;
-
-start_fail:
- running = false;
- if (proxy_thread != 0) { pthread_cancel(proxy_thread); pthread_join(proxy_thread, NULL); proxy_thread = 0; }
- if (cleanup_thread != 0) { pthread_cancel(cleanup_thread); pthread_join(cleanup_thread, NULL); cleanup_thread = 0; }
- if (udp_relay_thread != 0) { pthread_cancel(udp_relay_thread); pthread_join(udp_relay_thread, NULL); udp_relay_thread = 0; }
- return false;
-}
-
-bool ProxyBridge_Stop(void)
-{
- if (!running)
- return false;
-
- running = false;
-
- // cleanup iptables
- int ret1 = run_iptables_cmd("-t", "mangle", "-D", "OUTPUT", "-p", "tcp", "-j", "NFQUEUE", "--queue-num", "0", NULL, NULL, NULL, NULL);
- int ret2 = run_iptables_cmd("-t", "mangle", "-D", "OUTPUT", "-p", "udp", "-j", "NFQUEUE", "--queue-num", "0", NULL, NULL, NULL, NULL);
- int ret3 = run_iptables_cmd("-t", "nat", "-D", "OUTPUT", "-p", "tcp", "-m", "mark", "--mark", "1", "-j", "REDIRECT", "--to-port", "34010");
- int ret4 = run_iptables_cmd("-t", "nat", "-D", "OUTPUT", "-p", "udp", "-m", "mark", "--mark", "2", "-j", "REDIRECT", "--to-port", "34011");
- (void)ret1;
- (void)ret2;
- (void)ret3;
- (void)ret4;
-
- for (int i = 0; i < NUM_PACKET_THREADS; i++)
- {
- if (packet_thread[i] != 0)
- {
- pthread_cancel(packet_thread[i]);
- pthread_join(packet_thread[i], NULL);
- packet_thread[i] = 0;
- }
- }
-
- if (nfq_qh)
- {
- nfq_destroy_queue(nfq_qh);
- nfq_qh = NULL;
- }
-
- if (nfq_h)
- {
- nfq_close(nfq_h);
- nfq_h = NULL;
- }
-
- if (proxy_thread != 0)
- {
- pthread_cancel(proxy_thread);
- pthread_join(proxy_thread, NULL);
- proxy_thread = 0;
- }
-
- if (udp_relay_thread != 0)
- {
- pthread_cancel(udp_relay_thread);
- pthread_join(udp_relay_thread, NULL);
- udp_relay_thread = 0;
- }
-
- if (cleanup_thread != 0)
- {
- pthread_cancel(cleanup_thread);
- pthread_join(cleanup_thread, NULL);
- cleanup_thread = 0;
- }
-
- // Free all connections in hash table
- pthread_rwlock_wrlock(&conn_lock);
- for (int i = 0; i < CONNECTION_HASH_SIZE; i++)
- {
- while (connection_hash_table[i] != NULL)
- {
- CONNECTION_INFO *to_free = connection_hash_table[i];
- connection_hash_table[i] = connection_hash_table[i]->next;
- free(to_free);
- }
- }
- pthread_rwlock_unlock(&conn_lock);
-
- // Free all rules
- pthread_rwlock_wrlock(&rules_lock);
- while (rules_list != NULL)
- {
- PROCESS_RULE *to_free = rules_list;
- rules_list = rules_list->next;
- free(to_free->target_hosts);
- free(to_free->target_ports);
- free(to_free);
- }
- g_has_active_rules = false;
- g_next_rule_id = 1;
- pthread_rwlock_unlock(&rules_lock);
-
- clear_logged_connections();
- clear_pid_cache();
-
- log_message("proxybridge stopped");
- return true;
-}
-
-int ProxyBridge_TestConnection(const char* target_host, uint16_t target_port, char* result_buffer, size_t buffer_size)
-{
- int test_sock = -1;
- struct sockaddr_in proxy_addr;
- uint32_t target_ip;
- int ret = -1;
- char temp_buffer[512];
-
- if (g_proxy_host[0] == '\0' || g_proxy_port == 0)
- {
- snprintf(result_buffer, buffer_size, "error no proxy configured");
- return -1;
- }
-
- if (target_host == NULL || target_host[0] == '\0')
- {
- snprintf(result_buffer, buffer_size, "error invalid target host");
- return -1;
- }
-
- snprintf(temp_buffer, sizeof(temp_buffer), "testing connection to %s:%d via %s proxy %s:%d\n",
- target_host, target_port,
- g_proxy_type == PROXY_TYPE_HTTP ? "http" : "socks5",
- g_proxy_host, g_proxy_port);
- strncpy(result_buffer, temp_buffer, buffer_size - 1);
- result_buffer[buffer_size - 1] = '\0';
-
- struct addrinfo hints, *res;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_INET;
- hints.ai_socktype = SOCK_STREAM;
- int gai_ret = getaddrinfo(target_host, NULL, &hints, &res);
- if (gai_ret != 0)
- {
- snprintf(temp_buffer, sizeof(temp_buffer), "error failed to resolve hostname %s: %s\n",
- target_host, gai_strerror(gai_ret));
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
- return -1;
- }
- target_ip = ((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr;
- freeaddrinfo(res);
-
- snprintf(temp_buffer, sizeof(temp_buffer), "resolved %s to %d.%d.%d.%d\n",
- target_host,
- (target_ip >> 0) & 0xFF, (target_ip >> 8) & 0xFF,
- (target_ip >> 16) & 0xFF, (target_ip >> 24) & 0xFF);
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
-
- test_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- if (test_sock < 0)
- {
- snprintf(temp_buffer, sizeof(temp_buffer), "error socket creation failed\n");
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
- return -1;
- }
-
- configure_tcp_socket(test_sock, 65536, 10000);
-
- memset(&proxy_addr, 0, sizeof(proxy_addr));
- proxy_addr.sin_family = AF_INET;
- proxy_addr.sin_addr.s_addr = resolve_hostname(g_proxy_host);
- proxy_addr.sin_port = htons(g_proxy_port);
-
- snprintf(temp_buffer, sizeof(temp_buffer), "connecting to proxy %s:%d\n", g_proxy_host, g_proxy_port);
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
-
- if (connect(test_sock, (struct sockaddr*)&proxy_addr, sizeof(proxy_addr)) < 0)
- {
- snprintf(temp_buffer, sizeof(temp_buffer), "error failed to connect to proxy\n");
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
- close(test_sock);
- return -1;
- }
-
- strncat(result_buffer, "connected to proxy server\n", buffer_size - strlen(result_buffer) - 1);
-
- if (g_proxy_type == PROXY_TYPE_SOCKS5)
- {
- if (socks5_connect(test_sock, target_ip, target_port) != 0)
- {
- snprintf(temp_buffer, sizeof(temp_buffer), "error socks5 handshake failed\n");
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
- close(test_sock);
- return -1;
- }
- strncat(result_buffer, "socks5 handshake successful\n", buffer_size - strlen(result_buffer) - 1);
- }
- else
- {
- if (http_connect(test_sock, target_ip, target_port) != 0)
- {
- snprintf(temp_buffer, sizeof(temp_buffer), "error http connect failed\n");
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
- close(test_sock);
- return -1;
- }
- strncat(result_buffer, "http connect successful\n", buffer_size - strlen(result_buffer) - 1);
- }
-
- char http_request[512];
- snprintf(http_request, sizeof(http_request),
- "GET / HTTP/1.1\r\n"
- "Host: %s\r\n"
- "Connection: close\r\n"
- "User-Agent: ProxyBridge/1.0\r\n"
- "\r\n", target_host);
-
- if (send_all(test_sock, http_request, strlen(http_request)) < 0)
- {
- snprintf(temp_buffer, sizeof(temp_buffer), "error failed to send test request\n");
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
- close(test_sock);
- return -1;
- }
-
- strncat(result_buffer, "sent http get request\n", buffer_size - strlen(result_buffer) - 1);
- char response[1024];
- ssize_t bytes_received = recv(test_sock, response, sizeof(response) - 1, 0);
- if (bytes_received > 0)
- {
- response[bytes_received] = '\0';
-
- if (strstr(response, "HTTP/") != NULL)
- {
- char* status_line = strstr(response, "HTTP/");
- int status_code = 0;
- if (status_line != NULL)
- {
- sscanf(status_line, "HTTP/%*s %d", &status_code);
- }
-
- snprintf(temp_buffer, sizeof(temp_buffer), "success received http %d response %ld bytes\n", status_code, (long)bytes_received);
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
- ret = 0;
- }
- else
- {
- snprintf(temp_buffer, sizeof(temp_buffer), "error received data but not valid http response\n");
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
- ret = -1;
- }
- }
- else
- {
- snprintf(temp_buffer, sizeof(temp_buffer), "error failed to receive response\n");
- strncat(result_buffer, temp_buffer, buffer_size - strlen(result_buffer) - 1);
- ret = -1;
- }
-
- close(test_sock);
-
- if (ret == 0)
- {
- strncat(result_buffer, "\nproxy connection test passed\n", buffer_size - strlen(result_buffer) - 1);
- }
- else
- {
- strncat(result_buffer, "\nproxy connection test failed\n", buffer_size - strlen(result_buffer) - 1);
- }
-
- return ret;
-}
-
-// Library destructor - automatically cleanup when library is unloaded
-__attribute__((destructor))
-static void library_cleanup(void)
-{
- if (running)
- {
- log_message("library unloading - cleaning up automatically");
- ProxyBridge_Stop();
- }
- else
- {
- // Even if not running, ensure iptables rules are removed
- // This handles cases where the app crashed before calling Stop
- run_iptables_cmd("-t", "mangle", "-D", "OUTPUT", "-p", "tcp", "-j", "NFQUEUE", "--queue-num", "0", NULL, NULL, NULL, NULL);
- run_iptables_cmd("-t", "mangle", "-D", "OUTPUT", "-p", "udp", "-j", "NFQUEUE", "--queue-num", "0", NULL, NULL, NULL, NULL);
- run_iptables_cmd("-t", "nat", "-D", "OUTPUT", "-p", "tcp", "-m", "mark", "--mark", "1", "-j", "REDIRECT", "--to-port", "34010");
- run_iptables_cmd("-t", "nat", "-D", "OUTPUT", "-p", "udp", "-m", "mark", "--mark", "2", "-j", "REDIRECT", "--to-port", "34011");
- }
+ return ProxyBridge_TestProxy(0, host, port, buf, n);
}
diff --git a/Linux/src/ProxyBridge.h b/Linux/src/ProxyBridge.h
index bd80583..dc8b863 100644
--- a/Linux/src/ProxyBridge.h
+++ b/Linux/src/ProxyBridge.h
@@ -1,8 +1,9 @@
#ifndef PROXYBRIDGE_H
#define PROXYBRIDGE_H
-#define PROXYBRIDGE_VERSION "3.2.0"
+#define PROXYBRIDGE_VERSION "4.0.0"
+#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
@@ -30,20 +31,52 @@ typedef enum {
RULE_PROTOCOL_BOTH = 2
} RuleProtocol;
-uint32_t ProxyBridge_AddRule(const char* process_name, const char* target_hosts, const char* target_ports, RuleProtocol protocol, RuleAction action);
-bool ProxyBridge_EnableRule(uint32_t rule_id);
-bool ProxyBridge_DisableRule(uint32_t rule_id);
-bool ProxyBridge_DeleteRule(uint32_t rule_id);
-bool ProxyBridge_EditRule(uint32_t rule_id, const char* process_name, const char* target_hosts, const char* target_ports, RuleProtocol protocol, RuleAction action);
+/* ---- Proxy configurations -------------------------------------------------------------------------------------------
+ * Any number of proxies can be registered. Ids are non-zero and stable until the proxy is deleted.
+ * Returns 0 on failure (the reason is written to err, if given). */
+uint32_t ProxyBridge_AddProxy(const char* name, ProxyType type, const char* host, uint16_t port,
+ const char* username, const char* password, char* err, size_t err_size);
+bool ProxyBridge_EditProxy(uint32_t proxy_id, const char* name, ProxyType type, const char* host, uint16_t port,
+ const char* username, const char* password, char* err, size_t err_size);
+bool ProxyBridge_DeleteProxy(uint32_t proxy_id); /* rules that used it fall back to the default proxy */
+void ProxyBridge_ClearProxies(void);
+/* Which proxy a rule with proxy_id == 0 uses. 0 = the first proxy added. */
+void ProxyBridge_SetDefaultProxy(uint32_t proxy_id);
+
+/* ---- Rules ----------------------------------------------------------------------------------------------------------
+ * Rules are evaluated in list order, first match wins. process_name: ';' or ',' separated globs matched against the
+ * executable's full path and file name ("*" or empty = any). target_hosts: ';' or ',' separated IPv4/IPv6 addresses,
+ * CIDR (10.0.0.0/8), a-b ranges, octet wildcards (192.168.*.*) or "*" ("" = any). target_ports: list and ranges
+ * ("80;443;8000-9000", "" or "*" = any).
+ * proxy_id applies when action == RULE_ACTION_PROXY; 0 = default proxy.
+ * AddRule returns the new rule id, or 0 on validation failure (reason in err). */
+uint32_t ProxyBridge_AddRule(const char* process_name, const char* target_hosts, const char* target_ports,
+ RuleProtocol protocol, RuleAction action, uint32_t proxy_id, char* err, size_t err_size);
+bool ProxyBridge_EditRule(uint32_t rule_id, const char* process_name, const char* target_hosts, const char* target_ports,
+ RuleProtocol protocol, RuleAction action, uint32_t proxy_id, char* err, size_t err_size);
+bool ProxyBridge_EnableRule(uint32_t rule_id);
+bool ProxyBridge_DisableRule(uint32_t rule_id);
+bool ProxyBridge_DeleteRule(uint32_t rule_id);
+bool ProxyBridge_MoveRule(uint32_t rule_id, int new_index); /* reorder: priority = position */
+void ProxyBridge_ClearRules(void);
+/* Validates a rule without adding it; returns true if valid, otherwise writes the reason to err. */
+bool ProxyBridge_ValidateRule(const char* process_name, const char* target_hosts, const char* target_ports,
+ char* err, size_t err_size);
+
+/* ---- Legacy single-proxy helper -------------------------------------------------------------------------------------
+ * Sets (creating on first use) the default proxy. Equivalent to Add/EditProxy on the "default" entry. */
bool ProxyBridge_SetProxyConfig(ProxyType type, const char* proxy_ip, uint16_t proxy_port, const char* username, const char* password);
+
+/* ---- Runtime --------------------------------------------------------------------------------------------------------- */
void ProxyBridge_SetDnsViaProxy(bool enable);
void ProxyBridge_SetLogCallback(LogCallback callback);
void ProxyBridge_SetConnectionCallback(ConnectionCallback callback);
void ProxyBridge_SetTrafficLoggingEnabled(bool enable);
void ProxyBridge_ClearConnectionLogs(void);
-bool ProxyBridge_Start(void);
-bool ProxyBridge_Stop(void);
-int ProxyBridge_TestConnection(const char* target_host, uint16_t target_port, char* result_buffer, size_t buffer_size);
+bool ProxyBridge_Start(void); /* needs root (CAP_BPF/CAP_SYS_ADMIN) and a BTF kernel >= 5.8; returns false and logs why on failure */
+bool ProxyBridge_Stop(void); /* keeps rules and proxies; Start() may be called again */
+int ProxyBridge_TestConnection(const char* target_host, uint16_t target_port, char* result_buffer, size_t buffer_size);
+int ProxyBridge_TestProxy(uint32_t proxy_id, const char* target_host, uint16_t target_port, char* result_buffer, size_t buffer_size);
#ifdef __cplusplus
}
diff --git a/Linux/src/bpf/pb_bpf_shared.h b/Linux/src/bpf/pb_bpf_shared.h
new file mode 100644
index 0000000..bb403e2
--- /dev/null
+++ b/Linux/src/bpf/pb_bpf_shared.h
@@ -0,0 +1,75 @@
+// Types shared between the BPF object and userspace (pb_bpf.c). Plain C, no kernel headers needed.
+#ifndef PB_BPF_SHARED_H
+#define PB_BPF_SHARED_H
+
+#ifdef __BPF__
+typedef __u8 pb_u8; typedef __u16 pb_u16; typedef __u32 pb_u32; typedef __u64 pb_u64;
+#else
+#include <stdint.h>
+typedef uint8_t pb_u8; typedef uint16_t pb_u16; typedef uint32_t pb_u32; typedef uint64_t pb_u64;
+#endif
+
+#define PB_MAX_RULES 512
+#define PB_MAX_CLASSES 2048
+#define PB_RULES_PER_CLASS 16
+#define PB_BPF_MAX_V4 4
+#define PB_BPF_MAX_PORT 4
+
+// cfg array slots
+#define PB_CFG_ENABLED 0 // 1 when at least one rule is loaded
+#define PB_CFG_SELF_TGID 1 // process that hosts the relay (never redirected)
+#define PB_CFG_LOG 2 // 1 = emit events
+#define PB_CFG_TCP_PORT 3
+#define PB_CFG_UDP_PORT 4
+#define PB_CFG_DNS_VIA_PROXY 5
+#define PB_CFG_DNS_TAP 6 // 1 when a domain rule exists: port-53 flows of covered processes go through the relay
+#define PB_CFG_NETNS_LO 7 // cookie of the network namespace the relay lives in; sockets in other namespaces are ignored
+#define PB_CFG_NETNS_HI 8
+#define PB_CFG_SLOTS 12
+
+// brule flags
+#define PB_RF_ANY_HOST 0x01
+#define PB_RF_ANY_PORT 0x02
+#define PB_RF_HOST_COMPLEX 0x04 // host pattern not representable: "maybe" for every destination
+#define PB_RF_PORT_COMPLEX 0x08 // more port ranges than fit: "maybe" when the ports in the table do not match
+#define PB_RF_HAS_V6 0x10 // rule has IPv6 patterns: "maybe" for IPv6 destinations
+#define PB_RF_DOMAINS 0x40 // host list also contains domain patterns: answered by the dom_hit map (filled by the DNS tap)
+#define PB_RF_UDP_DIRECT 0x20 // PROXY rule whose proxy cannot carry UDP (HTTP): UDP flows go direct
+
+#define PB_CLASS_DECIDE 0xffffffffu // pb_bclass.n value: always take the slow path for this binary
+
+struct pb_exe_key { pb_u32 dev; pb_u32 pad; pb_u64 ino; };
+
+struct pb_brule {
+ pb_u16 proxy_id;
+ pb_u8 action; // 0 proxy, 1 direct, 2 block
+ pb_u8 proto_mask; // 1 tcp, 2 udp
+ pb_u8 flags;
+ pb_u8 n_v4;
+ pb_u8 n_port;
+ pb_u8 pad;
+ struct { pb_u32 lo, hi; } v4[PB_BPF_MAX_V4]; // host order
+ struct { pb_u16 lo, hi; } port[PB_BPF_MAX_PORT]; // host order
+};
+
+struct pb_dom_key { pb_u32 rule; pb_u32 ip; }; // ip in host order
+
+struct pb_bclass {
+ pb_u32 n;
+ pb_u32 tap; // 1: this binary is covered by a domain rule, so its DNS must be observed
+ pb_u32 rule[PB_RULES_PER_CLASS];
+};
+
+struct pb_event {
+ pb_u32 pid;
+ pb_u8 comm[16];
+ pb_u8 addr[16];
+ pb_u16 port;
+ pb_u16 proxy_id;
+ pb_u8 family;
+ pb_u8 proto;
+ pb_u8 action; // PB_ACT_*
+ pb_u8 pad;
+};
+
+#endif
diff --git a/Linux/src/bpf/proxybridge.bpf.c b/Linux/src/bpf/proxybridge.bpf.c
new file mode 100644
index 0000000..839f57c
--- /dev/null
+++ b/Linux/src/bpf/proxybridge.bpf.c
@@ -0,0 +1,433 @@
+// ProxyBridge eBPF datapath: cgroup socket-address hooks that redirect selected processes' connect()/sendmsg() to the
+// userspace relay and remember the original destination.
+#include <linux/types.h>
+#include <linux/bpf.h>
+#include <bpf/bpf_helpers.h>
+#include <bpf/bpf_endian.h>
+#include "pb_bpf_shared.h"
+
+// Minimal kernel type stubs (CO-RE relocated against the running kernel's BTF; avoids shipping a 160k-line vmlinux.h).
+#pragma clang attribute push(__attribute__((preserve_access_index)), apply_to = record)
+struct super_block { __u32 s_dev; };
+struct inode { struct super_block *i_sb; unsigned long i_ino; };
+struct file { struct inode *f_inode; };
+struct mm_struct { struct file *exe_file; };
+struct task_struct { struct mm_struct *mm; };
+#pragma clang attribute pop
+
+#define IPPROTO_TCP 6
+#define IPPROTO_UDP 17
+#define AF_INET 2
+#define AF_INET6 10
+
+#define ACT_PROXY 0
+#define ACT_DIRECT 1
+#define ACT_BLOCK 2
+#define ACT_DECIDE 3
+
+#define M_NO 0
+#define M_YES 1
+#define M_MAYBE 2
+
+struct pb_orig {
+ __u8 addr[16];
+ __u16 port;
+ __u16 proxy_id;
+ __u32 pid;
+ __u8 family, proto, action, pad;
+ __u32 exe_dev, exe_pad;
+ __u64 exe_ino;
+};
+
+struct { __uint(type, BPF_MAP_TYPE_ARRAY); __uint(max_entries, PB_CFG_SLOTS);
+ __type(key, __u32); __type(value, __u32); } cfg SEC(".maps");
+struct { __uint(type, BPF_MAP_TYPE_HASH); __uint(max_entries, 16384);
+ __type(key, struct pb_exe_key); __type(value, __u32); } exe2class SEC(".maps");
+struct { __uint(type, BPF_MAP_TYPE_ARRAY); __uint(max_entries, PB_MAX_CLASSES);
+ __type(key, __u32); __type(value, struct pb_bclass); } classes SEC(".maps");
+struct { __uint(type, BPF_MAP_TYPE_ARRAY); __uint(max_entries, PB_MAX_RULES);
+ __type(key, __u32); __type(value, struct pb_brule); } brules SEC(".maps");
+struct { __uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(max_entries, 32768);
+ __type(key, __u64); __type(value, struct pb_orig); } by_cookie SEC(".maps");
+struct { __uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(max_entries, 32768);
+ __type(key, __u32); __type(value, struct pb_orig); } by_port SEC(".maps");
+struct { __uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(max_entries, 32768);
+ __type(key, __u32); __type(value, struct pb_orig); } flows SEC(".maps");
+struct { __uint(type, BPF_MAP_TYPE_LRU_HASH); __uint(max_entries, 65536);
+ __type(key, struct pb_dom_key); __type(value, __u8); } dom_hit SEC(".maps"); // (rule, ip) pairs whose DNS name matches the rule
+struct { __uint(type, BPF_MAP_TYPE_RINGBUF); __uint(max_entries, 256 * 1024); } events SEC(".maps");
+struct { __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); __uint(max_entries, 8);
+ __type(key, __u32); __type(value, __u64); } stats SEC(".maps"); // 0 redirected 1 blocked 2 decide 3 evt dropped
+
+static __always_inline void stat_inc(__u32 k)
+{
+ __u64 *v = bpf_map_lookup_elem(&stats, &k);
+ if (v) (*v)++;
+}
+
+static __always_inline __u32 cfg_get(__u32 k)
+{
+ __u32 *v = bpf_map_lookup_elem(&cfg, &k);
+ return v ? *v : 0;
+}
+
+// Containers/other network namespaces have their own loopback: redirecting them to our relay would break them.
+static __always_inline int foreign_netns(void *ctx)
+{
+ __u64 want = ((__u64)cfg_get(PB_CFG_NETNS_HI) << 32) | cfg_get(PB_CFG_NETNS_LO);
+ return want && bpf_get_netns_cookie(ctx) != want;
+}
+
+// ---------------------------------------------------------------------------------------------------------------------
+// rule evaluation
+// ---------------------------------------------------------------------------------------------------------------------
+static __always_inline int rule_match(const struct pb_brule *r, __u32 ri, __u8 fam, __u32 ip4_host, __u16 port)
+{
+ int port_res = M_YES;
+ if (!(r->flags & PB_RF_ANY_PORT)) {
+ port_res = M_NO;
+ #pragma unroll
+ for (int i = 0; i < PB_BPF_MAX_PORT; i++) {
+ if (i >= r->n_port) break;
+ if (port >= r->port[i].lo && port <= r->port[i].hi) { port_res = M_YES; break; }
+ }
+ if (port_res == M_NO && (r->flags & PB_RF_PORT_COMPLEX)) port_res = M_MAYBE;
+ if (port_res == M_NO) return M_NO;
+ }
+ int host_res;
+ if (r->flags & PB_RF_ANY_HOST) host_res = M_YES;
+ else if (r->flags & PB_RF_HOST_COMPLEX) host_res = M_MAYBE;
+ else if (fam == AF_INET6) host_res = (r->flags & PB_RF_HAS_V6) ? M_MAYBE : M_NO;
+ else {
+ host_res = M_NO;
+ #pragma unroll
+ for (int i = 0; i < PB_BPF_MAX_V4; i++) {
+ if (i >= r->n_v4) break;
+ if (ip4_host >= r->v4[i].lo && ip4_host <= r->v4[i].hi) { host_res = M_YES; break; }
+ }
+ if (host_res == M_NO && (r->flags & PB_RF_DOMAINS)) {
+ struct pb_dom_key dk = { .rule = ri, .ip = ip4_host };
+ if (bpf_map_lookup_elem(&dom_hit, &dk)) host_res = M_YES;
+ }
+ }
+ if (host_res == M_NO) return M_NO;
+ return (host_res == M_MAYBE || port_res == M_MAYBE) ? M_MAYBE : M_YES;
+}
+
+static __always_inline int implicit_direct(__u8 fam, const __u8 *a, __u16 port, __u8 proto)
+{
+ if (fam == AF_INET) {
+ if (a[12] == 127 || a[12] == 0 || a[12] >= 224) return 1;
+ } else {
+ if (a[0] == 0xff) return 1;
+ if (a[0] == 0xfe && (a[1] & 0xc0) == 0x80) return 1;
+ int lo = 1;
+ #pragma unroll
+ for (int i = 0; i < 15; i++) if (a[i]) lo = 0;
+ if (lo && a[15] == 1) return 1;
+ }
+ if (proto == IPPROTO_UDP && (port == 67 || port == 68)) return 1;
+ if (port == 53 && !cfg_get(PB_CFG_DNS_VIA_PROXY)) return 1;
+ return 0;
+}
+
+// Returns an ACT_*; for ACT_PROXY *proxy_id is set.
+static __always_inline int decide(struct pb_orig *o, __u16 *proxy_id)
+{
+ if (!cfg_get(PB_CFG_ENABLED)) return ACT_DIRECT;
+ if (o->pid == cfg_get(PB_CFG_SELF_TGID)) return ACT_DIRECT;
+ int tap = o->port == 53 && cfg_get(PB_CFG_DNS_TAP);
+ if (!tap && implicit_direct(o->family, o->addr, o->port, o->proto)) return ACT_DIRECT;
+
+ struct task_struct *t = bpf_get_current_task_btf();
+ struct mm_struct *mm = t->mm;
+ if (!mm) return ACT_DIRECT; // kernel thread
+ struct pb_exe_key key = {};
+ key.dev = mm->exe_file->f_inode->i_sb->s_dev;
+ key.ino = mm->exe_file->f_inode->i_ino;
+ o->exe_dev = key.dev; o->exe_ino = key.ino; // lets userspace learn the exact kernel-side key
+ if (!key.ino) return ACT_DECIDE;
+
+ __u32 *cid = bpf_map_lookup_elem(&exe2class, &key);
+ if (!cid) return ACT_DECIDE; // binary not seen yet: relay classifies it
+ struct pb_bclass *c = bpf_map_lookup_elem(&classes, cid);
+ if (!c || c->n > PB_RULES_PER_CLASS) return ACT_DECIDE;
+ if (tap) {
+ // a domain rule covers this binary: its DNS answers must pass through the relay so names can be learned
+ if (c->tap) return ACT_DECIDE;
+ if (implicit_direct(o->family, o->addr, o->port, o->proto)) return ACT_DIRECT;
+ }
+
+ __u32 ip4 = (o->family == AF_INET) ? bpf_ntohl(*(const __u32 *)(o->addr + 12)) : 0;
+ __u8 pbit = o->proto == IPPROTO_TCP ? 1 : 2;
+ #pragma unroll
+ for (int i = 0; i < PB_RULES_PER_CLASS; i++) {
+ if (i >= c->n) break;
+ __u32 ri = c->rule[i];
+ struct pb_brule *r = bpf_map_lookup_elem(&brules, &ri);
+ if (!r) return ACT_DECIDE;
+ if (!(r->proto_mask & pbit)) continue;
+ int m = rule_match(r, ri, o->family, ip4, o->port);
+ if (m == M_NO) continue;
+ if (m == M_MAYBE) return ACT_DECIDE;
+ if (r->action == ACT_PROXY) {
+ if (o->proto == IPPROTO_UDP && (r->flags & PB_RF_UDP_DIRECT)) return ACT_DIRECT;
+ *proxy_id = r->proxy_id;
+ }
+ return r->action;
+ }
+ return ACT_DIRECT;
+}
+
+static __always_inline void emit(const struct pb_orig *o, int action, __u16 proxy_id)
+{
+ if (!cfg_get(PB_CFG_LOG)) return;
+ struct pb_event *e = bpf_ringbuf_reserve(&events, sizeof *e, 0);
+ if (!e) { stat_inc(3); return; }
+ e->pid = o->pid;
+ bpf_get_current_comm(e->comm, sizeof e->comm);
+ __builtin_memcpy(e->addr, o->addr, 16);
+ e->port = o->port; e->proxy_id = proxy_id;
+ e->family = o->family; e->proto = o->proto; e->action = action; e->pad = 0;
+ bpf_ringbuf_submit(e, 0);
+}
+
+// ---------------------------------------------------------------------------------------------------------------------
+// flow handling
+// ---------------------------------------------------------------------------------------------------------------------
+static __always_inline void set_mapped_v4(__u32 *ip6, __u32 ip4_be)
+{
+ ip6[0] = 0; ip6[1] = 0; ip6[2] = bpf_htonl(0x0000ffff); ip6[3] = ip4_be;
+}
+
+// Fills o from a sockaddr as seen in the hook. For v6 sockets a v4-mapped address is an IPv4 destination.
+static __always_inline void orig_from_v4(struct pb_orig *o, __u32 ip_be, __u16 port_be, __u8 proto)
+{
+ __builtin_memset(o, 0, sizeof *o);
+ o->addr[10] = 0xff; o->addr[11] = 0xff;
+ __builtin_memcpy(o->addr + 12, &ip_be, 4);
+ o->port = bpf_ntohs(port_be);
+ o->family = AF_INET; o->proto = proto;
+ o->pid = bpf_get_current_pid_tgid() >> 32;
+}
+
+static __always_inline void orig_from_v6(struct pb_orig *o, const __u32 ip6[4], __u16 port_be, __u8 proto)
+{
+ __builtin_memset(o, 0, sizeof *o);
+ __builtin_memcpy(o->addr, ip6, 16);
+ o->port = bpf_ntohs(port_be);
+ o->proto = proto;
+ o->pid = bpf_get_current_pid_tgid() >> 32;
+ if (ip6[0] == 0 && ip6[1] == 0 && ip6[2] == bpf_htonl(0x0000ffff)) o->family = AF_INET;
+ else o->family = AF_INET6;
+}
+
+// Deterministic loopback flow address (127.1-255.x.y) for a UDP destination; collisions are probed linearly.
+static __always_inline __u32 udp_flow_addr(struct pb_orig *o)
+{
+ const __u32 *w = (const __u32 *)o->addr;
+ __u32 h = w[0] * 2654435761u ^ w[1] * 40503u ^ w[2] * 2246822519u ^ w[3] * 3266489917u;
+ h ^= ((__u32)o->port << 16) | o->proxy_id;
+ h ^= (__u32)o->action * 668265263u;
+ if (o->action == ACT_DECIDE) h ^= o->pid * 374761393u;
+ h ^= h >> 15; h *= 2246822519u; h ^= h >> 13;
+ __u32 addr = 0;
+ for (int i = 0; i < 8; i++) {
+ addr = bpf_htonl(0x7f000000 | (((h + i) & 0x00ffffff) | 0x00010000));
+ struct pb_orig *ex = bpf_map_lookup_elem(&flows, &addr);
+ if (!ex) { bpf_map_update_elem(&flows, &addr, o, BPF_NOEXIST); break; }
+ if (__builtin_memcmp(ex->addr, o->addr, 16) == 0 && ex->port == o->port && ex->proxy_id == o->proxy_id &&
+ ex->action == o->action && (o->action != ACT_DECIDE || ex->pid == o->pid)) break;
+ }
+ return addr;
+}
+
+// 0 = leave the socket call untouched, 1 = it was redirected, -1 = block
+static __always_inline int route(struct pb_orig *o, __u16 *proxy_id_out)
+{
+ __u16 pid16 = 0;
+ int act = decide(o, &pid16);
+ switch (act) {
+ case ACT_DIRECT:
+ emit(o, ACT_DIRECT, 0);
+ return 0;
+ case ACT_BLOCK:
+ emit(o, ACT_BLOCK, 0);
+ stat_inc(1);
+ return -1;
+ case ACT_PROXY:
+ o->action = ACT_PROXY; o->proxy_id = pid16;
+ emit(o, ACT_PROXY, pid16);
+ stat_inc(0);
+ break;
+ default:
+ o->action = ACT_DECIDE; o->proxy_id = 0;
+ stat_inc(2);
+ break;
+ }
+ *proxy_id_out = o->proxy_id;
+ return 1;
+}
+
+// ---- TCP / connected UDP: connect4 / connect6 ------------------------------------------------------------------------
+SEC("cgroup/connect4")
+int pb_connect4(struct bpf_sock_addr *ctx)
+{
+ if (foreign_netns(ctx)) return 1;
+ if (ctx->protocol != IPPROTO_TCP && ctx->protocol != IPPROTO_UDP) return 1;
+ struct pb_orig o; __u16 pid;
+ orig_from_v4(&o, ctx->user_ip4, ctx->user_port, ctx->protocol);
+ int r = route(&o, &pid);
+ if (r < 0) return 0;
+ if (r == 0) return 1;
+ if (ctx->protocol == IPPROTO_TCP) {
+ __u64 ck = bpf_get_socket_cookie(ctx);
+ bpf_map_update_elem(&by_cookie, &ck, &o, BPF_ANY);
+ ctx->user_ip4 = bpf_htonl(0x7f000001);
+ ctx->user_port = bpf_htons((__u16)cfg_get(PB_CFG_TCP_PORT));
+ } else {
+ ctx->user_ip4 = udp_flow_addr(&o);
+ ctx->user_port = bpf_htons((__u16)cfg_get(PB_CFG_UDP_PORT));
+ }
+ return 1;
+}
+
+SEC("cgroup/connect6")
+int pb_connect6(struct bpf_sock_addr *ctx)
+{
+ if (foreign_netns(ctx)) return 1;
+ if (ctx->protocol != IPPROTO_TCP && ctx->protocol != IPPROTO_UDP) return 1;
+ __u32 ip6[4] = { ctx->user_ip6[0], ctx->user_ip6[1], ctx->user_ip6[2], ctx->user_ip6[3] };
+ struct pb_orig o; __u16 pid;
+ orig_from_v6(&o, ip6, ctx->user_port, ctx->protocol);
+ int r = route(&o, &pid);
+ if (r < 0) return 0;
+ if (r == 0) return 1;
+ if (ctx->protocol == IPPROTO_TCP) {
+ __u64 ck = bpf_get_socket_cookie(ctx);
+ bpf_map_update_elem(&by_cookie, &ck, &o, BPF_ANY);
+ set_mapped_v4(ctx->user_ip6, bpf_htonl(0x7f000001));
+ ctx->user_port = bpf_htons((__u16)cfg_get(PB_CFG_TCP_PORT));
+ } else {
+ set_mapped_v4(ctx->user_ip6, udp_flow_addr(&o));
+ ctx->user_port = bpf_htons((__u16)cfg_get(PB_CFG_UDP_PORT));
+ }
+ return 1;
+}
+
+// ---- unconnected UDP --------------------------------------------------------------------------------------------------
+SEC("cgroup/sendmsg4")
+int pb_sendmsg4(struct bpf_sock_addr *ctx)
+{
+ if (foreign_netns(ctx)) return 1;
+ if (ctx->protocol != IPPROTO_UDP) return 1;
+ struct pb_orig o; __u16 pid;
+ orig_from_v4(&o, ctx->user_ip4, ctx->user_port, IPPROTO_UDP);
+ int r = route(&o, &pid);
+ if (r < 0) return 0;
+ if (r == 0) return 1;
+ ctx->user_ip4 = udp_flow_addr(&o);
+ ctx->user_port = bpf_htons((__u16)cfg_get(PB_CFG_UDP_PORT));
+ return 1;
+}
+
+SEC("cgroup/sendmsg6")
+int pb_sendmsg6(struct bpf_sock_addr *ctx)
+{
+ if (foreign_netns(ctx)) return 1;
+ if (ctx->protocol != IPPROTO_UDP) return 1;
+ __u32 ip6[4] = { ctx->user_ip6[0], ctx->user_ip6[1], ctx->user_ip6[2], ctx->user_ip6[3] };
+ struct pb_orig o; __u16 pid;
+ orig_from_v6(&o, ip6, ctx->user_port, IPPROTO_UDP);
+ int r = route(&o, &pid);
+ if (r < 0) return 0;
+ if (r == 0) return 1;
+ // The kernel (udpv6_sendmsg) refuses a sendmsg6 program that rewrites a native IPv6 destination to a v4-mapped address,
+ // and loopback has only ::1 so a flow id cannot be encoded in the address. A flow that must be proxied therefore fails
+ // closed (EPERM; applications fall back to IPv4/TCP). Flows that merely need a userspace decision pass untouched.
+ if (o.action == ACT_PROXY) { stat_inc(1); return 0; }
+ return 1;
+}
+
+// Replies arrive from the flow address; show the application the real peer.
+SEC("cgroup/recvmsg4")
+int pb_recvmsg4(struct bpf_sock_addr *ctx)
+{
+ if (ctx->protocol != IPPROTO_UDP || ctx->user_port != bpf_htons((__u16)cfg_get(PB_CFG_UDP_PORT))) return 1;
+ __u32 key = ctx->user_ip4;
+ struct pb_orig *o = bpf_map_lookup_elem(&flows, &key);
+ if (!o) return 1;
+ if (o->family == AF_INET) {
+ ctx->user_ip4 = *(__u32 *)(o->addr + 12);
+ ctx->user_port = bpf_htons(o->port);
+ }
+ return 1;
+}
+
+SEC("cgroup/recvmsg6")
+int pb_recvmsg6(struct bpf_sock_addr *ctx)
+{
+ if (ctx->protocol != IPPROTO_UDP || ctx->user_port != bpf_htons((__u16)cfg_get(PB_CFG_UDP_PORT))) return 1;
+ if (ctx->user_ip6[0] || ctx->user_ip6[1] || ctx->user_ip6[2] != bpf_htonl(0x0000ffff)) return 1;
+ __u32 key = ctx->user_ip6[3];
+ struct pb_orig *o = bpf_map_lookup_elem(&flows, &key);
+ if (!o) return 1;
+ const __u32 *w = (const __u32 *)o->addr;
+ ctx->user_ip6[0] = w[0]; ctx->user_ip6[1] = w[1]; ctx->user_ip6[2] = w[2]; ctx->user_ip6[3] = w[3];
+ ctx->user_port = bpf_htons(o->port);
+ return 1;
+}
+
+// getpeername() on a redirected socket shows the original destination
+SEC("cgroup/getpeername4")
+int pb_getpeername4(struct bpf_sock_addr *ctx)
+{
+ struct pb_orig *o;
+ if (ctx->protocol == IPPROTO_UDP) {
+ __u32 key = ctx->user_ip4;
+ o = bpf_map_lookup_elem(&flows, &key);
+ } else if (ctx->protocol == IPPROTO_TCP) {
+ __u64 ck = bpf_get_socket_cookie(ctx);
+ o = bpf_map_lookup_elem(&by_cookie, &ck);
+ } else return 1;
+ if (o && o->family == AF_INET) {
+ ctx->user_ip4 = *(__u32 *)(o->addr + 12);
+ ctx->user_port = bpf_htons(o->port);
+ }
+ return 1;
+}
+
+SEC("cgroup/getpeername6")
+int pb_getpeername6(struct bpf_sock_addr *ctx)
+{
+ struct pb_orig *o;
+ if (ctx->protocol == IPPROTO_UDP) {
+ if (ctx->user_ip6[0] || ctx->user_ip6[1] || ctx->user_ip6[2] != bpf_htonl(0x0000ffff)) return 1;
+ __u32 key = ctx->user_ip6[3];
+ o = bpf_map_lookup_elem(&flows, &key);
+ } else if (ctx->protocol == IPPROTO_TCP) {
+ __u64 ck = bpf_get_socket_cookie(ctx);
+ o = bpf_map_lookup_elem(&by_cookie, &ck);
+ } else return 1;
+ if (o) {
+ const __u32 *w = (const __u32 *)o->addr;
+ ctx->user_ip6[0] = w[0]; ctx->user_ip6[1] = w[1]; ctx->user_ip6[2] = w[2]; ctx->user_ip6[3] = w[3];
+ ctx->user_port = bpf_htons(o->port);
+ }
+ return 1;
+}
+
+// Hand the original destination to the relay, keyed by the client's local port.
+SEC("sockops")
+int pb_sockops(struct bpf_sock_ops *s)
+{
+ if (s->op != BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB) return 1;
+ __u64 ck = bpf_get_socket_cookie(s);
+ struct pb_orig *o = bpf_map_lookup_elem(&by_cookie, &ck);
+ if (!o) return 1;
+ __u32 lp = s->local_port;
+ bpf_map_update_elem(&by_port, &lp, o, BPF_ANY);
+ return 1;
+}
+
+char LICENSE[] SEC("license") = "GPL";
diff --git a/Linux/src/pb_bpf.c b/Linux/src/pb_bpf.c
new file mode 100644
index 0000000..7dedb85
--- /dev/null
+++ b/Linux/src/pb_bpf.c
@@ -0,0 +1,456 @@
+#include <bpf/bpf.h>
+#include <bpf/libbpf.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/resource.h>
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <sys/statfs.h>
+#include <sys/sysmacros.h>
+#include <unistd.h>
+#include "pb_bpf.h"
+#include "proxybridge.skel.h"
+
+#ifndef CGROUP2_SUPER_MAGIC
+#define CGROUP2_SUPER_MAGIC 0x63677270
+#endif
+
+#define MAX_KNOWN_EXES 16384
+
+struct exe_ent { uint32_t dev; uint64_t ino; char path[240]; };
+
+static struct {
+ pthread_mutex_t lock;
+ struct proxybridge_bpf *skel;
+ int linkfds[16];
+ int nlinks;
+ struct ring_buffer *rb;
+ pthread_t evt_thread;
+ bool evt_started;
+ volatile bool stop;
+ pb_event_cb cb;
+ bool running;
+
+ struct exe_ent *exes; size_t nexes; // executables we know about (kernel-side keys)
+ struct pb_bclass *cls; size_t ncls; // current class table (index = class id)
+ bool have_rules;
+} G = { .lock = PTHREAD_MUTEX_INITIALIZER };
+
+// ---- logging bridge -------------------------------------------------------------------------------------------------
+static int libbpf_print(enum libbpf_print_level lvl, const char *fmt, va_list ap)
+{
+ if (lvl == LIBBPF_DEBUG) return 0;
+ char buf[1024];
+ vsnprintf(buf, sizeof buf, fmt, ap);
+ size_t n = strlen(buf);
+ while (n && (buf[n - 1] == '\n')) buf[--n] = 0;
+ if (n) pb_core_log("libbpf: %s", buf);
+ return 0;
+}
+
+// ---- cgroup2 root -----------------------------------------------------------------------------------------------------
+static int open_cgroup_root(void)
+{
+ static const char *cands[] = { "/sys/fs/cgroup", "/sys/fs/cgroup/unified", NULL };
+ for (int i = 0; cands[i]; i++) {
+ struct statfs sf;
+ if (statfs(cands[i], &sf) == 0 && (unsigned long)sf.f_type == CGROUP2_SUPER_MAGIC)
+ return open(cands[i], O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ }
+ return -1;
+}
+
+// ---- cfg ---------------------------------------------------------------------------------------------------------------
+static void cfg_set(uint32_t slot, uint32_t val)
+{
+ bpf_map_update_elem(bpf_map__fd(G.skel->maps.cfg), &slot, &val, BPF_ANY);
+}
+
+// ---- attach ------------------------------------------------------------------------------------------------------------
+static bool attach(struct bpf_program *prog, enum bpf_attach_type type, int cgfd, bool optional)
+{
+ if (!bpf_program__autoload(prog)) return true;
+ // ALLOW_MULTI lets us coexist with other sock_addr programs on the root cgroup; fall back to a plain attach
+ LIBBPF_OPTS(bpf_link_create_opts, opts, .flags = BPF_F_ALLOW_MULTI);
+ int lfd = bpf_link_create(bpf_program__fd(prog), cgfd, type, &opts);
+ if (lfd < 0 && errno == EINVAL)
+ lfd = bpf_link_create(bpf_program__fd(prog), cgfd, type, NULL);
+ if (lfd < 0) {
+ if (optional) return true;
+ pb_core_log("attach %s failed: %s", bpf_program__name(prog), strerror(errno));
+ return false;
+ }
+ G.linkfds[G.nlinks++] = lfd;
+ return true;
+}
+
+static void detach_all(void)
+{
+ for (int i = 0; i < G.nlinks; i++) close(G.linkfds[i]);
+ G.nlinks = 0;
+}
+
+// ---- events ------------------------------------------------------------------------------------------------------------
+static int on_event(void *ctx, void *data, size_t len)
+{
+ (void)ctx;
+ if (len >= sizeof(struct pb_event) && G.cb) G.cb(data);
+ return 0;
+}
+
+static void *evt_loop(void *arg)
+{
+ (void)arg;
+ while (!G.stop) ring_buffer__poll(G.rb, 200);
+ return NULL;
+}
+
+// ---- start / stop -----------------------------------------------------------------------------------------------------
+int pb_bpf_start(const struct pb_bpf_cfg *cfg, pb_event_cb cb)
+{
+ pthread_mutex_lock(&G.lock);
+ if (G.running) { pthread_mutex_unlock(&G.lock); return 0; }
+ int rc = -1, cgfd = -1;
+
+ if (geteuid() != 0) { pb_core_log("ProxyBridge needs root (CAP_BPF/CAP_SYS_ADMIN) to load its eBPF programs"); goto out; }
+ libbpf_set_print(libbpf_print);
+ struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
+ setrlimit(RLIMIT_MEMLOCK, &rl); // pre-5.11 kernels charge maps to memlock
+
+ cgfd = open_cgroup_root();
+ if (cgfd < 0) { pb_core_log("cgroup v2 is not mounted (need a unified hierarchy at /sys/fs/cgroup)"); goto out; }
+
+ G.skel = proxybridge_bpf__open();
+ if (!G.skel) { pb_core_log("cannot open BPF object: %s", strerror(errno)); goto out; }
+ int err = proxybridge_bpf__load(G.skel);
+ if (err) {
+ // getpeername hooks need kernel >= 5.8; retry without them
+ proxybridge_bpf__destroy(G.skel);
+ G.skel = proxybridge_bpf__open();
+ if (G.skel) {
+ bpf_program__set_autoload(G.skel->progs.pb_getpeername4, false);
+ bpf_program__set_autoload(G.skel->progs.pb_getpeername6, false);
+ err = proxybridge_bpf__load(G.skel);
+ }
+ if (err || !G.skel) { pb_core_log("loading the BPF programs failed (kernel needs BTF and cgroup sock_addr support, >= 5.8): %s", strerror(-err ? -err : errno)); goto out; }
+ }
+
+ { // sockets of other network namespaces (containers) must not be redirected to our loopback relay
+ int ns = socket(AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+ uint64_t cookie = 0; socklen_t cl = sizeof cookie;
+ if (ns >= 0 && getsockopt(ns, SOL_SOCKET, 71 /* SO_NETNS_COOKIE */, &cookie, &cl) == 0 && cookie) {
+ cfg_set(PB_CFG_NETNS_LO, (uint32_t)cookie);
+ cfg_set(PB_CFG_NETNS_HI, (uint32_t)(cookie >> 32));
+ } else pb_core_log("kernel has no SO_NETNS_COOKIE: connections from other network namespaces are not isolated");
+ if (ns >= 0) close(ns);
+ }
+ cfg_set(PB_CFG_SELF_TGID, cfg->self_tgid);
+ cfg_set(PB_CFG_TCP_PORT, cfg->tcp_port);
+ cfg_set(PB_CFG_UDP_PORT, cfg->udp_port);
+ cfg_set(PB_CFG_LOG, cfg->log);
+ cfg_set(PB_CFG_DNS_VIA_PROXY, cfg->dns_via_proxy);
+ cfg_set(PB_CFG_ENABLED, 0);
+
+ bool ok = attach(G.skel->progs.pb_connect4, BPF_CGROUP_INET4_CONNECT, cgfd, false) &&
+ attach(G.skel->progs.pb_connect6, BPF_CGROUP_INET6_CONNECT, cgfd, true) &&
+ attach(G.skel->progs.pb_sendmsg4, BPF_CGROUP_UDP4_SENDMSG, cgfd, false) &&
+ attach(G.skel->progs.pb_sendmsg6, BPF_CGROUP_UDP6_SENDMSG, cgfd, true) &&
+ attach(G.skel->progs.pb_recvmsg4, BPF_CGROUP_UDP4_RECVMSG, cgfd, false) &&
+ attach(G.skel->progs.pb_recvmsg6, BPF_CGROUP_UDP6_RECVMSG, cgfd, true) &&
+ attach(G.skel->progs.pb_getpeername4, BPF_CGROUP_INET4_GETPEERNAME, cgfd, true) &&
+ attach(G.skel->progs.pb_getpeername6, BPF_CGROUP_INET6_GETPEERNAME, cgfd, true) &&
+ attach(G.skel->progs.pb_sockops, BPF_CGROUP_SOCK_OPS, cgfd, false);
+ if (!ok) goto out;
+
+ G.cb = cb;
+ G.stop = false;
+ G.rb = ring_buffer__new(bpf_map__fd(G.skel->maps.events), on_event, NULL, NULL);
+ if (!G.rb) { pb_core_log("cannot create event ring buffer"); goto out; }
+ if (pthread_create(&G.evt_thread, NULL, evt_loop, NULL) != 0) { pb_core_log("cannot start event thread"); goto out; }
+ G.evt_started = true;
+ G.running = true;
+ rc = 0;
+out:
+ if (cgfd >= 0) close(cgfd);
+ if (rc != 0) {
+ detach_all();
+ if (G.rb) { ring_buffer__free(G.rb); G.rb = NULL; }
+ if (G.skel) { proxybridge_bpf__destroy(G.skel); G.skel = NULL; }
+ }
+ pthread_mutex_unlock(&G.lock);
+ return rc;
+}
+
+void pb_bpf_stop(void)
+{
+ pthread_mutex_lock(&G.lock);
+ if (G.skel) {
+ G.stop = true;
+ if (G.evt_started) { pthread_mutex_unlock(&G.lock); pthread_join(G.evt_thread, NULL); pthread_mutex_lock(&G.lock); G.evt_started = false; }
+ detach_all();
+ if (G.rb) { ring_buffer__free(G.rb); G.rb = NULL; }
+ proxybridge_bpf__destroy(G.skel);
+ G.skel = NULL;
+ }
+ free(G.exes); G.exes = NULL; G.nexes = 0;
+ free(G.cls); G.cls = NULL; G.ncls = 0;
+ G.running = false;
+ pthread_mutex_unlock(&G.lock);
+}
+
+bool pb_bpf_running(void) { return G.running; }
+
+void pb_bpf_set_flags(bool log, bool dns_via_proxy)
+{
+ pthread_mutex_lock(&G.lock);
+ if (G.skel) { cfg_set(PB_CFG_LOG, log); cfg_set(PB_CFG_DNS_VIA_PROXY, dns_via_proxy); }
+ pthread_mutex_unlock(&G.lock);
+}
+
+// ---- executables --------------------------------------------------------------------------------------------------------
+static uint32_t kernel_dev(dev_t d) { return (major(d) << 20) | minor(d); }
+
+static struct exe_ent *exe_find(uint32_t dev, uint64_t ino)
+{
+ for (size_t i = 0; i < G.nexes; i++)
+ if (G.exes[i].ino == ino && G.exes[i].dev == dev) return &G.exes[i];
+ return NULL;
+}
+
+static struct exe_ent *exe_add(uint32_t dev, uint64_t ino, const char *path)
+{
+ struct exe_ent *e = exe_find(dev, ino);
+ if (e) { if (path && *path) snprintf(e->path, sizeof e->path, "%s", path); return e; }
+ if (G.nexes >= MAX_KNOWN_EXES) return NULL;
+ if (!G.exes) { G.exes = calloc(MAX_KNOWN_EXES, sizeof *G.exes); if (!G.exes) return NULL; }
+ e = &G.exes[G.nexes++];
+ e->dev = dev; e->ino = ino;
+ snprintf(e->path, sizeof e->path, "%s", path ? path : "");
+ return e;
+}
+
+static void strip_deleted(char *p)
+{
+ size_t n = strlen(p);
+ static const char suf[] = " (deleted)";
+ if (n > sizeof suf - 1 && !strcmp(p + n - (sizeof suf - 1), suf)) p[n - (sizeof suf - 1)] = 0;
+}
+
+static void scan_proc(void)
+{
+ DIR *d = opendir("/proc");
+ if (!d) return;
+ struct dirent *de;
+ while ((de = readdir(d))) {
+ if (de->d_name[0] < '1' || de->d_name[0] > '9') continue;
+ char lnk[300], path[240];
+ snprintf(lnk, sizeof lnk, "/proc/%.200s/exe", de->d_name);
+ struct stat st;
+ if (stat(lnk, &st) != 0) continue;
+ ssize_t n = readlink(lnk, path, sizeof path - 1);
+ if (n <= 0) continue;
+ path[n] = 0;
+ strip_deleted(path);
+ exe_add(kernel_dev(st.st_dev), st.st_ino, path);
+ }
+ closedir(d);
+}
+
+// ---- compilation -----------------------------------------------------------------------------------------------------------
+static void compile_rule(const struct pb_rule_view *v, struct pb_brule *b)
+{
+ const struct pb_rule *r = v->rule;
+ memset(b, 0, sizeof *b);
+ b->action = (uint8_t)v->action;
+ b->proxy_id = v->action == RULE_ACTION_PROXY ? v->proxy_id : 0;
+ b->proto_mask = r->protocol == RULE_PROTOCOL_TCP ? 1 : r->protocol == RULE_PROTOCOL_UDP ? 2 : 3;
+ if (v->action == RULE_ACTION_PROXY && v->udp_direct) b->flags |= PB_RF_UDP_DIRECT;
+
+ if (r->any_port) b->flags |= PB_RF_ANY_PORT;
+ else {
+ for (int i = 0; i < r->nports; i++) {
+ if (b->n_port < PB_BPF_MAX_PORT) { b->port[b->n_port].lo = r->ports[i].lo; b->port[b->n_port].hi = r->ports[i].hi; b->n_port++; }
+ else b->flags |= PB_RF_PORT_COMPLEX;
+ }
+ }
+ if (r->any_host) b->flags |= PB_RF_ANY_HOST;
+ else {
+ if (r->ndomains) b->flags |= PB_RF_DOMAINS;
+ for (int i = 0; i < r->nhosts; i++) {
+ const struct pb_host_pat *h = &r->hosts[i];
+ if (h->kind == PB_HOST_V4_RANGE && b->n_v4 < PB_BPF_MAX_V4) { b->v4[b->n_v4].lo = h->lo4; b->v4[b->n_v4].hi = h->hi4; b->n_v4++; }
+ else if (h->kind == PB_HOST_V6_RANGE) b->flags |= PB_RF_HAS_V6;
+ else b->flags |= PB_RF_HOST_COMPLEX; // box patterns / too many ranges: let the relay decide
+ }
+ }
+}
+
+// a rule that cannot be skipped by later ones: every host, every port, both protocols
+static bool rule_is_catchall(const struct pb_brule *b)
+{
+ return (b->flags & PB_RF_ANY_HOST) && (b->flags & PB_RF_ANY_PORT) && b->proto_mask == 3;
+}
+
+static int class_for(const struct pb_rule_view *v, const struct pb_brule *br, size_t n, const char *path, struct pb_bclass *out)
+{
+ memset(out, 0, sizeof *out);
+ for (size_t i = 0; i < n; i++) {
+ if (!v[i].rule->enabled) continue;
+ if (!pb_rule_match_process(v[i].rule, path)) continue;
+ if (pb_rule_has_domains(v[i].rule)) out->tap = 1;
+ if (out->n >= PB_RULES_PER_CLASS) { memset(out, 0, sizeof *out); out->n = PB_CLASS_DECIDE; out->tap = 1; return 0; }
+ out->rule[out->n++] = (uint32_t)i;
+ if (rule_is_catchall(&br[i])) break; // nothing after a catch-all can apply
+ }
+ return 0;
+}
+
+static int class_intern(const struct pb_bclass *c)
+{
+ for (size_t i = 0; i < G.ncls; i++)
+ if (!memcmp(&G.cls[i], c, sizeof *c)) return (int)i;
+ if (G.ncls >= PB_MAX_CLASSES) return -1;
+ G.cls[G.ncls] = *c;
+ return (int)G.ncls++;
+}
+
+static void write_class_slot(uint32_t id)
+{
+ bpf_map_update_elem(bpf_map__fd(G.skel->maps.classes), &id, &G.cls[id], BPF_ANY);
+}
+
+int pb_bpf_sync(const struct pb_rule_view *v, size_t n)
+{
+ if (n > PB_MAX_RULES) { pb_core_log("too many rules (max %d)", PB_MAX_RULES); return -1; }
+ pthread_mutex_lock(&G.lock);
+ if (!G.skel) { pthread_mutex_unlock(&G.lock); return -1; }
+
+ struct pb_brule *br = calloc(n ? n : 1, sizeof *br);
+ if (!G.cls) G.cls = calloc(PB_MAX_CLASSES, sizeof *G.cls);
+ if (!br || !G.cls) { free(br); pthread_mutex_unlock(&G.lock); return -1; }
+
+ size_t active = 0;
+ for (size_t i = 0; i < n; i++) {
+ compile_rule(&v[i], &br[i]);
+ uint32_t k = (uint32_t)i;
+ bpf_map_update_elem(bpf_map__fd(G.skel->maps.brules), &k, &br[i], BPF_ANY);
+ if (v[i].rule->enabled) active++;
+ }
+
+ scan_proc();
+ G.ncls = 0;
+ memset(G.cls, 0, PB_MAX_CLASSES * sizeof *G.cls);
+ G.ncls = 1; // class 0 = no rule applies (direct)
+ int mapfd = bpf_map__fd(G.skel->maps.exe2class);
+
+ // remember what was installed so entries for vanished binaries can be dropped
+ struct pb_exe_key k = {}, next;
+ struct pb_exe_key *old = NULL; size_t nold = 0, capold = 0;
+ int ret = bpf_map_get_next_key(mapfd, NULL, &next);
+ while (ret == 0) {
+ if (nold == capold) { capold = capold ? capold * 2 : 256; old = realloc(old, capold * sizeof *old); if (!old) break; }
+ old[nold++] = next;
+ k = next;
+ ret = bpf_map_get_next_key(mapfd, &k, &next);
+ }
+
+ for (size_t i = 0; i < G.nexes; i++) {
+ struct pb_bclass c;
+ class_for(v, br, n, G.exes[i].path, &c);
+ int id = class_intern(&c);
+ struct pb_exe_key key = { .dev = G.exes[i].dev, .ino = G.exes[i].ino };
+ if (id < 0) { bpf_map_delete_elem(mapfd, &key); continue; } // out of classes: slow path
+ uint32_t cid = (uint32_t)id;
+ bpf_map_update_elem(mapfd, &key, &cid, BPF_ANY);
+ }
+ for (size_t i = 0; i < G.ncls; i++) write_class_slot((uint32_t)i);
+ for (size_t i = 0; i < nold; i++)
+ if (!exe_find(old[i].dev, old[i].ino)) bpf_map_delete_elem(mapfd, &old[i]);
+ free(old);
+ free(br);
+
+ bool domains = false;
+ for (size_t i = 0; i < n; i++) domains |= v[i].rule->enabled && pb_rule_has_domains(v[i].rule);
+ cfg_set(PB_CFG_DNS_TAP, domains ? 1 : 0);
+ G.have_rules = active > 0;
+ cfg_set(PB_CFG_ENABLED, G.have_rules ? 1 : 0);
+ pthread_mutex_unlock(&G.lock);
+ return 0;
+}
+
+void pb_bpf_learn(const struct pb_orig *o, const char *exe_path, const struct pb_rule_view *v, size_t n)
+{
+ if (!o->exe_ino || n > PB_MAX_RULES) return;
+ pthread_mutex_lock(&G.lock);
+ if (!G.skel || !G.cls) { pthread_mutex_unlock(&G.lock); return; }
+ struct exe_ent *known = exe_find(o->exe_dev, o->exe_ino);
+ struct exe_ent *e = known ? NULL : exe_add(o->exe_dev, o->exe_ino, exe_path); // already classified: nothing to learn
+ if (e) {
+ struct pb_brule *br = calloc(n ? n : 1, sizeof *br);
+ if (br) {
+ for (size_t i = 0; i < n; i++) compile_rule(&v[i], &br[i]);
+ struct pb_bclass c;
+ class_for(v, br, n, e->path, &c);
+ int id = class_intern(&c);
+ if (id >= 0) {
+ write_class_slot((uint32_t)id);
+ struct pb_exe_key key = { .dev = e->dev, .ino = e->ino };
+ uint32_t cid = (uint32_t)id;
+ bpf_map_update_elem(bpf_map__fd(G.skel->maps.exe2class), &key, &cid, BPF_ANY);
+ }
+ free(br);
+ }
+ }
+ pthread_mutex_unlock(&G.lock);
+}
+
+// ---- lookups for the relay -------------------------------------------------------------------------------------------------
+int pb_bpf_take_tcp_orig(uint16_t client_port, struct pb_orig *out)
+{
+ uint32_t key = client_port;
+ int fd = G.skel ? bpf_map__fd(G.skel->maps.by_port) : -1;
+ if (fd < 0 || bpf_map_lookup_elem(fd, &key, out) != 0) return -1;
+ bpf_map_delete_elem(fd, &key);
+ return 0;
+}
+
+int pb_bpf_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out)
+{
+ int fd = G.skel ? bpf_map__fd(G.skel->maps.flows) : -1;
+ return (fd >= 0 && bpf_map_lookup_elem(fd, &flow_ip_be, out) == 0) ? 0 : -1;
+}
+
+// ---- domain rules ------------------------------------------------------------------------------------------------------------
+void pb_bpf_dom_set(uint32_t rule_idx, uint32_t ip_host)
+{
+ if (!G.skel) return;
+ struct pb_dom_key k = { .rule = rule_idx, .ip = ip_host };
+ uint8_t one = 1;
+ bpf_map_update_elem(bpf_map__fd(G.skel->maps.dom_hit), &k, &one, BPF_ANY);
+}
+
+void pb_bpf_dom_clear(void)
+{
+ if (!G.skel) return;
+ int fd = bpf_map__fd(G.skel->maps.dom_hit);
+ struct pb_dom_key k, next;
+ int rc = bpf_map_get_next_key(fd, NULL, &next);
+ while (rc == 0) {
+ k = next;
+ rc = bpf_map_get_next_key(fd, &k, &next);
+ bpf_map_delete_elem(fd, &k);
+ }
+}
+
+void pb_bpf_set_dns_tap(bool on)
+{
+ pthread_mutex_lock(&G.lock);
+ if (G.skel) cfg_set(PB_CFG_DNS_TAP, on ? 1 : 0);
+ pthread_mutex_unlock(&G.lock);
+}
diff --git a/Linux/src/pb_bpf.h b/Linux/src/pb_bpf.h
new file mode 100644
index 0000000..2a4c7da
--- /dev/null
+++ b/Linux/src/pb_bpf.h
@@ -0,0 +1,46 @@
+// eBPF backend: loads/attaches the datapath, compiles rules into BPF maps, reads flow events.
+#ifndef PB_BPF_H
+#define PB_BPF_H
+
+#include "pb_internal.h"
+#include "pb_rules.h"
+#include "bpf/pb_bpf_shared.h"
+
+struct pb_bpf_cfg {
+ uint16_t tcp_port, udp_port; // relay ports (already bound by the relay)
+ uint32_t self_tgid; // process hosting the relay; never redirected
+ bool log;
+ bool dns_via_proxy;
+};
+
+// One rule as seen by the compiler: the parsed rule plus its resolved proxy.
+struct pb_rule_view {
+ const struct pb_rule *rule;
+ int action; // effective action (PROXY with no usable proxy has already become BLOCK)
+ uint16_t proxy_id; // resolved (0 for DIRECT/BLOCK)
+ bool udp_direct; // PROXY rule whose proxy is HTTP: UDP goes direct
+};
+
+typedef void (*pb_event_cb)(const struct pb_event *e);
+
+// Returns 0 on success; on failure returns -1 after logging the reason (kernel too old, not root, no cgroup2, verifier...).
+int pb_bpf_start(const struct pb_bpf_cfg *cfg, pb_event_cb cb);
+void pb_bpf_stop(void);
+bool pb_bpf_running(void);
+
+void pb_bpf_set_flags(bool log, bool dns_via_proxy);
+// Recompiles the rule set (and rescans /proc for running executables). Returns -1 if it does not fit (too many rules).
+int pb_bpf_sync(const struct pb_rule_view *v, size_t n);
+// Slow-path learning: install the class for the exact executable key the kernel reported in `o`, using the same rule set
+// that decide() just evaluated.
+void pb_bpf_learn(const struct pb_orig *o, const char *exe_path, const struct pb_rule_view *v, size_t n);
+
+// Domain rules: (rule index, address) pairs whose DNS name matches. Set by the DNS tap before the answer reaches the client.
+void pb_bpf_dom_set(uint32_t rule_idx, uint32_t ip_host);
+void pb_bpf_dom_clear(void);
+void pb_bpf_set_dns_tap(bool on);
+
+int pb_bpf_take_tcp_orig(uint16_t client_port, struct pb_orig *out);
+int pb_bpf_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out);
+
+#endif
diff --git a/Linux/src/pb_dns.c b/Linux/src/pb_dns.c
new file mode 100644
index 0000000..8906d48
--- /dev/null
+++ b/Linux/src/pb_dns.c
@@ -0,0 +1,263 @@
+#include <stdbool.h>
+#include <arpa/inet.h>
+#include <ctype.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "pb_dns.h"
+
+#define BUCKETS 16384
+
+struct ent {
+ uint32_t ip;
+ char *names[PB_DNS_MAX_NAMES]; int n;
+ struct ent *hnext; // hash chain
+ struct ent *prev, *next; // age order: head = oldest
+};
+
+static struct {
+ pthread_mutex_t lock;
+ struct ent *bucket[BUCKETS];
+ struct ent *head, *tail;
+ size_t count;
+} T = { .lock = PTHREAD_MUTEX_INITIALIZER };
+
+static unsigned hash_ip(uint32_t ip) { ip *= 2654435761u; return (ip >> 12) & (BUCKETS - 1); }
+
+static void ent_unlink_age(struct ent *e)
+{
+ if (e->prev) e->prev->next = e->next; else T.head = e->next;
+ if (e->next) e->next->prev = e->prev; else T.tail = e->prev;
+ e->prev = e->next = NULL;
+}
+
+static void ent_push_tail(struct ent *e)
+{
+ e->prev = T.tail; e->next = NULL;
+ if (T.tail) T.tail->next = e; else T.head = e;
+ T.tail = e;
+}
+
+static void ent_free(struct ent *e)
+{
+ for (int i = 0; i < e->n; i++) free(e->names[i]);
+ free(e);
+}
+
+static void evict_oldest(struct pb_dns_result *res)
+{
+ struct ent *e = T.head;
+ if (!e) return;
+ ent_unlink_age(e);
+ for (struct ent **pp = &T.bucket[hash_ip(e->ip)]; *pp; pp = &(*pp)->hnext)
+ if (*pp == e) { *pp = e->hnext; break; }
+ if (res && res->nevicted < 32) res->evicted[res->nevicted++] = e->ip;
+ ent_free(e);
+ T.count--;
+}
+
+static struct ent *find(uint32_t ip)
+{
+ for (struct ent *e = T.bucket[hash_ip(ip)]; e; e = e->hnext) if (e->ip == ip) return e;
+ return NULL;
+}
+
+// Adds names to ip's entry (creating it), refreshing its age. Caller holds the lock.
+static void add_mapping(uint32_t ip, char names[][256], int nn, struct pb_dns_result *res)
+{
+ struct ent *e = find(ip);
+ if (!e) {
+ while (T.count >= PB_DNS_MAX_ENTRIES) evict_oldest(res);
+ e = calloc(1, sizeof *e);
+ if (!e) return;
+ e->ip = ip;
+ unsigned h = hash_ip(ip);
+ e->hnext = T.bucket[h]; T.bucket[h] = e;
+ T.count++;
+ } else {
+ ent_unlink_age(e);
+ }
+ ent_push_tail(e);
+ for (int i = 0; i < nn; i++) {
+ bool have = false;
+ for (int j = 0; j < e->n; j++) if (!strcmp(e->names[j], names[i])) { have = true; break; }
+ if (have) continue;
+ char *c = strdup(names[i]);
+ if (!c) continue;
+ if (e->n == PB_DNS_MAX_NAMES) { free(e->names[0]); memmove(&e->names[0], &e->names[1], (PB_DNS_MAX_NAMES - 1) * sizeof(char *)); e->n--; }
+ e->names[e->n++] = c;
+ }
+ if (res) {
+ bool dup = false;
+ for (int i = 0; i < res->nips; i++) if (res->ips[i] == ip) dup = true;
+ if (!dup && res->nips < 32) res->ips[res->nips++] = ip;
+ }
+}
+
+// ---- wire format -----------------------------------------------------------------------------------------------------
+
+// Reads a (possibly compressed) name at *off into out (lower-case, dotted). Advances *off past the name as stored at that
+// position. Returns false on malformed data.
+static bool read_name(const uint8_t *m, size_t len, size_t *off, char *out, size_t outsz)
+{
+ size_t pos = *off, o = 0;
+ int hops = 0;
+ bool jumped = false;
+ for (;;) {
+ if (pos >= len) return false;
+ uint8_t l = m[pos];
+ if (l == 0) { pos++; break; }
+ if ((l & 0xC0) == 0xC0) {
+ if (pos + 1 >= len) return false;
+ size_t ptr = ((size_t)(l & 0x3F) << 8) | m[pos + 1];
+ if (!jumped) *off = pos + 2;
+ jumped = true;
+ if (++hops > 16 || ptr >= len) return false;
+ pos = ptr;
+ continue;
+ }
+ if (l & 0xC0) return false;
+ if (pos + 1 + l > len) return false;
+ if (o + l + 2 > outsz) return false;
+ if (o) out[o++] = '.';
+ for (uint8_t i = 0; i < l; i++) out[o++] = (char)tolower(m[pos + 1 + i]);
+ pos += 1u + l;
+ }
+ out[o] = 0;
+ if (!jumped) *off = pos;
+ return true;
+}
+
+static uint16_t rd16(const uint8_t *p) { return (uint16_t)((p[0] << 8) | p[1]); }
+
+int pb_dns_observe(const uint8_t *m, size_t len, struct pb_dns_result *res)
+{
+ if (res) memset(res, 0, sizeof *res);
+ if (len < 12) return 0;
+ uint16_t flags = rd16(m + 2), qd = rd16(m + 4), an = rd16(m + 6);
+ if (!(flags & 0x8000) || (flags & 0x7800) || (flags & 0x000F)) return 0; // response, QUERY opcode, NOERROR only
+ if (qd > 4 || an == 0 || an > 128) return 0;
+
+ char names[PB_DNS_MAX_NAMES][256];
+ int nn = 0;
+ size_t off = 12;
+ char buf[256];
+ for (int i = 0; i < qd; i++) {
+ if (!read_name(m, len, &off, buf, sizeof buf) || off + 4 > len) return 0;
+ off += 4;
+ if (nn < PB_DNS_MAX_NAMES) { bool dup = false; for (int k = 0; k < nn; k++) if (!strcmp(names[k], buf)) dup = true; if (!dup) strcpy(names[nn++], buf); }
+ }
+
+ uint32_t ips[64]; int nips = 0;
+ // first pass collects the chain of names (CNAME owners/targets and A owners), second pass assigns them to every address
+ struct { size_t rdata; uint16_t type, rdlen; char owner[256]; } rr[128];
+ int nrr = 0;
+ for (int i = 0; i < an; i++) {
+ char owner[256];
+ if (!read_name(m, len, &off, owner, sizeof owner) || off + 10 > len) break;
+ uint16_t type = rd16(m + off), rdlen = rd16(m + off + 8);
+ size_t rd = off + 10;
+ if (rd + rdlen > len) break;
+ strcpy(rr[nrr].owner, owner); rr[nrr].type = type; rr[nrr].rdlen = rdlen; rr[nrr].rdata = rd; nrr++;
+ off = rd + rdlen;
+ }
+ for (int i = 0; i < nrr; i++) {
+ bool addname = false;
+ char target[256];
+ if (rr[i].type == 5) { // CNAME: owner and target are both names of the final address
+ size_t o2 = rr[i].rdata;
+ if (read_name(m, len, &o2, target, sizeof target)) {
+ addname = true;
+ for (int pass = 0; pass < 2; pass++) {
+ const char *nm = pass ? target : rr[i].owner;
+ bool dup = false;
+ for (int k = 0; k < nn; k++) if (!strcmp(names[k], nm)) dup = true;
+ if (!dup && nn < PB_DNS_MAX_NAMES) strcpy(names[nn++], nm);
+ }
+ }
+ } else if (rr[i].type == 1 && rr[i].rdlen == 4) {
+ if (nips < 64) {
+ ips[nips++] = ((uint32_t)m[rr[i].rdata] << 24) | ((uint32_t)m[rr[i].rdata + 1] << 16) | ((uint32_t)m[rr[i].rdata + 2] << 8) | m[rr[i].rdata + 3];
+ bool dup = false;
+ for (int k = 0; k < nn; k++) if (!strcmp(names[k], rr[i].owner)) dup = true;
+ if (!dup && nn < PB_DNS_MAX_NAMES) strcpy(names[nn++], rr[i].owner);
+ }
+ }
+ (void)addname;
+ }
+ if (!nips || !nn) return 0;
+
+ pthread_mutex_lock(&T.lock);
+ for (int i = 0; i < nips; i++) {
+ uint32_t ip = ips[i];
+ if ((ip >> 24) == 127 || ip == 0) continue; // answers pointing at loopback/unspecified are never redirected
+ add_mapping(ip, names, nn, res);
+ }
+ pthread_mutex_unlock(&T.lock);
+ return nips;
+}
+
+int pb_dns_lookup(uint32_t ip, char out[][256], int max)
+{
+ int n = 0;
+ pthread_mutex_lock(&T.lock);
+ struct ent *e = find(ip);
+ if (e) for (; n < e->n && n < max; n++) snprintf(out[n], 256, "%s", e->names[n]);
+ pthread_mutex_unlock(&T.lock);
+ return n;
+}
+
+int pb_dns_load_hosts(const char *path, struct pb_dns_result *res)
+{
+ if (res) memset(res, 0, sizeof *res);
+ FILE *f = fopen(path, "r");
+ if (!f) return 0;
+ char line[1024];
+ int added = 0;
+ while (fgets(line, sizeof line, f)) {
+ char *hash = strchr(line, '#');
+ if (hash) *hash = 0;
+ char *save = NULL, *ipstr = strtok_r(line, " \t\r\n", &save);
+ struct in_addr a;
+ if (!ipstr || inet_pton(AF_INET, ipstr, &a) != 1) continue;
+ uint32_t ip = ntohl(a.s_addr);
+ if ((ip >> 24) == 127 || ip == 0) continue;
+ char names[PB_DNS_MAX_NAMES][256];
+ int nn = 0;
+ for (char *nm; nn < PB_DNS_MAX_NAMES && (nm = strtok_r(NULL, " \t\r\n", &save)); ) {
+ snprintf(names[nn], 256, "%s", nm);
+ for (char *c = names[nn]; *c; c++) *c = (char)tolower((unsigned char)*c);
+ nn++;
+ }
+ if (!nn) continue;
+ pthread_mutex_lock(&T.lock);
+ add_mapping(ip, names, nn, res);
+ pthread_mutex_unlock(&T.lock);
+ added++;
+ }
+ fclose(f);
+ return added;
+}
+
+void pb_dns_for_each(void (*cb)(uint32_t, const char *const *, int, void *), void *ctx)
+{
+ pthread_mutex_lock(&T.lock);
+ for (struct ent *e = T.head; e; e = e->next) cb(e->ip, (const char *const *)e->names, e->n, ctx);
+ pthread_mutex_unlock(&T.lock);
+}
+
+void pb_dns_clear(void)
+{
+ pthread_mutex_lock(&T.lock);
+ while (T.head) evict_oldest(NULL);
+ pthread_mutex_unlock(&T.lock);
+}
+
+size_t pb_dns_count(void)
+{
+ pthread_mutex_lock(&T.lock);
+ size_t n = T.count;
+ pthread_mutex_unlock(&T.lock);
+ return n;
+}
diff --git a/Linux/src/pb_dns.h b/Linux/src/pb_dns.h
new file mode 100644
index 0000000..550e491
--- /dev/null
+++ b/Linux/src/pb_dns.h
@@ -0,0 +1,33 @@
+// DNS awareness: learns IPv4 -> domain-name mappings from DNS answers that pass through the relay (the "DNS tap") so that
+// domain rules can be applied to connections the kernel only sees as IP addresses.
+#ifndef PB_DNS_H
+#define PB_DNS_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#define PB_DNS_MAX_NAMES 8
+#define PB_DNS_MAX_ENTRIES 32768 // bounded: oldest mappings are evicted first
+
+struct pb_dns_result {
+ uint32_t ips[32]; int nips; // addresses (host order) whose mapping was added or refreshed
+ uint32_t evicted[32]; int nevicted; // addresses dropped to stay within PB_DNS_MAX_ENTRIES
+};
+
+// Parses a DNS response message (no TCP length prefix). Returns the number of A records learned (0 if the message is not a
+// successful response or has no A records). Safe on arbitrary/malicious input.
+int pb_dns_observe(const uint8_t *msg, size_t len, struct pb_dns_result *res);
+
+// Copies up to max names known for ip (host order) into out; returns the count.
+int pb_dns_lookup(uint32_t ip, char out[][256], int max);
+
+// Adds static mappings from /etc/hosts. Returns the number of addresses added.
+int pb_dns_load_hosts(const char *path, struct pb_dns_result *res);
+
+// Visits every mapping (used to re-arm kernel state after a rule change). cb must not call back into pb_dns_*.
+void pb_dns_for_each(void (*cb)(uint32_t ip, const char *const *names, int n, void *ctx), void *ctx);
+
+void pb_dns_clear(void);
+size_t pb_dns_count(void);
+
+#endif
diff --git a/Linux/src/pb_internal.h b/Linux/src/pb_internal.h
new file mode 100644
index 0000000..83e72f0
--- /dev/null
+++ b/Linux/src/pb_internal.h
@@ -0,0 +1,121 @@
+// Internal interfaces shared by the ProxyBridge Linux modules (eBPF backend).
+//
+// proxybridge.bpf.c kernel side: rewrites connect()/sendmsg() destinations to the relay
+// pb_rules.c rule store, validation, full userspace matcher
+// pb_bpf.c loads/attaches BPF, compiles rules into BPF maps, reads events
+// pb_relay.c userspace relay: TCP (SOCKS5 / HTTP CONNECT), UDP (SOCKS5 UDP ASSOCIATE), DIRECT
+// ProxyBridge.c public API glue
+#ifndef PB_INTERNAL_H
+#define PB_INTERNAL_H
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <sys/socket.h>
+#include "ProxyBridge.h"
+
+#define PB_TCP_RELAY_PORT_DEFAULT 24010 // outside the default ephemeral range 32768-60999
+#define PB_UDP_RELAY_PORT_DEFAULT 24011
+
+// ---------------------------------------------------------------------------------------------
+// Decision values
+// ---------------------------------------------------------------------------------------------
+#define PB_ACT_PROXY 0 // matches RuleAction
+#define PB_ACT_DIRECT 1
+#define PB_ACT_BLOCK 2
+#define PB_ACT_DECIDE 3 // kernel could not decide: relay must call pb_core_decide()
+
+// ---------------------------------------------------------------------------------------------
+// Original destination record. Produced by the BPF programs, looked up by the relay.
+// Layout is shared with the BPF object: keep in sync with proxybridge.bpf.c (struct pb_orig).
+// ---------------------------------------------------------------------------------------------
+struct pb_orig {
+ uint8_t addr[16]; // original destination, network order. IPv4 is stored as ::ffff:a.b.c.d
+ uint16_t port; // original destination port, host order
+ uint16_t proxy_id; // valid when action == PB_ACT_PROXY
+ uint32_t pid; // tgid of the process that opened the flow
+ uint8_t family; // AF_INET or AF_INET6 (of the ORIGINAL destination)
+ uint8_t proto; // IPPROTO_TCP or IPPROTO_UDP
+ uint8_t action; // PB_ACT_PROXY or PB_ACT_DECIDE (DIRECT/BLOCK never reach the relay from the kernel)
+ uint8_t pad;
+ uint32_t exe_dev; // kernel-side (dev, inode) of the process's executable (valid for PB_ACT_DECIDE flows)
+ uint32_t exe_pad;
+ uint64_t exe_ino;
+};
+
+// Result of a userspace decision (slow path).
+struct pb_decision {
+ int action; // PB_ACT_PROXY / PB_ACT_DIRECT / PB_ACT_BLOCK
+ uint32_t proxy_id; // for PB_ACT_PROXY
+};
+
+// A configured upstream proxy (snapshot copy handed to the relay; the relay owns the copy).
+struct pb_proxy {
+ uint32_t id;
+ ProxyType type; // PROXY_TYPE_HTTP / PROXY_TYPE_SOCKS5
+ char name[64];
+ char host[256]; // IP literal or hostname (relay must resolve it, with a timeout, outside the epoll loop)
+ uint16_t port;
+ char user[256]; // empty string = no auth
+ char pass[256];
+};
+
+// ---------------------------------------------------------------------------------------------
+// Services the CORE provides to the relay (implemented in pb_bpf.c / ProxyBridge.c)
+// ---------------------------------------------------------------------------------------------
+
+// TCP: original destination for a relayed connection, keyed by the *client's* source port as seen by the relay
+// (accept() peer port; peer address is 127.0.0.1). Consumes (deletes) the entry. Returns 0 on success.
+int pb_core_take_tcp_orig(uint16_t client_port, struct pb_orig *out);
+
+// UDP: original destination for a datagram, keyed by the loopback address it was sent to (IP_PKTINFO ipi_addr, network
+// order). Does not delete (flows are shared and LRU-evicted). Returns 0 on success.
+int pb_core_get_udp_flow(uint32_t flow_ip_be, struct pb_orig *out);
+
+// Slow-path decision for a pb_orig with action == PB_ACT_DECIDE (evaluates the full rule set for o->pid).
+void pb_core_decide(const struct pb_orig *o, struct pb_decision *out);
+
+// Copies the proxy config with this id (or the default proxy when id == 0). Returns 0 on success, -1 if unknown.
+int pb_core_get_proxy(uint32_t id, struct pb_proxy *out);
+
+// Logging / events. Both thread-safe, may be called from any relay thread.
+void pb_core_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
+// One event per relayed flow after the final action is known (proxy_desc e.g. "SOCKS5 127.0.0.1:1080" / "DIRECT" / "BLOCK").
+void pb_core_flow_event(const struct pb_orig *o, int action, const char *proxy_desc);
+
+// DNS tap. The relay calls this for every DNS message travelling server->client on a flow whose ORIGINAL destination port is 53:
+// the payload of each UDP reply datagram, or each complete TCP-DNS message (2-byte length prefix already stripped). It must be
+// called BEFORE the message is delivered to the client, because the core uses it to arm kernel rules for the addresses in the
+// answer. Thread-safe and cheap when no domain rules exist (returns immediately).
+void pb_core_dns_observe(const uint8_t *msg, size_t len);
+
+// Whether DNS (UDP/TCP port 53) should be sent through the proxy even if rules say DIRECT is not set. Informational.
+bool pb_core_dns_via_proxy(void);
+
+// ---------------------------------------------------------------------------------------------
+// Services the RELAY provides to the core (implemented in pb_relay.c)
+// ---------------------------------------------------------------------------------------------
+struct pb_relay_cfg {
+ uint16_t tcp_port; // listen port on 127.0.0.1 (0 = PB_TCP_RELAY_PORT_DEFAULT)
+ uint16_t udp_port; // UDP listen port, bound with SO_BINDTODEVICE "lo" (0 = default)
+ int max_tcp_conns; // hard cap on concurrent relayed TCP connections (0 = 32768)
+ int tcp_idle_timeout_s; // 0 = 300
+ int udp_idle_timeout_s; // 0 = 60
+ int handshake_timeout_s; // proxy connect + handshake budget (0 = 10)
+};
+
+// Binds the sockets (returns -1 and logs via pb_core_log on failure, leaving nothing running), starts the worker threads.
+int pb_relay_start(const struct pb_relay_cfg *cfg);
+// Stops all threads, closes every fd (listeners, client/upstream sockets, epoll, eventfds). Safe to call twice. After it
+// returns, pb_relay_start() must work again (no leaked listeners).
+void pb_relay_stop(void);
+// Actual ports in use (valid after a successful start).
+uint16_t pb_relay_tcp_port(void);
+uint16_t pb_relay_udp_port(void);
+
+// Synchronous proxy test used by ProxyBridge_TestConnection: connects to `target_host:target_port` THROUGH `proxy` and sends
+// an HTTP HEAD/GET if port is 80/443-ish (caller decides); returns bytes of response in buf (NUL-terminated) or -1 on error with
+// a human readable reason in buf. Must not depend on relay_start(). 10 second budget.
+int pb_relay_test_proxy(const struct pb_proxy *proxy, const char *target_host, uint16_t target_port, char *buf, size_t buflen);
+
+#endif
diff --git a/Linux/src/pb_relay.c b/Linux/src/pb_relay.c
new file mode 100644
index 0000000..e1de2bb
--- /dev/null
+++ b/Linux/src/pb_relay.c
@@ -0,0 +1,1781 @@
+// pb_relay.c - userspace relay for the eBPF backend.
+//
+// TCP: acceptor thread -> bounded handshake worker pool (blocking steps with deadlines) -> epoll data threads.
+// UDP: one epoll thread owning every session; SOCKS5 UDP ASSOCIATE setup runs in the worker pool.
+// Ownership: a conn/session is only touched by the thread that owns its epoll; workers hand objects over via queues.
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include <arpa/inet.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <poll.h>
+#include <pthread.h>
+#include <stdarg.h>
+#include <stdatomic.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/epoll.h>
+#include <sys/eventfd.h>
+#include <sys/socket.h>
+#include <sys/timerfd.h>
+#include <time.h>
+#include <unistd.h>
+
+#include "pb_internal.h"
+
+#define SCRATCH_SZ 65536 // per data thread read buffer; idle connections hold no buffer
+#define HDR_MAX 8192
+#define NWORKERS 16
+#define MAX_DATA 8
+#define PIPE_SZ (1 << 20)
+#define JOBQ_MAX 4096 // handshake queue; excess accepts are shed with a log
+#define MAX_UDP_SESS 1024
+#define MAX_FLOWS 64
+#define UDP_QMAX 32
+#define UDP_QBYTES (256 * 1024)
+#define UDP_MAXDG 65536
+#define DC_SIZE 1024
+#define SESS_BUCKETS 256
+#define DIRECT_ID 0xFFFFFFFFu
+
+static char TAG_STOP, TAG_WAKE, TAG_UDP, TAG_TIMER;
+
+// ---------------------------------------------------------------------------------------------
+// Utilities
+// ---------------------------------------------------------------------------------------------
+static int64_t now_ms(void)
+{
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+
+static void close_fd(int *fd)
+{
+ if (*fd >= 0) { close(*fd); *fd = -1; }
+}
+
+static void fmt_ip(int family, const uint8_t *addr16, char *out, size_t n)
+{
+ if (family == AF_INET) inet_ntop(AF_INET, addr16 + 12, out, (socklen_t)n);
+ else inet_ntop(AF_INET6, addr16, out, (socklen_t)n);
+}
+
+static void orig_str(const struct pb_orig *o, char *out, size_t n)
+{
+ char ip[INET6_ADDRSTRLEN];
+ fmt_ip(o->family, o->addr, ip, sizeof ip);
+ snprintf(out, n, "%s:%u", ip, o->port);
+}
+
+static socklen_t orig_to_sa(const struct pb_orig *o, struct sockaddr_storage *ss)
+{
+ memset(ss, 0, sizeof *ss);
+ if (o->family == AF_INET) {
+ struct sockaddr_in *a = (struct sockaddr_in *)ss;
+ a->sin_family = AF_INET;
+ a->sin_port = htons(o->port);
+ memcpy(&a->sin_addr, o->addr + 12, 4);
+ return sizeof *a;
+ }
+ struct sockaddr_in6 *a = (struct sockaddr_in6 *)ss;
+ a->sin6_family = AF_INET6;
+ a->sin6_port = htons(o->port);
+ memcpy(&a->sin6_addr, o->addr, 16);
+ return sizeof *a;
+}
+
+// Waits for fd readiness. 0 = ready (or error/hup: the next I/O call reports it), -1 = timeout, -2 = stop requested.
+static int wait_fd(int fd, short ev, int64_t deadline, int stopfd)
+{
+ for (;;) {
+ int64_t rem = deadline - now_ms();
+ if (rem <= 0) return -1;
+ struct pollfd p[2] = { { .fd = fd, .events = ev }, { .fd = stopfd, .events = POLLIN } };
+ int r = poll(p, stopfd >= 0 ? 2 : 1, rem > 60000 ? 60000 : (int)rem);
+ if (r < 0) { if (errno == EINTR) continue; return -1; }
+ if (r == 0) continue;
+ if (stopfd >= 0 && p[1].revents) return -2;
+ if (p[0].revents) return 0;
+ }
+}
+
+// Blocking-with-deadline I/O context for handshakes (fd is non-blocking).
+struct io {
+ int fd;
+ int64_t dl;
+ int stopfd;
+ char err[200];
+};
+
+static void seterr(struct io *x, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
+static void seterr(struct io *x, const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(x->err, sizeof x->err, fmt, ap);
+ va_end(ap);
+}
+
+static void io_waitfail(struct io *x, int w)
+{
+ seterr(x, w == -1 ? "timed out" : "relay stopping");
+}
+
+static int io_send(struct io *x, const void *buf, size_t n)
+{
+ const uint8_t *p = buf;
+ while (n) {
+ ssize_t r = send(x->fd, p, n, MSG_NOSIGNAL);
+ if (r > 0) { p += r; n -= (size_t)r; continue; }
+ if (r < 0 && errno == EINTR) continue;
+ if (r < 0 && errno == EAGAIN) {
+ int w = wait_fd(x->fd, POLLOUT, x->dl, x->stopfd);
+ if (w) { io_waitfail(x, w); return -1; }
+ continue;
+ }
+ seterr(x, "send failed: %s", strerror(errno));
+ return -1;
+ }
+ return 0;
+}
+
+// Receives 1..n bytes.
+static ssize_t io_recv(struct io *x, void *buf, size_t n)
+{
+ for (;;) {
+ ssize_t r = recv(x->fd, buf, n, 0);
+ if (r > 0) return r;
+ if (r == 0) { seterr(x, "connection closed by peer during handshake"); return -1; }
+ if (errno == EINTR) continue;
+ if (errno == EAGAIN) {
+ int w = wait_fd(x->fd, POLLIN, x->dl, x->stopfd);
+ if (w) { io_waitfail(x, w); return -1; }
+ continue;
+ }
+ seterr(x, "recv failed: %s", strerror(errno));
+ return -1;
+ }
+}
+
+static int io_recv_exact(struct io *x, void *buf, size_t n)
+{
+ uint8_t *p = buf;
+ while (n) {
+ ssize_t r = io_recv(x, p, n);
+ if (r < 0) return -1;
+ p += r;
+ n -= (size_t)r;
+ }
+ return 0;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Connecting
+// ---------------------------------------------------------------------------------------------
+static void tune_sock(int fd)
+{
+ int one = 1, idle = 60, intvl = 15, cnt = 4;
+ setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one);
+ setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof one);
+ setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof idle);
+ setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof intvl);
+ setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof cnt);
+}
+
+static int connect_addr(const struct sockaddr *sa, socklen_t len, int64_t dl, int stopfd, int *eno)
+{
+ int fd = socket(sa->sa_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
+ if (fd < 0) { *eno = errno; return -1; }
+ tune_sock(fd);
+ if (connect(fd, sa, len) < 0) {
+ if (errno != EINPROGRESS) { *eno = errno; close(fd); return -1; }
+ int w = wait_fd(fd, POLLOUT, dl, stopfd);
+ if (w) { *eno = w == -1 ? ETIMEDOUT : ECANCELED; close(fd); return -1; }
+ int e = 0;
+ socklen_t el = sizeof e;
+ getsockopt(fd, SOL_SOCKET, SO_ERROR, &e, &el);
+ if (e) { *eno = e; close(fd); return -1; }
+ }
+ return fd;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Hostname resolution (IPv4): at most RES_MAX_THREADS short-lived detached lookups, deadline-bounded for the waiter,
+// results cached (fresh for 60 s; last good answer reused for up to 10 min when re-resolution fails).
+// ---------------------------------------------------------------------------------------------
+#define RES_MAX_THREADS 4
+#define RES_DEADLINE_MS 5000
+#define RES_TTL_MS 60000
+#define RES_STALE_MS 600000
+#define RES_CACHE_N 64
+
+struct resreq {
+ struct resreq *next;
+ char name[256];
+ int refs;
+ bool done;
+ int gai;
+ struct in_addr addr;
+ pthread_cond_t cv;
+};
+struct rescache { char name[256]; struct in_addr addr; int64_t when; bool used; };
+
+static pthread_mutex_t res_mu = PTHREAD_MUTEX_INITIALIZER;
+static struct resreq *res_inflight;
+static int res_threads;
+static struct rescache res_cache[RES_CACHE_N];
+
+static struct rescache *res_cache_find(const char *name) // res_mu held
+{
+ for (int i = 0; i < RES_CACHE_N; i++) if (res_cache[i].used && !strcmp(res_cache[i].name, name)) return &res_cache[i];
+ return NULL;
+}
+
+static void res_unref(struct resreq *r) // res_mu held
+{
+ if (--r->refs == 0) { pthread_cond_destroy(&r->cv); free(r); }
+}
+
+static void *res_thread(void *arg)
+{
+ struct resreq *r = arg;
+ struct addrinfo hints, *res = NULL;
+ memset(&hints, 0, sizeof hints);
+ hints.ai_family = AF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+ int gr = getaddrinfo(r->name, NULL, &hints, &res);
+ pthread_mutex_lock(&res_mu);
+ if (gr == 0 && res && res->ai_family == AF_INET) {
+ r->addr = ((struct sockaddr_in *)res->ai_addr)->sin_addr;
+ struct rescache *c = res_cache_find(r->name);
+ if (!c) { // reuse a free slot, else evict the oldest
+ c = &res_cache[0];
+ for (int i = 0; i < RES_CACHE_N; i++) {
+ if (!res_cache[i].used) { c = &res_cache[i]; break; }
+ if (res_cache[i].when < c->when) c = &res_cache[i];
+ }
+ }
+ snprintf(c->name, sizeof c->name, "%s", r->name);
+ c->addr = r->addr; c->when = now_ms(); c->used = true;
+ } else {
+ r->gai = gr ? gr : EAI_NONAME;
+ }
+ r->done = true;
+ for (struct resreq **pp = &res_inflight; *pp; pp = &(*pp)->next)
+ if (*pp == r) { *pp = r->next; break; }
+ res_threads--;
+ pthread_cond_broadcast(&r->cv);
+ res_unref(r);
+ pthread_mutex_unlock(&res_mu);
+ if (res) freeaddrinfo(res);
+ return NULL;
+}
+
+static int resolve_v4(const char *name, int64_t dl, int stopfd, struct in_addr *out, char *err, size_t errn)
+{
+ int64_t limit = now_ms() + RES_DEADLINE_MS;
+ if (dl > limit) dl = limit;
+ pthread_mutex_lock(&res_mu);
+ struct rescache *c = res_cache_find(name);
+ if (c && now_ms() - c->when < RES_TTL_MS) { *out = c->addr; pthread_mutex_unlock(&res_mu); return 0; }
+ struct resreq *r;
+ for (r = res_inflight; r; r = r->next) if (!strcmp(r->name, name)) break;
+ const char *why = NULL;
+ if (!r) {
+ if (res_threads >= RES_MAX_THREADS) {
+ why = "resolver busy";
+ } else {
+ r = calloc(1, sizeof *r);
+ pthread_condattr_t ca;
+ pthread_condattr_init(&ca);
+ pthread_condattr_setclock(&ca, CLOCK_MONOTONIC);
+ if (r) pthread_cond_init(&r->cv, &ca);
+ pthread_condattr_destroy(&ca);
+ pthread_t th;
+ pthread_attr_t at;
+ pthread_attr_init(&at);
+ pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
+ pthread_attr_setstacksize(&at, 256 * 1024);
+ if (r) {
+ snprintf(r->name, sizeof r->name, "%s", name);
+ r->refs = 2; // thread + this waiter
+ r->next = res_inflight; res_inflight = r;
+ res_threads++;
+ if (pthread_create(&th, &at, res_thread, r) != 0) {
+ res_inflight = r->next; res_threads--; r->refs = 1;
+ res_unref(r); r = NULL; why = "cannot start resolver thread";
+ }
+ } else why = "out of memory";
+ pthread_attr_destroy(&at);
+ }
+ } else {
+ r->refs++;
+ }
+ int rc = -1;
+ if (r) {
+ while (!r->done) {
+ int64_t rem = dl - now_ms();
+ if (rem <= 0) { why = "timed out"; break; }
+ struct pollfd sp = { .fd = stopfd, .events = POLLIN };
+ if (stopfd >= 0 && poll(&sp, 1, 0) > 0) { why = "relay stopping"; break; }
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ int64_t ms = rem < 50 ? rem : 50;
+ ts.tv_nsec += ms * 1000000;
+ ts.tv_sec += ts.tv_nsec / 1000000000; ts.tv_nsec %= 1000000000;
+ pthread_cond_timedwait(&r->cv, &res_mu, &ts);
+ }
+ if (r->done && !r->gai) { *out = r->addr; rc = 0; }
+ else if (r->done) { snprintf(err, errn, "cannot resolve '%s': %s", name, gai_strerror(r->gai)); why = NULL; }
+ res_unref(r);
+ }
+ if (rc != 0) {
+ c = res_cache_find(name); // the lookup may have refreshed it; else try a stale answer
+ if (c && now_ms() - c->when < RES_STALE_MS) { *out = c->addr; rc = 0; }
+ }
+ pthread_mutex_unlock(&res_mu);
+ if (rc != 0 && why) snprintf(err, errn, "cannot resolve '%s': %s", name, why);
+ return rc;
+}
+
+// Resolves and connects to the proxy; on failure writes a readable reason to err.
+static int connect_host(const char *host, uint16_t port, int64_t dl, int stopfd, char *err, size_t errn)
+{
+ struct sockaddr_storage ss[1];
+ socklen_t sl[1];
+ int n = 0;
+ struct in_addr a4;
+ struct in6_addr a6;
+ memset(ss, 0, sizeof ss);
+ if (inet_pton(AF_INET, host, &a4) == 1 || (inet_pton(AF_INET6, host, &a6) != 1 && resolve_v4(host, dl, stopfd, &a4, err, errn) == 0)) {
+ struct sockaddr_in *s = (struct sockaddr_in *)&ss[0];
+ s->sin_family = AF_INET; s->sin_port = htons(port); s->sin_addr = a4;
+ sl[0] = sizeof *s; n = 1;
+ } else if (inet_pton(AF_INET6, host, &a6) == 1) {
+ struct sockaddr_in6 *s = (struct sockaddr_in6 *)&ss[0];
+ s->sin6_family = AF_INET6; s->sin6_port = htons(port); s->sin6_addr = a6;
+ sl[0] = sizeof *s; n = 1;
+ } else {
+ return -1; // resolve_v4 filled err
+ }
+ int eno = ETIMEDOUT;
+ for (int i = 0; i < n; i++) {
+ int64_t rem = dl - now_ms();
+ int64_t d = (i + 1 < n && rem > 2) ? now_ms() + rem / 2 : dl;
+ int fd = connect_addr((struct sockaddr *)&ss[i], sl[i], d, stopfd, &eno);
+ if (fd >= 0) return fd;
+ if (eno == ECANCELED) break;
+ }
+ snprintf(err, errn, "connect to %s:%u failed: %s", host, port, strerror(eno));
+ return -1;
+}
+
+// ---------------------------------------------------------------------------------------------
+// SOCKS5 / HTTP CONNECT handshakes
+// ---------------------------------------------------------------------------------------------
+struct s5dst { uint8_t atyp; uint8_t addr[16]; char host[256]; uint16_t port; };
+struct s5bnd { uint8_t atyp; uint8_t addr[16]; uint16_t port; };
+
+static const char *socks5_rep_str(int rep)
+{
+ switch (rep) {
+ case 1: return "general SOCKS server failure";
+ case 2: return "connection not allowed by ruleset";
+ case 3: return "network unreachable";
+ case 4: return "host unreachable";
+ case 5: return "connection refused by target";
+ case 6: return "TTL expired";
+ case 7: return "command not supported";
+ case 8: return "address type not supported";
+ default: return "unknown error";
+ }
+}
+
+static void s5dst_from_orig(struct s5dst *d, const struct pb_orig *o)
+{
+ memset(d, 0, sizeof *d);
+ d->port = o->port;
+ if (o->family == AF_INET) { d->atyp = 1; memcpy(d->addr, o->addr + 12, 4); }
+ else { d->atyp = 4; memcpy(d->addr, o->addr, 16); }
+}
+
+// cmd: 1 = CONNECT, 3 = UDP ASSOCIATE
+static int socks5_request(struct io *x, const struct pb_proxy *p, uint8_t cmd, const struct s5dst *d, struct s5bnd *b)
+{
+ bool auth = p->user[0] != 0;
+ uint8_t g[4] = { 5, auth ? 2 : 1, 0, 2 };
+ if (io_send(x, g, auth ? 4 : 3)) return -1;
+ uint8_t r[2];
+ if (io_recv_exact(x, r, 2)) return -1;
+ if (r[0] != 5) { seterr(x, "not a SOCKS5 server (bad greeting reply 0x%02x)", r[0]); return -1; }
+ if (r[1] == 0xFF) { seterr(x, "SOCKS5 proxy rejected all auth methods (credentials required or not accepted)"); return -1; }
+ if (r[1] == 2) {
+ size_t ul = strlen(p->user), pl = strlen(p->pass);
+ if (!auth) { seterr(x, "SOCKS5 proxy requires username/password but none configured"); return -1; }
+ if (ul > 255 || pl > 255) { seterr(x, "SOCKS5 credentials too long"); return -1; }
+ uint8_t ab[3 + 255 + 255];
+ size_t o = 0;
+ ab[o++] = 1; ab[o++] = (uint8_t)ul; memcpy(ab + o, p->user, ul); o += ul;
+ ab[o++] = (uint8_t)pl; memcpy(ab + o, p->pass, pl); o += pl;
+ if (io_send(x, ab, o)) return -1;
+ if (io_recv_exact(x, r, 2)) return -1;
+ if (r[1] != 0) { seterr(x, "SOCKS5 authentication failed (wrong username or password)"); return -1; }
+ } else if (r[1] != 0) {
+ seterr(x, "SOCKS5 proxy selected unsupported auth method 0x%02x", r[1]);
+ return -1;
+ }
+ uint8_t rq[4 + 1 + 255 + 2];
+ size_t o = 0;
+ rq[o++] = 5; rq[o++] = cmd; rq[o++] = 0; rq[o++] = d->atyp;
+ if (d->atyp == 1) { memcpy(rq + o, d->addr, 4); o += 4; }
+ else if (d->atyp == 4) { memcpy(rq + o, d->addr, 16); o += 16; }
+ else {
+ size_t hl = strlen(d->host);
+ if (hl == 0 || hl > 255) { seterr(x, "invalid target host name"); return -1; }
+ rq[o++] = (uint8_t)hl; memcpy(rq + o, d->host, hl); o += hl;
+ }
+ rq[o++] = (uint8_t)(d->port >> 8); rq[o++] = (uint8_t)d->port;
+ if (io_send(x, rq, o)) return -1;
+ uint8_t h[4];
+ if (io_recv_exact(x, h, 4)) return -1;
+ if (h[0] != 5) { seterr(x, "bad SOCKS5 reply version 0x%02x", h[0]); return -1; }
+ if (h[1] != 0) { seterr(x, "SOCKS5 request failed: %s (code %u)", socks5_rep_str(h[1]), h[1]); return -1; }
+ struct s5bnd tmp;
+ if (!b) b = &tmp;
+ memset(b, 0, sizeof *b);
+ b->atyp = h[3];
+ size_t al;
+ if (h[3] == 1) al = 4;
+ else if (h[3] == 4) al = 16;
+ else if (h[3] == 3) {
+ uint8_t l;
+ if (io_recv_exact(x, &l, 1)) return -1;
+ uint8_t skip[256];
+ if (io_recv_exact(x, skip, l)) return -1;
+ al = 0;
+ } else { seterr(x, "SOCKS5 reply has unknown address type %u", h[3]); return -1; }
+ if (al && io_recv_exact(x, b->addr, al)) return -1;
+ uint8_t pt[2];
+ if (io_recv_exact(x, pt, 2)) return -1;
+ b->port = (uint16_t)(pt[0] << 8 | pt[1]);
+ return 0;
+}
+
+static void b64(const char *in, size_t n, char *out)
+{
+ static const char t[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+ size_t i, o = 0;
+ for (i = 0; i + 2 < n; i += 3) {
+ uint32_t v = (uint8_t)in[i] << 16 | (uint8_t)in[i + 1] << 8 | (uint8_t)in[i + 2];
+ out[o++] = t[v >> 18]; out[o++] = t[(v >> 12) & 63]; out[o++] = t[(v >> 6) & 63]; out[o++] = t[v & 63];
+ }
+ if (i < n) {
+ uint32_t v = (uint8_t)in[i] << 16 | (i + 1 < n ? (uint8_t)in[i + 1] << 8 : 0);
+ out[o++] = t[v >> 18]; out[o++] = t[(v >> 12) & 63];
+ out[o++] = i + 1 < n ? t[(v >> 6) & 63] : '=';
+ out[o++] = '=';
+ }
+ out[o] = 0;
+}
+
+// host: IP literal (v6 without brackets) or hostname. Bytes received after the response headers go to left/leftn.
+static int http_connect(struct io *x, const struct pb_proxy *p, const char *host, uint16_t port, uint8_t *left, size_t *leftn)
+{
+ char hp[300];
+ snprintf(hp, sizeof hp, strchr(host, ':') ? "[%s]:%u" : "%s:%u", host, port);
+ char req[1024 + 700];
+ int n = snprintf(req, sizeof req, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n", hp, hp);
+ if (p->user[0]) {
+ char cred[520], enc[720];
+ int cl = snprintf(cred, sizeof cred, "%s:%s", p->user, p->pass);
+ if (cl < 0 || cl >= (int)sizeof cred) { seterr(x, "HTTP proxy credentials too long"); return -1; }
+ b64(cred, (size_t)cl, enc);
+ n += snprintf(req + n, sizeof req - (size_t)n, "Proxy-Authorization: Basic %s\r\n", enc);
+ }
+ n += snprintf(req + n, sizeof req - (size_t)n, "\r\n");
+ if (io_send(x, req, (size_t)n)) return -1;
+
+ uint8_t buf[HDR_MAX];
+ size_t tot = 0, hend = 0;
+ while (!hend) {
+ if (tot >= sizeof buf) { seterr(x, "HTTP proxy response headers too large"); return -1; }
+ ssize_t r = io_recv(x, buf + tot, sizeof buf - tot);
+ if (r < 0) return -1;
+ size_t from = tot >= 3 ? tot - 3 : 0;
+ tot += (size_t)r;
+ for (size_t i = from; i + 4 <= tot; i++)
+ if (!memcmp(buf + i, "\r\n\r\n", 4)) { hend = i + 4; break; }
+ }
+ int code = 0;
+ if (hend >= 12 && !memcmp(buf, "HTTP/", 5)) {
+ const uint8_t *sp = memchr(buf, ' ', hend);
+ if (sp && sp + 4 <= buf + hend) code = (sp[1] - '0') * 100 + (sp[2] - '0') * 10 + (sp[3] - '0');
+ }
+ if (code < 200 || code > 299) {
+ if (code == 0) seterr(x, "invalid HTTP proxy response");
+ else if (code == 407) seterr(x, "HTTP proxy authentication required (407): check username/password");
+ else if (code == 403) seterr(x, "HTTP proxy forbids this connection (403)");
+ else if (code >= 500) seterr(x, "HTTP proxy or upstream error (%d)", code);
+ else seterr(x, "HTTP proxy refused CONNECT (%d)", code);
+ return -1;
+ }
+ *leftn = tot - hend;
+ if (*leftn) memcpy(left, buf + hend, *leftn);
+ return 0;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Relay state
+// ---------------------------------------------------------------------------------------------
+struct conn {
+ struct conn *prev, *next;
+ int fd[2]; // 0 = client, 1 = upstream
+ size_t off[2], len[2]; // pend[d]: unsent tail of bytes read from fd[d] (heap, freed once drained)
+ uint8_t *pend[2];
+ bool dns; // original destination port 53: upstream->client is parsed as TCP-DNS
+ bool doff; // stopped observing (malformed stream)
+ uint8_t *dbuf; // bytes of the current, not yet complete, DNS message(s)
+ size_t dhave, dcap;
+ uint32_t mask[2];
+ bool eof[2], shut[2], dead;
+ int64_t last;
+};
+
+static void conn_bufs_free(struct conn *c)
+{
+ free(c->pend[0]); free(c->pend[1]); free(c->dbuf);
+ c->pend[0] = c->pend[1] = c->dbuf = NULL;
+}
+
+struct dthread {
+ pthread_t th;
+ bool started;
+ int ep, wake;
+ pthread_mutex_t mu;
+ struct conn *inq_head, *inq_tail;
+ struct conn *conns; // owned by thread
+ struct conn *grave;
+ uint8_t *scratch;
+ int pfd[2]; // reusable splice pipe; always empty between connections
+ bool nosplice;
+ atomic_int load;
+};
+
+enum { J_TCP = 1, J_UDP };
+struct sess;
+struct job {
+ struct job *next;
+ int kind;
+ int fd;
+ struct pb_orig o;
+ struct sess *s;
+};
+
+struct flowent { uint8_t addr[16]; uint16_t port; uint32_t ip_be; int64_t last; };
+struct pkt { size_t len; uint8_t d[]; };
+
+enum { SK_DIRECT = 1, SK_SOCKS5, SK_DROP };
+enum { ST_SETUP = 1, ST_READY, ST_FAILED };
+struct ref { struct sess *s; int which; };
+
+struct sess {
+ struct sess *hnext, *prev, *next, *dnext;
+ struct sockaddr_in cli;
+ uint32_t id, flow_be; // id = proxy id or DIRECT_ID; flow_be only for DIRECT sessions
+ int kind, state;
+ int up_fd, ctl_fd;
+ int family; // DIRECT: family of original destination
+ bool connected; // DIRECT: v6 sockets are connected; v4 are not (replies from any port of the host are accepted)
+ struct sockaddr_storage dst; // DIRECT destination
+ socklen_t dstlen;
+ uint16_t dport; // DIRECT: original destination port (53 => DNS tap)
+ bool dead, ok, warned;
+ int64_t last, fail_until;
+ struct pb_proxy proxy;
+ char err[700];
+ struct ref ref[2];
+ int nflows;
+ struct flowent flows[MAX_FLOWS];
+ struct pkt *q[UDP_QMAX];
+ int nq;
+ size_t qbytes;
+};
+
+struct dce { // per-(client, flow ip) decision cache
+ bool used;
+ struct sockaddr_in cli;
+ uint32_t flow_be;
+ uint8_t addr[16];
+ uint16_t port;
+ int action;
+ int64_t last;
+};
+
+static struct {
+ pthread_mutex_t life;
+ bool running;
+ struct pb_relay_cfg cfg;
+ int lfd, ufd, stopfd, tmfd, uep, uwake;
+ atomic_bool stopping;
+ atomic_int nconn;
+ atomic_uint rr;
+ uint16_t tcp_port, udp_port;
+
+ pthread_t acceptor; bool acc_started;
+ pthread_t workers[NWORKERS]; int nworkers;
+ struct dthread data[MAX_DATA];
+ int ndata;
+ pthread_t udpth; bool udp_started;
+
+ pthread_mutex_t jmu;
+ pthread_cond_t jcv;
+ struct job *jhead, *jtail;
+ int jcount;
+
+ pthread_mutex_t dmu; // UDP setup completion queue
+ struct sess *done;
+
+ // UDP thread-confined state
+ struct sess *sess_head;
+ struct sess *buckets[SESS_BUCKETS];
+ int nsess;
+ struct sess *sgrave;
+ struct dce *dc;
+ uint8_t *rxbuf, *txbuf;
+ int64_t drop_count, drop_logged;
+} R = { .life = PTHREAD_MUTEX_INITIALIZER, .jmu = PTHREAD_MUTEX_INITIALIZER, .jcv = PTHREAD_COND_INITIALIZER,
+ .dmu = PTHREAD_MUTEX_INITIALIZER, .lfd = -1, .ufd = -1, .stopfd = -1, .tmfd = -1, .uep = -1, .uwake = -1 };
+
+static void proxy_desc(const struct pb_proxy *p, char *out, size_t n)
+{
+ snprintf(out, n, "%s %s:%u", p->type == PROXY_TYPE_SOCKS5 ? "SOCKS5" : "HTTP", p->host, p->port);
+}
+
+// ---------------------------------------------------------------------------------------------
+// Job queue / worker pool
+// ---------------------------------------------------------------------------------------------
+static int job_push(int kind, int fd, const struct pb_orig *o, struct sess *s)
+{
+ struct job *j = calloc(1, sizeof *j);
+ if (!j) return -1;
+ j->kind = kind; j->fd = fd; j->s = s;
+ if (o) j->o = *o;
+ pthread_mutex_lock(&R.jmu);
+ if (R.jcount >= JOBQ_MAX || atomic_load(&R.stopping)) {
+ pthread_mutex_unlock(&R.jmu);
+ free(j);
+ return -1;
+ }
+ if (R.jtail) R.jtail->next = j; else R.jhead = j;
+ R.jtail = j;
+ R.jcount++;
+ pthread_cond_signal(&R.jcv);
+ pthread_mutex_unlock(&R.jmu);
+ return 0;
+}
+
+static void conn_handoff(int cfd, int ufd, const uint8_t *left, size_t leftn, bool dns)
+{
+ struct conn *c = calloc(1, sizeof *c);
+ if (!c) { close(cfd); close(ufd); atomic_fetch_sub(&R.nconn, 1); return; }
+ c->fd[0] = cfd; c->fd[1] = ufd;
+ c->dns = dns;
+ if (leftn) {
+ uint8_t *m = malloc(leftn);
+ if (!m) { close(cfd); close(ufd); free(c); atomic_fetch_sub(&R.nconn, 1); return; }
+ memcpy(m, left, leftn);
+ if (dns) { c->dbuf = m; c->dhave = c->dcap = leftn; } // must pass through the DNS parser
+ else { c->pend[1] = m; c->len[1] = leftn; }
+ }
+ unsigned start = atomic_fetch_add(&R.rr, 1);
+ struct dthread *t = &R.data[start % R.ndata];
+ for (int i = 1; i < R.ndata; i++) { // least-loaded, ties go to the round-robin choice
+ struct dthread *u = &R.data[(start + i) % R.ndata];
+ if (atomic_load(&u->load) < atomic_load(&t->load)) t = u;
+ }
+ atomic_fetch_add(&t->load, 1);
+ pthread_mutex_lock(&t->mu);
+ if (atomic_load(&R.stopping)) {
+ pthread_mutex_unlock(&t->mu);
+ atomic_fetch_sub(&t->load, 1);
+ close(cfd); close(ufd); conn_bufs_free(c); free(c);
+ atomic_fetch_sub(&R.nconn, 1);
+ return;
+ }
+ if (t->inq_tail) t->inq_tail->next = c; else t->inq_head = c;
+ t->inq_tail = c;
+ pthread_mutex_unlock(&t->mu);
+ eventfd_write(t->wake, 1);
+}
+
+static void abort_close(int fd)
+{
+ struct linger l = { 1, 0 };
+ setsockopt(fd, SOL_SOCKET, SO_LINGER, &l, sizeof l);
+ close(fd);
+}
+
+static void tcp_job_run(struct job *j)
+{
+ struct pb_orig *o = &j->o;
+ int cfd = j->fd, up = -1, action = o->action;
+ uint32_t pid = o->proxy_id;
+ int64_t dl = now_ms() + (int64_t)R.cfg.handshake_timeout_s * 1000;
+ char dst[80], err[1024] = "", desc[300];
+ uint8_t left[HDR_MAX];
+ size_t leftn = 0;
+ orig_str(o, dst, sizeof dst);
+
+ if (action == PB_ACT_DECIDE) {
+ struct pb_decision d;
+ pb_core_decide(o, &d);
+ action = d.action; pid = d.proxy_id;
+ }
+ if (action == PB_ACT_DIRECT) {
+ pb_core_flow_event(o, PB_ACT_DIRECT, "DIRECT");
+ struct sockaddr_storage ss;
+ socklen_t sl = orig_to_sa(o, &ss);
+ int eno = 0;
+ up = connect_addr((struct sockaddr *)&ss, sl, dl, R.stopfd, &eno);
+ if (up < 0) snprintf(err, sizeof err, "direct connect to %s failed: %s", dst, strerror(eno));
+ } else if (action == PB_ACT_PROXY) {
+ struct pb_proxy px;
+ if (pb_core_get_proxy(pid, &px) != 0) {
+ pb_core_flow_event(o, PB_ACT_PROXY, "unknown proxy");
+ snprintf(err, sizeof err, "no proxy configured (id %u) for %s", pid, dst);
+ } else {
+ proxy_desc(&px, desc, sizeof desc);
+ pb_core_flow_event(o, PB_ACT_PROXY, desc);
+ char cerr[200];
+ up = connect_host(px.host, px.port, dl, R.stopfd, cerr, sizeof cerr);
+ if (up < 0) {
+ snprintf(err, sizeof err, "proxy %s: %s", desc, cerr);
+ } else {
+ struct io x = { .fd = up, .dl = dl, .stopfd = R.stopfd };
+ int rc;
+ if (px.type == PROXY_TYPE_SOCKS5) {
+ struct s5dst d;
+ s5dst_from_orig(&d, o);
+ rc = socks5_request(&x, &px, 1, &d, NULL);
+ } else {
+ char ip[INET6_ADDRSTRLEN];
+ fmt_ip(o->family, o->addr, ip, sizeof ip);
+ rc = http_connect(&x, &px, ip, o->port, left, &leftn);
+ }
+ if (rc) {
+ snprintf(err, sizeof err, "proxy %s -> %s: %s", desc, dst, x.err);
+ close(up); up = -1;
+ }
+ }
+ }
+ } else {
+ pb_core_flow_event(o, PB_ACT_BLOCK, "BLOCK");
+ abort_close(cfd);
+ atomic_fetch_sub(&R.nconn, 1);
+ return;
+ }
+ if (up < 0) {
+ pb_core_log("relay: %s", err);
+ close(cfd);
+ atomic_fetch_sub(&R.nconn, 1);
+ return;
+ }
+ conn_handoff(cfd, up, left, leftn, o->port == 53);
+}
+
+static void udp_job_run(struct sess *s)
+{
+ int64_t dl = now_ms() + (int64_t)R.cfg.handshake_timeout_s * 1000;
+ char cerr[200], desc[300];
+ int ctl = -1, up = -1;
+ proxy_desc(&s->proxy, desc, sizeof desc);
+ s->ok = false;
+ ctl = connect_host(s->proxy.host, s->proxy.port, dl, R.stopfd, cerr, sizeof cerr);
+ if (ctl < 0) { snprintf(s->err, sizeof s->err, "%s: %s", desc, cerr); goto out; }
+ struct io x = { .fd = ctl, .dl = dl, .stopfd = R.stopfd };
+ struct s5dst d;
+ struct s5bnd b;
+ memset(&d, 0, sizeof d);
+ d.atyp = 1;
+ if (socks5_request(&x, &s->proxy, 3, &d, &b)) { snprintf(s->err, sizeof s->err, "%s UDP ASSOCIATE: %s", desc, x.err); goto out; }
+ if (b.atyp == 3) { snprintf(s->err, sizeof s->err, "%s: UDP relay address is a domain name (unsupported)", desc); goto out; }
+ struct sockaddr_storage ra;
+ socklen_t rl;
+ memset(&ra, 0, sizeof ra);
+ static const uint8_t zero[16];
+ bool unspec = !memcmp(b.addr, zero, b.atyp == 1 ? 4 : 16);
+ if (unspec) { // use the address we reached the proxy at
+ rl = sizeof ra;
+ if (getpeername(ctl, (struct sockaddr *)&ra, &rl) < 0) { snprintf(s->err, sizeof s->err, "%s: getpeername: %s", desc, strerror(errno)); goto out; }
+ if (ra.ss_family == AF_INET) ((struct sockaddr_in *)&ra)->sin_port = htons(b.port);
+ else ((struct sockaddr_in6 *)&ra)->sin6_port = htons(b.port);
+ } else if (b.atyp == 1) {
+ struct sockaddr_in *a = (struct sockaddr_in *)&ra;
+ a->sin_family = AF_INET; a->sin_port = htons(b.port); memcpy(&a->sin_addr, b.addr, 4);
+ rl = sizeof *a;
+ } else {
+ struct sockaddr_in6 *a = (struct sockaddr_in6 *)&ra;
+ a->sin6_family = AF_INET6; a->sin6_port = htons(b.port); memcpy(&a->sin6_addr, b.addr, 16);
+ rl = sizeof *a;
+ }
+ up = socket(ra.ss_family, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
+ if (up < 0 || connect(up, (struct sockaddr *)&ra, rl) < 0) {
+ snprintf(s->err, sizeof s->err, "%s: UDP relay socket: %s", desc, strerror(errno));
+ goto out;
+ }
+ s->ctl_fd = ctl; s->up_fd = up; s->ok = true;
+ ctl = up = -1;
+out:
+ close_fd(&ctl);
+ close_fd(&up);
+ pthread_mutex_lock(&R.dmu);
+ s->dnext = R.done;
+ R.done = s;
+ pthread_mutex_unlock(&R.dmu);
+ eventfd_write(R.uwake, 1);
+}
+
+static void *worker_main(void *arg)
+{
+ (void)arg;
+ for (;;) {
+ pthread_mutex_lock(&R.jmu);
+ while (!R.jhead && !atomic_load(&R.stopping)) pthread_cond_wait(&R.jcv, &R.jmu);
+ if (atomic_load(&R.stopping)) { pthread_mutex_unlock(&R.jmu); return NULL; }
+ struct job *j = R.jhead;
+ R.jhead = j->next;
+ if (!R.jhead) R.jtail = NULL;
+ R.jcount--;
+ pthread_mutex_unlock(&R.jmu);
+ if (j->kind == J_TCP) tcp_job_run(j); else udp_job_run(j->s);
+ free(j);
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Acceptor
+// ---------------------------------------------------------------------------------------------
+static void *acceptor_main(void *arg)
+{
+ (void)arg;
+ int64_t last_cap_log = 0;
+ while (!atomic_load(&R.stopping)) {
+ struct pollfd p[2] = { { .fd = R.lfd, .events = POLLIN }, { .fd = R.stopfd, .events = POLLIN } };
+ if (poll(p, 2, -1) < 0) { if (errno == EINTR) continue; break; }
+ if (p[1].revents) break;
+ for (int i = 0; i < 256; i++) {
+ struct sockaddr_in pa;
+ socklen_t pl = sizeof pa;
+ int fd = accept4(R.lfd, (struct sockaddr *)&pa, &pl, SOCK_NONBLOCK | SOCK_CLOEXEC);
+ if (fd < 0) {
+ if (errno == EMFILE || errno == ENFILE || errno == ENOBUFS || errno == ENOMEM) {
+ pb_core_log("relay: accept: %s, backing off", strerror(errno));
+ struct pollfd s = { .fd = R.stopfd, .events = POLLIN };
+ poll(&s, 1, 200);
+ }
+ break; // EAGAIN or error: back to poll
+ }
+ struct pb_orig o;
+ if (pb_core_take_tcp_orig(ntohs(pa.sin_port), &o) != 0) {
+ pb_core_log("relay: no original destination for client port %u, closing", ntohs(pa.sin_port));
+ close(fd);
+ continue;
+ }
+ tune_sock(fd);
+ if (atomic_fetch_add(&R.nconn, 1) >= R.cfg.max_tcp_conns) {
+ atomic_fetch_sub(&R.nconn, 1);
+ int64_t t = now_ms();
+ if (t - last_cap_log > 5000) { last_cap_log = t; pb_core_log("relay: connection limit (%d) reached, dropping new connections", R.cfg.max_tcp_conns); }
+ close(fd);
+ continue;
+ }
+ if (job_push(J_TCP, fd, &o, NULL) != 0) {
+ atomic_fetch_sub(&R.nconn, 1);
+ close(fd);
+ int64_t t = now_ms();
+ if (t - last_cap_log > 5000) { last_cap_log = t; pb_core_log("relay: handshake queue full (%d), shedding new connections", JOBQ_MAX); }
+ }
+ }
+ }
+ return NULL;
+}
+
+// ---------------------------------------------------------------------------------------------
+// TCP data threads
+// ---------------------------------------------------------------------------------------------
+static void pipe_discard(int fd)
+{
+ char b[4096];
+ while (read(fd, b, sizeof b) > 0) {}
+}
+
+// Reads `n` bytes the pipe holds into a fresh heap tail for direction d.
+static int spill_from_pipe(struct conn *c, int d, int pipe_rd, size_t n)
+{
+ c->pend[d] = malloc(n);
+ if (!c->pend[d]) { pipe_discard(pipe_rd); return -1; }
+ size_t got = 0;
+ while (got < n) {
+ ssize_t r = read(pipe_rd, c->pend[d] + got, n - got);
+ if (r <= 0) { if (r < 0 && errno == EINTR) continue; break; }
+ got += (size_t)r;
+ }
+ pipe_discard(pipe_rd);
+ c->off[d] = 0;
+ c->len[d] = got;
+ if (!got) { free(c->pend[d]); c->pend[d] = NULL; return -1; }
+ return 0;
+}
+
+// Zero-copy forward of one chunk in direction d via the thread's pipe. Returns 1 progress, 0 nothing to do (EAGAIN),
+// -1 fatal, -2 splice unsupported (use the copy path), 2 EOF.
+static int pump_splice(struct dthread *t, struct conn *c, int d)
+{
+ int o = 1 - d;
+ ssize_t n = splice(c->fd[d], NULL, t->pfd[1], NULL, PIPE_SZ, SPLICE_F_NONBLOCK | SPLICE_F_MOVE);
+ if (n == 0) return 2;
+ if (n < 0) {
+ if (errno == EAGAIN || errno == EINTR) return 0;
+ if (errno == EINVAL || errno == ENOSYS) return -2;
+ return -1;
+ }
+ ssize_t w = splice(t->pfd[0], NULL, c->fd[o], NULL, (size_t)n, SPLICE_F_NONBLOCK | SPLICE_F_MOVE);
+ if (w < 0) {
+ if (errno != EAGAIN && errno != EINTR) { pipe_discard(t->pfd[0]); return -1; }
+ w = 0;
+ }
+ if (w < n && spill_from_pipe(c, d, t->pfd[0], (size_t)(n - w)) != 0) return -1;
+ return 1;
+}
+
+// Upstream->client for TCP-DNS: only whole messages (after pb_core_dns_observe returned) are forwarded.
+// Returns 1 progress, 0 none, -1 fatal.
+static int dns_pump_up(struct conn *c, uint8_t *scratch)
+{
+ int progress = 0;
+ ssize_t n = recv(c->fd[1], scratch, SCRATCH_SZ, 0);
+ if (n < 0 && errno != EAGAIN && errno != EINTR) return -1;
+ if (n > 0) {
+ if (c->dhave + (size_t)n > c->dcap) {
+ size_t nc = c->dhave + (size_t)n;
+ uint8_t *nb = realloc(c->dbuf, nc);
+ if (!nb) return -1;
+ c->dbuf = nb; c->dcap = nc;
+ }
+ memcpy(c->dbuf + c->dhave, scratch, (size_t)n);
+ c->dhave += (size_t)n;
+ progress = 1;
+ } else if (n == 0) {
+ c->eof[1] = true;
+ progress = 1;
+ }
+ size_t fwd = 0;
+ if (c->doff) {
+ fwd = c->dhave;
+ } else {
+ while (c->dhave - fwd >= 2) {
+ size_t L = (size_t)(c->dbuf[fwd] << 8 | c->dbuf[fwd + 1]);
+ if (L == 0) { c->doff = true; fwd = c->dhave; break; } // malformed: relay raw from here on
+ if (c->dhave - fwd < 2 + L) break;
+ pb_core_dns_observe(c->dbuf + fwd + 2, L);
+ fwd += 2 + L;
+ }
+ if (c->eof[1]) fwd = c->dhave; // truncated trailing message: pass through unobserved
+ }
+ if (fwd) {
+ ssize_t w = send(c->fd[0], c->dbuf, fwd, MSG_NOSIGNAL);
+ if (w < 0) {
+ if (errno != EAGAIN && errno != EINTR) return -1;
+ w = 0;
+ }
+ if ((size_t)w < fwd) {
+ c->pend[1] = malloc(fwd - (size_t)w);
+ if (!c->pend[1]) return -1;
+ memcpy(c->pend[1], c->dbuf + w, fwd - (size_t)w);
+ c->off[1] = 0; c->len[1] = fwd - (size_t)w;
+ }
+ memmove(c->dbuf, c->dbuf + fwd, c->dhave - fwd);
+ c->dhave -= fwd;
+ progress = 1;
+ }
+ return progress;
+}
+
+static int conn_pump(struct dthread *t, struct conn *c)
+{
+ uint8_t *scratch = t->scratch;
+ for (int iter = 0; iter < 16; iter++) {
+ bool progress = false;
+ for (int d = 0; d < 2; d++) {
+ int o = 1 - d;
+ if (c->dns && d == 1 && c->len[1] == 0 && (!c->eof[1] || c->dhave)) {
+ int r = dns_pump_up(c, scratch);
+ if (r < 0) return -1;
+ if (r) progress = true;
+ } else if (c->len[d] == 0 && !c->eof[d]) {
+ int sp = -2;
+ if (!t->nosplice && !c->dns) {
+ sp = pump_splice(t, c, d);
+ if (sp == -1) return -1;
+ if (sp == -2) t->nosplice = true;
+ else if (sp == 2) { c->eof[d] = true; progress = true; }
+ else if (sp == 1) progress = true;
+ }
+ if (sp == -2) {
+ ssize_t n = recv(c->fd[d], scratch, SCRATCH_SZ, 0);
+ if (n > 0) {
+ progress = true;
+ ssize_t w = send(c->fd[o], scratch, (size_t)n, MSG_NOSIGNAL);
+ if (w < 0) {
+ if (errno != EAGAIN && errno != EINTR) return -1;
+ w = 0;
+ }
+ if (w < n) { // spill the unsent tail; no more reads in this direction until drained
+ c->pend[d] = malloc((size_t)(n - w));
+ if (!c->pend[d]) return -1;
+ memcpy(c->pend[d], scratch + w, (size_t)(n - w));
+ c->off[d] = 0;
+ c->len[d] = (size_t)(n - w);
+ }
+ }
+ else if (n == 0) { c->eof[d] = true; progress = true; }
+ else if (errno != EAGAIN && errno != EINTR) return -1;
+ }
+ } else if (c->len[d] > 0) {
+ ssize_t n = send(c->fd[o], c->pend[d] + c->off[d], c->len[d], MSG_NOSIGNAL);
+ if (n > 0) {
+ c->off[d] += (size_t)n; c->len[d] -= (size_t)n; progress = true;
+ if (!c->len[d]) { free(c->pend[d]); c->pend[d] = NULL; }
+ }
+ else if (errno != EAGAIN && errno != EINTR) return -1;
+ }
+ if (c->len[d] == 0 && c->eof[d] && !c->shut[d]) {
+ shutdown(c->fd[o], SHUT_WR);
+ c->shut[d] = true;
+ progress = true;
+ }
+ }
+ if (progress) c->last = now_ms();
+ if (c->shut[0] && c->shut[1]) return 1;
+ if (!progress) break;
+ }
+ return 0;
+}
+
+static int conn_update(struct dthread *t, struct conn *c)
+{
+ for (int i = 0; i < 2; i++) {
+ uint32_t want = 0;
+ if (!c->eof[i] && c->len[i] == 0) want |= EPOLLIN;
+ if (c->len[1 - i] > 0) want |= EPOLLOUT;
+ if (want == c->mask[i]) continue;
+ struct epoll_event ev = { .events = want, .data.ptr = c };
+ int rc;
+ if (!want) rc = epoll_ctl(t->ep, EPOLL_CTL_DEL, c->fd[i], NULL);
+ else rc = epoll_ctl(t->ep, c->mask[i] ? EPOLL_CTL_MOD : EPOLL_CTL_ADD, c->fd[i], &ev);
+ if (rc < 0) return -1;
+ c->mask[i] = want;
+ }
+ return 0;
+}
+
+static void conn_close(struct dthread *t, struct conn *c)
+{
+ close(c->fd[0]);
+ close(c->fd[1]);
+ c->dead = true;
+ conn_bufs_free(c);
+ c->pend[0] = c->pend[1] = NULL;
+ if (c->prev) c->prev->next = c->next; else t->conns = c->next;
+ if (c->next) c->next->prev = c->prev;
+ c->next = t->grave;
+ c->prev = NULL;
+ t->grave = c;
+ atomic_fetch_sub(&R.nconn, 1);
+ atomic_fetch_sub(&t->load, 1);
+}
+
+// Returns after pump + epoll mask refresh; closes the conn when done/failed.
+static void conn_service(struct dthread *t, struct conn *c)
+{
+ int r = conn_pump(t, c);
+ if (r == 0 && conn_update(t, c) != 0) r = -1;
+ if (r != 0) conn_close(t, c);
+}
+
+static void dthread_adopt(struct dthread *t)
+{
+ pthread_mutex_lock(&t->mu);
+ struct conn *c = t->inq_head;
+ t->inq_head = t->inq_tail = NULL;
+ pthread_mutex_unlock(&t->mu);
+ while (c) {
+ struct conn *n = c->next;
+ c->next = t->conns; c->prev = NULL;
+ if (t->conns) t->conns->prev = c;
+ t->conns = c;
+ c->last = now_ms();
+ conn_service(t, c);
+ c = n;
+ }
+}
+
+static void free_grave(struct dthread *t)
+{
+ while (t->grave) { struct conn *n = t->grave->next; free(t->grave); t->grave = n; }
+}
+
+static void *data_main(void *arg)
+{
+ struct dthread *t = arg;
+ struct epoll_event evs[64];
+ int64_t last_sweep = now_ms();
+ int64_t sweep_every = (int64_t)R.cfg.tcp_idle_timeout_s * 250; // idle/4, clamped to 1s..5s
+ if (sweep_every < 1000) sweep_every = 1000;
+ if (sweep_every > 5000) sweep_every = 5000;
+ while (!atomic_load(&R.stopping)) {
+ int n = epoll_wait(t->ep, evs, 64, 1000);
+ if (n < 0 && errno != EINTR) break;
+ for (int i = 0; i < n; i++) {
+ void *p = evs[i].data.ptr;
+ if (p == &TAG_STOP) goto done;
+ if (p == &TAG_WAKE) {
+ eventfd_t v;
+ eventfd_read(t->wake, &v);
+ dthread_adopt(t);
+ } else if (!((struct conn *)p)->dead) {
+ conn_service(t, p);
+ }
+ }
+ free_grave(t);
+ int64_t now = now_ms();
+ if (now - last_sweep >= sweep_every) {
+ last_sweep = now;
+ int64_t lim = (int64_t)R.cfg.tcp_idle_timeout_s * 1000;
+ for (struct conn *c = t->conns, *nx; c; c = nx) {
+ nx = c->next;
+ if (now - c->last > lim) conn_close(t, c);
+ }
+ free_grave(t);
+ }
+ }
+done:
+ return NULL;
+}
+
+// ---------------------------------------------------------------------------------------------
+// UDP
+// ---------------------------------------------------------------------------------------------
+static void udp_droplog(const char *why)
+{
+ R.drop_count++;
+ int64_t t = now_ms();
+ if (t - R.drop_logged > 5000) {
+ pb_core_log("relay: UDP datagram dropped (%s); %lld dropped so far", why, (long long)R.drop_count);
+ R.drop_logged = t;
+ }
+}
+
+static uint32_t sess_hash(const struct sockaddr_in *c, uint32_t id, uint32_t flow)
+{
+ uint32_t h = 2166136261u;
+ uint32_t v[4] = { c->sin_addr.s_addr, c->sin_port, id, flow };
+ for (int i = 0; i < 4; i++) { h ^= v[i]; h *= 16777619u; h ^= h >> 15; }
+ return h % SESS_BUCKETS;
+}
+
+static struct sess *sess_find(const struct sockaddr_in *c, uint32_t id, uint32_t flow)
+{
+ for (struct sess *s = R.buckets[sess_hash(c, id, flow)]; s; s = s->hnext)
+ if (s->cli.sin_addr.s_addr == c->sin_addr.s_addr && s->cli.sin_port == c->sin_port && s->id == id && s->flow_be == flow)
+ return s;
+ return NULL;
+}
+
+static void sess_free_queue(struct sess *s)
+{
+ for (int i = 0; i < s->nq; i++) free(s->q[i]);
+ s->nq = 0; s->qbytes = 0;
+}
+
+static void sess_destroy(struct sess *s)
+{
+ close_fd(&s->up_fd); // closing removes from epoll
+ close_fd(&s->ctl_fd);
+ sess_free_queue(s);
+ uint32_t h = sess_hash(&s->cli, s->id, s->flow_be);
+ for (struct sess **pp = &R.buckets[h]; *pp; pp = &(*pp)->hnext)
+ if (*pp == s) { *pp = s->hnext; break; }
+ if (s->prev) s->prev->next = s->next; else R.sess_head = s->next;
+ if (s->next) s->next->prev = s->prev;
+ s->dead = true;
+ s->next = R.sgrave;
+ R.sgrave = s;
+ R.nsess--;
+}
+
+static void sess_free_grave(void)
+{
+ while (R.sgrave) { struct sess *n = R.sgrave->next; free(R.sgrave); R.sgrave = n; }
+}
+
+static struct sess *sess_new(const struct sockaddr_in *cli, uint32_t id, uint32_t flow, int kind)
+{
+ if (R.nsess >= MAX_UDP_SESS) return NULL;
+ struct sess *s = calloc(1, sizeof *s);
+ if (!s) return NULL;
+ s->cli = *cli; s->id = id; s->flow_be = flow; s->kind = kind;
+ s->up_fd = s->ctl_fd = -1;
+ s->ref[0].s = s->ref[1].s = s;
+ s->ref[0].which = 0; s->ref[1].which = 1;
+ s->last = now_ms();
+ uint32_t h = sess_hash(cli, id, flow);
+ s->hnext = R.buckets[h]; R.buckets[h] = s;
+ s->next = R.sess_head;
+ if (R.sess_head) R.sess_head->prev = s;
+ R.sess_head = s;
+ R.nsess++;
+ return s;
+}
+
+static void udp_reply(const struct sockaddr_in *cli, uint32_t flow_be, const uint8_t *data, size_t n)
+{
+ struct iovec iov = { (void *)data, n };
+ union { char b[CMSG_SPACE(sizeof(struct in_pktinfo))]; struct cmsghdr a; } cb;
+ memset(&cb, 0, sizeof cb);
+ struct msghdr mh = { .msg_name = (void *)cli, .msg_namelen = sizeof *cli, .msg_iov = &iov, .msg_iovlen = 1,
+ .msg_control = cb.b, .msg_controllen = sizeof cb.b };
+ struct cmsghdr *cm = CMSG_FIRSTHDR(&mh);
+ cm->cmsg_level = IPPROTO_IP; cm->cmsg_type = IP_PKTINFO; cm->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
+ struct in_pktinfo pi;
+ memset(&pi, 0, sizeof pi);
+ pi.ipi_spec_dst.s_addr = flow_be;
+ memcpy(CMSG_DATA(cm), &pi, sizeof pi);
+ sendmsg(R.ufd, &mh, MSG_DONTWAIT | MSG_NOSIGNAL);
+}
+
+static int sess_arm(struct sess *s, int which, uint32_t events)
+{
+ int fd = which ? s->ctl_fd : s->up_fd;
+ struct epoll_event ev = { .events = events, .data.ptr = &s->ref[which] };
+ return epoll_ctl(R.uep, EPOLL_CTL_ADD, fd, &ev);
+}
+
+static void flow_upsert(struct sess *s, const struct pb_orig *o, uint32_t flow_be)
+{
+ int victim = 0;
+ for (int i = 0; i < s->nflows; i++) {
+ if (s->flows[i].port == o->port && !memcmp(s->flows[i].addr, o->addr, 16)) { victim = -1; s->flows[i].ip_be = flow_be; s->flows[i].last = s->last; break; }
+ if (s->flows[i].last < s->flows[victim].last) victim = i;
+ }
+ if (victim < 0) return;
+ if (s->nflows < MAX_FLOWS) victim = s->nflows++;
+ memcpy(s->flows[victim].addr, o->addr, 16);
+ s->flows[victim].port = o->port;
+ s->flows[victim].ip_be = flow_be;
+ s->flows[victim].last = s->last;
+}
+
+// Wraps the datagram with a SOCKS5 UDP header into R.txbuf; returns total length or 0.
+static size_t socks5_wrap(const struct pb_orig *o, const uint8_t *pl, size_t n)
+{
+ size_t h = o->family == AF_INET ? 10 : 22;
+ if (n + h > UDP_MAXDG) return 0;
+ uint8_t *b = R.txbuf;
+ b[0] = b[1] = b[2] = 0;
+ if (o->family == AF_INET) { b[3] = 1; memcpy(b + 4, o->addr + 12, 4); }
+ else { b[3] = 4; memcpy(b + 4, o->addr, 16); }
+ b[h - 2] = (uint8_t)(o->port >> 8); b[h - 1] = (uint8_t)o->port;
+ memcpy(b + h, pl, n);
+ return n + h;
+}
+
+static void udp_dgram(const struct sockaddr_in *cli, uint32_t flow_be, const uint8_t *pl, size_t n)
+{
+ struct pb_orig o;
+ if (pb_core_get_udp_flow(flow_be, &o) != 0) { udp_droplog("unknown flow address"); return; }
+ int64_t now = now_ms();
+ uint32_t hv = (cli->sin_addr.s_addr * 2654435761u) ^ (cli->sin_port * 40503u) ^ (flow_be * 2246822519u);
+ struct dce *e = &R.dc[hv % DC_SIZE];
+ uint32_t pid = o.proxy_id;
+ if (!(e->used && e->cli.sin_addr.s_addr == cli->sin_addr.s_addr && e->cli.sin_port == cli->sin_port && e->flow_be == flow_be &&
+ e->port == o.port && !memcmp(e->addr, o.addr, 16) && now - e->last <= (int64_t)R.cfg.udp_idle_timeout_s * 1000)) {
+ int act = o.action;
+ if (act == PB_ACT_DECIDE) {
+ struct pb_decision d;
+ pb_core_decide(&o, &d);
+ act = d.action; pid = d.proxy_id;
+ }
+ char desc[300] = "BLOCK";
+ if (act == PB_ACT_PROXY) {
+ struct pb_proxy px;
+ if (pb_core_get_proxy(pid, &px) != 0) {
+ pb_core_log("relay: UDP: no proxy configured (id %u), dropping", pid);
+ act = PB_ACT_BLOCK;
+ } else {
+ proxy_desc(&px, desc, sizeof desc);
+ if (px.type != PROXY_TYPE_SOCKS5) snprintf(desc + strlen(desc), sizeof desc - strlen(desc), " (UDP unsupported)");
+ }
+ } else if (act == PB_ACT_DIRECT) {
+ strcpy(desc, "DIRECT");
+ } else {
+ act = PB_ACT_BLOCK;
+ }
+ pb_core_flow_event(&o, act, desc);
+ e->used = true; e->cli = *cli; e->flow_be = flow_be; memcpy(e->addr, o.addr, 16); e->port = o.port; e->action = act;
+ }
+ e->last = now;
+ if (e->action == PB_ACT_BLOCK) return;
+
+ struct sess *s;
+ if (e->action == PB_ACT_DIRECT) {
+ s = sess_find(cli, DIRECT_ID, flow_be);
+ if (!s) {
+ struct sockaddr_storage ss;
+ socklen_t sl = orig_to_sa(&o, &ss);
+ s = sess_new(cli, DIRECT_ID, flow_be, SK_DIRECT);
+ if (!s) { udp_droplog("UDP session limit reached"); return; }
+ s->family = o.family;
+ s->dst = ss; s->dstlen = sl; s->dport = o.port;
+ s->connected = o.family != AF_INET;
+ s->up_fd = socket(ss.ss_family, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
+ if (s->up_fd < 0 || (s->connected && connect(s->up_fd, (struct sockaddr *)&ss, sl) < 0) || sess_arm(s, 0, EPOLLIN) < 0) {
+ pb_core_log("relay: UDP direct socket failed: %s", strerror(errno));
+ sess_destroy(s);
+ return;
+ }
+ s->state = ST_READY;
+ }
+ s->last = now;
+ if (s->connected) send(s->up_fd, pl, n, MSG_DONTWAIT | MSG_NOSIGNAL);
+ else sendto(s->up_fd, pl, n, MSG_DONTWAIT | MSG_NOSIGNAL, (struct sockaddr *)&s->dst, s->dstlen);
+ return;
+ }
+
+ // PROXY: re-resolve to get the canonical id and type
+ struct pb_proxy px;
+ if (pb_core_get_proxy(pid, &px) != 0) { udp_droplog("proxy vanished"); return; }
+ s = sess_find(cli, px.id, 0);
+ if (!s) {
+ s = sess_new(cli, px.id, 0, px.type == PROXY_TYPE_SOCKS5 ? SK_SOCKS5 : SK_DROP);
+ if (!s) { udp_droplog("UDP session limit reached"); return; }
+ s->proxy = px;
+ if (s->kind == SK_DROP) {
+ s->state = ST_READY;
+ } else {
+ s->state = ST_SETUP;
+ if (job_push(J_UDP, -1, NULL, s) != 0) { s->state = ST_FAILED; s->fail_until = now + 5000; udp_droplog("setup queue full"); }
+ }
+ }
+ s->last = now;
+ if (s->kind == SK_DROP) {
+ if (!s->warned) {
+ s->warned = true;
+ pb_core_log("relay: UDP cannot be proxied through HTTP proxy '%s'; dropping UDP from %s:%u", px.name,
+ inet_ntoa(cli->sin_addr), ntohs(cli->sin_port));
+ }
+ return;
+ }
+ if (s->state == ST_FAILED) { udp_droplog("proxy UDP setup failed"); return; }
+ flow_upsert(s, &o, flow_be);
+ size_t wl = socks5_wrap(&o, pl, n);
+ if (!wl) { udp_droplog("datagram too large"); return; }
+ if (s->state == ST_SETUP) {
+ if (s->nq >= UDP_QMAX || s->qbytes + wl > UDP_QBYTES) { udp_droplog("setup queue full"); return; }
+ struct pkt *p = malloc(sizeof *p + wl);
+ if (!p) return;
+ p->len = wl; memcpy(p->d, R.txbuf, wl);
+ s->q[s->nq++] = p; s->qbytes += wl;
+ return;
+ }
+ send(s->up_fd, R.txbuf, wl, MSG_DONTWAIT | MSG_NOSIGNAL);
+}
+
+static void udp_recv_client(void)
+{
+ for (int i = 0; i < 128; i++) {
+ struct sockaddr_in cli;
+ union { char b[CMSG_SPACE(sizeof(struct in_pktinfo))]; struct cmsghdr a; } cb;
+ struct iovec iov = { R.rxbuf, UDP_MAXDG };
+ struct msghdr mh = { .msg_name = &cli, .msg_namelen = sizeof cli, .msg_iov = &iov, .msg_iovlen = 1,
+ .msg_control = cb.b, .msg_controllen = sizeof cb.b };
+ ssize_t n = recvmsg(R.ufd, &mh, MSG_DONTWAIT);
+ if (n < 0) return;
+ if (mh.msg_flags & MSG_TRUNC) continue;
+ bool have = false;
+ struct in_pktinfo pi;
+ for (struct cmsghdr *c = CMSG_FIRSTHDR(&mh); c; c = CMSG_NXTHDR(&mh, c))
+ if (c->cmsg_level == IPPROTO_IP && c->cmsg_type == IP_PKTINFO) { memcpy(&pi, CMSG_DATA(c), sizeof pi); have = true; }
+ if (!have || (ntohl(pi.ipi_addr.s_addr) >> 24) != 127) { udp_droplog("destination not in 127.0.0.0/8"); continue; }
+ udp_dgram(&cli, pi.ipi_addr.s_addr, R.rxbuf, (size_t)n);
+ }
+}
+
+static void udp_recv_upstream(struct sess *s)
+{
+ for (int i = 0; i < 64 && !s->dead; i++) {
+ struct sockaddr_in from;
+ socklen_t fl = sizeof from;
+ ssize_t n = recvfrom(s->up_fd, R.rxbuf, UDP_MAXDG, MSG_DONTWAIT, (struct sockaddr *)&from, &fl);
+ if (n < 0) return; // includes ECONNREFUSED from ICMP: ignore
+ s->last = now_ms();
+ if (s->kind == SK_DIRECT) {
+ // unconnected v4 socket: accept replies from the destination host on any port (some servers answer from
+ // another port); anything from another host is dropped.
+ if (!s->connected && (fl < sizeof from || from.sin_addr.s_addr != ((struct sockaddr_in *)&s->dst)->sin_addr.s_addr)) {
+ udp_droplog("reply from unexpected host");
+ continue;
+ }
+ if (s->dport == 53) pb_core_dns_observe(R.rxbuf, (size_t)n);
+ udp_reply(&s->cli, s->flow_be, R.rxbuf, (size_t)n);
+ continue;
+ }
+ const uint8_t *b = R.rxbuf;
+ if (n < 10 || b[2] != 0) continue; // fragments unsupported
+ size_t h;
+ uint8_t addr[16] = { 0 };
+ bool known = true;
+ uint16_t port;
+ if (b[3] == 1) { h = 10; memset(addr + 10, 0xff, 2); memcpy(addr + 12, b + 4, 4); }
+ else if (b[3] == 4) { if (n < 22) continue; h = 22; memcpy(addr, b + 4, 16); }
+ else if (b[3] == 3) { h = 7 + (size_t)b[4]; if ((size_t)n < h) continue; known = false; }
+ else continue;
+ port = (uint16_t)(b[h - 2] << 8 | b[h - 1]);
+ // Source mapping: exact (ip,port) the client sent to; otherwise the same ip on another port is delivered from the
+ // flow address of the most recently used destination with that ip; any other source is dropped (and counted).
+ uint32_t flow = 0;
+ uint16_t fport = 0;
+ bool found = false;
+ if (known) {
+ int best = -1;
+ for (int k = 0; k < s->nflows; k++) {
+ if (memcmp(s->flows[k].addr, addr, 16)) continue;
+ if (s->flows[k].port == port) { best = k; break; }
+ if (best < 0 || s->flows[k].last > s->flows[best].last) best = k;
+ }
+ if (best >= 0) { flow = s->flows[best].ip_be; fport = s->flows[best].port; found = true; }
+ } else if (s->nflows == 1) {
+ flow = s->flows[0].ip_be; fport = s->flows[0].port; found = true;
+ }
+ if (!found) { udp_droplog("reply from unknown source"); continue; }
+ if (fport == 53) pb_core_dns_observe(b + h, (size_t)n - h);
+ udp_reply(&s->cli, flow, b + h, (size_t)n - h);
+ }
+}
+
+static void udp_setup_done(void)
+{
+ pthread_mutex_lock(&R.dmu);
+ struct sess *l = R.done;
+ R.done = NULL;
+ pthread_mutex_unlock(&R.dmu);
+ while (l) {
+ struct sess *s = l;
+ l = s->dnext;
+ if (s->ok && sess_arm(s, 0, EPOLLIN) == 0 && sess_arm(s, 1, EPOLLIN | EPOLLRDHUP) == 0) {
+ s->state = ST_READY;
+ s->last = now_ms();
+ for (int i = 0; i < s->nq; i++) send(s->up_fd, s->q[i]->d, s->q[i]->len, MSG_DONTWAIT | MSG_NOSIGNAL);
+ sess_free_queue(s);
+ } else {
+ if (s->ok) snprintf(s->err, sizeof s->err, "epoll_ctl: %s", strerror(errno));
+ pb_core_log("relay: UDP associate failed: %s", s->err);
+ close_fd(&s->up_fd);
+ close_fd(&s->ctl_fd);
+ sess_free_queue(s);
+ s->state = ST_FAILED;
+ s->fail_until = now_ms() + 5000;
+ }
+ }
+}
+
+static void udp_ctl_event(struct sess *s)
+{
+ char tmp[256];
+ for (;;) {
+ ssize_t n = recv(s->ctl_fd, tmp, sizeof tmp, MSG_DONTWAIT);
+ if (n > 0) continue;
+ if (n < 0 && errno == EAGAIN) return;
+ if (n < 0 && errno == EINTR) continue;
+ break;
+ }
+ pb_core_log("relay: SOCKS5 UDP control connection closed, dropping session for %s:%u", inet_ntoa(s->cli.sin_addr), ntohs(s->cli.sin_port));
+ sess_destroy(s);
+}
+
+static void udp_sweep(void)
+{
+ int64_t now = now_ms(), lim = (int64_t)R.cfg.udp_idle_timeout_s * 1000;
+ for (struct sess *s = R.sess_head, *n; s; s = n) {
+ n = s->next;
+ if (s->state == ST_SETUP) continue;
+ if (s->state == ST_FAILED ? now >= s->fail_until : now - s->last > lim) sess_destroy(s);
+ }
+}
+
+static void *udp_main(void *arg)
+{
+ (void)arg;
+ struct epoll_event evs[64];
+ while (!atomic_load(&R.stopping)) {
+ int n = epoll_wait(R.uep, evs, 64, 1000);
+ if (n < 0 && errno != EINTR) break;
+ for (int i = 0; i < n; i++) {
+ void *p = evs[i].data.ptr;
+ if (p == &TAG_STOP) return NULL;
+ if (p == &TAG_UDP) udp_recv_client();
+ else if (p == &TAG_WAKE) { eventfd_t v; eventfd_read(R.uwake, &v); udp_setup_done(); }
+ else if (p == &TAG_TIMER) { uint64_t v; if (read(R.tmfd, &v, sizeof v) > 0) udp_sweep(); }
+ else {
+ struct ref *r = p;
+ struct sess *s = r->s;
+ if (s->dead) continue;
+ if (r->which == 1) udp_ctl_event(s); else udp_recv_upstream(s);
+ }
+ }
+ sess_free_grave();
+ }
+ return NULL;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Start / stop
+// ---------------------------------------------------------------------------------------------
+static void teardown(void)
+{
+ atomic_store(&R.stopping, true);
+ if (R.stopfd >= 0) eventfd_write(R.stopfd, 1);
+ pthread_mutex_lock(&R.jmu);
+ pthread_cond_broadcast(&R.jcv);
+ pthread_mutex_unlock(&R.jmu);
+ if (R.acc_started) pthread_join(R.acceptor, NULL);
+ for (int i = 0; i < R.nworkers; i++) pthread_join(R.workers[i], NULL);
+ for (int i = 0; i < R.ndata; i++) if (R.data[i].started) pthread_join(R.data[i].th, NULL);
+ if (R.udp_started) pthread_join(R.udpth, NULL);
+ R.acc_started = R.udp_started = false;
+ R.nworkers = 0;
+
+ // everything is single-threaded from here on
+ while (R.jhead) {
+ struct job *j = R.jhead;
+ R.jhead = j->next;
+ if (j->kind == J_TCP) { close(j->fd); atomic_fetch_sub(&R.nconn, 1); }
+ free(j);
+ }
+ R.jtail = NULL; R.jcount = 0;
+ for (int i = 0; i < R.ndata; i++) {
+ struct dthread *t = &R.data[i];
+ for (struct conn *c = t->inq_head, *n; c; c = n) { n = c->next; close(c->fd[0]); close(c->fd[1]); conn_bufs_free(c); free(c); atomic_fetch_sub(&R.nconn, 1); }
+ t->inq_head = t->inq_tail = NULL;
+ for (struct conn *c = t->conns, *n; c; c = n) { n = c->next; close(c->fd[0]); close(c->fd[1]); conn_bufs_free(c); free(c); atomic_fetch_sub(&R.nconn, 1); }
+ t->conns = NULL;
+ free_grave(t);
+ free(t->scratch); t->scratch = NULL;
+ close_fd(&t->pfd[0]); close_fd(&t->pfd[1]);
+ t->started = false;
+ close_fd(&t->ep);
+ close_fd(&t->wake);
+ }
+ while (R.sess_head) sess_destroy(R.sess_head);
+ sess_free_grave();
+ memset(R.buckets, 0, sizeof R.buckets);
+ R.done = NULL;
+ R.nsess = 0;
+ free(R.dc); R.dc = NULL;
+ free(R.rxbuf); R.rxbuf = NULL;
+ free(R.txbuf); R.txbuf = NULL;
+ close_fd(&R.lfd);
+ close_fd(&R.ufd);
+ close_fd(&R.tmfd);
+ close_fd(&R.uep);
+ close_fd(&R.uwake);
+ close_fd(&R.stopfd);
+}
+
+static int add_ep(int ep, int fd, void *tag, uint32_t ev)
+{
+ struct epoll_event e = { .events = ev, .data.ptr = tag };
+ return epoll_ctl(ep, EPOLL_CTL_ADD, fd, &e);
+}
+
+int pb_relay_start(const struct pb_relay_cfg *cfg)
+{
+ pthread_mutex_lock(&R.life);
+ if (R.running) { pthread_mutex_unlock(&R.life); return 0; }
+ struct pb_relay_cfg c = { 0 };
+ if (cfg) c = *cfg;
+ if (!c.tcp_port) c.tcp_port = PB_TCP_RELAY_PORT_DEFAULT;
+ if (!c.udp_port) c.udp_port = PB_UDP_RELAY_PORT_DEFAULT;
+ if (c.max_tcp_conns <= 0) c.max_tcp_conns = 32768;
+ if (c.tcp_idle_timeout_s <= 0) c.tcp_idle_timeout_s = 300;
+ if (c.udp_idle_timeout_s <= 0) c.udp_idle_timeout_s = 60;
+ if (c.handshake_timeout_s <= 0) c.handshake_timeout_s = 10;
+ R.cfg = c;
+ atomic_store(&R.stopping, false);
+ atomic_store(&R.nconn, 0);
+ R.drop_count = 0; R.drop_logged = 0;
+ const char *why = "";
+ int one = 1;
+ long ncpu = sysconf(_SC_NPROCESSORS_ONLN);
+ R.ndata = ncpu < 2 ? 2 : (ncpu > MAX_DATA ? MAX_DATA : (int)ncpu);
+#ifdef PB_RELAY_NDATA // benchmarking override
+ R.ndata = PB_RELAY_NDATA;
+#endif
+ for (int i = 0; i < R.ndata; i++) {
+ memset(&R.data[i], 0, sizeof R.data[i]);
+ R.data[i].ep = R.data[i].wake = -1;
+ R.data[i].pfd[0] = R.data[i].pfd[1] = -1;
+ pthread_mutex_init(&R.data[i].mu, NULL);
+ }
+
+ R.stopfd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
+ R.uwake = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
+ if (R.stopfd < 0 || R.uwake < 0) { why = "eventfd"; goto fail; }
+
+ R.lfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
+ if (R.lfd < 0) { why = "tcp socket"; goto fail; }
+ setsockopt(R.lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(c.tcp_port), .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
+ if (bind(R.lfd, (struct sockaddr *)&a, sizeof a) < 0 || listen(R.lfd, 4096) < 0) {
+ pb_core_log("relay: cannot listen on 127.0.0.1:%u: %s", c.tcp_port, strerror(errno));
+ goto fail_quiet;
+ }
+
+ R.ufd = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
+ if (R.ufd < 0) { why = "udp socket"; goto fail; }
+ if (setsockopt(R.ufd, SOL_SOCKET, SO_BINDTODEVICE, "lo", 3) < 0)
+ pb_core_log("relay: SO_BINDTODEVICE lo failed (%s); relying on destination address filtering", strerror(errno));
+ int rb = 4 << 20;
+ setsockopt(R.ufd, SOL_SOCKET, SO_RCVBUF, &rb, sizeof rb);
+ if (setsockopt(R.ufd, IPPROTO_IP, IP_PKTINFO, &one, sizeof one) < 0) { why = "IP_PKTINFO"; goto fail; }
+ a.sin_port = htons(c.udp_port);
+ a.sin_addr.s_addr = htonl(INADDR_ANY);
+ if (bind(R.ufd, (struct sockaddr *)&a, sizeof a) < 0) {
+ pb_core_log("relay: cannot bind UDP port %u: %s", c.udp_port, strerror(errno));
+ goto fail_quiet;
+ }
+ R.tcp_port = c.tcp_port; R.udp_port = c.udp_port;
+
+ R.uep = epoll_create1(EPOLL_CLOEXEC);
+ R.tmfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
+ R.dc = calloc(DC_SIZE, sizeof *R.dc);
+ R.rxbuf = malloc(UDP_MAXDG);
+ R.txbuf = malloc(UDP_MAXDG + 32);
+ if (R.uep < 0 || R.tmfd < 0 || !R.dc || !R.rxbuf || !R.txbuf) { why = "udp resources"; goto fail; }
+ struct itimerspec its = { .it_interval = { 1, 0 }, .it_value = { 1, 0 } };
+ if (timerfd_settime(R.tmfd, 0, &its, NULL) < 0 ||
+ add_ep(R.uep, R.ufd, &TAG_UDP, EPOLLIN) || add_ep(R.uep, R.stopfd, &TAG_STOP, EPOLLIN) ||
+ add_ep(R.uep, R.uwake, &TAG_WAKE, EPOLLIN) || add_ep(R.uep, R.tmfd, &TAG_TIMER, EPOLLIN)) { why = "udp epoll"; goto fail; }
+
+ for (int i = 0; i < R.ndata; i++) {
+ struct dthread *t = &R.data[i];
+ t->scratch = malloc(SCRATCH_SZ);
+ if (pipe2(t->pfd, O_CLOEXEC | O_NONBLOCK) == 0) fcntl(t->pfd[0], F_SETPIPE_SZ, PIPE_SZ);
+ else t->pfd[0] = t->pfd[1] = -1, t->nosplice = true;
+#ifdef PB_RELAY_COPY_ONLY // benchmarking override
+ t->nosplice = true;
+#endif
+ t->ep = epoll_create1(EPOLL_CLOEXEC);
+ t->wake = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
+ if (!t->scratch || t->ep < 0 || t->wake < 0 || add_ep(t->ep, t->wake, &TAG_WAKE, EPOLLIN) || add_ep(t->ep, R.stopfd, &TAG_STOP, EPOLLIN)) {
+ why = "tcp epoll"; goto fail;
+ }
+ }
+ pthread_attr_t at;
+ pthread_attr_init(&at);
+ pthread_attr_setstacksize(&at, 512 * 1024);
+ bool ok = true;
+ for (int i = 0; i < R.ndata && ok; i++) {
+ ok = pthread_create(&R.data[i].th, &at, data_main, &R.data[i]) == 0;
+ R.data[i].started = ok;
+ }
+ for (int i = 0; i < NWORKERS && ok; i++) {
+ ok = pthread_create(&R.workers[i], &at, worker_main, NULL) == 0;
+ if (ok) R.nworkers++;
+ }
+ if (ok) { ok = pthread_create(&R.udpth, &at, udp_main, NULL) == 0; R.udp_started = ok; }
+ if (ok) { ok = pthread_create(&R.acceptor, &at, acceptor_main, NULL) == 0; R.acc_started = ok; }
+ pthread_attr_destroy(&at);
+ if (!ok) { why = "pthread_create"; goto fail; }
+ R.running = true;
+ pthread_mutex_unlock(&R.life);
+ return 0;
+
+fail:
+ pb_core_log("relay: start failed (%s): %s", why, strerror(errno));
+fail_quiet:
+ teardown();
+ pthread_mutex_unlock(&R.life);
+ return -1;
+}
+
+void pb_relay_stop(void)
+{
+ pthread_mutex_lock(&R.life);
+ if (R.running) {
+ teardown();
+ R.running = false;
+ }
+ pthread_mutex_unlock(&R.life);
+}
+
+uint16_t pb_relay_tcp_port(void) { return R.tcp_port; }
+uint16_t pb_relay_udp_port(void) { return R.udp_port; }
+
+// ---------------------------------------------------------------------------------------------
+// Synchronous proxy test
+// ---------------------------------------------------------------------------------------------
+int pb_relay_test_proxy(const struct pb_proxy *proxy, const char *host, uint16_t port, char *buf, size_t buflen)
+{
+ if (!buf || !buflen) return -1;
+ int64_t dl = now_ms() + 10000;
+ int fd = -1, rc = -1;
+ char err[256] = "";
+ uint8_t left[HDR_MAX];
+ size_t leftn = 0;
+ fd = connect_host(proxy->host, proxy->port, dl, -1, err, sizeof err);
+ if (fd < 0) { snprintf(buf, buflen, "Cannot reach proxy: %s", err); return -1; }
+ struct io x = { .fd = fd, .dl = dl, .stopfd = -1 };
+ if (proxy->type == PROXY_TYPE_SOCKS5) {
+ struct s5dst d;
+ memset(&d, 0, sizeof d);
+ d.port = port;
+ struct in_addr a4; struct in6_addr a6;
+ if (inet_pton(AF_INET, host, &a4) == 1) { d.atyp = 1; memcpy(d.addr, &a4, 4); }
+ else if (inet_pton(AF_INET6, host, &a6) == 1) { d.atyp = 4; memcpy(d.addr, &a6, 16); }
+ else { d.atyp = 3; snprintf(d.host, sizeof d.host, "%s", host); }
+ rc = socks5_request(&x, proxy, 1, &d, NULL);
+ } else {
+ rc = http_connect(&x, proxy, host, port, left, &leftn);
+ }
+ if (rc) { snprintf(buf, buflen, "%s", x.err); close(fd); return -1; }
+ if (port != 80) {
+ snprintf(buf, buflen, "Tunnel established");
+ close(fd);
+ return 0;
+ }
+ char req[600];
+ int n = snprintf(req, sizeof req, "HEAD / HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", host);
+ char resp[1024];
+ size_t got = 0;
+ if (io_send(&x, req, (size_t)n)) { snprintf(buf, buflen, "%s", x.err); close(fd); return -1; }
+ if (leftn) { got = leftn < sizeof resp ? leftn : sizeof resp - 1; memcpy(resp, left, got); }
+ while (!memchr(resp, '\n', got) && got < sizeof resp - 1) {
+ ssize_t r = io_recv(&x, resp + got, sizeof resp - 1 - got);
+ if (r < 0) break;
+ got += (size_t)r;
+ }
+ close(fd);
+ resp[got] = 0;
+ char *nl = strpbrk(resp, "\r\n");
+ if (nl) *nl = 0;
+ if (!resp[0]) { snprintf(buf, buflen, "No response through proxy: %s", x.err); return -1; }
+ snprintf(buf, buflen, "%s", resp);
+ return 0;
+}
diff --git a/Linux/src/pb_rules.c b/Linux/src/pb_rules.c
new file mode 100644
index 0000000..e6a4bdf
--- /dev/null
+++ b/Linux/src/pb_rules.c
@@ -0,0 +1,446 @@
+#include <arpa/inet.h>
+#include <ctype.h>
+#include <errno.h>
+#include <stdarg.h>
+#include <netinet/in.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "pb_rules.h"
+
+static void set_err(char *err, size_t n, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
+static void set_err(char *err, size_t n, const char *fmt, ...)
+{
+ if (!err || !n) return;
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(err, n, fmt, ap);
+ va_end(ap);
+}
+
+// ---- tokenising ------------------------------------------------------------------------------------------------------
+
+// Splits on ';' or ',' and trims whitespace. Returns the number of tokens (<= max) or -1 if there are more than max.
+static int split_list(const char *s, char tokens[][256], int max)
+{
+ int n = 0;
+ while (*s) {
+ while (*s == ';' || *s == ',' || isspace((unsigned char)*s)) s++;
+ if (!*s) break;
+ const char *e = s;
+ while (*e && *e != ';' && *e != ',') e++;
+ const char *t = e;
+ while (t > s && isspace((unsigned char)t[-1])) t--;
+ if (n >= max) return -1;
+ size_t len = (size_t)(t - s);
+ if (len >= 256) len = 255;
+ memcpy(tokens[n], s, len);
+ tokens[n][len] = 0;
+ n++;
+ s = e;
+ }
+ return n;
+}
+
+// ---- glob ------------------------------------------------------------------------------------------------------------
+
+bool pb_glob_match(const char *p, const char *s)
+{
+ const char *star = NULL, *ss = s;
+ while (*s) {
+ if (*p == '*') { star = p++; ss = s; }
+ else if (*p == '?' || *p == *s) { p++; s++; }
+ else if (star) { p = star + 1; s = ++ss; }
+ else return false;
+ }
+ while (*p == '*') p++;
+ return *p == 0;
+}
+
+// ---- parsing helpers -------------------------------------------------------------------------------------------------
+
+static bool parse_uint(const char *s, size_t len, unsigned max, unsigned *out)
+{
+ if (!len || len > 5) return false;
+ unsigned v = 0;
+ for (size_t i = 0; i < len; i++) {
+ if (!isdigit((unsigned char)s[i])) return false;
+ v = v * 10 + (unsigned)(s[i] - '0');
+ }
+ if (v > max) return false;
+ *out = v;
+ return true;
+}
+
+static bool parse_ipv4(const char *s, uint32_t *out)
+{
+ struct in_addr a;
+ // inet_pton rejects leading garbage / short forms, which is what we want for validation
+ if (inet_pton(AF_INET, s, &a) != 1) return false;
+ *out = ntohl(a.s_addr);
+ return true;
+}
+
+// "10", "*", "1-5" -> inclusive octet range
+static bool parse_octet(const char *s, size_t len, uint8_t *lo, uint8_t *hi)
+{
+ unsigned a, b;
+ if (len == 1 && s[0] == '*') { *lo = 0; *hi = 255; return true; }
+ const char *dash = memchr(s, '-', len);
+ if (dash) {
+ if (!parse_uint(s, (size_t)(dash - s), 255, &a) || !parse_uint(dash + 1, len - (size_t)(dash - s) - 1, 255, &b) || a > b) return false;
+ *lo = (uint8_t)a; *hi = (uint8_t)b;
+ return true;
+ }
+ if (!parse_uint(s, len, 255, &a)) return false;
+ *lo = *hi = (uint8_t)a;
+ return true;
+}
+
+static bool v6_prefix_range(const uint8_t *base, unsigned prefix, uint8_t *lo, uint8_t *hi)
+{
+ if (prefix > 128) return false;
+ for (int i = 0; i < 16; i++) {
+ int bits = (int)prefix - i * 8;
+ uint8_t mask = bits >= 8 ? 0xff : bits <= 0 ? 0 : (uint8_t)(0xff << (8 - bits));
+ lo[i] = base[i] & mask;
+ hi[i] = base[i] | (uint8_t)~mask;
+ }
+ return true;
+}
+
+static bool looks_like_domain(const char *tok)
+{
+ // anything that is not purely IP-ish: contains a letter (other than none), '?' or a '*' attached to letters
+ for (const char *c = tok; *c; c++)
+ if (isalpha((unsigned char)*c) || *c == '_' || *c == '?') return true;
+ return false;
+}
+
+static bool parse_domain_token(const char *tok, char *out, char *err, size_t errlen)
+{
+ size_t n = strlen(tok);
+ if (n == 0 || n > 253) { set_err(err, errlen, "invalid domain pattern '%s'", tok); return false; }
+ for (size_t i = 0; i < n; i++) {
+ unsigned char c = (unsigned char)tok[i];
+ if (!(isalnum(c) || c == '-' || c == '.' || c == '_' || c == '*' || c == '?')) {
+ set_err(err, errlen, "invalid character '%c' in domain pattern '%s'", c, tok);
+ return false;
+ }
+ out[i] = (char)tolower(c);
+ }
+ out[n] = 0;
+ if (out[0] == '.' || out[n - 1] == '.' || strstr(out, "..")) { set_err(err, errlen, "invalid domain pattern '%s'", tok); return false; }
+ return true;
+}
+
+bool pb_domain_match(const char *pattern, const char *name)
+{
+ char lower[256];
+ size_t n = strlen(name);
+ if (n >= sizeof lower) return false;
+ for (size_t i = 0; i <= n; i++) lower[i] = (char)tolower((unsigned char)name[i]);
+ while (n && lower[n - 1] == '.') lower[--n] = 0; // tolerate a trailing root dot
+ return pb_glob_match(pattern, lower);
+}
+
+static bool parse_host_token(const char *tok, struct pb_host_pat *p, char *err, size_t errlen)
+{
+ memset(p, 0, sizeof *p);
+ if (strchr(tok, ':')) { // ---- IPv6
+ char buf[256];
+ snprintf(buf, sizeof buf, "%s", tok);
+ char *slash = strchr(buf, '/'), *dash = strchr(buf, '-');
+ struct in6_addr a, b;
+ p->kind = PB_HOST_V6_RANGE;
+ if (slash) {
+ *slash = 0;
+ unsigned pre;
+ if (inet_pton(AF_INET6, buf, &a) != 1 || !parse_uint(slash + 1, strlen(slash + 1), 128, &pre)) goto bad6;
+ v6_prefix_range(a.s6_addr, pre, p->lo6, p->hi6);
+ } else if (dash) {
+ *dash = 0;
+ if (inet_pton(AF_INET6, buf, &a) != 1 || inet_pton(AF_INET6, dash + 1, &b) != 1) goto bad6;
+ if (memcmp(a.s6_addr, b.s6_addr, 16) > 0) { set_err(err, errlen, "IPv6 range '%s' has start > end", tok); return false; }
+ memcpy(p->lo6, a.s6_addr, 16); memcpy(p->hi6, b.s6_addr, 16);
+ } else {
+ if (inet_pton(AF_INET6, buf, &a) != 1) goto bad6;
+ memcpy(p->lo6, a.s6_addr, 16); memcpy(p->hi6, a.s6_addr, 16);
+ }
+ return true;
+bad6:
+ set_err(err, errlen, "invalid IPv6 address or range '%s'", tok);
+ return false;
+ }
+
+ const char *slash = strchr(tok, '/'), *dash = strchr(tok, '-');
+ uint32_t a, b;
+ char buf[256];
+ if (slash) { // ---- IPv4 CIDR
+ snprintf(buf, sizeof buf, "%.*s", (int)(slash - tok), tok);
+ unsigned pre;
+ if (!parse_ipv4(buf, &a) || !parse_uint(slash + 1, strlen(slash + 1), 32, &pre)) goto bad4;
+ uint32_t mask = pre ? 0xffffffffu << (32 - pre) : 0;
+ p->kind = PB_HOST_V4_RANGE; p->lo4 = a & mask; p->hi4 = a | ~mask;
+ return true;
+ }
+ int dots_before = 0;
+ for (const char *c = tok; dash && c < dash; c++) dots_before += *c == '.';
+ if (dash && dots_before == 3) { // ---- IPv4 a.b.c.d-e.f.g.h
+ snprintf(buf, sizeof buf, "%.*s", (int)(dash - tok), tok);
+ if (!parse_ipv4(buf, &a) || !parse_ipv4(dash + 1, &b)) goto bad4;
+ if (a > b) { set_err(err, errlen, "IPv4 range '%s' has start > end", tok); return false; }
+ p->kind = PB_HOST_V4_RANGE; p->lo4 = a; p->hi4 = b;
+ return true;
+ }
+ // ---- IPv4 with per-octet '*' or 'lo-hi'
+ const char *s = tok;
+ for (int i = 0; i < 4; i++) {
+ const char *e = strchr(s, '.');
+ size_t len = e ? (size_t)(e - s) : strlen(s);
+ if ((i < 3) != (e != NULL)) goto bad4;
+ if (!parse_octet(s, len, &p->box_lo[i], &p->box_hi[i])) goto bad4;
+ s = e ? e + 1 : s + len;
+ }
+ // exact address or a contiguous prefix box collapses to a numeric range
+ {
+ int i = 0;
+ while (i < 4 && p->box_lo[i] == p->box_hi[i]) i++; // leading fixed octets
+ bool contiguous = true;
+ if (i < 4) {
+ for (int j = i + 1; j < 4; j++)
+ if (p->box_lo[j] != 0 || p->box_hi[j] != 255) contiguous = false;
+ }
+ if (contiguous) {
+ p->kind = PB_HOST_V4_RANGE;
+ p->lo4 = p->hi4 = 0;
+ for (int j = 0; j < 4; j++) {
+ p->lo4 = (p->lo4 << 8) | p->box_lo[j];
+ p->hi4 = (p->hi4 << 8) | p->box_hi[j];
+ }
+ } else {
+ p->kind = PB_HOST_V4_BOX;
+ }
+ }
+ return true;
+bad4:
+ set_err(err, errlen, "invalid IPv4 address, range or pattern '%s'", tok);
+ return false;
+}
+
+static bool parse_port_token(const char *tok, struct pb_port_range *r, char *err, size_t errlen)
+{
+ unsigned a, b;
+ const char *dash = strchr(tok, '-');
+ if (dash) {
+ if (!parse_uint(tok, (size_t)(dash - tok), 65535, &a) || !parse_uint(dash + 1, strlen(dash + 1), 65535, &b) || a > b || a == 0) {
+ set_err(err, errlen, "invalid port range '%s'", tok);
+ return false;
+ }
+ } else {
+ if (!parse_uint(tok, strlen(tok), 65535, &a) || a == 0) {
+ set_err(err, errlen, "invalid port '%s' (1-65535)", tok);
+ return false;
+ }
+ b = a;
+ }
+ r->lo = (uint16_t)a; r->hi = (uint16_t)b;
+ return true;
+}
+
+// ---- public: parse / free / clone ------------------------------------------------------------------------------------
+
+void pb_rule_free(struct pb_rule *r)
+{
+ free(r->procs); free(r->hosts); free(r->ports); free(r->domains);
+ r->procs = NULL; r->hosts = NULL; r->ports = NULL; r->domains = NULL;
+ r->nprocs = r->nhosts = r->nports = r->ndomains = 0;
+}
+
+bool pb_rule_clone(struct pb_rule *dst, const struct pb_rule *src)
+{
+ *dst = *src;
+ dst->procs = NULL; dst->hosts = NULL; dst->ports = NULL; dst->domains = NULL;
+ if (src->nprocs && !(dst->procs = malloc(sizeof(*dst->procs) * (size_t)src->nprocs))) goto oom;
+ if (src->nhosts && !(dst->hosts = malloc(sizeof(*dst->hosts) * (size_t)src->nhosts))) goto oom;
+ if (src->nports && !(dst->ports = malloc(sizeof(*dst->ports) * (size_t)src->nports))) goto oom;
+ if (src->ndomains && !(dst->domains = malloc(sizeof(*dst->domains) * (size_t)src->ndomains))) goto oom;
+ if (src->nprocs) memcpy(dst->procs, src->procs, sizeof(*dst->procs) * (size_t)src->nprocs);
+ if (src->nhosts) memcpy(dst->hosts, src->hosts, sizeof(*dst->hosts) * (size_t)src->nhosts);
+ if (src->nports) memcpy(dst->ports, src->ports, sizeof(*dst->ports) * (size_t)src->nports);
+ if (src->ndomains) memcpy(dst->domains, src->domains, sizeof(*dst->domains) * (size_t)src->ndomains);
+ return true;
+oom:
+ pb_rule_free(dst);
+ return false;
+}
+
+static bool is_any(const char *s)
+{
+ while (isspace((unsigned char)*s)) s++;
+ if (!*s) return true;
+ return s[0] == '*' && (s[1] == 0 || isspace((unsigned char)s[1]));
+}
+
+bool pb_rule_parse(struct pb_rule *out, const char *process, const char *hosts, const char *ports, char *err, size_t errlen)
+{
+ memset(out, 0, sizeof *out);
+ if (!process) process = "";
+ if (!hosts) hosts = "";
+ if (!ports) ports = "";
+ if (strlen(process) >= sizeof out->process_src || strlen(hosts) >= sizeof out->hosts_src || strlen(ports) >= sizeof out->ports_src) {
+ set_err(err, errlen, "pattern too long (max 511 characters)");
+ return false;
+ }
+ snprintf(out->process_src, sizeof out->process_src, "%s", process);
+ snprintf(out->hosts_src, sizeof out->hosts_src, "%s", hosts);
+ snprintf(out->ports_src, sizeof out->ports_src, "%s", ports);
+
+ char (*tok)[256] = malloc(sizeof(char[256]) * PB_MAX_PATTERNS);
+ if (!tok) { set_err(err, errlen, "out of memory"); return false; }
+
+ // process
+ if (is_any(process)) out->any_proc = true;
+ else {
+ int n = split_list(process, tok, PB_MAX_PATTERNS);
+ if (n < 0) { set_err(err, errlen, "too many process patterns (max %d)", PB_MAX_PATTERNS); goto fail; }
+ out->procs = malloc(sizeof(char[256]) * (size_t)(n ? n : 1));
+ if (!out->procs) goto oom;
+ for (int i = 0; i < n; i++) {
+ if (!strcmp(tok[i], "*")) { out->any_proc = true; continue; }
+ memcpy(out->procs[out->nprocs++], tok[i], 256);
+ }
+ if (out->any_proc) { free(out->procs); out->procs = NULL; out->nprocs = 0; }
+ }
+
+ // hosts
+ if (is_any(hosts)) out->any_host = true;
+ else {
+ int n = split_list(hosts, tok, PB_MAX_PATTERNS);
+ if (n < 0) { set_err(err, errlen, "too many host patterns (max %d)", PB_MAX_PATTERNS); goto fail; }
+ out->hosts = calloc((size_t)(n ? n : 1), sizeof *out->hosts);
+ out->domains = malloc(sizeof(char[256]) * (size_t)(n ? n : 1));
+ if (!out->hosts || !out->domains) goto oom;
+ for (int i = 0; i < n; i++) {
+ if (!strcmp(tok[i], "*")) { out->any_host = true; break; }
+ if (looks_like_domain(tok[i]) && !strchr(tok[i], ':')) {
+ if (!parse_domain_token(tok[i], out->domains[out->ndomains], err, errlen)) goto fail;
+ out->ndomains++;
+ continue;
+ }
+ if (!parse_host_token(tok[i], &out->hosts[out->nhosts], err, errlen)) goto fail;
+ out->nhosts++;
+ }
+ if (out->any_host) { free(out->hosts); free(out->domains); out->hosts = NULL; out->domains = NULL; out->nhosts = out->ndomains = 0; }
+ }
+
+ // ports
+ if (is_any(ports)) out->any_port = true;
+ else {
+ int n = split_list(ports, tok, PB_MAX_PATTERNS);
+ if (n < 0) { set_err(err, errlen, "too many port patterns (max %d)", PB_MAX_PATTERNS); goto fail; }
+ out->ports = calloc((size_t)(n ? n : 1), sizeof *out->ports);
+ if (!out->ports) goto oom;
+ for (int i = 0; i < n; i++) {
+ if (!strcmp(tok[i], "*")) { out->any_port = true; break; }
+ if (!parse_port_token(tok[i], &out->ports[out->nports], err, errlen)) goto fail;
+ out->nports++;
+ }
+ if (out->any_port) { free(out->ports); out->ports = NULL; out->nports = 0; }
+ }
+ free(tok);
+ return true;
+oom:
+ set_err(err, errlen, "out of memory");
+fail:
+ free(tok);
+ pb_rule_free(out);
+ return false;
+}
+
+// ---- matching --------------------------------------------------------------------------------------------------------
+
+bool pb_rule_match_process(const struct pb_rule *r, const char *exe_path)
+{
+ if (r->any_proc) return true;
+ if (!exe_path || !*exe_path) return false;
+ const char *base = strrchr(exe_path, '/');
+ base = base ? base + 1 : exe_path;
+ for (int i = 0; i < r->nprocs; i++)
+ if (pb_glob_match(r->procs[i], base) || pb_glob_match(r->procs[i], exe_path)) return true;
+ return false;
+}
+
+bool pb_rule_match_proto(const struct pb_rule *r, int ipproto)
+{
+ switch (r->protocol) {
+ case RULE_PROTOCOL_TCP: return ipproto == IPPROTO_TCP;
+ case RULE_PROTOCOL_UDP: return ipproto == IPPROTO_UDP;
+ default: return true;
+ }
+}
+
+bool pb_rule_has_domains(const struct pb_rule *r) { return r->ndomains > 0; }
+
+bool pb_rule_match_dest(const struct pb_rule *r, int family, const uint8_t addr16[16], uint16_t port,
+ const char *const *names, int nnames)
+{
+ if (!r->any_port) {
+ bool ok = false;
+ for (int i = 0; i < r->nports && !ok; i++) ok = port >= r->ports[i].lo && port <= r->ports[i].hi;
+ if (!ok) return false;
+ }
+ if (r->any_host) return true;
+ for (int i = 0; i < r->nhosts; i++) {
+ const struct pb_host_pat *h = &r->hosts[i];
+ if (family == AF_INET) {
+ uint32_t a = ((uint32_t)addr16[12] << 24) | ((uint32_t)addr16[13] << 16) | ((uint32_t)addr16[14] << 8) | addr16[15];
+ if (h->kind == PB_HOST_V4_RANGE && a >= h->lo4 && a <= h->hi4) return true;
+ if (h->kind == PB_HOST_V4_BOX) {
+ bool ok = true;
+ for (int j = 0; j < 4 && ok; j++) {
+ uint8_t o = addr16[12 + j];
+ ok = o >= h->box_lo[j] && o <= h->box_hi[j];
+ }
+ if (ok) return true;
+ }
+ } else if (h->kind == PB_HOST_V6_RANGE) {
+ if (memcmp(addr16, h->lo6, 16) >= 0 && memcmp(addr16, h->hi6, 16) <= 0) return true;
+ }
+ }
+ for (int d = 0; d < r->ndomains; d++)
+ for (int k = 0; k < nnames; k++)
+ if (pb_domain_match(r->domains[d], names[k])) return true;
+ return false;
+}
+
+bool pb_implicit_direct(int family, const uint8_t a[16], uint16_t port, int ipproto, bool dns_via_proxy)
+{
+ if (family == AF_INET) {
+ if (a[12] == 127) return true; // loopback
+ if (a[12] >= 224) return true; // multicast + reserved + broadcast
+ if (a[12] == 0) return true; // 0.0.0.0/8
+ } else {
+ static const uint8_t lo[16] = { [15] = 1 };
+ if (!memcmp(a, lo, 16)) return true; // ::1
+ if (a[0] == 0xff) return true; // multicast
+ if (a[0] == 0xfe && (a[1] & 0xc0) == 0x80) return true; // link-local (needs scope id anyway)
+ }
+ if (ipproto == IPPROTO_UDP && (port == 67 || port == 68)) return true; // DHCP
+ if (port == 53 && !dns_via_proxy) return true;
+ return false;
+}
+
+int pb_rules_eval(const struct pb_rule *rules, size_t n, const char *exe_path, int family, const uint8_t addr16[16],
+ uint16_t port, int ipproto, const char *const *names, int nnames)
+{
+ for (size_t i = 0; i < n; i++) {
+ const struct pb_rule *r = &rules[i];
+ if (!r->enabled) continue;
+ if (!pb_rule_match_proto(r, ipproto)) continue;
+ if (!pb_rule_match_process(r, exe_path)) continue;
+ if (!pb_rule_match_dest(r, family, addr16, port, names, nnames)) continue;
+ return (int)i;
+ }
+ return -1;
+}
diff --git a/Linux/src/pb_rules.h b/Linux/src/pb_rules.h
new file mode 100644
index 0000000..4c18df4
--- /dev/null
+++ b/Linux/src/pb_rules.h
@@ -0,0 +1,60 @@
+// Rule model: parsing/validation and the full userspace matcher (the reference semantics; the BPF side is a compiled subset).
+#ifndef PB_RULES_H
+#define PB_RULES_H
+
+#include "pb_internal.h"
+
+#define PB_MAX_PATTERNS 64
+
+enum { PB_HOST_V4_RANGE = 1, PB_HOST_V4_BOX, PB_HOST_V6_RANGE };
+
+struct pb_host_pat {
+ int kind;
+ uint32_t lo4, hi4; // PB_HOST_V4_RANGE, host order
+ uint8_t box_lo[4], box_hi[4]; // PB_HOST_V4_BOX: per-octet inclusive range (e.g. 192.168.*.* or 10.1-5.*.*)
+ uint8_t lo6[16], hi6[16]; // PB_HOST_V6_RANGE, network order
+};
+
+struct pb_port_range { uint16_t lo, hi; };
+
+struct pb_rule {
+ uint32_t id;
+ bool enabled;
+ RuleProtocol protocol;
+ RuleAction action;
+ uint32_t proxy_id; // action == PROXY: 0 = default proxy
+
+ char process_src[512], hosts_src[512], ports_src[512]; // original text, kept for the UI / export
+
+ bool any_proc;
+ char (*procs)[256]; int nprocs;
+ bool any_host;
+ struct pb_host_pat *hosts; int nhosts;
+ char (*domains)[256]; int ndomains; // lower-case domain globs ("*.github.com", "example.org"), matched against DNS-learned names
+ bool any_port;
+ struct pb_port_range *ports; int nports;
+};
+
+// Parses and validates the three pattern strings into `out` (id/enabled/action/protocol/proxy_id are left to the caller).
+// On failure returns false and writes a human readable reason to err. On success the caller must pb_rule_free().
+bool pb_rule_parse(struct pb_rule *out, const char *process, const char *hosts, const char *ports, char *err, size_t errlen);
+void pb_rule_free(struct pb_rule *r);
+bool pb_rule_clone(struct pb_rule *dst, const struct pb_rule *src); // deep copy
+
+bool pb_glob_match(const char *pattern, const char *str);
+bool pb_rule_match_process(const struct pb_rule *r, const char *exe_path);
+bool pb_rule_match_proto(const struct pb_rule *r, int ipproto);
+// names/nnames: domain names the DNS tap has learned for this destination address (may be NULL/0).
+bool pb_rule_match_dest(const struct pb_rule *r, int family, const uint8_t addr16[16], uint16_t port,
+ const char *const *names, int nnames);
+bool pb_rule_has_domains(const struct pb_rule *r);
+bool pb_domain_match(const char *pattern, const char *name); // case-insensitive; glob if it contains * or ?, else exact
+
+// Destinations that are never redirected (loopback, multicast, broadcast, DHCP, DNS when !dns_via_proxy).
+bool pb_implicit_direct(int family, const uint8_t addr16[16], uint16_t port, int ipproto, bool dns_via_proxy);
+
+// First enabled matching rule wins. Returns the index of the matching rule or -1 (no rule: DIRECT).
+int pb_rules_eval(const struct pb_rule *rules, size_t n, const char *exe_path, int family, const uint8_t addr16[16],
+ uint16_t port, int ipproto, const char *const *names, int nnames);
+
+#endif
diff --git a/Linux/src/tests/dns_test.c b/Linux/src/tests/dns_test.c
new file mode 100644
index 0000000..928b9cf
--- /dev/null
+++ b/Linux/src/tests/dns_test.c
@@ -0,0 +1,92 @@
+#include <stdbool.h>
+#include <arpa/inet.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include "../pb_dns.h"
+
+static int fails;
+#define CHECK(c) do { if (!(c)) { printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); fails++; } } while (0)
+
+// tiny DNS message builder -------------------------------------------------------------------------------------------
+struct msg { uint8_t b[2048]; size_t n; };
+static void w16(struct msg *m, unsigned v) { m->b[m->n++] = (uint8_t)(v >> 8); m->b[m->n++] = (uint8_t)v; }
+static void w32(struct msg *m, unsigned v) { w16(m, v >> 16); w16(m, v & 0xffff); }
+static size_t wname(struct msg *m, const char *name)
+{
+ size_t start = m->n;
+ while (*name) {
+ const char *dot = strchr(name, '.'); size_t l = dot ? (size_t)(dot - name) : strlen(name);
+ m->b[m->n++] = (uint8_t)l; memcpy(m->b + m->n, name, l); m->n += l; name += l + (dot ? 1 : 0);
+ }
+ m->b[m->n++] = 0;
+ return start;
+}
+static void ptr(struct msg *m, size_t at) { w16(m, 0xC000 | (unsigned)at); }
+static void header(struct msg *m, unsigned flags, unsigned qd, unsigned an) { m->n = 0; w16(m, 0x1234); w16(m, flags); w16(m, qd); w16(m, an); w16(m, 0); w16(m, 0); }
+static void a_rr(struct msg *m, size_t owner_off, const char *ip) { ptr(m, owner_off); w16(m, 1); w16(m, 1); w32(m, 60); w16(m, 4); struct in_addr a; inet_pton(AF_INET, ip, &a); memcpy(m->b + m->n, &a, 4); m->n += 4; }
+static uint32_t H(const char *ip) { struct in_addr a; inet_pton(AF_INET, ip, &a); return ntohl(a.s_addr); }
+static bool has(uint32_t ip, const char *name) { char n[8][256]; int c = pb_dns_lookup(ip, n, 8); for (int i = 0; i < c; i++) if (!strcmp(n[i], name)) return true; return false; }
+
+int main(void)
+{
+ struct msg m; struct pb_dns_result r;
+
+ // 1. plain A answer with a compressed owner name
+ header(&m, 0x8180, 1, 2); size_t q = wname(&m, "www.Example.COM"); w16(&m, 1); w16(&m, 1);
+ a_rr(&m, q, "93.184.216.34"); a_rr(&m, q, "93.184.216.35");
+ CHECK(pb_dns_observe(m.b, m.n, &r) == 2 && r.nips == 2);
+ CHECK(has(H("93.184.216.34"), "www.example.com") && has(H("93.184.216.35"), "www.example.com")); // lower-cased
+
+ // 2. CNAME chain: www.shop.test -> cdn.edge.net -> A
+ header(&m, 0x8180, 1, 3); q = wname(&m, "www.shop.test"); w16(&m, 1); w16(&m, 1);
+ ptr(&m, q); w16(&m, 5); w16(&m, 1); w32(&m, 300); size_t lenpos = m.n; w16(&m, 0); size_t t = wname(&m, "cdn.edge.net"); w16(&m, 0); /* patch below */
+ m.b[lenpos] = 0; m.b[lenpos + 1] = (uint8_t)(m.n - lenpos - 2 - 2); m.n -= 2;
+ a_rr(&m, t, "198.51.100.7");
+ // fix an count (we wrote 3 but only 2 RRs)
+ m.b[7] = 2;
+ CHECK(pb_dns_observe(m.b, m.n, &r) == 1);
+ CHECK(has(H("198.51.100.7"), "www.shop.test") && has(H("198.51.100.7"), "cdn.edge.net"));
+
+ // 3. rejects: query (QR=0), NXDOMAIN, no answers, loopback answers
+ header(&m, 0x0100, 1, 0); q = wname(&m, "x.test"); w16(&m, 1); w16(&m, 1);
+ CHECK(pb_dns_observe(m.b, m.n, &r) == 0);
+ header(&m, 0x8183, 1, 0); q = wname(&m, "x.test"); w16(&m, 1); w16(&m, 1);
+ CHECK(pb_dns_observe(m.b, m.n, &r) == 0);
+ header(&m, 0x8180, 1, 1); q = wname(&m, "local.test"); w16(&m, 1); w16(&m, 1); a_rr(&m, q, "127.0.0.9");
+ pb_dns_observe(m.b, m.n, &r); CHECK(!has(H("127.0.0.9"), "local.test"));
+
+ // 4. hostile input must not crash or loop: pointer loops, truncated records, random garbage
+ header(&m, 0x8180, 1, 1); m.b[m.n++] = 0xC0; m.b[m.n++] = 12; // name pointing at itself
+ w16(&m, 1); w16(&m, 1); CHECK(pb_dns_observe(m.b, m.n, &r) == 0);
+ header(&m, 0x8180, 1, 1); q = wname(&m, "t.test"); w16(&m, 1); w16(&m, 1); ptr(&m, q); w16(&m, 1); w16(&m, 1); w32(&m, 1); w16(&m, 4); m.b[m.n++] = 1; // rdata truncated
+ CHECK(pb_dns_observe(m.b, m.n, &r) == 0);
+ srand(7);
+ for (int i = 0; i < 200000; i++) {
+ size_t n = (size_t)(rand() % 200); uint8_t g[200];
+ for (size_t k = 0; k < n; k++) g[k] = (uint8_t)rand();
+ if (n >= 12 && (i & 1)) { g[2] = 0x81; g[3] = 0x80; g[5] = 1; g[7] = (uint8_t)(1 + rand() % 3); }
+ pb_dns_observe(g, n, &r);
+ }
+
+ // 5. bounded table: oldest mappings are evicted and reported
+ pb_dns_clear();
+ int evicted = 0;
+ for (uint32_t i = 0; i < PB_DNS_MAX_ENTRIES + 500; i++) {
+ header(&m, 0x8180, 1, 1); q = wname(&m, "bulk.test"); w16(&m, 1); w16(&m, 1);
+ ptr(&m, q); w16(&m, 1); w16(&m, 1); w32(&m, 60); w16(&m, 4); uint32_t ip = 0x0A000000u + 0x010000u + i; m.b[m.n++] = (uint8_t)(ip >> 24); m.b[m.n++] = (uint8_t)(ip >> 16); m.b[m.n++] = (uint8_t)(ip >> 8); m.b[m.n++] = (uint8_t)ip;
+ pb_dns_observe(m.b, m.n, &r); evicted += r.nevicted;
+ }
+ CHECK(pb_dns_count() == PB_DNS_MAX_ENTRIES); CHECK(evicted == 500);
+ CHECK(!has(0x0A010000u, "bulk.test") && has(0x0A010000u + 600, "bulk.test"));
+
+ // 6. /etc/hosts style file
+ pb_dns_clear();
+ FILE *f = fopen("/tmp/pb_dns_test_hosts", "w"); fprintf(f, "# c\n127.0.0.1 localhost\n192.0.2.44 intranet.test wiki.Intranet.test # x\n::1 ip6\nbogus line\n"); fclose(f);
+ CHECK(pb_dns_load_hosts("/tmp/pb_dns_test_hosts", &r) == 1);
+ CHECK(has(H("192.0.2.44"), "intranet.test") && has(H("192.0.2.44"), "wiki.intranet.test"));
+ remove("/tmp/pb_dns_test_hosts");
+
+ printf(fails ? "DNS TESTS FAILED (%d)\n" : "dns tests passed\n", fails);
+ return fails != 0;
+}
diff --git a/Linux/src/tests/relay_test.c b/Linux/src/tests/relay_test.c
new file mode 100644
index 0000000..51c35a0
--- /dev/null
+++ b/Linux/src/tests/relay_test.c
@@ -0,0 +1,1473 @@
+// Root-free loopback test harness for pb_relay.c. Fakes every pb_core_* function and runs in-process fake
+// SOCKS5 / HTTP CONNECT proxies and echo servers. The kernel redirect is simulated (see README comments below):
+// TCP: client bind()s a known source port, the fake pb_core_take_tcp_orig() maps that port to the destination.
+// UDP: client sends to 127.x.y.z:udp_port, the fake pb_core_get_udp_flow() maps 127.x.y.z to the destination.
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include <arpa/inet.h>
+#include <dirent.h>
+#include <errno.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <poll.h>
+#include <pthread.h>
+#include <stdarg.h>
+#include <stdatomic.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/socket.h>
+#include <time.h>
+#include <unistd.h>
+#include <sys/epoll.h>
+#include <sys/resource.h>
+#include <sys/ioctl.h>
+#include <net/if.h>
+#include <sched.h>
+#include <fcntl.h>
+
+#include "../pb_internal.h"
+
+// ---------------------------------------------------------------------------------------------
+// Fake core
+// ---------------------------------------------------------------------------------------------
+static pthread_mutex_t g_mu = PTHREAD_MUTEX_INITIALIZER;
+static struct pb_orig g_tcp[65536];
+static bool g_tcp_valid[65536];
+static struct { uint32_t ip_be; struct pb_orig o; bool used; } g_flows[64];
+static struct pb_proxy g_px[16];
+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 char g_log[64][512];
+static int g_log_n;
+
+int pb_core_take_tcp_orig(uint16_t p, struct pb_orig *out)
+{
+ pthread_mutex_lock(&g_mu);
+ int ok = g_tcp_valid[p];
+ if (ok) { *out = g_tcp[p]; g_tcp_valid[p] = false; }
+ pthread_mutex_unlock(&g_mu);
+ return ok ? 0 : -1;
+}
+int pb_core_get_udp_flow(uint32_t ip, struct pb_orig *out)
+{
+ int ok = 0;
+ pthread_mutex_lock(&g_mu);
+ for (int i = 0; i < 64; i++)
+ if (g_flows[i].used && g_flows[i].ip_be == ip) { *out = g_flows[i].o; ok = 1; break; }
+ pthread_mutex_unlock(&g_mu);
+ return ok ? 0 : -1;
+}
+void pb_core_decide(const struct pb_orig *o, struct pb_decision *out)
+{
+ (void)o;
+ atomic_fetch_add(&g_decide_calls, 1);
+ *out = g_decision;
+}
+int pb_core_get_proxy(uint32_t id, struct pb_proxy *out)
+{
+ if (id == 0) id = g_default_px;
+ if (id >= 16 || !g_px_used[id]) return -1;
+ *out = g_px[id];
+ return 0;
+}
+void pb_core_log(const char *fmt, ...)
+{
+ char b[512];
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(b, sizeof b, fmt, ap);
+ va_end(ap);
+ pthread_mutex_lock(&g_mu);
+ snprintf(g_log[g_log_n++ % 64], 512, "%s", b);
+ pthread_mutex_unlock(&g_mu);
+ if (getenv("VERBOSE")) fprintf(stderr, " [log] %s\n", b);
+}
+void pb_core_flow_event(const struct pb_orig *o, int action, const char *d)
+{
+ (void)o; (void)d;
+ atomic_fetch_add(&g_ev, 1);
+ if (action == PB_ACT_PROXY) atomic_fetch_add(&g_ev_proxy, 1);
+ else if (action == PB_ACT_DIRECT) atomic_fetch_add(&g_ev_direct, 1);
+ else atomic_fetch_add(&g_ev_block, 1);
+}
+bool pb_core_dns_via_proxy(void) { return false; }
+
+struct obs { int64_t t0, t1; size_t len; uint32_t h; };
+static struct obs g_obs[64];
+static atomic_int g_obs_n, g_obs_sleep;
+static int64_t mono_ms(void)
+{
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+static uint32_t fnv(const uint8_t *p, size_t n)
+{
+ uint32_t h = 2166136261u;
+ while (n--) { h ^= *p++; h *= 16777619u; }
+ return h;
+}
+void pb_core_dns_observe(const uint8_t *m, size_t len)
+{
+ int64_t t0 = mono_ms();
+ int sl = atomic_load(&g_obs_sleep);
+ if (sl) usleep((useconds_t)sl * 1000);
+ int i = atomic_fetch_add(&g_obs_n, 1);
+ if (i < 64) g_obs[i] = (struct obs){ t0, mono_ms(), len, fnv(m, len) };
+}
+
+static bool log_has(const char *s)
+{
+ bool r = false;
+ pthread_mutex_lock(&g_mu);
+ for (int i = 0; i < 64 && i < g_log_n; i++) if (strstr(g_log[i], s)) r = true;
+ pthread_mutex_unlock(&g_mu);
+ return r;
+}
+static void log_clear(void) { pthread_mutex_lock(&g_mu); g_log_n = 0; memset(g_log, 0, sizeof g_log); pthread_mutex_unlock(&g_mu); }
+static void ev_clear(void) { g_ev = g_ev_proxy = g_ev_direct = g_ev_block = 0; }
+
+// ---------------------------------------------------------------------------------------------
+// Test plumbing
+// ---------------------------------------------------------------------------------------------
+static int g_pass, g_fail;
+#define CHECK(cond, ...) do { if (cond) { g_pass++; printf("PASS "); } else { g_fail++; printf("FAIL "); } \
+ printf(__VA_ARGS__); printf("\n"); fflush(stdout); } while (0)
+
+static const uint16_t TPORT = 39011, UPORT = 39012;
+static atomic_int g_next_port = 20000;
+
+static void fill_orig(struct pb_orig *o, const char *ip, uint16_t port, int proto, int action, uint32_t px)
+{
+ memset(o, 0, sizeof *o);
+ struct in_addr a;
+ inet_pton(AF_INET, ip, &a);
+ memset(o->addr + 10, 0xff, 2);
+ memcpy(o->addr + 12, &a, 4);
+ o->port = port; o->family = AF_INET; o->proto = (uint8_t)proto; o->action = (uint8_t)action; o->proxy_id = (uint16_t)px;
+}
+static void set_tcp(uint16_t src, const char *ip, uint16_t port, int action, uint32_t px)
+{
+ pthread_mutex_lock(&g_mu);
+ fill_orig(&g_tcp[src], ip, port, IPPROTO_TCP, action, px);
+ g_tcp_valid[src] = true;
+ pthread_mutex_unlock(&g_mu);
+}
+static int g_nflows;
+static void set_flow(const char *flow_ip, const char *ip, uint16_t port, int action, uint32_t px)
+{
+ struct in_addr f;
+ inet_pton(AF_INET, flow_ip, &f);
+ pthread_mutex_lock(&g_mu);
+ int i;
+ for (i = 0; i < g_nflows; i++) if (g_flows[i].ip_be == f.s_addr) break;
+ if (i == g_nflows) g_nflows++;
+ g_flows[i].used = true; g_flows[i].ip_be = f.s_addr;
+ fill_orig(&g_flows[i].o, ip, port, IPPROTO_UDP, action, px);
+ pthread_mutex_unlock(&g_mu);
+}
+static void set_proxy_host(uint32_t id, const char *host)
+{
+ snprintf(g_px[id].host, sizeof g_px[id].host, "%s", host);
+}
+static void set_proxy(uint32_t id, ProxyType t, uint16_t port, const char *u, const char *p)
+{
+ memset(&g_px[id], 0, sizeof g_px[id]);
+ g_px[id].id = id; g_px[id].type = t; snprintf(g_px[id].name, 64, "px%u", id);
+ snprintf(g_px[id].host, sizeof g_px[id].host, "127.0.0.1");
+ g_px[id].port = port;
+ if (u) snprintf(g_px[id].user, sizeof g_px[id].user, "%s", u);
+ if (p) snprintf(g_px[id].pass, sizeof g_px[id].pass, "%s", p);
+ g_px_used[id] = true;
+}
+
+static int count_fds(void)
+{
+ int n = 0;
+ DIR *d = opendir("/proc/self/fd");
+ while (readdir(d)) n++;
+ closedir(d);
+ return n - 3; // ., .., and the dir fd itself
+}
+static int64_t now_ms(void)
+{
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+static void msleep(int ms) { usleep((useconds_t)ms * 1000); }
+
+// ---------------------------------------------------------------------------------------------
+// Fake servers
+// ---------------------------------------------------------------------------------------------
+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 int rd_full(int fd, void *b, size_t n)
+{
+ uint8_t *p = b;
+ while (n) { ssize_t r = recv(fd, p, n, 0); if (r <= 0) return -1; p += r; n -= (size_t)r; }
+ return 0;
+}
+static int wr_full(int fd, const void *b, size_t n)
+{
+ const uint8_t *p = b;
+ while (n) { ssize_t r = send(fd, p, n, MSG_NOSIGNAL); if (r <= 0) return -1; p += r; n -= (size_t)r; }
+ return 0;
+}
+
+struct pipe_arg { int a, b; };
+static void *pipe_dir(void *p)
+{
+ struct pipe_arg *x = p;
+ char *buf = malloc(262144);
+ ssize_t r;
+ while ((r = recv(x->a, buf, 262144, 0)) > 0)
+ if (wr_full(x->b, buf, (size_t)r)) break;
+ free(buf);
+ shutdown(x->b, SHUT_WR);
+ if (r < 0) shutdown(x->a, SHUT_RD);
+ return NULL;
+}
+static void pipe_both(int a, int b)
+{
+ struct pipe_arg x = { a, b }, y = { b, a };
+ pthread_t t;
+ pthread_create(&t, NULL, pipe_dir, &x);
+ pipe_dir(&y);
+ pthread_join(t, NULL);
+}
+
+static void echo_handler(int fd, const struct srvcfg *c)
+{
+ (void)c;
+ char buf[32768];
+ ssize_t r;
+ while ((r = recv(fd, buf, sizeof buf, 0)) > 0)
+ if (wr_full(fd, buf, (size_t)r)) break;
+ shutdown(fd, SHUT_WR);
+}
+
+static int connect_target(int atyp, const uint8_t *addr, const char *host, uint16_t port)
+{
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(port) };
+ if (atyp == 1) memcpy(&a.sin_addr, addr, 4);
+ else if (atyp == 3) { if (!strcmp(host, "localhost") || !strcmp(host, "echo.test")) a.sin_addr.s_addr = htonl(INADDR_LOOPBACK); else return -1; }
+ else return -1;
+ int fd = socket(AF_INET, SOCK_STREAM, 0);
+ if (connect(fd, (struct sockaddr *)&a, sizeof a) < 0) { close(fd); return -1; }
+ return fd;
+}
+
+static void socks_udp_assoc(int tfd)
+{
+ atomic_fetch_add(&g_assoc_count, 1);
+ int u = socket(AF_INET, SOCK_DGRAM, 0);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
+ bind(u, (struct sockaddr *)&a, sizeof a);
+ socklen_t al = sizeof a;
+ getsockname(u, (struct sockaddr *)&a, &al);
+ uint8_t rep[10] = { 5, 0, 0, 1, 127, 0, 0, 1, (uint8_t)(ntohs(a.sin_port) >> 8), (uint8_t)ntohs(a.sin_port) };
+ wr_full(tfd, rep, 10);
+ struct sockaddr_in cli = { 0 };
+ bool have = false;
+ for (;;) {
+ struct pollfd p[2] = { { tfd, POLLIN, 0 }, { u, POLLIN, 0 } };
+ if (poll(p, 2, 10000) < 0) break;
+ if (p[0].revents) { char b[64]; if (recv(tfd, b, sizeof b, 0) <= 0) break; }
+ if (p[1].revents & POLLIN) {
+ uint8_t b[70000];
+ struct sockaddr_in from;
+ socklen_t fl = sizeof from;
+ ssize_t n = recvfrom(u, b, sizeof b, 0, (struct sockaddr *)&from, &fl);
+ if (n < 1) continue;
+ if (!have) { cli = from; have = true; }
+ if (from.sin_addr.s_addr == cli.sin_addr.s_addr && from.sin_port == cli.sin_port) {
+ if (n < 10 || b[3] != 1) continue;
+ struct sockaddr_in d = { .sin_family = AF_INET };
+ memcpy(&d.sin_addr, b + 4, 4); memcpy(&d.sin_port, b + 8, 2);
+ sendto(u, b + 10, (size_t)n - 10, 0, (struct sockaddr *)&d, sizeof d);
+ atomic_fetch_add(&g_s5_udp_dgrams, 1);
+ } else {
+ uint8_t o[70020] = { 0, 0, 0, 1 };
+ memcpy(o + 4, &from.sin_addr, 4); memcpy(o + 8, &from.sin_port, 2);
+ memcpy(o + 10, b, (size_t)n);
+ sendto(u, o, (size_t)n + 10, 0, (struct sockaddr *)&cli, sizeof cli);
+ }
+ }
+ }
+ close(u);
+}
+
+static void socks_handler(int fd, const struct srvcfg *c)
+{
+ 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;
+ bool has0 = false, has2 = false;
+ for (int i = 0; i < h[1]; i++) { if (m[i] == 0) has0 = true; if (m[i] == 2) has2 = true; }
+ uint8_t sel[2] = { 5, 0xFF };
+ if (c->auth && has2) sel[1] = 2; else if (!c->auth && has0) sel[1] = 0;
+ wr_full(fd, sel, 2);
+ if (sel[1] == 0xFF) return;
+ if (sel[1] == 2) {
+ uint8_t v, l; char u[256], p[256];
+ if (rd_full(fd, &v, 1) || rd_full(fd, &l, 1) || rd_full(fd, u, l)) return;
+ u[l] = 0;
+ if (rd_full(fd, &l, 1) || rd_full(fd, p, l)) return;
+ p[l] = 0;
+ bool ok = !strcmp(u, c->user) && !strcmp(p, c->pass);
+ uint8_t r[2] = { 1, ok ? 0 : 1 };
+ wr_full(fd, r, 2);
+ if (!ok) return;
+ }
+ uint8_t rq[4];
+ if (rd_full(fd, rq, 4)) return;
+ uint8_t addr[16] = { 0 };
+ char host[256] = "";
+ if (rq[3] == 1) { if (rd_full(fd, addr, 4)) return; }
+ else if (rq[3] == 4) { if (rd_full(fd, addr, 16)) return; }
+ else if (rq[3] == 3) { uint8_t l; if (rd_full(fd, &l, 1) || rd_full(fd, host, l)) return; host[l] = 0; }
+ uint8_t pt[2];
+ if (rd_full(fd, pt, 2)) return;
+ uint16_t port = (uint16_t)(pt[0] << 8 | pt[1]);
+ if (rq[1] == 3) { socks_udp_assoc(fd); return; }
+ int t = connect_target(rq[3], addr, host, port);
+ uint8_t rep[10] = { 5, t < 0 ? 5 : 0, 0, 1, 0, 0, 0, 0, 0, 0 };
+ wr_full(fd, rep, 10);
+ if (t < 0) return;
+ pipe_both(fd, t);
+ close(t);
+}
+
+static void http_handler(int fd, const struct srvcfg *c)
+{
+ char b[4096];
+ size_t n = 0;
+ while (n < sizeof b - 1) {
+ ssize_t r = recv(fd, b + n, 1, 0);
+ if (r <= 0) return;
+ n++;
+ if (n >= 4 && !memcmp(b + n - 4, "\r\n\r\n", 4)) break;
+ }
+ b[n] = 0;
+ if (c->auth) {
+ // Basic base64("user:pass") computed by the test config: pass holds the expected token in user field? keep simple:
+ char want[200];
+ snprintf(want, sizeof want, "Proxy-Authorization: Basic %s", c->pass);
+ if (!strstr(b, want)) { const char *r = "HTTP/1.1 407 Proxy Authentication Required\r\n\r\n"; wr_full(fd, r, strlen(r)); return; }
+ }
+ char host[200]; unsigned port;
+ if (sscanf(b, "CONNECT %199[^:]:%u", host, &port) != 2) return;
+ struct in_addr a;
+ int t = -1;
+ if (inet_pton(AF_INET, host, &a) == 1) t = connect_target(1, (uint8_t *)&a, "", (uint16_t)port);
+ else t = connect_target(3, NULL, host, (uint16_t)port);
+ if (t < 0) { const char *r = "HTTP/1.1 502 Bad Gateway\r\n\r\n"; wr_full(fd, r, strlen(r)); return; }
+ const char *ok = c->leftover ? "HTTP/1.1 200 Connection established\r\nX: y\r\n\r\nLEFTOVER" : "HTTP/1.1 200 Connection established\r\n\r\n";
+ wr_full(fd, ok, strlen(ok));
+ pipe_both(fd, t);
+ close(t);
+}
+
+static void *conn_thread(void *p)
+{
+ struct hctx *x = p;
+ x->s->h(x->fd, &x->s->cfg);
+ close(x->fd);
+ free(x);
+ return NULL;
+}
+static void *accept_thread(void *p)
+{
+ struct srv *s = p;
+ for (;;) {
+ int fd = accept(s->lfd, NULL, NULL);
+ if (fd < 0) { if (errno == EINTR) continue; return NULL; }
+ struct hctx *x = malloc(sizeof *x);
+ x->fd = fd; x->s = s;
+ pthread_t t;
+ pthread_create(&t, NULL, conn_thread, x);
+ pthread_detach(t);
+ }
+}
+static struct srv *srv_start_p(void (*h)(int, const struct srvcfg *), const struct srvcfg *cfg, uint16_t port)
+{
+ struct srv *s = calloc(1, sizeof *s);
+ s->h = h;
+ if (cfg) s->cfg = *cfg;
+ s->lfd = socket(AF_INET, SOCK_STREAM, 0);
+ int one = 1;
+ setsockopt(s->lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK), .sin_port = htons(port) };
+ if (bind(s->lfd, (struct sockaddr *)&a, sizeof a) < 0) { close(s->lfd); free(s); return NULL; }
+ listen(s->lfd, 256);
+ socklen_t al = sizeof a;
+ getsockname(s->lfd, (struct sockaddr *)&a, &al);
+ s->port = ntohs(a.sin_port);
+ pthread_t t;
+ pthread_create(&t, NULL, accept_thread, s);
+ pthread_detach(t);
+ return s;
+}
+#define srv_start(h, c) srv_start_p(h, c, 0)
+
+struct udpecho { int fd; uint16_t port; };
+static void *udpecho_thread(void *p)
+{
+ struct udpecho *e = p;
+ char b[70000];
+ for (;;) {
+ struct sockaddr_in f;
+ socklen_t fl = sizeof f;
+ ssize_t n = recvfrom(e->fd, b, sizeof b, 0, (struct sockaddr *)&f, &fl);
+ if (n < 0) { if (errno == EINTR) continue; return NULL; }
+ sendto(e->fd, b, (size_t)n, 0, (struct sockaddr *)&f, fl);
+ }
+}
+static uint16_t udpecho_start(void)
+{
+ struct udpecho *e = calloc(1, sizeof *e);
+ e->fd = socket(AF_INET, SOCK_DGRAM, 0);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
+ bind(e->fd, (struct sockaddr *)&a, sizeof a);
+ socklen_t al = sizeof a;
+ getsockname(e->fd, (struct sockaddr *)&a, &al);
+ e->port = ntohs(a.sin_port);
+ pthread_t t;
+ pthread_create(&t, NULL, udpecho_thread, e);
+ pthread_detach(t);
+ return e->port;
+}
+
+// ---------------------------------------------------------------------------------------------
+// Client helpers
+// ---------------------------------------------------------------------------------------------
+static int relay_connect(uint16_t src)
+{
+ int fd = socket(AF_INET, SOCK_STREAM, 0);
+ int one = 1;
+ setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK), .sin_port = htons(src) };
+ if (bind(fd, (struct sockaddr *)&a, sizeof a) < 0) { close(fd); return -1; }
+ a.sin_port = htons(pb_relay_tcp_port());
+ if (connect(fd, (struct sockaddr *)&a, sizeof a) < 0) { close(fd); return -1; }
+ struct timeval tv = { 30, 0 };
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
+ return fd;
+}
+static uint16_t new_src(void) { return (uint16_t)atomic_fetch_add(&g_next_port, 1); }
+
+static inline uint8_t pat(uint64_t i) { return (uint8_t)((i * 0x9E3779B1u) >> 11); }
+
+struct xf { int fd; uint64_t total; bool half; };
+static void *xf_send(void *p)
+{
+ struct xf *x = p;
+ uint8_t buf[65536];
+ uint64_t off = 0;
+ while (off < x->total) {
+ size_t n = x->total - off > sizeof buf ? sizeof buf : (size_t)(x->total - off);
+ for (size_t j = 0; j < n; j++) buf[j] = pat(off + j);
+ if (wr_full(x->fd, buf, n)) break;
+ off += n;
+ }
+ if (x->half) shutdown(x->fd, SHUT_WR);
+ return NULL;
+}
+// Sends `total` patterned bytes and verifies the echo. Returns bytes verified, -1 on mismatch.
+static int64_t xfer(int fd, uint64_t total, bool half)
+{
+ struct xf x = { fd, total, half };
+ pthread_t t;
+ pthread_create(&t, NULL, xf_send, &x);
+ uint8_t buf[65536];
+ uint64_t got = 0;
+ int64_t res = 0;
+ for (;;) {
+ if (!half && got >= total) break;
+ ssize_t r = recv(fd, buf, sizeof buf, 0);
+ if (r <= 0) break;
+ for (ssize_t j = 0; j < r; j++) if (buf[j] != pat(got + (uint64_t)j)) { res = -1; goto out; }
+ got += (uint64_t)r;
+ }
+ res = (int64_t)got;
+out:
+ if (res < 0) shutdown(fd, SHUT_RDWR);
+ pthread_join(t, NULL);
+ return res;
+}
+// True when the peer closes (EOF or reset) within timeout_ms with no data.
+static bool expect_closed(int fd, int timeout_ms)
+{
+ struct pollfd p = { fd, POLLIN, 0 };
+ if (poll(&p, 1, timeout_ms) <= 0) return false;
+ char b[64];
+ ssize_t r = recv(fd, b, sizeof b, 0);
+ return r == 0 || (r < 0 && errno != EAGAIN);
+}
+
+static int relay_up(int tcp_idle, int udp_idle, int maxc, int hs)
+{
+ struct pb_relay_cfg c = { TPORT, UPORT, maxc, tcp_idle, udp_idle, hs };
+ return pb_relay_start(&c);
+}
+
+static uint16_t free_port(void)
+{
+ int fd = socket(AF_INET, SOCK_STREAM, 0);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
+ bind(fd, (struct sockaddr *)&a, sizeof a);
+ socklen_t al = sizeof a;
+ getsockname(fd, (struct sockaddr *)&a, &al);
+ close(fd);
+ return ntohs(a.sin_port);
+}
+
+// One echo round trip of `n` bytes through the relay for the given action.
+static int64_t tcp_roundtrip(const char *dst_ip, uint16_t dst_port, int action, uint32_t px, uint64_t n, bool half)
+{
+ uint16_t src = new_src();
+ set_tcp(src, dst_ip, dst_port, action, px);
+ int fd = relay_connect(src);
+ if (fd < 0) return -2;
+ int64_t r = xfer(fd, n, half);
+ close(fd);
+ return r;
+}
+
+// ---------------------------------------------------------------------------------------------
+// UDP client helpers
+// ---------------------------------------------------------------------------------------------
+static int udp_client(void)
+{
+ int fd = socket(AF_INET, SOCK_DGRAM, 0);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
+ bind(fd, (struct sockaddr *)&a, sizeof a);
+ struct timeval tv = { 1, 0 };
+ setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
+ return fd;
+}
+static void udp_send_flow(int fd, const char *flow_ip, const char *msg)
+{
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(pb_relay_udp_port()) };
+ inet_pton(AF_INET, flow_ip, &a.sin_addr);
+ sendto(fd, msg, strlen(msg), 0, (struct sockaddr *)&a, sizeof a);
+}
+// Receives one datagram; returns length or -1; src_ip filled with the sender address.
+static int udp_recv(int fd, char *buf, size_t n, char *src_ip, uint16_t *src_port)
+{
+ struct sockaddr_in f;
+ socklen_t fl = sizeof f;
+ ssize_t r = recvfrom(fd, buf, n - 1, 0, (struct sockaddr *)&f, &fl);
+ if (r < 0) return -1;
+ buf[r] = 0;
+ inet_ntop(AF_INET, &f.sin_addr, src_ip, 32);
+ *src_port = ntohs(f.sin_port);
+ return (int)r;
+}
+static bool udp_echo_ok(int fd, const char *flow_ip, const char *msg)
+{
+ char b[256], ip[32];
+ uint16_t sp;
+ udp_send_flow(fd, flow_ip, msg);
+ int r = udp_recv(fd, b, sizeof b, ip, &sp);
+ return r == (int)strlen(msg) && !strcmp(b, msg) && !strcmp(ip, flow_ip) && sp == pb_relay_udp_port();
+}
+
+// ---------------------------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------------------------
+static struct srv *g_echo, *g_s5, *g_s5auth, *g_http, *g_httpauth, *g_httpleft, *g_silent;
+static uint16_t g_uecho1, g_uecho2;
+
+static void *conc_thread(void *p)
+{
+ int idx = (int)(intptr_t)p;
+ uint64_t mb = getenv("LARGE_MB") ? strtoull(getenv("LARGE_MB"), NULL, 10) : 8;
+ int mode = idx % 3;
+ int64_t r = tcp_roundtrip("127.0.0.1", g_echo->port, mode == 2 ? PB_ACT_DIRECT : PB_ACT_PROXY, mode == 0 ? 1 : (mode == 1 ? 3 : 0),
+ mb << 20, false);
+ return (void *)(intptr_t)(r == (int64_t)(mb << 20));
+}
+
+static void test_tcp_basic(void)
+{
+ ev_clear();
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 1, 100000, false) == 100000, "TCP via SOCKS5 (no auth)");
+ CHECK(g_ev == 1 && g_ev_proxy == 1, "flow_event exactly once for proxied flow (got %d)", (int)g_ev);
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 2, 100000, false) == 100000, "TCP via SOCKS5 (user/pass auth)");
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 3, 100000, false) == 100000, "TCP via HTTP CONNECT");
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 4, 100000, false) == 100000, "TCP via HTTP CONNECT with Basic auth");
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 0, 5000, false) == 5000, "TCP via default proxy (id 0)");
+ ev_clear();
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_DIRECT, 0, 100000, false) == 100000, "TCP DIRECT");
+ CHECK(g_ev == 1 && g_ev_direct == 1, "flow_event for direct");
+
+ // HTTP leftover bytes after the 200 response must reach the client first
+ uint16_t src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_PROXY, 5);
+ int fd = relay_connect(src);
+ char b[16] = { 0 };
+ bool ok = fd >= 0 && rd_full(fd, b, 8) == 0 && !memcmp(b, "LEFTOVER", 8);
+ CHECK(ok, "HTTP CONNECT leftover bytes forwarded to client");
+ if (fd >= 0) close(fd);
+
+ // BLOCK
+ ev_clear();
+ src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_BLOCK, 0);
+ fd = relay_connect(src);
+ send(fd, "x", 1, MSG_NOSIGNAL);
+ CHECK(fd >= 0 && expect_closed(fd, 3000), "TCP BLOCK closes client");
+ CHECK(g_ev_block == 1, "flow_event BLOCK");
+ close(fd);
+
+ // DECIDE
+ g_decision = (struct pb_decision){ PB_ACT_DIRECT, 0 };
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_DECIDE, 0, 5000, false) == 5000, "TCP DECIDE -> DIRECT");
+ g_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, "TCP DECIDE -> PROXY");
+ g_decision = (struct pb_decision){ PB_ACT_BLOCK, 0 };
+ src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_DECIDE, 0);
+ fd = relay_connect(src);
+ CHECK(fd >= 0 && expect_closed(fd, 3000), "TCP DECIDE -> BLOCK");
+ close(fd);
+
+ // no orig entry
+ fd = relay_connect(new_src());
+ CHECK(fd >= 0 && expect_closed(fd, 3000), "TCP without original destination is closed");
+ close(fd);
+
+ // domain-name target through test helper is covered separately; IPv6 original destination (no v6 proxy server: direct to ::1)
+}
+
+static void test_tcp_bad_proxy(void)
+{
+ log_clear();
+ uint16_t dead = free_port();
+ set_proxy(6, PROXY_TYPE_SOCKS5, dead, NULL, NULL);
+ uint16_t src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_PROXY, 6);
+ int fd = relay_connect(src);
+ CHECK(fd >= 0 && expect_closed(fd, 5000) && log_has("refused"), "bad proxy (connection refused): client closed + logged");
+ close(fd);
+
+ log_clear();
+ set_proxy(7, PROXY_TYPE_SOCKS5, g_s5auth->port, "alice", "WRONG");
+ src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_PROXY, 7);
+ fd = relay_connect(src);
+ CHECK(fd >= 0 && expect_closed(fd, 5000) && log_has("authentication failed"), "SOCKS5 wrong password: client closed + logged");
+ close(fd);
+
+ log_clear();
+ set_proxy(8, PROXY_TYPE_HTTP, g_httpauth->port, "alice", "WRONG");
+ src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_PROXY, 8);
+ fd = relay_connect(src);
+ CHECK(fd >= 0 && expect_closed(fd, 5000) && log_has("407"), "HTTP 407: client closed + logged");
+ close(fd);
+
+ log_clear();
+ src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_PROXY, 12); // unknown proxy id
+ fd = relay_connect(src);
+ CHECK(fd >= 0 && expect_closed(fd, 5000) && log_has("no proxy configured"), "unknown proxy id: client closed + logged");
+ close(fd);
+
+ // dead target through a working proxy -> SOCKS5 REP 5
+ log_clear();
+ src = new_src();
+ set_tcp(src, "127.0.0.1", dead, PB_ACT_PROXY, 1);
+ fd = relay_connect(src);
+ CHECK(fd >= 0 && expect_closed(fd, 5000) && log_has("connection refused by target"), "SOCKS5 REP code mapped in log");
+ close(fd);
+}
+
+static void sink_handler(int fd, const struct srvcfg *c)
+{
+ (void)c;
+ char *buf = malloc(262144);
+ uint64_t total = 0;
+ ssize_t r;
+ while ((r = recv(fd, buf, 262144, 0)) > 0) total += (uint64_t)r;
+ free(buf);
+ wr_full(fd, &total, 8);
+}
+static struct srv *g_sink;
+struct thru { int action; uint32_t px; uint64_t bytes; int ok; };
+static void *thru_thread(void *p)
+{
+ struct thru *t = p;
+ uint16_t src = new_src();
+ set_tcp(src, "127.0.0.1", g_sink->port, t->action, t->px);
+ int fd = relay_connect(src);
+ static const char z[65536];
+ uint64_t sent = 0, total = 0;
+ while (fd >= 0 && sent < t->bytes) { if (wr_full(fd, z, sizeof z)) break; sent += sizeof z; }
+ if (fd >= 0) { shutdown(fd, SHUT_WR); t->ok = rd_full(fd, &total, 8) == 0 && total == sent && sent == t->bytes; close(fd); }
+ return NULL;
+}
+static void test_throughput(void)
+{
+ uint64_t mb = getenv("THRU_MB") ? strtoull(getenv("THRU_MB"), NULL, 10) : 256;
+ struct { const char *name; int action; uint32_t px; } m[] = { { "DIRECT via relay", PB_ACT_DIRECT, 0 }, { "SOCKS5 via relay + fake proxy", PB_ACT_PROXY, 1 } };
+ for (int k = 0; k < 2; k++) {
+ enum { N = 8 };
+ pthread_t th[N];
+ struct thru t[N];
+ int64_t t0 = now_ms();
+ for (int i = 0; i < N; i++) { t[i] = (struct thru){ m[k].action, m[k].px, mb << 20, 0 }; pthread_create(&th[i], NULL, thru_thread, &t[i]); }
+ int ok = 0;
+ for (int i = 0; i < N; i++) { pthread_join(th[i], NULL); ok += t[i].ok; }
+ int64_t ms = now_ms() - t0;
+ CHECK(ok == N, "throughput %s: %d x %lluMB, %.0f MB/s aggregate (%lld ms)", m[k].name, N, (unsigned long long)mb,
+ (double)(N * mb) * 1000.0 / (double)(ms + 1), (long long)ms);
+ }
+}
+
+static void test_tcp_halfclose(void)
+{
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 1, 300000, true) == 300000, "half-close via SOCKS5: all echoed then EOF");
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 3, 300000, true) == 300000, "half-close via HTTP CONNECT");
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_DIRECT, 0, 300000, true) == 300000, "half-close DIRECT");
+}
+
+static void test_tcp_large(void)
+{
+ uint64_t mb = getenv("LARGE_MB") ? strtoull(getenv("LARGE_MB"), NULL, 10) : 8;
+ int64_t t0 = now_ms();
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 1, 50ull << 20, false) == (int64_t)(50ull << 20), "50MB single transfer via SOCKS5, checksum ok (%lld ms, %.0f MB/s each way)", (long long)(now_ms() - t0), 50000.0 / (double)(now_ms() - t0 + 1));
+ enum { N = 50 };
+ pthread_t th[N];
+ t0 = now_ms();
+ for (int i = 0; i < N; i++) pthread_create(&th[i], NULL, conc_thread, (void *)(intptr_t)i);
+ int ok = 0;
+ for (int i = 0; i < N; i++) { void *r; pthread_join(th[i], &r); ok += (int)(intptr_t)r; }
+ CHECK(ok == N, "%d concurrent x %lluMB (socks5/http/direct mix) integrity: %d/%d ok (%lld ms)", N, (unsigned long long)mb, ok, N, (long long)(now_ms() - t0));
+}
+
+// Single-threaded SOCKS5 "hold" server: accepts any CONNECT and then just swallows data, so 10k connections cost
+// the test process almost nothing and the RSS delta mostly reflects the relay.
+static atomic_int g_hold_ready;
+static void *hold_thread(void *arg)
+{
+ int lfd = (int)(intptr_t)arg;
+ enum { MAXFD = 1 << 18 };
+ uint8_t *stage = calloc(MAXFD, 1);
+ int ep = epoll_create1(0);
+ struct epoll_event ev = { .events = EPOLLIN, .data.fd = lfd };
+ epoll_ctl(ep, EPOLL_CTL_ADD, lfd, &ev);
+ for (;;) {
+ struct epoll_event evs[128];
+ int n = epoll_wait(ep, evs, 128, -1);
+ for (int i = 0; i < n; i++) {
+ int fd = evs[i].data.fd;
+ if (fd == lfd) {
+ int c;
+ while ((c = accept4(lfd, NULL, NULL, SOCK_NONBLOCK)) >= 0) {
+ if (c >= MAXFD) { close(c); continue; }
+ stage[c] = 0;
+ struct epoll_event e = { .events = EPOLLIN, .data.fd = c };
+ epoll_ctl(ep, EPOLL_CTL_ADD, c, &e);
+ }
+ continue;
+ }
+ uint8_t b[4096];
+ ssize_t r;
+ if (stage[fd] == 0) {
+ r = recv(fd, b, 3, 0);
+ if (r == 3) { send(fd, "\5\0", 2, MSG_NOSIGNAL); stage[fd] = 1; continue; }
+ } else if (stage[fd] == 1) {
+ r = recv(fd, b, 10, 0);
+ if (r == 10) {
+ uint8_t rep[10] = { 5, 0, 0, 1 };
+ send(fd, rep, 10, MSG_NOSIGNAL);
+ stage[fd] = 2;
+ atomic_fetch_add(&g_hold_ready, 1);
+ continue;
+ }
+ } else {
+ r = recv(fd, b, sizeof b, 0);
+ if (r > 0) continue;
+ }
+ if (r < 0 && errno == EAGAIN) continue;
+ close(fd);
+ }
+ }
+ return NULL;
+}
+
+static long rss_kb(void)
+{
+ long pages = 0, rss = 0;
+ FILE *f = fopen("/proc/self/statm", "r");
+ if (f) { if (fscanf(f, "%ld %ld", &pages, &rss) != 2) rss = 0; fclose(f); }
+ return rss * (sysconf(_SC_PAGESIZE) / 1024);
+}
+
+static void test_tcp_10k(void)
+{
+ enum { N = 10000 };
+ struct rlimit rl;
+ getrlimit(RLIMIT_NOFILE, &rl);
+ rl.rlim_cur = rl.rlim_max < 200000 ? rl.rlim_max : 200000;
+ setrlimit(RLIMIT_NOFILE, &rl);
+ int lfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
+ int one = 1;
+ setsockopt(lfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
+ bind(lfd, (struct sockaddr *)&a, sizeof a);
+ listen(lfd, 4096);
+ socklen_t al = sizeof a;
+ getsockname(lfd, (struct sockaddr *)&a, &al);
+ pthread_t t;
+ pthread_create(&t, NULL, hold_thread, (void *)(intptr_t)lfd);
+ pthread_detach(t);
+ set_proxy(10, PROXY_TYPE_SOCKS5, ntohs(a.sin_port), NULL, NULL);
+
+ pb_relay_stop();
+ CHECK(relay_up(300, 60, 0, 10) == 0, "restart relay with default limits for 10k test");
+ msleep(300);
+ atomic_store(&g_next_port, 21000);
+ atomic_store(&g_hold_ready, 0);
+ int base_fds = count_fds();
+ long rss0 = rss_kb();
+ int *fds = malloc(N * sizeof *fds);
+ int opened = 0;
+ for (int i = 0; i < N; i++) {
+ fds[i] = -1;
+ for (int tries = 0; tries < 5 && fds[i] < 0; tries++) {
+ uint16_t src = new_src();
+ set_tcp(src, "127.0.0.1", 9, PB_ACT_PROXY, 10);
+ fds[i] = relay_connect(src);
+ }
+ if (fds[i] >= 0) opened++;
+ if (i % 100 == 99) { // pace so the bounded handshake queue is not what we measure
+ int64_t t0 = now_ms();
+ while (atomic_load(&g_hold_ready) < i - 200 && now_ms() - t0 < 30000) msleep(2);
+ }
+ }
+ int64_t t0 = now_ms();
+ while (atomic_load(&g_hold_ready) < N && now_ms() - t0 < 60000) msleep(20);
+ msleep(500);
+ long rss1 = rss_kb();
+ int alive = 0;
+ for (int i = 0; i < N; i += 100) {
+ struct pollfd p = { fds[i], POLLIN, 0 };
+ if (fds[i] >= 0 && poll(&p, 1, 0) == 0) alive++;
+ }
+ CHECK(opened == N && g_hold_ready == N, "10000 idle connections established through SOCKS5 (opened=%d handshaken=%d)", opened, (int)g_hold_ready);
+ CHECK(alive == N / 100, "sampled idle connections still open (%d/%d)", alive, N / 100);
+ printf(" RSS before=%ld KB after=%ld KB delta=%ld MB\n", rss0, rss1, (rss1 - rss0) / 1024);
+ CHECK((rss1 - rss0) / 1024 < 100, "RSS delta for 10k idle connections < 100MB (%ld MB)", (rss1 - rss0) / 1024);
+ for (int i = 0; i < N; i++) if (fds[i] >= 0) close(fds[i]);
+ free(fds);
+ t0 = now_ms();
+ while (count_fds() > base_fds + 1 && now_ms() - t0 < 20000) msleep(50);
+ CHECK(count_fds() <= base_fds + 1, "all fds released after closing 10k connections (base=%d now=%d)", base_fds, count_fds());
+ pb_relay_stop();
+ CHECK(relay_up(300, 60, 0, 5) == 0, "restart relay");
+}
+
+static void test_tcp_idle(void)
+{
+ pb_relay_stop();
+ CHECK(relay_up(2, 60, 0, 5) == 0, "restart relay with tcp_idle=2s");
+ uint16_t src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_PROXY, 1);
+ int fd = relay_connect(src);
+ send(fd, "hi", 2, 0);
+ char b[4];
+ rd_full(fd, b, 2);
+ int64_t t0 = now_ms();
+ bool closed = expect_closed(fd, 6000);
+ CHECK(closed && now_ms() - t0 < 5500, "idle TCP connection closed after ~2s (%lld ms)", (long long)(now_ms() - t0));
+ close(fd);
+
+ src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_DIRECT, 0);
+ fd = relay_connect(src);
+ bool alive = true;
+ for (int i = 0; i < 6 && alive; i++) {
+ send(fd, "p", 1, 0);
+ alive = rd_full(fd, b, 1) == 0;
+ msleep(700);
+ }
+ CHECK(alive, "active connection survives past idle timeout");
+ close(fd);
+}
+
+static void test_tcp_cap(void)
+{
+ pb_relay_stop();
+ CHECK(relay_up(300, 60, 5, 5) == 0, "restart relay with max_tcp_conns=5");
+ int fds[5];
+ int up = 0;
+ for (int i = 0; i < 5; i++) {
+ uint16_t s = new_src();
+ set_tcp(s, "127.0.0.1", g_echo->port, PB_ACT_DIRECT, 0);
+ fds[i] = relay_connect(s);
+ char b[1];
+ send(fds[i], "x", 1, 0);
+ if (rd_full(fds[i], b, 1) == 0) up++;
+ }
+ CHECK(up == 5, "5 connections within cap work");
+ uint16_t s = new_src();
+ set_tcp(s, "127.0.0.1", g_echo->port, PB_ACT_DIRECT, 0);
+ int extra = relay_connect(s);
+ send(extra, "x", 1, MSG_NOSIGNAL);
+ CHECK(expect_closed(extra, 3000), "6th connection closed immediately (cap)");
+ close(extra);
+ close(fds[0]);
+ msleep(500);
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_DIRECT, 0, 1000, false) == 1000, "slot freed after close");
+ for (int i = 1; i < 5; i++) close(fds[i]);
+ msleep(300);
+}
+
+static void test_handshake_timeout(void)
+{
+ pb_relay_stop();
+ CHECK(relay_up(300, 60, 0, 2) == 0, "restart relay with handshake_timeout=2s");
+ log_clear();
+ set_proxy(9, PROXY_TYPE_SOCKS5, g_silent->port, NULL, NULL);
+ uint16_t s = new_src();
+ set_tcp(s, "127.0.0.1", g_echo->port, PB_ACT_PROXY, 9);
+ int fd = relay_connect(s);
+ int64_t t0 = now_ms();
+ bool closed = expect_closed(fd, 6000);
+ CHECK(closed && now_ms() - t0 < 4500 && log_has("timed out"), "silent proxy: handshake times out (%lld ms)", (long long)(now_ms() - t0));
+ close(fd);
+}
+
+static void test_udp(void)
+{
+ char b[256], ip[32];
+ uint16_t sp;
+ int c = udp_client();
+ set_flow("127.1.2.3", "127.0.0.1", g_uecho1, PB_ACT_PROXY, 1);
+ set_flow("127.1.2.4", "127.0.0.1", g_uecho2, PB_ACT_PROXY, 1);
+ int a0 = g_assoc_count;
+ CHECK(udp_echo_ok(c, "127.1.2.3", "hello-one"), "UDP via SOCKS5 UDP ASSOCIATE, reply from flow address 127.1.2.3");
+ CHECK(udp_echo_ok(c, "127.1.2.4", "hello-two"), "second destination from same client socket, reply from 127.1.2.4");
+ CHECK(udp_echo_ok(c, "127.1.2.3", "again"), "first destination again");
+ CHECK(g_assoc_count - a0 == 1, "exactly one UDP ASSOCIATE for the session (got %d)", (int)g_assoc_count - a0);
+
+ // burst while association is being set up (new client => new session): queued datagrams all delivered
+ int c2 = udp_client();
+ for (int i = 0; i < 10; i++) { char m[32]; snprintf(m, sizeof m, "burst%d", i); udp_send_flow(c2, "127.1.2.3", m); }
+ int got = 0;
+ while (udp_recv(c2, b, sizeof b, ip, &sp) > 0) got++;
+ CHECK(got == 10, "10 datagrams sent during association setup delivered (got %d)", got);
+ close(c2);
+
+ // SOCKS5 with auth for UDP
+ set_flow("127.1.2.5", "127.0.0.1", g_uecho1, PB_ACT_PROXY, 2);
+ c2 = udp_client();
+ CHECK(udp_echo_ok(c2, "127.1.2.5", "auth-udp"), "UDP via authenticated SOCKS5");
+ close(c2);
+
+ // direct
+ set_flow("127.1.3.1", "127.0.0.1", g_uecho1, PB_ACT_DIRECT, 0);
+ set_flow("127.1.3.2", "127.0.0.1", g_uecho2, PB_ACT_DIRECT, 0);
+ CHECK(udp_echo_ok(c, "127.1.3.1", "direct-1") && udp_echo_ok(c, "127.1.3.2", "direct-2"), "UDP DIRECT, two destinations");
+
+ // block / unknown flow / non-loopback
+ set_flow("127.1.4.1", "127.0.0.1", g_uecho1, PB_ACT_BLOCK, 0);
+ udp_send_flow(c, "127.1.4.1", "blocked");
+ CHECK(udp_recv(c, b, sizeof b, ip, &sp) < 0, "UDP BLOCK dropped");
+ udp_send_flow(c, "127.9.9.9", "unknown");
+ CHECK(udp_recv(c, b, sizeof b, ip, &sp) < 0, "UDP unknown flow dropped");
+
+ // HTTP proxy cannot do UDP
+ log_clear();
+ set_flow("127.1.4.2", "127.0.0.1", g_uecho1, PB_ACT_PROXY, 3);
+ udp_send_flow(c, "127.1.4.2", "via-http");
+ udp_send_flow(c, "127.1.4.2", "via-http2");
+ CHECK(udp_recv(c, b, sizeof b, ip, &sp) < 0 && log_has("HTTP proxy"), "UDP via HTTP proxy dropped + logged");
+
+ // DECIDE cached per (client, flow)
+ g_decision = (struct pb_decision){ PB_ACT_DIRECT, 0 };
+ set_flow("127.1.4.3", "127.0.0.1", g_uecho1, PB_ACT_DECIDE, 0);
+ g_decide_calls = 0;
+ bool ok = udp_echo_ok(c, "127.1.4.3", "d1") && udp_echo_ok(c, "127.1.4.3", "d2") && udp_echo_ok(c, "127.1.4.3", "d3");
+ CHECK(ok && g_decide_calls == 1, "UDP DECIDE -> DIRECT, decided once (calls=%d)", (int)g_decide_calls);
+
+ // bad proxy for UDP: nothing comes back, no crash
+ set_flow("127.1.4.4", "127.0.0.1", g_uecho1, PB_ACT_PROXY, 6);
+ udp_send_flow(c, "127.1.4.4", "dead-proxy");
+ CHECK(udp_recv(c, b, sizeof b, ip, &sp) < 0, "UDP via dead SOCKS5 proxy: no reply, relay survives");
+ CHECK(udp_echo_ok(c, "127.1.3.1", "still-alive"), "relay still serves UDP afterwards");
+ close(c);
+}
+
+static void test_udp_idle(void)
+{
+ pb_relay_stop();
+ CHECK(relay_up(300, 2, 0, 5) == 0, "restart relay with udp_idle=2s");
+ int c = udp_client();
+ set_flow("127.1.5.1", "127.0.0.1", g_uecho1, PB_ACT_DIRECT, 0);
+ set_flow("127.1.5.2", "127.0.0.1", g_uecho2, PB_ACT_PROXY, 1);
+ int base = count_fds();
+ bool ok = udp_echo_ok(c, "127.1.5.1", "x") && udp_echo_ok(c, "127.1.5.2", "y");
+ msleep(200);
+ int mid = count_fds(); // direct: +1 fd; socks5: +ctl +udp in relay and +3 in the fake server
+ msleep(5000);
+ int end = count_fds();
+ CHECK(ok && mid > base && end == base, "UDP sessions expire after idle and free their fds (base=%d mid=%d end=%d)", base, mid, end);
+ CHECK(udp_echo_ok(c, "127.1.5.1", "again"), "new session after expiry works");
+ close(c);
+}
+
+static void test_start_stop(void)
+{
+ pb_relay_stop();
+ pb_relay_stop();
+ msleep(500);
+ int before = count_fds();
+ int bad = 0;
+ for (int i = 0; i < 20; i++) {
+ if (relay_up(0, 0, 0, 0) != 0) { bad++; continue; }
+ if (i % 4 == 0) {
+ bool a = tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 1, 2000, false) == 2000;
+ int c = udp_client();
+ set_flow("127.1.6.1", "127.0.0.1", g_uecho1, PB_ACT_DIRECT, 0);
+ bool b = udp_echo_ok(c, "127.1.6.1", "z");
+ close(c);
+ if (!a || !b) bad++;
+ }
+ pb_relay_stop();
+ }
+ pb_relay_stop();
+ msleep(500);
+ int after = count_fds();
+ CHECK(bad == 0 && before == after, "start/stop x20 (with traffic): fds before=%d after=%d, failures=%d", before, after, bad);
+
+ // start while ports are taken: must fail and leak nothing
+ int l = socket(AF_INET, SOCK_STREAM, 0);
+ int one = 1;
+ setsockopt(l, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK), .sin_port = htons(TPORT) };
+ if (bind(l, (struct sockaddr *)&a, sizeof a) < 0) perror("test bind");
+ listen(l, 1);
+ int b4 = count_fds();
+ log_clear();
+ int r1 = relay_up(0, 0, 0, 0);
+ int af = count_fds();
+ CHECK(r1 == -1 && b4 == af && log_has("cannot listen"), "start fails when TCP port busy, no fd leak, logged");
+ close(l);
+ int u = socket(AF_INET, SOCK_DGRAM, 0);
+ a.sin_port = htons(UPORT);
+ a.sin_addr.s_addr = htonl(INADDR_ANY);
+ if (bind(u, (struct sockaddr *)&a, sizeof a) < 0) perror("test bind");
+ b4 = count_fds();
+ r1 = relay_up(0, 0, 0, 0);
+ af = count_fds();
+ CHECK(r1 == -1 && b4 == af, "start fails when UDP port busy, no fd leak (TCP listener released)");
+ close(u);
+ CHECK(relay_up(0, 0, 0, 0) == 0, "start works after failed starts");
+ pb_relay_stop();
+}
+
+static void test_proxy_helper(void)
+{
+ char b[256];
+ // HTTP target on port 80 is not available on loopback in tests: use a tiny HTTP server through the proxies.
+ struct srvcfg hc = { 0 };
+ (void)hc;
+ int r = pb_relay_test_proxy(&g_px[1], "echo.test", g_echo->port, b, sizeof b);
+ CHECK(r == 0 && !strcmp(b, "Tunnel established"), "test_proxy SOCKS5 domain ATYP, non-80 port: '%s'", b);
+ r = pb_relay_test_proxy(&g_px[2], "127.0.0.1", g_echo->port, b, sizeof b);
+ CHECK(r == 0, "test_proxy SOCKS5 with auth: '%s'", b);
+ r = pb_relay_test_proxy(&g_px[3], "echo.test", g_echo->port, b, sizeof b);
+ CHECK(r == 0 && !strcmp(b, "Tunnel established"), "test_proxy HTTP CONNECT hostname: '%s'", b);
+ r = pb_relay_test_proxy(&g_px[7], "127.0.0.1", g_echo->port, b, sizeof b);
+ CHECK(r == -1 && strstr(b, "authentication failed"), "test_proxy wrong password -> readable error: '%s'", b);
+ r = pb_relay_test_proxy(&g_px[6], "127.0.0.1", 80, b, sizeof b);
+ CHECK(r == -1 && strstr(b, "Cannot reach proxy"), "test_proxy dead proxy -> readable error: '%s'", b);
+ r = pb_relay_test_proxy(&g_px[1], "nonexistent.test", 443, b, sizeof b);
+ CHECK(r == -1 && strstr(b, "refused"), "test_proxy unreachable target -> error: '%s'", b);
+}
+
+// Tiny HTTP origin to exercise the port-80 HEAD path of pb_relay_test_proxy (it listens on a high port, so we
+// verify the HEAD logic via a SOCKS5 server mapping port 80 is not possible; instead call with the origin port and
+// confirm the tunnel path only. HEAD logic is covered by the echo server answering the request verbatim.)
+// ---------------------------------------------------------------------------------------------
+// Network namespace so that we can bind port 53 without real root
+// ---------------------------------------------------------------------------------------------
+static bool g_have53;
+static bool can_bind53(void)
+{
+ int fd = socket(AF_INET, SOCK_STREAM, 0);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK), .sin_port = htons(53) };
+ bool ok = bind(fd, (struct sockaddr *)&a, sizeof a) == 0;
+ close(fd);
+ return ok;
+}
+static void setup_netns(void)
+{
+ if (can_bind53()) { g_have53 = true; return; }
+ uid_t uid = getuid();
+ gid_t gid = getgid();
+ if (unshare(CLONE_NEWUSER | CLONE_NEWNET) != 0) { printf("NOTE unshare(user+net) failed: %s\n", strerror(errno)); return; }
+ int fd = open("/proc/self/setgroups", O_WRONLY);
+ if (fd >= 0) { if (write(fd, "deny", 4) < 0) {} close(fd); }
+ char b[64];
+ fd = open("/proc/self/uid_map", O_WRONLY);
+ if (fd >= 0) { int n = snprintf(b, sizeof b, "0 %u 1", uid); if (write(fd, b, (size_t)n) < 0) {} close(fd); }
+ fd = open("/proc/self/gid_map", O_WRONLY);
+ if (fd >= 0) { int n = snprintf(b, sizeof b, "0 %u 1", gid); if (write(fd, b, (size_t)n) < 0) {} close(fd); }
+ int s = socket(AF_INET, SOCK_DGRAM, 0);
+ struct ifreq ifr;
+ memset(&ifr, 0, sizeof ifr);
+ snprintf(ifr.ifr_name, IFNAMSIZ, "lo");
+ ifr.ifr_flags = IFF_UP | IFF_RUNNING;
+ ioctl(s, SIOCSIFFLAGS, &ifr);
+ close(s);
+ g_have53 = can_bind53();
+ printf("NOTE using private network namespace (port 53 bindable: %s)\n", g_have53 ? "yes" : "no");
+}
+
+// ---------------------------------------------------------------------------------------------
+// DNS tap tests
+// ---------------------------------------------------------------------------------------------
+static void mk_msg(int mode, int idx, uint8_t *m, size_t len)
+{
+ for (size_t i = 0; i < len; i++) m[i] = (uint8_t)(mode * 31 + idx * 17 + (int)i * 7);
+}
+static void dns_tcp_handler(int fd, const struct srvcfg *c)
+{
+ (void)c;
+ int one = 1;
+ setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one);
+ uint8_t l[2], q[512];
+ if (rd_full(fd, l, 2)) return;
+ size_t n = (size_t)(l[0] << 8 | l[1]);
+ if (n > sizeof q || rd_full(fd, q, n)) return;
+ int mode = q[0];
+ uint8_t out[300];
+ if (mode == 'a') { // one 100-byte message, written one byte at a time
+ out[0] = 0; out[1] = 100; mk_msg(mode, 0, out + 2, 100);
+ for (int i = 0; i < 102; i++) { wr_full(fd, out + i, 1); usleep(1500); }
+ } else if (mode == 'b') { // two messages in a single write
+ out[0] = 0; out[1] = 40; mk_msg(mode, 0, out + 2, 40);
+ out[42] = 0; out[43] = 60; mk_msg(mode, 1, out + 44, 60);
+ wr_full(fd, out, 104);
+ } else { // 'c': plain single write
+ out[0] = 0; out[1] = 100; mk_msg(mode, 0, out + 2, 100);
+ wr_full(fd, out, 102);
+ }
+}
+static void *dns_udp_thread(void *p)
+{
+ int fd = (int)(intptr_t)p;
+ uint8_t b[600];
+ for (;;) {
+ struct sockaddr_in f;
+ socklen_t fl = sizeof f;
+ ssize_t n = recvfrom(fd, b, sizeof b, 0, (struct sockaddr *)&f, &fl);
+ if (n < 1) continue;
+ uint8_t m[100];
+ mk_msg(b[0], 0, m, 100);
+ sendto(fd, m, 100, 0, (struct sockaddr *)&f, fl);
+ }
+ return NULL;
+}
+
+static bool dns_tcp_case(const char *name, int action, uint32_t px, int mode, int nmsg)
+{
+ atomic_store(&g_obs_n, 0);
+ uint16_t src = new_src();
+ set_tcp(src, "127.0.0.1", 53, action, px);
+ int fd = relay_connect(src);
+ uint8_t q[3] = { 0, 1, (uint8_t)mode };
+ wr_full(fd, q, 3);
+ uint8_t got[400];
+ size_t have = 0;
+ int64_t first = 0;
+ for (;;) {
+ ssize_t r = recv(fd, got + have, sizeof got - have, 0);
+ if (r <= 0) break;
+ if (!have) first = mono_ms();
+ have += (size_t)r;
+ }
+ close(fd);
+ uint8_t exp[300];
+ size_t el = 0;
+ size_t lens[2] = { mode == 'b' ? 40 : 100, 60 };
+ uint32_t hashes[2];
+ for (int i = 0; i < nmsg; i++) {
+ exp[el++] = 0; exp[el++] = (uint8_t)lens[i];
+ mk_msg(mode, i, exp + el, lens[i]);
+ hashes[i] = fnv(exp + el, lens[i]);
+ el += lens[i];
+ }
+ bool ok = have == el && !memcmp(got, exp, el) && g_obs_n == nmsg;
+ for (int i = 0; ok && i < nmsg; i++) ok = g_obs[i].len == lens[i] && g_obs[i].h == hashes[i];
+ bool before = nmsg > 0 && g_obs[0].t1 <= first; // observe finished before the client saw any byte
+ CHECK(ok && before, "TCP DNS tap %s: stream intact, %d observe call(s) (got %d), observe completed %lld ms before first client byte", name,
+ nmsg, (int)g_obs_n, nmsg ? (long long)(first - g_obs[0].t1) : -1LL);
+ return ok;
+}
+
+static void test_dns(void)
+{
+ CHECK(g_obs_n == 0, "no DNS observe calls for non-port-53 flows so far (%d)", (int)g_obs_n);
+ if (!g_have53) { printf("SKIP DNS tests (cannot bind port 53)\n"); return; }
+ struct srv *d = srv_start_p(dns_tcp_handler, NULL, 53);
+ int ufd = socket(AF_INET, SOCK_DGRAM, 0);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK), .sin_port = htons(53) };
+ int ub = bind(ufd, (struct sockaddr *)&a, sizeof a);
+ CHECK(d && ub == 0, "DNS fake servers on 127.0.0.1:53");
+ if (!d || ub) return;
+ pthread_t t;
+ pthread_create(&t, NULL, dns_udp_thread, (void *)(intptr_t)ufd);
+ pthread_detach(t);
+ atomic_store(&g_obs_sleep, 50);
+
+ dns_tcp_case("DIRECT single write", PB_ACT_DIRECT, 0, 'c', 1);
+ dns_tcp_case("DIRECT 1-byte writes", PB_ACT_DIRECT, 0, 'a', 1);
+ dns_tcp_case("DIRECT two messages in one write", PB_ACT_DIRECT, 0, 'b', 2);
+ dns_tcp_case("via SOCKS5 single write", PB_ACT_PROXY, 1, 'c', 1);
+ dns_tcp_case("via SOCKS5 1-byte writes", PB_ACT_PROXY, 1, 'a', 1);
+ dns_tcp_case("via SOCKS5 two messages", PB_ACT_PROXY, 1, 'b', 2);
+ dns_tcp_case("via HTTP CONNECT 1-byte writes", PB_ACT_PROXY, 3, 'a', 1);
+ dns_tcp_case("via HTTP CONNECT two messages", PB_ACT_PROXY, 3, 'b', 2);
+
+ // non-53 TCP must not be observed
+ atomic_store(&g_obs_n, 0);
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_DIRECT, 0, 1000, false) == 1000 && g_obs_n == 0, "TCP non-53 not observed");
+
+ // UDP
+ struct { const char *name; int action; uint32_t px; const char *flow; } u[] = {
+ { "UDP DIRECT", PB_ACT_DIRECT, 0, "127.1.7.1" }, { "UDP via SOCKS5", PB_ACT_PROXY, 1, "127.1.7.2" } };
+ for (int k = 0; k < 2; k++) {
+ set_flow(u[k].flow, "127.0.0.1", 53, u[k].action, u[k].px);
+ atomic_store(&g_obs_n, 0);
+ int c = udp_client();
+ char b[256], ip[32];
+ uint16_t sp;
+ udp_send_flow(c, u[k].flow, "q");
+ int n = udp_recv(c, b, sizeof b, ip, &sp);
+ int64_t tr = mono_ms();
+ uint8_t m[100];
+ mk_msg('q', 0, m, 100);
+ bool ok = n == 100 && !memcmp(b, m, 100) && !strcmp(ip, u[k].flow) && g_obs_n == 1 && g_obs[0].h == fnv(m, 100) && g_obs[0].t1 <= tr;
+ CHECK(ok, "%s DNS tap: reply observed (calls=%d) before delivery, from flow address", u[k].name, (int)g_obs_n);
+ close(c);
+ }
+ // non-53 UDP not observed
+ atomic_store(&g_obs_n, 0);
+ int c = udp_client();
+ set_flow("127.1.7.3", "127.0.0.1", g_uecho1, PB_ACT_DIRECT, 0);
+ CHECK(udp_echo_ok(c, "127.1.7.3", "plain") && g_obs_n == 0, "UDP non-53 not observed");
+ close(c);
+ atomic_store(&g_obs_sleep, 0);
+}
+
+// ---------------------------------------------------------------------------------------------
+// Latency, hostname proxies, UDP sizes / odd servers
+// ---------------------------------------------------------------------------------------------
+static double pingpong_us(int fd, int n)
+{
+ char b = 'x';
+ int64_t t0 = now_ms();
+ struct timespec a, z;
+ clock_gettime(CLOCK_MONOTONIC, &a);
+ (void)t0;
+ for (int i = 0; i < n; i++) {
+ if (send(fd, &b, 1, MSG_NOSIGNAL) != 1 || recv(fd, &b, 1, 0) != 1) return -1;
+ }
+ clock_gettime(CLOCK_MONOTONIC, &z);
+ return ((double)(z.tv_sec - a.tv_sec) * 1e9 + (double)(z.tv_nsec - a.tv_nsec)) / 1000.0 / n;
+}
+static void test_latency(void)
+{
+ int one = 1;
+ int d = socket(AF_INET, SOCK_STREAM, 0);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK), .sin_port = htons(g_echo->port) };
+ connect(d, (struct sockaddr *)&a, sizeof a);
+ setsockopt(d, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one);
+ double direct = pingpong_us(d, 1000);
+ close(d);
+ double res[3];
+ int acts[3] = { PB_ACT_DIRECT, PB_ACT_PROXY, PB_ACT_PROXY };
+ uint32_t pxs[3] = { 0, 1, 3 };
+ for (int k = 0; k < 3; k++) {
+ uint16_t src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, acts[k], pxs[k]);
+ int fd = relay_connect(src);
+ setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one);
+ res[k] = pingpong_us(fd, 1000);
+ close(fd);
+ }
+ printf(" avg RTT per 1-byte round trip: direct echo %.0f us, relay DIRECT %.0f us, relay+SOCKS5 %.0f us, relay+HTTP %.0f us\n",
+ direct, res[0], res[1], res[2]);
+ CHECK(direct > 0 && res[0] > 0 && res[1] > 0 && res[2] > 0 && res[0] < 5000 && res[1] < 5000 && res[2] < 5000,
+ "no Nagle/delayed-ACK stall through relay (all averages < 5 ms)");
+}
+
+static void test_hostname(void)
+{
+ set_proxy(11, PROXY_TYPE_SOCKS5, g_s5->port, NULL, NULL);
+ set_proxy_host(11, "localhost");
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 11, 20000, false) == 20000, "TCP via SOCKS5 proxy configured as hostname 'localhost'");
+ CHECK(tcp_roundtrip("127.0.0.1", g_echo->port, PB_ACT_PROXY, 11, 20000, false) == 20000, "second connection uses resolver cache");
+ set_proxy(12, PROXY_TYPE_HTTP, g_http->port, NULL, NULL);
+ set_proxy_host(12, "localhost");
+ char b[256];
+ int r = pb_relay_test_proxy(&g_px[12], "echo.test", g_echo->port, b, sizeof b);
+ CHECK(r == 0, "pb_relay_test_proxy with hostname proxy: '%s'", b);
+ set_proxy(13, PROXY_TYPE_SOCKS5, g_s5->port, NULL, NULL);
+ set_proxy_host(13, "no-such-host.invalid");
+ int64_t t0 = now_ms();
+ r = pb_relay_test_proxy(&g_px[13], "echo.test", g_echo->port, b, sizeof b);
+ int64_t dt = now_ms() - t0;
+ CHECK(r == -1 && strstr(b, "cannot resolve") && dt < 7000, "unresolvable proxy hostname -> readable error in %lld ms: '%s'", (long long)dt, b);
+ log_clear();
+ uint16_t src = new_src();
+ set_tcp(src, "127.0.0.1", g_echo->port, PB_ACT_PROXY, 13);
+ int fd = relay_connect(src);
+ CHECK(fd >= 0 && expect_closed(fd, 8000) && log_has("cannot resolve"), "relay TCP with unresolvable proxy: client closed + logged");
+ close(fd);
+}
+
+// A UDP server that answers from a different socket than the one it received on.
+// payload starting with 'B': reply from another port on 127.0.0.1; 'C': reply from 127.0.0.2.
+static void *odd_udp_thread(void *p)
+{
+ int fd = (int)(intptr_t)p;
+ int b = socket(AF_INET, SOCK_DGRAM, 0), c = socket(AF_INET, SOCK_DGRAM, 0);
+ struct sockaddr_in x = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
+ bind(b, (struct sockaddr *)&x, sizeof x);
+ x.sin_addr.s_addr = htonl(0x7f000002);
+ bind(c, (struct sockaddr *)&x, sizeof x);
+ char m[600];
+ for (;;) {
+ struct sockaddr_in f;
+ socklen_t fl = sizeof f;
+ ssize_t n = recvfrom(fd, m, sizeof m, 0, (struct sockaddr *)&f, &fl);
+ if (n < 1) continue;
+ sendto(m[0] == 'C' ? c : b, m, (size_t)n, 0, (struct sockaddr *)&f, fl);
+ }
+ return NULL;
+}
+
+static bool udp_big(int c, const char *flow, size_t n, bool expect)
+{
+ uint8_t *tx = malloc(n), *rx = malloc(70000);
+ for (size_t i = 0; i < n; i++) tx[i] = pat(i);
+ struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(pb_relay_udp_port()) };
+ inet_pton(AF_INET, flow, &a.sin_addr);
+ ssize_t s = sendto(c, tx, n, 0, (struct sockaddr *)&a, sizeof a);
+ struct sockaddr_in f;
+ socklen_t fl = sizeof f;
+ ssize_t r = recvfrom(c, rx, 70000, 0, (struct sockaddr *)&f, &fl);
+ char ip[32];
+ inet_ntop(AF_INET, &f.sin_addr, ip, sizeof ip);
+ bool ok = s == (ssize_t)n && (expect ? (r == (ssize_t)n && !memcmp(rx, tx, n) && !strcmp(ip, flow)) : r < 0);
+ free(tx); free(rx);
+ return ok;
+}
+
+static void test_udp_odd(void)
+{
+ int c = udp_client();
+ int rb = 1 << 21;
+ setsockopt(c, SOL_SOCKET, SO_RCVBUF, &rb, sizeof rb);
+ set_flow("127.1.8.1", "127.0.0.1", g_uecho1, PB_ACT_DIRECT, 0);
+ set_flow("127.1.8.2", "127.0.0.1", g_uecho1, PB_ACT_PROXY, 1);
+ CHECK(udp_big(c, "127.1.8.1", 65507, true), "UDP DIRECT 65507-byte datagram round trip intact");
+ CHECK(udp_big(c, "127.1.8.2", 65497, true), "UDP via SOCKS5 65497-byte datagram (max with 10-byte header) round trip intact");
+ CHECK(udp_big(c, "127.1.8.2", 30000, true), "UDP via SOCKS5 30000-byte datagram intact");
+ CHECK(udp_big(c, "127.1.8.2", 65507, false), "UDP via SOCKS5 65507 (header would exceed IPv4 limit): dropped, no corruption");
+ CHECK(udp_echo_ok(c, "127.1.8.2", "small-after-big") && udp_echo_ok(c, "127.1.8.1", "small-direct-after-big"), "small datagrams unaffected after oversized ones");
+
+ uint16_t odd_port;
+ int ofd = socket(AF_INET, SOCK_DGRAM, 0);
+ struct sockaddr_in x = { .sin_family = AF_INET, .sin_addr.s_addr = htonl(INADDR_LOOPBACK) };
+ bind(ofd, (struct sockaddr *)&x, sizeof x);
+ socklen_t xl = sizeof x;
+ getsockname(ofd, (struct sockaddr *)&x, &xl);
+ odd_port = ntohs(x.sin_port);
+ pthread_t t;
+ pthread_create(&t, NULL, odd_udp_thread, (void *)(intptr_t)ofd);
+ pthread_detach(t);
+ set_flow("127.1.8.3", "127.0.0.1", odd_port, PB_ACT_DIRECT, 0);
+ set_flow("127.1.8.4", "127.0.0.1", odd_port, PB_ACT_PROXY, 1);
+ char b[64], ip[32];
+ uint16_t sp;
+ const char *fl[2] = { "127.1.8.3", "127.1.8.4" };
+ const char *nm[2] = { "DIRECT", "SOCKS5" };
+ for (int k = 0; k < 2; k++) {
+ udp_send_flow(c, fl[k], "Bport");
+ int n = udp_recv(c, b, sizeof b, ip, &sp);
+ CHECK(n == 5 && !strcmp(ip, fl[k]), "%s: reply from a different port of the same host delivered from the flow address", nm[k]);
+ udp_send_flow(c, fl[k], "Chost");
+ n = udp_recv(c, b, sizeof b, ip, &sp);
+ CHECK(n < 0, "%s: reply from a different host dropped", nm[k]);
+ }
+ close(c);
+}
+
+int main(void)
+{
+ setvbuf(stdout, NULL, _IOLBF, 0);
+ setup_netns();
+ struct srvcfg c = { 0 };
+ g_echo = srv_start(echo_handler, NULL);
+ g_s5 = srv_start(socks_handler, &c);
+ struct srvcfg ca = { .auth = true }; strcpy(ca.user, "alice"); strcpy(ca.pass, "secret");
+ g_s5auth = srv_start(socks_handler, &ca);
+ g_http = srv_start(http_handler, &c);
+ // HTTP auth: server expects base64("alice:secret") == "YWxpY2U6c2VjcmV0"
+ struct srvcfg ch = { .auth = true }; strcpy(ch.pass, "YWxpY2U6c2VjcmV0");
+ g_httpauth = srv_start(http_handler, &ch);
+ struct srvcfg cl = { .leftover = true };
+ g_httpleft = srv_start(http_handler, &cl);
+ struct srvcfg cs = { .silent = true };
+ g_silent = srv_start(socks_handler, &cs);
+ g_sink = srv_start(sink_handler, NULL);
+ g_uecho1 = udpecho_start();
+ g_uecho2 = udpecho_start();
+
+ set_proxy(1, PROXY_TYPE_SOCKS5, g_s5->port, NULL, NULL);
+ set_proxy(2, PROXY_TYPE_SOCKS5, g_s5auth->port, "alice", "secret");
+ set_proxy(3, PROXY_TYPE_HTTP, g_http->port, NULL, NULL);
+ set_proxy(4, PROXY_TYPE_HTTP, g_httpauth->port, "alice", "secret");
+ set_proxy(5, PROXY_TYPE_HTTP, g_httpleft->port, NULL, NULL);
+ g_default_px = 1;
+
+ CHECK(relay_up(300, 60, 0, 5) == 0, "pb_relay_start");
+ test_tcp_basic();
+ test_tcp_bad_proxy();
+ test_tcp_halfclose();
+ test_udp();
+ test_proxy_helper();
+ test_udp_odd();
+ test_hostname();
+ test_latency();
+ test_dns();
+ test_tcp_large();
+ test_throughput();
+ test_tcp_10k();
+ test_tcp_idle();
+ test_tcp_cap();
+ test_handshake_timeout();
+ test_udp_idle();
+ test_start_stop();
+ pb_relay_stop();
+ printf("\nRESULT: %d passed, %d failed\n", g_pass, g_fail);
+ return g_fail ? 1 : 0;
+}
diff --git a/Linux/src/tests/rules_test.c b/Linux/src/tests/rules_test.c
new file mode 100644
index 0000000..bc1b1c9
--- /dev/null
+++ b/Linux/src/tests/rules_test.c
@@ -0,0 +1,100 @@
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <arpa/inet.h>
+#include "../pb_rules.h"
+
+static int fails;
+#define CHECK(c) do { if (!(c)) { printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); fails++; } } while (0)
+
+static void a4(uint8_t o[16], const char *s) { memset(o, 0, 16); o[10] = o[11] = 0xff; inet_pton(AF_INET, s, o + 12); }
+static void a6(uint8_t o[16], const char *s) { inet_pton(AF_INET6, s, o); }
+
+static struct pb_rule R(const char *p, const char *h, const char *pt)
+{
+ struct pb_rule r; char err[128];
+ bool ok = pb_rule_parse(&r, p, h, pt, err, sizeof err);
+ if (!ok) printf("parse error: %s\n", err);
+ CHECK(ok);
+ return r;
+}
+static bool bad(const char *p, const char *h, const char *pt)
+{
+ struct pb_rule r; char err[128];
+ bool ok = pb_rule_parse(&r, p, h, pt, err, sizeof err);
+ if (ok) pb_rule_free(&r); else printf(" (rejected as expected: %s)\n", err);
+ return !ok;
+}
+
+int main(void)
+{
+ uint8_t a[16];
+ struct pb_rule r;
+
+ r = R("firefox;chrome*", "", ""); CHECK(!r.any_proc && r.nprocs == 2);
+ CHECK(pb_rule_match_process(&r, "/usr/lib/firefox/firefox")); CHECK(pb_rule_match_process(&r, "/opt/google/chrome/chrome"));
+ CHECK(pb_rule_match_process(&r, "/opt/chromium/chromedriver")); CHECK(!pb_rule_match_process(&r, "/usr/bin/curl")); pb_rule_free(&r);
+ r = R("*chrome*", "", ""); CHECK(pb_rule_match_process(&r, "/opt/google/chrome/chrome")); CHECK(pb_rule_match_process(&r, "/usr/bin/mychromex")); pb_rule_free(&r);
+ r = R("/usr/bin/*", "", ""); CHECK(pb_rule_match_process(&r, "/usr/bin/curl")); CHECK(!pb_rule_match_process(&r, "/opt/x/curl")); pb_rule_free(&r);
+ r = R("", "", ""); CHECK(r.any_proc && r.any_host && r.any_port); pb_rule_free(&r);
+ r = R("*", "*", "*"); CHECK(r.any_proc && r.any_host && r.any_port); pb_rule_free(&r);
+
+ r = R("", "192.168.*.*;10.0.0.0/8", "80;443;8000-9000");
+ a4(a, "192.168.4.5"); CHECK(pb_rule_match_dest(&r, AF_INET, a, 443, NULL, 0));
+ a4(a, "10.200.1.1"); CHECK(pb_rule_match_dest(&r, AF_INET, a, 8500, NULL, 0));
+ a4(a, "10.200.1.1"); CHECK(!pb_rule_match_dest(&r, AF_INET, a, 22, NULL, 0));
+ a4(a, "172.16.0.1"); CHECK(!pb_rule_match_dest(&r, AF_INET, a, 80, NULL, 0));
+ CHECK(r.hosts[0].kind == PB_HOST_V4_RANGE); // 192.168.*.* collapses to a range
+ pb_rule_free(&r);
+
+ r = R("", "10.1-5.*.7", ""); CHECK(r.hosts[0].kind == PB_HOST_V4_BOX);
+ a4(a, "10.3.99.7"); CHECK(pb_rule_match_dest(&r, AF_INET, a, 1, NULL, 0)); a4(a, "10.6.99.7"); CHECK(!pb_rule_match_dest(&r, AF_INET, a, 1, NULL, 0));
+ a4(a, "10.3.99.8"); CHECK(!pb_rule_match_dest(&r, AF_INET, a, 1, NULL, 0)); pb_rule_free(&r);
+
+ r = R("", "1.2.3.4-1.2.3.9", ""); a4(a, "1.2.3.9"); CHECK(pb_rule_match_dest(&r, AF_INET, a, 1, NULL, 0)); a4(a, "1.2.3.10"); CHECK(!pb_rule_match_dest(&r, AF_INET, a, 1, NULL, 0)); pb_rule_free(&r);
+ r = R("", "2001:db8::/32;fd00::1", ""); a6(a, "2001:db8:ffff::1"); CHECK(pb_rule_match_dest(&r, AF_INET6, a, 1, NULL, 0));
+ a6(a, "2001:db9::1"); CHECK(!pb_rule_match_dest(&r, AF_INET6, a, 1, NULL, 0)); a6(a, "fd00::1"); CHECK(pb_rule_match_dest(&r, AF_INET6, a, 1, NULL, 0));
+ a4(a, "1.1.1.1"); CHECK(!pb_rule_match_dest(&r, AF_INET, a, 1, NULL, 0)); pb_rule_free(&r);
+
+ CHECK(bad("", "999.1.1.1", "")); CHECK(bad("", "1.2.3", "")); CHECK(bad("", "1.2.3.4.5", "")); CHECK(bad("", "10.0.0.0/33", ""));
+ CHECK(bad("", "exa$mple.com", "")); CHECK(bad("", ".example.com", "")); CHECK(bad("", "a..b.com", "")); CHECK(bad("", "5.5.5.5-1.1.1.1", "")); CHECK(bad("", "", "abc"));
+ CHECK(bad("", "", "0")); CHECK(bad("", "", "70000")); CHECK(bad("", "", "90-80")); CHECK(bad("", "::g", "")); CHECK(bad("", "1::/129", ""));
+
+ struct pb_rule rules[3]; memset(rules, 0, sizeof rules);
+ rules[0] = R("curl", "", "443"); rules[0].enabled = true; rules[0].action = RULE_ACTION_BLOCK;
+ rules[1] = R("curl", "", ""); rules[1].enabled = true; rules[1].action = RULE_ACTION_PROXY;
+ rules[2] = R("", "", ""); rules[2].enabled = true; rules[2].action = RULE_ACTION_DIRECT; rules[2].protocol = RULE_PROTOCOL_UDP;
+ a4(a, "9.9.9.9");
+ CHECK(pb_rules_eval(rules, 3, "/usr/bin/curl", AF_INET, a, 443, IPPROTO_TCP, NULL, 0) == 0);
+ CHECK(pb_rules_eval(rules, 3, "/usr/bin/curl", AF_INET, a, 80, IPPROTO_TCP, NULL, 0) == 1);
+ CHECK(pb_rules_eval(rules, 3, "/usr/bin/wget", AF_INET, a, 80, IPPROTO_TCP, NULL, 0) == -1);
+ CHECK(pb_rules_eval(rules, 3, "/usr/bin/wget", AF_INET, a, 80, IPPROTO_UDP, NULL, 0) == 2);
+ rules[0].enabled = false; CHECK(pb_rules_eval(rules, 3, "/usr/bin/curl", AF_INET, a, 443, IPPROTO_TCP, NULL, 0) == 1);
+ for (int i = 0; i < 3; i++) pb_rule_free(&rules[i]);
+
+ CHECK(pb_implicit_direct(AF_INET, (a4(a, "127.0.0.53"), a), 53, IPPROTO_UDP, true));
+ CHECK(pb_implicit_direct(AF_INET, (a4(a, "224.0.0.251"), a), 5353, IPPROTO_UDP, true));
+ CHECK(!pb_implicit_direct(AF_INET, (a4(a, "8.8.8.8"), a), 53, IPPROTO_UDP, true));
+ CHECK(pb_implicit_direct(AF_INET, (a4(a, "8.8.8.8"), a), 53, IPPROTO_UDP, false));
+ CHECK(pb_implicit_direct(AF_INET6, (a6(a, "::1"), a), 80, IPPROTO_TCP, true));
+ CHECK(!pb_implicit_direct(AF_INET6, (a6(a, "2001:db8::1"), a), 80, IPPROTO_TCP, true));
+ // ---- domain rules
+ r = R("", "*.github.com;example.org;10.0.0.0/8", "443");
+ CHECK(r.ndomains == 2 && r.nhosts == 1 && !r.any_host);
+ const char *gh[] = { "api.github.com" }, *ex[] = { "EXAMPLE.org." }, *no[] = { "github.com", "notgithub.com", "example.org.evil.com" };
+ a4(a, "140.82.1.1");
+ CHECK(pb_rule_match_dest(&r, AF_INET, a, 443, gh, 1));
+ CHECK(pb_rule_match_dest(&r, AF_INET, a, 443, ex, 1)); // case-insensitive, trailing root dot tolerated
+ CHECK(!pb_rule_match_dest(&r, AF_INET, a, 443, no, 3)); // "*.github.com" does not match the bare apex; exact stays exact
+ CHECK(!pb_rule_match_dest(&r, AF_INET, a, 80, gh, 1)); // port still has to match
+ a4(a, "10.1.2.3"); CHECK(pb_rule_match_dest(&r, AF_INET, a, 443, NULL, 0)); // IP pattern in the same list still works
+ pb_rule_free(&r);
+ r = R("", "github.com;*.github.com", ""); CHECK(r.ndomains == 2); pb_rule_free(&r);
+ CHECK(pb_domain_match("a?c.com", "abc.com")); CHECK(!pb_domain_match("a?c.com", "abbc.com")); CHECK(pb_domain_match("*", "x.y"));
+ CHECK(bad("", "bad name.com", ""));
+ {
+ struct pb_rule c; r = R("curl", "*.example.com", "80"); CHECK(pb_rule_clone(&c, &r) && c.ndomains == 1 && !strcmp(c.domains[0], "*.example.com")); pb_rule_free(&c); pb_rule_free(&r);
+ }
+ printf(fails ? "RULES TESTS FAILED (%d)\n" : "rules tests passed\n", fails);
+ return fails != 0;
+}
diff --git a/Linux/src/tests/run_relay_test.sh b/Linux/src/tests/run_relay_test.sh
new file mode 100755
index 0000000..23b86ed
--- /dev/null
+++ b/Linux/src/tests/run_relay_test.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+# Builds and runs the root-free relay test (loopback only). Usage: run_relay_test.sh [plain|asan|both] (default both)
+set -e
+cd "$(dirname "$0")"
+mode="${1:-both}"
+out="${TMPDIR:-/tmp}"
+CF="-std=gnu11 -Wall -Wextra -O1 -g -D_GNU_SOURCE -fstack-protector-strong -I.. "
+if [ "$mode" = plain ] || [ "$mode" = both ]; then
+ gcc $CF -O2 relay_test.c ../pb_relay.c -o "$out/relay_test" -lpthread
+ "$out/relay_test"
+fi
+if [ "$mode" = asan ] || [ "$mode" = both ]; then
+ gcc $CF -fsanitize=address,undefined -fno-omit-frame-pointer relay_test.c ../pb_relay.c -o "$out/relay_test_asan" -lpthread
+ LARGE_MB="${LARGE_MB:-4}" THRU_MB="${THRU_MB:-32}" ASAN_OPTIONS=detect_leaks=1 UBSAN_OPTIONS=halt_on_error=1:print_stacktrace=1 "$out/relay_test_asan"
+fi