Skip to content

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

feat(linux/cli): --profile and --list-profiles, .pbprofile reader/writer shared with the Windows format

anof-cyberaffde029e522
diff --git a/Linux/cli/Makefile b/Linux/cli/Makefile
index ed4e85d..d4f10d8 100644
--- a/Linux/cli/Makefile
+++ b/Linux/cli/Makefile
@@ -4,12 +4,12 @@ include ../common.mk
BUILD_DIR ?= .
LIBDIR ?= ../src
-CFLAGS = $(CFLAGS_COMMON) -fPIE -I../src
+CFLAGS = $(CFLAGS_COMMON) -fPIE -I../src -I../profile
LDFLAGS = -pie $(HARDEN_LDFLAGS) -L$(LIBDIR) -Wl,-rpath,/usr/local/lib $(STRIP_FLAG)
LIBS = -lproxybridge -lpthread
TARGET = $(BUILD_DIR)/ProxyBridge
-OBJECTS = $(BUILD_DIR)/main.o
+OBJECTS = $(BUILD_DIR)/main.o $(BUILD_DIR)/pb_profile.o
all: $(TARGET)
@@ -22,6 +22,9 @@ $(TARGET): $(OBJECTS)
$(BUILD_DIR)/%.o: %.c | $(BUILD_DIR)
$(CC) $(CFLAGS) -c $< -o $@
+$(BUILD_DIR)/pb_profile.o: ../profile/pb_profile.c ../profile/pb_profile.h | $(BUILD_DIR)
+ $(CC) $(CFLAGS) -c $< -o $@
+
clean:
rm -f $(OBJECTS) $(TARGET)
diff --git a/Linux/cli/main.c b/Linux/cli/main.c
index dc43640..81cd9d6 100644
--- a/Linux/cli/main.c
+++ b/Linux/cli/main.c
@@ -5,16 +5,20 @@
#include <signal.h>
#include <stdbool.h>
#include <ctype.h>
+#include <dirent.h>
+#include <sys/stat.h>
#include "../src/ProxyBridge.h"
+#include "../profile/pb_profile.h"
-#define MAX_RULES 100
-#define MAX_PROXIES 32
-#define MAX_RULE_STR 1024
+#define MAX_RULES 1024
+#define MAX_PROXIES 64
+#define MAX_RULE_STR 2048
+#define FIELD 512 /* same limit as the library */
typedef struct {
- char process_name[256];
- char target_hosts[256];
- char target_ports[256];
+ char process_name[FIELD];
+ char target_hosts[FIELD];
+ char target_ports[FIELD];
RuleProtocol protocol;
RuleAction action;
char proxy_ref[64]; /* proxy name or 1-based index; empty = default */
@@ -105,6 +109,11 @@ static void show_help(const char* prog)
printf(" *:*:53:UDP:PROXY=tor\n");
printf(" firefox:*.github.com;github.com:443:TCP:PROXY=work\n\n");
+ printf(" --profile <name|file> Load proxies and rules from a .pbprofile (a file path, or the name of a profile saved\n");
+ printf(" by the GUI). Same format as the Windows and macOS apps; repeatable, and can be\n");
+ printf(" combined with --proxy and --rule. Disabled rules are skipped.\n");
+ printf(" --list-profiles List the profiles saved by the GUI and exit\n\n");
+
printf(" --dns-via-proxy <bool> Route DNS queries through the proxy (true/false/1/0, default true)\n\n");
printf(" --verbose <level> 0 none (default), 1 logs, 2 connections, 3 both\n\n");
@@ -114,6 +123,8 @@ static void show_help(const char* prog)
printf(" --help, -h Show this help message\n\n");
printf("EXAMPLES:\n");
+ printf(" sudo %s --profile work\n", prog);
+ printf(" sudo %s --profile ./myconfig.pbprofile --verbose 2\n\n", prog);
printf(" sudo %s --rule curl:*:*:TCP:PROXY\n\n", prog);
printf(" sudo %s --proxy socks5://192.168.1.10:1080 --proxy work=http://proxy.corp:8080 \\\n", prog);
printf(" --rule firefox:*:*:BOTH:PROXY --rule curl:*:*:TCP:PROXY=work --verbose 2\n\n");
@@ -316,6 +327,118 @@ static uint32_t find_proxy(const ProxyEntry* proxies, int n, const char* ref)
return UINT32_MAX;
}
+static const char* profile_default_ref = NULL;
+static char profile_default_name[64];
+
+/* Appends the proxies and rules of a .pbprofile (a path, or the name of a profile saved by the GUI). */
+static bool load_profile(const char* arg, ProxyEntry* proxies, int* num_proxies, ProxyRule* rules, int* num_rules, bool* dns)
+{
+ char* path = pbp_resolve(pbp_config_dir(), arg);
+ char err[256];
+ struct pbp_profile prof;
+ if (!path)
+ {
+ fprintf(stderr, "ERROR: Invalid profile '%s'\n", arg);
+ return false;
+ }
+ if (pbp_load_file(path, &prof, err, sizeof(err)) != 0)
+ {
+ fprintf(stderr, "ERROR: %s\n", err);
+ free(path);
+ return false;
+ }
+
+ struct stat st;
+ bool has_secret = false;
+ for (size_t i = 0; i < prof.nproxies; i++)
+ if (prof.proxies[i].pass[0]) has_secret = true;
+ if (has_secret && stat(path, &st) == 0 && (st.st_mode & 077))
+ fprintf(stderr, "WARNING: %s holds proxy credentials but other users can read it (chmod 600 recommended)\n", path);
+ printf("Profile: %s\n", path);
+ free(path);
+
+ bool ok = true;
+ if ((size_t)*num_proxies + prof.nproxies > MAX_PROXIES || (size_t)*num_rules + prof.nrules > MAX_RULES)
+ {
+ fprintf(stderr, "ERROR: Profile has too many proxies (max %d) or rules (max %d)\n", MAX_PROXIES, MAX_RULES);
+ ok = false;
+ }
+ for (size_t i = 0; ok && i < prof.nproxies; i++)
+ {
+ ProxyEntry* p = &proxies[(*num_proxies)++];
+ memset(p, 0, sizeof(*p));
+ snprintf(p->name, sizeof(p->name), "%s", prof.proxies[i].name);
+ p->type = prof.proxies[i].type ? PROXY_TYPE_SOCKS5 : PROXY_TYPE_HTTP;
+ snprintf(p->host, sizeof(p->host), "%s", prof.proxies[i].host);
+ p->port = prof.proxies[i].port;
+ snprintf(p->username, sizeof(p->username), "%s", prof.proxies[i].user);
+ snprintf(p->password, sizeof(p->password), "%s", prof.proxies[i].pass);
+ }
+ for (size_t i = 0; ok && i < prof.nrules; i++)
+ {
+ const struct pbp_rule* r = &prof.rules[i];
+ ProxyRule* out = &rules[*num_rules];
+ if (strlen(r->process) >= FIELD || strlen(r->hosts) >= FIELD || strlen(r->ports) >= FIELD)
+ {
+ fprintf(stderr, "ERROR: Profile rule %zu has a field longer than %d characters\n", i + 1, FIELD - 1);
+ ok = false;
+ break;
+ }
+ if (!r->enabled)
+ continue;
+ memset(out, 0, sizeof(*out));
+ snprintf(out->process_name, sizeof(out->process_name), "%s", r->process);
+ snprintf(out->target_hosts, sizeof(out->target_hosts), "%s", r->hosts);
+ snprintf(out->target_ports, sizeof(out->target_ports), "%s", r->ports);
+ out->protocol = (RuleProtocol)r->protocol;
+ out->action = (RuleAction)r->action;
+ const struct pbp_proxy* px = r->action == RULE_ACTION_PROXY && r->proxy_id ? pbp_find_proxy(&prof, r->proxy_id) : NULL;
+ if (px)
+ snprintf(out->proxy_ref, sizeof(out->proxy_ref), "%s", px->name);
+ (*num_rules)++;
+ }
+ if (ok && prof.default_proxy_id)
+ {
+ const struct pbp_proxy* d = pbp_find_proxy(&prof, prof.default_proxy_id);
+ if (d)
+ {
+ snprintf(profile_default_name, sizeof(profile_default_name), "%s", d->name);
+ profile_default_ref = profile_default_name;
+ }
+ }
+ *dns = prof.dns_via_proxy;
+ pbp_free(&prof);
+ return ok;
+}
+
+static int list_profiles(void)
+{
+ char dir[1024];
+ snprintf(dir, sizeof(dir), "%s/profiles", pbp_config_dir());
+ DIR* d = opendir(dir);
+ if (!d)
+ {
+ fprintf(stderr, "No profiles directory at %s\n", dir);
+ return 1;
+ }
+ struct dirent* de;
+ int n = 0;
+ while ((de = readdir(d)) != NULL)
+ {
+ char* name = pbp_name_from_filename(de->d_name);
+ if (name)
+ {
+ printf("%s\n", name);
+ n++;
+ }
+ free(name);
+ }
+ closedir(d);
+ if (!n)
+ fprintf(stderr, "No profiles in %s\n", dir);
+ return 0;
+}
+
static bool is_root(void)
{
return getuid() == 0;
@@ -323,11 +446,12 @@ static bool is_root(void)
int main(int argc, char *argv[])
{
- ProxyEntry proxies[MAX_PROXIES];
+ static ProxyEntry proxies[MAX_PROXIES];
int num_proxies = 0;
- ProxyRule rules[MAX_RULES];
+ static ProxyRule rules[MAX_RULES];
int num_rules = 0;
bool dns_via_proxy = true;
+ bool dns_explicit = false;
for (int i = 1; i < argc; i++)
{
@@ -338,6 +462,12 @@ int main(int argc, char *argv[])
}
}
+ for (int i = 1; i < argc; i++)
+ {
+ if (strcmp(argv[i], "--list-profiles") == 0)
+ return list_profiles();
+ }
+
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0)
@@ -357,6 +487,14 @@ int main(int argc, char *argv[])
memset(argv[i], 0, strlen(argv[i])); /* keep credentials out of `ps` */
num_proxies++;
}
+ else if (strcmp(argv[i], "--profile") == 0 && i + 1 < argc)
+ {
+ bool dns = dns_via_proxy;
+ if (!load_profile(argv[++i], proxies, &num_proxies, rules, &num_rules, &dns))
+ return 1;
+ if (!dns_explicit)
+ dns_via_proxy = dns;
+ }
else if (strcmp(argv[i], "--rule") == 0 && i + 1 < argc)
{
if (num_rules >= MAX_RULES)
@@ -371,6 +509,7 @@ int main(int argc, char *argv[])
else if (strcmp(argv[i], "--dns-via-proxy") == 0 && i + 1 < argc)
{
char* value = argv[++i];
+ dns_explicit = true;
if (strcmp(value, "true") == 0 || strcmp(value, "1") == 0)
dns_via_proxy = true;
else if (strcmp(value, "false") == 0 || strcmp(value, "0") == 0)
@@ -441,6 +580,12 @@ int main(int argc, char *argv[])
printf(" [%d]%s%s%s %s://%s:%u%s\n", i + 1, p->name[0] ? " " : "", p->name, i == 0 ? " (default)" : "",
p->type == PROXY_TYPE_HTTP ? "http" : "socks5", p->host, p->port, p->username[0] ? " (auth)" : "");
}
+ if (profile_default_ref)
+ {
+ uint32_t def = find_proxy(proxies, num_proxies, profile_default_ref);
+ if (def != UINT32_MAX && def != 0)
+ ProxyBridge_SetDefaultProxy(def);
+ }
printf("DNS via Proxy: %s\n", dns_via_proxy ? "Enabled" : "Disabled");
if (num_rules > 0)
diff --git a/Linux/profile/pb_profile.c b/Linux/profile/pb_profile.c
new file mode 100644
index 0000000..90e85e9
--- /dev/null
+++ b/Linux/profile/pb_profile.c
@@ -0,0 +1,804 @@
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+#include "pb_profile.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+// ---- minimal JSON reader: bounded depth and node count, everything copied out of the input ----
+
+enum { J_NULL, J_BOOL, J_NUM, J_STR, J_ARR, J_OBJ };
+#define MAX_DEPTH 12
+#define MAX_NODES 200000
+
+struct jv {
+ int t;
+ bool b;
+ double n;
+ char *s;
+ struct jv *kid;
+ char **key;
+ size_t nk, cap;
+};
+
+struct jp {
+ const char *p, *end;
+ unsigned nodes;
+ char *err;
+ size_t errlen;
+};
+
+static void jfree(struct jv *v)
+{
+ free(v->s);
+ for (size_t i = 0; i < v->nk; i++) {
+ jfree(&v->kid[i]);
+ if (v->key) free(v->key[i]);
+ }
+ free(v->kid);
+ free(v->key);
+ memset(v, 0, sizeof *v);
+}
+
+static int jfail(struct jp *j, const char *fmt, ...)
+{
+ if (j->err && j->errlen) {
+ va_list ap;
+ va_start(ap, fmt);
+ vsnprintf(j->err, j->errlen, fmt, ap);
+ va_end(ap);
+ }
+ return -1;
+}
+
+static void skip_ws(struct jp *j)
+{
+ while (j->p < j->end && (*j->p == ' ' || *j->p == '\t' || *j->p == '\n' || *j->p == '\r')) j->p++;
+}
+
+static int hex4(const char *p)
+{
+ int v = 0;
+ for (int i = 0; i < 4; i++) {
+ char c = p[i];
+ v <<= 4;
+ if (c >= '0' && c <= '9') v |= c - '0';
+ else if (c >= 'a' && c <= 'f') v |= c - 'a' + 10;
+ else if (c >= 'A' && c <= 'F') v |= c - 'A' + 10;
+ else return -1;
+ }
+ return v;
+}
+
+static char *put_utf8(char *o, unsigned cp)
+{
+ if (cp < 0x80) *o++ = (char)cp;
+ else if (cp < 0x800) { *o++ = (char)(0xC0 | cp >> 6); *o++ = (char)(0x80 | (cp & 0x3F)); }
+ else if (cp < 0x10000) { *o++ = (char)(0xE0 | cp >> 12); *o++ = (char)(0x80 | ((cp >> 6) & 0x3F)); *o++ = (char)(0x80 | (cp & 0x3F)); }
+ else { *o++ = (char)(0xF0 | cp >> 18); *o++ = (char)(0x80 | ((cp >> 12) & 0x3F)); *o++ = (char)(0x80 | ((cp >> 6) & 0x3F)); *o++ = (char)(0x80 | (cp & 0x3F)); }
+ return o;
+}
+
+// j->p is on the opening quote. The decoded text is never longer than the raw text.
+static int parse_string(struct jp *j, char **out)
+{
+ const char *q = j->p + 1, *s = q;
+ while (q < j->end && *q != '"') q += (*q == '\\' && q + 1 < j->end) ? 2 : 1;
+ if (q >= j->end) return jfail(j, "unterminated string");
+ char *buf = malloc((size_t)(q - s) + 1), *o = buf;
+ if (!buf) return jfail(j, "out of memory");
+ for (const char *r = s; r < q; r++) {
+ if (*r != '\\') { *o++ = *r; continue; }
+ r++;
+ switch (*r) {
+ case 'n': *o++ = '\n'; break;
+ case 't': *o++ = '\t'; break;
+ case 'r': *o++ = '\r'; break;
+ case 'b': *o++ = '\b'; break;
+ case 'f': *o++ = '\f'; break;
+ case '"': case '\\': case '/': *o++ = *r; break;
+ case 'u': {
+ int cp = (q - r >= 5) ? hex4(r + 1) : -1;
+ if (cp < 0) { free(buf); return jfail(j, "bad \\u escape"); }
+ r += 4;
+ if (cp >= 0xD800 && cp < 0xDC00) {
+ int lo = (q - r >= 7 && r[1] == '\\' && r[2] == 'u') ? hex4(r + 3) : -1;
+ if (lo < 0xDC00 || lo > 0xDFFF) { free(buf); return jfail(j, "bad surrogate pair"); }
+ cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
+ r += 6;
+ } else if (cp >= 0xDC00 && cp <= 0xDFFF) { free(buf); return jfail(j, "bad surrogate pair"); }
+ if (cp == 0) { free(buf); return jfail(j, "NUL in string"); }
+ o = put_utf8(o, (unsigned)cp);
+ break;
+ }
+ default: free(buf); return jfail(j, "bad escape \\%c", *r);
+ }
+ }
+ *o = 0;
+ j->p = q + 1;
+ *out = buf;
+ return 0;
+}
+
+static int jadd(struct jv *c, char *key, struct jv *child)
+{
+ if (c->nk == c->cap) {
+ size_t n = c->cap ? c->cap * 2 : 8;
+ struct jv *k = realloc(c->kid, n * sizeof *k);
+ if (!k) return -1;
+ c->kid = k;
+ char **ks = realloc(c->key, n * sizeof *ks);
+ if (!ks) return -1;
+ c->key = ks;
+ c->cap = n;
+ }
+ c->kid[c->nk] = *child;
+ c->key[c->nk] = key;
+ c->nk++;
+ return 0;
+}
+
+static int parse_value(struct jp *j, struct jv *v, int depth);
+
+static int parse_container(struct jp *j, struct jv *v, int depth, bool obj)
+{
+ char close = obj ? '}' : ']';
+ v->t = obj ? J_OBJ : J_ARR;
+ j->p++;
+ skip_ws(j);
+ if (j->p < j->end && *j->p == close) { j->p++; return 0; }
+ for (;;) {
+ char *key = NULL;
+ skip_ws(j);
+ if (obj) {
+ if (j->p >= j->end || *j->p != '"') return jfail(j, "expected a key");
+ if (parse_string(j, &key) < 0) return -1;
+ skip_ws(j);
+ if (j->p >= j->end || *j->p != ':') { free(key); return jfail(j, "expected ':'"); }
+ j->p++;
+ }
+ struct jv child = {0};
+ if (parse_value(j, &child, depth + 1) < 0 || jadd(v, key, &child) < 0) {
+ jfree(&child);
+ free(key);
+ return j->err && j->err[0] ? -1 : jfail(j, "out of memory");
+ }
+ skip_ws(j);
+ if (j->p < j->end && *j->p == ',') { j->p++; continue; }
+ if (j->p < j->end && *j->p == close) { j->p++; return 0; }
+ return jfail(j, "expected ',' or '%c'", close);
+ }
+}
+
+static int parse_value(struct jp *j, struct jv *v, int depth)
+{
+ if (depth > MAX_DEPTH) return jfail(j, "nested too deeply");
+ if (++j->nodes > MAX_NODES) return jfail(j, "too many values");
+ skip_ws(j);
+ if (j->p >= j->end) return jfail(j, "unexpected end of file");
+ char c = *j->p;
+ if (c == '{' || c == '[') return parse_container(j, v, depth, c == '{');
+ if (c == '"') { v->t = J_STR; return parse_string(j, &v->s); }
+ size_t left = (size_t)(j->end - j->p);
+ if (left >= 4 && !strncmp(j->p, "true", 4)) { v->t = J_BOOL; v->b = true; j->p += 4; return 0; }
+ if (left >= 5 && !strncmp(j->p, "false", 5)) { v->t = J_BOOL; j->p += 5; return 0; }
+ if (left >= 4 && !strncmp(j->p, "null", 4)) { v->t = J_NULL; j->p += 4; return 0; }
+ if (c == '-' || (c >= '0' && c <= '9')) {
+ bool neg = c == '-';
+ double n = 0;
+ j->p += neg;
+ if (j->p >= j->end || *j->p < '0' || *j->p > '9') return jfail(j, "bad number");
+ while (j->p < j->end && *j->p >= '0' && *j->p <= '9') n = n * 10 + (*j->p++ - '0');
+ if (j->p < j->end && *j->p == '.') {
+ j->p++;
+ while (j->p < j->end && *j->p >= '0' && *j->p <= '9') j->p++;
+ }
+ if (j->p < j->end && (*j->p == 'e' || *j->p == 'E')) {
+ j->p++;
+ if (j->p < j->end && (*j->p == '+' || *j->p == '-')) j->p++;
+ while (j->p < j->end && *j->p >= '0' && *j->p <= '9') j->p++;
+ }
+ v->t = J_NUM;
+ v->n = neg ? -n : n;
+ return 0;
+ }
+ return jfail(j, "unexpected character '%c'", c);
+}
+
+static const struct jv *jget(const struct jv *o, const char *key)
+{
+ if (o->t != J_OBJ) return NULL;
+ for (size_t i = 0; i < o->nk; i++)
+ if (!strcasecmp(o->key[i], key)) return &o->kid[i];
+ return NULL;
+}
+
+// Text of a string value, or of a whole number (older files store ports and ids either way).
+static char *jtext(const struct jv *o, const char *key)
+{
+ const struct jv *v = jget(o, key);
+ if (!v) return NULL;
+ if (v->t == J_STR) return strdup(v->s);
+ if (v->t == J_NUM && v->n >= 0 && v->n < 4294967296.0) {
+ char b[24];
+ snprintf(b, sizeof b, "%.0f", v->n);
+ return strdup(b);
+ }
+ return NULL;
+}
+
+static bool jbool(const struct jv *o, const char *key, bool def)
+{
+ const struct jv *v = jget(o, key);
+ if (!v) return def;
+ if (v->t == J_BOOL) return v->b;
+ if (v->t == J_STR) return !strcasecmp(v->s, "true") ? true : !strcasecmp(v->s, "false") ? false : def;
+ return def;
+}
+
+static long jnum(const struct jv *o, const char *key, long def)
+{
+ const struct jv *v = jget(o, key);
+ if (!v) return def;
+ if (v->t == J_NUM) return (v->n >= 0 && v->n < 4294967296.0) ? (long)v->n : -1;
+ if (v->t == J_STR) {
+ const char *s = v->s;
+ long n = 0;
+ if (!*s) return def;
+ for (; *s; s++) {
+ if (*s < '0' || *s > '9' || n > 99999999) return -1;
+ n = n * 10 + (*s - '0');
+ }
+ return n;
+ }
+ return -1;
+}
+
+// ---- host list helpers ----
+
+static bool is_sep(char c) { return c == ';' || c == ','; }
+
+// Anything made only of digits and the IP pattern characters is an address pattern; IPv6 has a ':'.
+static bool token_is_domain(const char *t, size_t n)
+{
+ for (size_t i = 0; i < n; i++)
+ if (t[i] == ':') return false;
+ for (size_t i = 0; i < n; i++)
+ if (!((t[i] >= '0' && t[i] <= '9') || t[i] == '.' || t[i] == '*' || t[i] == '-' || t[i] == '/' || t[i] == '?')) return true;
+ return false;
+}
+
+static void append_token(char **dst, size_t *len, const char *t, size_t n)
+{
+ char *b = realloc(*dst, *len + n + 2);
+ if (!b) return;
+ if (*len) b[(*len)++] = ';';
+ memcpy(b + *len, t, n);
+ *len += n;
+ b[*len] = 0;
+ *dst = b;
+}
+
+void pbp_split_hosts(const char *hosts, char **ips, char **domains)
+{
+ char *a = NULL, *d = NULL;
+ size_t la = 0, ld = 0;
+ for (const char *p = hosts ? hosts : ""; *p;) {
+ while (*p && (is_sep(*p) || *p == ' ' || *p == '\t')) p++;
+ const char *s = p;
+ while (*p && !is_sep(*p)) p++;
+ const char *e = p;
+ while (e > s && (e[-1] == ' ' || e[-1] == '\t')) e--;
+ if (e == s) continue;
+ if (token_is_domain(s, (size_t)(e - s))) append_token(&d, &ld, s, (size_t)(e - s));
+ else append_token(&a, &la, s, (size_t)(e - s));
+ }
+ *ips = a ? a : strdup("");
+ *domains = d ? d : strdup("");
+}
+
+char *pbp_merge_hosts(const char *ips, const char *domains)
+{
+ char *a = NULL, *d = NULL;
+ size_t la = 0, ld = 0;
+ // normalise both lists to ';' separated, trimmed tokens
+ for (int pass = 0; pass < 2; pass++) {
+ for (const char *p = pass ? (domains ? domains : "") : (ips ? ips : ""); *p;) {
+ while (*p && (is_sep(*p) || *p == ' ' || *p == '\t')) p++;
+ const char *s = p;
+ while (*p && !is_sep(*p)) p++;
+ const char *e = p;
+ while (e > s && (e[-1] == ' ' || e[-1] == '\t')) e--;
+ if (e > s) append_token(pass ? &d : &a, pass ? &ld : &la, s, (size_t)(e - s));
+ }
+ }
+ bool any = !a || !strcmp(a, "*");
+ char *out;
+ if (!d) out = strdup(any ? "*" : a);
+ else if (any) out = strdup(d);
+ else if (asprintf(&out, "%s;%s", a, d) < 0) out = NULL;
+ free(a);
+ free(d);
+ return out;
+}
+
+// ---- profile <-> JSON ----
+
+void pbp_free(struct pbp_profile *p)
+{
+ if (!p) return;
+ for (size_t i = 0; i < p->nproxies; i++) {
+ free(p->proxies[i].name); free(p->proxies[i].host); free(p->proxies[i].user); free(p->proxies[i].pass);
+ }
+ for (size_t i = 0; i < p->nrules; i++) {
+ free(p->rules[i].process); free(p->rules[i].hosts); free(p->rules[i].ports);
+ }
+ free(p->proxies);
+ free(p->rules);
+ free(p->name);
+ memset(p, 0, sizeof *p);
+}
+
+struct pbp_proxy *pbp_find_proxy(const struct pbp_profile *p, uint32_t id)
+{
+ for (size_t i = 0; i < p->nproxies; i++)
+ if (p->proxies[i].id == id) return &p->proxies[i];
+ return NULL;
+}
+
+static char *dup_or(char *s, const char *def)
+{
+ if (s && *s) return s;
+ free(s);
+ return strdup(def);
+}
+
+// Only the proxies before the one being read count: it is already included in nproxies.
+static bool name_taken(const struct pbp_profile *p, const char *name)
+{
+ for (size_t i = 0; i + 1 < p->nproxies; i++)
+ if (!strcmp(p->proxies[i].name, name)) return true;
+ return false;
+}
+
+static int read_proxy(struct pbp_profile *p, const struct jv *o, size_t idx, char *err, size_t errlen)
+{
+ struct pbp_proxy *x = &p->proxies[p->nproxies];
+ memset(x, 0, sizeof *x);
+ p->nproxies++; // counted first so pbp_free releases a half-built entry
+
+ char *type = jtext(o, "Type");
+ long port = jnum(o, "Port", 0);
+ x->host = jtext(o, "Host");
+ if (!x->host || !*x->host || port < 1 || port > 65535) {
+ free(type);
+ snprintf(err, errlen, "ProxyConfigs[%zu]: needs a Host and a Port between 1 and 65535", idx);
+ return -1;
+ }
+ x->port = (uint16_t)port;
+ if (type && (!strcasecmp(type, "socks5") || !strcasecmp(type, "socks"))) x->type = 1;
+ else if (type && (!strcasecmp(type, "http") || !strcasecmp(type, "https"))) x->type = 0;
+ else {
+ snprintf(err, errlen, "ProxyConfigs[%zu]: unknown Type '%s' (use SOCKS5 or HTTP)", idx, type ? type : "");
+ free(type);
+ return -1;
+ }
+ free(type);
+
+ long id = jnum(o, "Id", 0);
+ uint32_t want = id > 0 ? (uint32_t)id : 0;
+ uint32_t max = 0;
+ for (size_t i = 0; i + 1 < p->nproxies; i++) {
+ if (p->proxies[i].id > max) max = p->proxies[i].id;
+ if (p->proxies[i].id == want) want = 0;
+ }
+ x->id = want ? want : max + 1;
+
+ x->name = jtext(o, "Name");
+ if (!x->name || !*x->name || name_taken(p, x->name)) {
+ char fallback[48];
+ snprintf(fallback, sizeof fallback, "proxy%u", x->id);
+ free(x->name);
+ x->name = strdup(fallback);
+ }
+ x->user = dup_or(jtext(o, "Username"), "");
+ x->pass = dup_or(jtext(o, "Password"), "");
+ if (!x->name || !x->user || !x->pass) { snprintf(err, errlen, "out of memory"); return -1; }
+ return 0;
+}
+
+static int read_rule(struct pbp_profile *p, const struct jv *o, size_t idx, char *err, size_t errlen)
+{
+ struct pbp_rule *r = &p->rules[p->nrules];
+ memset(r, 0, sizeof *r);
+ p->nrules++;
+
+ char *hosts = jtext(o, "TargetHosts"), *domains = jtext(o, "TargetDomains");
+ r->hosts = pbp_merge_hosts(hosts, domains);
+ free(hosts);
+ free(domains);
+ r->process = dup_or(jtext(o, "ProcessName"), "*");
+ r->ports = dup_or(jtext(o, "TargetPorts"), "*");
+ if (!r->hosts || !r->process || !r->ports) { snprintf(err, errlen, "out of memory"); return -1; }
+
+ char *proto = jtext(o, "Protocol"), *act = jtext(o, "Action");
+ int rc = 0;
+ if (!proto || !*proto || !strcasecmp(proto, "TCP")) r->protocol = 0;
+ else if (!strcasecmp(proto, "UDP")) r->protocol = 1;
+ else if (!strcasecmp(proto, "BOTH")) r->protocol = 2;
+ else { snprintf(err, errlen, "ProxyRules[%zu]: unknown Protocol '%s'", idx, proto); rc = -1; }
+ if (!rc) {
+ if (!act || !*act || !strcasecmp(act, "PROXY")) r->action = 0;
+ else if (!strcasecmp(act, "DIRECT")) r->action = 1;
+ else if (!strcasecmp(act, "BLOCK")) r->action = 2;
+ else { snprintf(err, errlen, "ProxyRules[%zu]: unknown Action '%s'", idx, act); rc = -1; }
+ }
+ free(proto);
+ free(act);
+ if (rc) return rc;
+
+ r->enabled = jbool(o, "IsEnabled", true);
+ long pid = jnum(o, "ProxyConfigId", 0);
+ if (pid < 0 || (pid > 0 && !pbp_find_proxy(p, (uint32_t)pid))) {
+ snprintf(err, errlen, "ProxyRules[%zu]: ProxyConfigId %ld does not match any proxy", idx, pid);
+ return -1;
+ }
+ r->proxy_id = (uint32_t)pid;
+ return 0;
+}
+
+int pbp_parse(const char *json, size_t len, struct pbp_profile *out, char *err, size_t errlen)
+{
+ memset(out, 0, sizeof *out);
+ if (len > PBP_MAX_FILE) { snprintf(err, errlen, "file is larger than %u MiB", PBP_MAX_FILE >> 20); return -1; }
+ char *copy = malloc(len + 1);
+ if (!copy) { snprintf(err, errlen, "out of memory"); return -1; }
+ memcpy(copy, json, len);
+ copy[len] = 0;
+
+ err[0] = 0;
+ struct jp j = { copy, copy + len, 0, err, errlen };
+ struct jv root = {0};
+ if (len >= 3 && !memcmp(copy, "\xEF\xBB\xBF", 3)) j.p += 3; // editors on Windows add a BOM
+ int rc = parse_value(&j, &root, 0);
+ if (rc == 0) {
+ skip_ws(&j);
+ if (j.p != j.end) rc = jfail(&j, "unexpected data after the profile");
+ else if (root.t != J_OBJ) rc = jfail(&j, "a profile is a JSON object");
+ }
+ if (rc < 0) {
+ char tmp[200];
+ snprintf(tmp, sizeof tmp, "not a valid profile: %s", err[0] ? err : "parse error");
+ snprintf(err, errlen, "%s", tmp);
+ jfree(&root);
+ free(copy);
+ return -1;
+ }
+
+ const struct jv *cfgs = jget(&root, "ProxyConfigs"), *rules = jget(&root, "ProxyRules");
+ if ((cfgs && cfgs->t != J_ARR) || (rules && rules->t != J_ARR)) {
+ snprintf(err, errlen, "ProxyConfigs and ProxyRules must be arrays");
+ rc = -1;
+ } else if ((cfgs && cfgs->nk > PBP_MAX_PROXIES) || (rules && rules->nk > PBP_MAX_RULES)) {
+ snprintf(err, errlen, "too many proxies (max %d) or rules (max %d)", PBP_MAX_PROXIES, PBP_MAX_RULES);
+ rc = -1;
+ }
+ if (rc == 0) {
+ out->name = jtext(&root, "Name");
+ out->logging = jbool(&root, "IsTrafficLoggingEnabled", true);
+ out->dns_via_proxy = jbool(&root, "DnsViaProxy", true);
+ long dp = jnum(&root, "DefaultProxyId", 0);
+ out->default_proxy_id = dp > 0 ? (uint32_t)dp : 0;
+ if (cfgs && cfgs->nk) out->proxies = calloc(cfgs->nk, sizeof *out->proxies);
+ if (rules && rules->nk) out->rules = calloc(rules->nk, sizeof *out->rules);
+ if ((cfgs && cfgs->nk && !out->proxies) || (rules && rules->nk && !out->rules)) {
+ snprintf(err, errlen, "out of memory");
+ rc = -1;
+ }
+ }
+ for (size_t i = 0; rc == 0 && cfgs && i < cfgs->nk; i++)
+ rc = cfgs->kid[i].t == J_OBJ ? read_proxy(out, &cfgs->kid[i], i, err, errlen)
+ : (snprintf(err, errlen, "ProxyConfigs[%zu] is not an object", i), -1);
+ for (size_t i = 0; rc == 0 && rules && i < rules->nk; i++)
+ rc = rules->kid[i].t == J_OBJ ? read_rule(out, &rules->kid[i], i, err, errlen)
+ : (snprintf(err, errlen, "ProxyRules[%zu] is not an object", i), -1);
+ if (rc == 0 && out->default_proxy_id && !pbp_find_proxy(out, out->default_proxy_id)) {
+ snprintf(err, errlen, "DefaultProxyId %u does not match any proxy", out->default_proxy_id);
+ rc = -1;
+ }
+ jfree(&root);
+ free(copy);
+ if (rc) pbp_free(out);
+ return rc;
+}
+
+// ---- serializer ----
+
+struct sb { char *p; size_t len, cap; bool oom; };
+
+static void sb_add(struct sb *b, const char *s, size_t n)
+{
+ if (b->oom) return;
+ if (b->len + n + 1 > b->cap) {
+ size_t c = b->cap ? b->cap : 1024;
+ while (c < b->len + n + 1) c *= 2;
+ char *np = realloc(b->p, c);
+ if (!np) { b->oom = true; return; }
+ b->p = np;
+ b->cap = c;
+ }
+ memcpy(b->p + b->len, s, n);
+ b->len += n;
+ b->p[b->len] = 0;
+}
+
+static void sb_puts(struct sb *b, const char *s) { sb_add(b, s, strlen(s)); }
+
+static void sb_fmt(struct sb *b, const char *fmt, ...)
+{
+ char t[64];
+ va_list ap;
+ va_start(ap, fmt);
+ int n = vsnprintf(t, sizeof t, fmt, ap);
+ va_end(ap);
+ if (n > 0 && (size_t)n < sizeof t) sb_add(b, t, (size_t)n);
+}
+
+static void sb_str(struct sb *b, const char *s)
+{
+ sb_add(b, "\"", 1);
+ for (; s && *s; s++) {
+ unsigned char c = (unsigned char)*s;
+ switch (c) {
+ case '"': sb_puts(b, "\\\""); break;
+ case '\\': sb_puts(b, "\\\\"); break;
+ case '\n': sb_puts(b, "\\n"); break;
+ case '\r': sb_puts(b, "\\r"); break;
+ case '\t': sb_puts(b, "\\t"); break;
+ default:
+ if (c < 0x20) { char u[8]; snprintf(u, sizeof u, "\\u%04x", c); sb_puts(b, u); }
+ else sb_add(b, (const char *)&c, 1);
+ }
+ }
+ sb_add(b, "\"", 1);
+}
+
+static void sb_kv(struct sb *b, const char *indent, const char *key, const char *val, const char *tail)
+{
+ sb_puts(b, indent);
+ sb_str(b, key);
+ sb_puts(b, ": ");
+ sb_str(b, val);
+ sb_puts(b, tail);
+}
+
+char *pbp_serialize(const struct pbp_profile *p)
+{
+ struct sb b = {0};
+ sb_puts(&b, "{\n \"Version\": \"1.0\",\n");
+ sb_kv(&b, " ", "Name", p->name ? p->name : "", ",\n");
+ sb_puts(&b, " \"LocalhostViaProxy\": false,\n");
+ sb_puts(&b, p->logging ? " \"IsTrafficLoggingEnabled\": true,\n" : " \"IsTrafficLoggingEnabled\": false,\n");
+ sb_puts(&b, p->dns_via_proxy ? " \"DnsViaProxy\": true,\n" : " \"DnsViaProxy\": false,\n");
+ sb_fmt(&b, " \"DefaultProxyId\": %u,\n", p->default_proxy_id);
+
+ sb_puts(&b, " \"ProxyConfigs\": [");
+ for (size_t i = 0; i < p->nproxies; i++) {
+ const struct pbp_proxy *x = &p->proxies[i];
+ char port[8];
+ snprintf(port, sizeof port, "%u", x->port);
+ sb_puts(&b, i ? ",\n {\n" : "\n {\n");
+ sb_fmt(&b, " \"Id\": %u,\n", x->id);
+ sb_kv(&b, " ", "Name", x->name, ",\n");
+ sb_kv(&b, " ", "Type", x->type ? "SOCKS5" : "HTTP", ",\n");
+ sb_kv(&b, " ", "Host", x->host, ",\n");
+ sb_kv(&b, " ", "Port", port, ",\n");
+ sb_kv(&b, " ", "Username", x->user, ",\n");
+ sb_kv(&b, " ", "Password", x->pass, ",\n");
+ sb_puts(&b, " \"SendDomainToProxy\": false\n }");
+ }
+ sb_puts(&b, p->nproxies ? "\n ],\n" : "],\n");
+
+ sb_puts(&b, " \"ProxyRules\": [");
+ for (size_t i = 0; i < p->nrules; i++) {
+ const struct pbp_rule *r = &p->rules[i];
+ char *ips, *doms;
+ pbp_split_hosts(r->hosts, &ips, &doms);
+ sb_puts(&b, i ? ",\n {\n" : "\n {\n");
+ sb_kv(&b, " ", "Name", "", ",\n");
+ sb_kv(&b, " ", "ProcessName", r->process, ",\n");
+ sb_kv(&b, " ", "TargetHosts", ips && *ips ? ips : "*", ",\n");
+ sb_kv(&b, " ", "TargetPorts", r->ports, ",\n");
+ sb_kv(&b, " ", "TargetDomains", doms ? doms : "", ",\n");
+ sb_kv(&b, " ", "Protocol", r->protocol == 1 ? "UDP" : r->protocol == 2 ? "BOTH" : "TCP", ",\n");
+ sb_kv(&b, " ", "Action", r->action == 1 ? "DIRECT" : r->action == 2 ? "BLOCK" : "PROXY", ",\n");
+ sb_puts(&b, r->enabled ? " \"IsEnabled\": true,\n" : " \"IsEnabled\": false,\n");
+ sb_fmt(&b, " \"ProxyConfigId\": %u\n }", r->proxy_id);
+ free(ips);
+ free(doms);
+ }
+ sb_puts(&b, p->nrules ? "\n ]\n}\n" : "]\n}\n");
+ if (b.oom) { free(b.p); return NULL; }
+ return b.p;
+}
+
+// ---- files ----
+
+int pbp_load_file(const char *path, struct pbp_profile *out, char *err, size_t errlen)
+{
+ memset(out, 0, sizeof *out);
+ int fd = open(path, O_RDONLY | O_CLOEXEC);
+ if (fd < 0) { snprintf(err, errlen, "cannot open %s: %s", path, strerror(errno)); return -1; }
+ struct stat st;
+ if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
+ close(fd);
+ snprintf(err, errlen, "%s is not a regular file", path);
+ return -1;
+ }
+ if (st.st_size <= 0 || (unsigned long)st.st_size > PBP_MAX_FILE) {
+ close(fd);
+ snprintf(err, errlen, st.st_size <= 0 ? "%s is empty" : "%s is too large", path);
+ return -1;
+ }
+ size_t n = (size_t)st.st_size, got = 0;
+ char *buf = malloc(n);
+ while (buf && got < n) {
+ ssize_t r = read(fd, buf + got, n - got);
+ if (r < 0 && errno == EINTR) continue;
+ if (r <= 0) break;
+ got += (size_t)r;
+ }
+ close(fd);
+ if (!buf || got != n) {
+ free(buf);
+ snprintf(err, errlen, "cannot read %s", path);
+ return -1;
+ }
+ int rc = pbp_parse(buf, n, out, err, errlen);
+ free(buf);
+ return rc;
+}
+
+int pbp_write_file(const char *path, const char *data, char *err, size_t errlen)
+{
+ char *tmp = NULL;
+ if (asprintf(&tmp, "%s.tmp.XXXXXX", path) < 0) { snprintf(err, errlen, "out of memory"); return -1; }
+ int fd = mkstemp(tmp); // created 0600
+ int rc = -1;
+ if (fd < 0) {
+ snprintf(err, errlen, "cannot write %s: %s", path, strerror(errno));
+ } else {
+ size_t n = strlen(data), off = 0;
+ while (off < n) {
+ ssize_t w = write(fd, data + off, n - off);
+ if (w < 0 && errno == EINTR) continue;
+ if (w <= 0) break;
+ off += (size_t)w;
+ }
+ if (off == n && fsync(fd) == 0 && close(fd) == 0 && rename(tmp, path) == 0) rc = 0;
+ else {
+ snprintf(err, errlen, "cannot write %s: %s", path, strerror(errno));
+ close(fd);
+ unlink(tmp);
+ }
+ }
+ free(tmp);
+ return rc;
+}
+
+int pbp_save_file(const char *path, const struct pbp_profile *p, char *err, size_t errlen)
+{
+ char *json = pbp_serialize(p);
+ if (!json) { snprintf(err, errlen, "out of memory"); return -1; }
+ int rc = pbp_write_file(path, json, err, errlen);
+ free(json);
+ return rc;
+}
+
+int pbp_settings_load(const char *path, char **active, bool *logging, bool *dns)
+{
+ char err[200];
+ FILE *f = fopen(path, "r");
+ if (!f) return -1;
+ char *buf = malloc(65537);
+ size_t n = buf ? fread(buf, 1, 65536, f) : 0;
+ fclose(f);
+ if (!buf) return -1;
+ buf[n] = 0;
+ struct jp j = { buf, buf + n, 0, err, sizeof err };
+ struct jv root = {0};
+ int rc = parse_value(&j, &root, 0);
+ if (rc == 0 && root.t == J_OBJ) {
+ char *a = jtext(&root, "ActiveProfileName");
+ if (a && *a) { free(*active); *active = a; } else free(a);
+ *logging = jbool(&root, "IsTrafficLoggingEnabled", *logging);
+ *dns = jbool(&root, "DnsViaProxy", *dns);
+ } else rc = -1;
+ jfree(&root);
+ free(buf);
+ return rc;
+}
+
+int pbp_settings_save(const char *path, const char *active, bool logging, bool dns, char *err, size_t errlen)
+{
+ struct sb b = {0};
+ sb_puts(&b, "{\n");
+ sb_kv(&b, " ", "ActiveProfileName", active ? active : "", ",\n");
+ sb_puts(&b, logging ? " \"IsTrafficLoggingEnabled\": true,\n" : " \"IsTrafficLoggingEnabled\": false,\n");
+ sb_puts(&b, dns ? " \"DnsViaProxy\": true\n}\n" : " \"DnsViaProxy\": false\n}\n");
+ if (b.oom) { free(b.p); snprintf(err, errlen, "out of memory"); return -1; }
+ int rc = pbp_write_file(path, b.p, err, errlen);
+ free(b.p);
+ return rc;
+}
+
+// ---- profile names and files ----
+
+#define MAX_FILENAME 240
+
+char *pbp_filename_for(const char *name)
+{
+ if (!name || !*name) return NULL;
+ size_t n = strlen(name);
+ char *out = malloc(n * 3 + sizeof PBP_EXT), *o = out;
+ if (!out) return NULL;
+ for (size_t i = 0; i < n; i++) {
+ unsigned char c = (unsigned char)name[i];
+ bool plain = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' ||
+ c == ' ' || c >= 0x80 || (c == '.' && i > 0);
+ if (plain) *o++ = (char)c;
+ else o += sprintf(o, "%%%02X", c);
+ }
+ strcpy(o, PBP_EXT);
+ if (strlen(out) > MAX_FILENAME) { free(out); return NULL; }
+ return out;
+}
+
+char *pbp_name_from_filename(const char *filename)
+{
+ size_t n = strlen(filename), e = sizeof PBP_EXT - 1;
+ if (n <= e || strcmp(filename + n - e, PBP_EXT) != 0) return NULL;
+ char *out = malloc(n), *o = out;
+ if (!out) return NULL;
+ size_t m = n - e;
+ for (size_t i = 0; i < m; i++) {
+ if (filename[i] != '%') { *o++ = filename[i]; continue; }
+ char t[4] = { '0', '0', i + 2 < m ? filename[i + 1] : 'x', i + 2 < m ? filename[i + 2] : 'x' };
+ int v = hex4(t);
+ if (v <= 0) { free(out); return NULL; }
+ *o++ = (char)v;
+ i += 2;
+ }
+ *o = 0;
+ if (!*out) { free(out); return NULL; }
+ return out;
+}
+
+const char *pbp_config_dir(void)
+{
+ const char *env = getenv("PROXYBRIDGE_CONFIG_DIR");
+ return (env && *env) ? env : "/etc/proxybridge";
+}
+
+char *pbp_resolve(const char *dir, const char *s)
+{
+ if (!s || !*s) return NULL;
+ size_t n = strlen(s), e = sizeof PBP_EXT - 1;
+ bool has_ext = n > e && !strcmp(s + n - e, PBP_EXT);
+ if (strchr(s, '/')) return strdup(s);
+ if (has_ext && access(s, R_OK) == 0) return strdup(s);
+ char *name = strndup(s, has_ext ? n - e : n);
+ char *file = name ? pbp_filename_for(name) : NULL, *path = NULL;
+ if (file && asprintf(&path, "%s/profiles/%s", dir, file) < 0) path = NULL;
+ free(name);
+ free(file);
+ return path;
+}
diff --git a/Linux/profile/pb_profile.h b/Linux/profile/pb_profile.h
new file mode 100644
index 0000000..9a547bf
--- /dev/null
+++ b/Linux/profile/pb_profile.h
@@ -0,0 +1,79 @@
+// .pbprofile: the JSON profile format shared with the Windows and macOS apps (PascalCase keys).
+//
+// { "Version": "1.0", "Name": "...", "IsTrafficLoggingEnabled": true,
+// "ProxyConfigs": [ { "Id": 1, "Name": "work", "Type": "SOCKS5", "Host": "...", "Port": "1080",
+// "Username": "", "Password": "", "SendDomainToProxy": false } ],
+// "ProxyRules": [ { "ProcessName": "...", "TargetHosts": "...", "TargetPorts": "...", "TargetDomains": "...",
+// "Protocol": "TCP|UDP|BOTH", "Action": "PROXY|DIRECT|BLOCK", "IsEnabled": true,
+// "ProxyConfigId": 1 } ] }
+//
+// Linux keeps domain names in the host list; they are split into TargetDomains on export and merged back on import.
+// Fields this program does not use (LocalhostViaProxy, LogFilters, ...) are ignored on import.
+#ifndef PB_PROFILE_H
+#define PB_PROFILE_H
+
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+
+#define PBP_MAX_FILE (4u << 20)
+#define PBP_MAX_PROXIES 256
+#define PBP_MAX_RULES 4096
+#define PBP_EXT ".pbprofile"
+
+struct pbp_proxy {
+ uint32_t id; // stable within the file; rules refer to it
+ char *name;
+ int type; // 0 = HTTP, 1 = SOCKS5 (same values as ProxyType)
+ char *host;
+ uint16_t port;
+ char *user, *pass;
+};
+
+struct pbp_rule {
+ char *process, *hosts, *ports; // hosts holds IPs and domain names together
+ int protocol; // 0 TCP, 1 UDP, 2 BOTH (RuleProtocol)
+ int action; // 0 PROXY, 1 DIRECT, 2 BLOCK (RuleAction)
+ bool enabled;
+ uint32_t proxy_id; // 0 = default proxy
+};
+
+struct pbp_profile {
+ char *name;
+ bool logging; // IsTrafficLoggingEnabled
+ bool dns_via_proxy; // DnsViaProxy (Linux extension)
+ uint32_t default_proxy_id; // DefaultProxyId (Linux extension); 0 = first proxy
+ struct pbp_proxy *proxies; size_t nproxies;
+ struct pbp_rule *rules; size_t nrules;
+};
+
+// Returns 0 or -1 with a reason in err. On failure *out is empty and need not be freed.
+int pbp_parse(const char *json, size_t len, struct pbp_profile *out, char *err, size_t errlen);
+char *pbp_serialize(const struct pbp_profile *p); // malloc'd, NUL terminated
+void pbp_free(struct pbp_profile *p);
+
+int pbp_load_file(const char *path, struct pbp_profile *out, char *err, size_t errlen);
+// Writes data to path atomically (temporary file + fsync + rename), mode 0600.
+int pbp_write_file(const char *path, const char *data, char *err, size_t errlen);
+// Atomic (temporary file + rename), mode 0600 because the file holds proxy credentials.
+int pbp_save_file(const char *path, const struct pbp_profile *p, char *err, size_t errlen);
+
+// settings.json next to the profiles: which profile is active, plus the GUI-wide switches (absent keys keep the defaults).
+int pbp_settings_load(const char *path, char **active, bool *logging, bool *dns); // -1 if missing or unreadable
+int pbp_settings_save(const char *path, const char *active, bool logging, bool dns, char *err, size_t errlen);
+
+// Profile name <-> file name inside a profiles directory (percent-encoding, so any name is safe).
+char *pbp_filename_for(const char *name); // malloc'd, includes the extension
+char *pbp_name_from_filename(const char *filename); // NULL if it is not a profile file
+// Directory holding settings.json and profiles/ (PROXYBRIDGE_CONFIG_DIR overrides /etc/proxybridge, used by tests).
+const char *pbp_config_dir(void);
+// "name" or a path: a path is used as is, a bare name is looked up as <dir>/profiles/<name>.pbprofile.
+char *pbp_resolve(const char *dir, const char *name_or_path);
+
+// Splits a host list into IP-like and domain tokens (either output may be empty); the caller frees both.
+void pbp_split_hosts(const char *hosts, char **ips, char **domains);
+char *pbp_merge_hosts(const char *ips, const char *domains);
+
+struct pbp_proxy *pbp_find_proxy(const struct pbp_profile *p, uint32_t id);
+
+#endif
diff --git a/Linux/profile/tests/profile_test.c b/Linux/profile/tests/profile_test.c
new file mode 100644
index 0000000..f5fdcb8
--- /dev/null
+++ b/Linux/profile/tests/profile_test.c
@@ -0,0 +1,277 @@
+// Unit tests for the .pbprofile reader/writer (build with sanitizers via run_tests.sh).
+#define _GNU_SOURCE
+#include "../pb_profile.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+static int fails, checks;
+#define CHECK(c) do { checks++; if (!(c)) { fails++; printf("FAIL %s:%d %s\n", __FILE__, __LINE__, #c); } } while (0)
+
+// The sample from the Windows README, plus the optional fields the Windows GUI writes.
+static const char *WINDOWS_SAMPLE =
+ "{ \"Version\": \"1.0\", \"LocalhostViaProxy\": false, \"IsTrafficLoggingEnabled\": true,\n"
+ " \"ProxyConfigs\": [\n"
+ " { \"Id\": 1, \"Type\": \"socks5\", \"Host\": \"127.0.0.1\", \"Port\": \"1080\", \"Username\": \"\", \"Password\": \"\" },\n"
+ " { \"Id\": 2, \"Name\": \"corp\", \"Type\": \"http\", \"Host\": \"10.0.0.2\", \"Port\": \"8080\", \"Username\": \"bob\", \"Password\": \"p\\\"w\", \"SendDomainToProxy\": true }\n"
+ " ],\n"
+ " \"ProxyRules\": [\n"
+ " { \"ProcessName\": \"chrome.exe\", \"TargetHosts\": \"*\", \"TargetPorts\": \"*\", \"Protocol\": \"TCP\", \"Action\": \"PROXY\", \"IsEnabled\": true, \"ProxyConfigId\": 1 },\n"
+ " { \"ProcessName\": \"firefox.exe\", \"TargetHosts\": \"192.168.*.*\", \"TargetPorts\": \"80;443\", \"TargetDomains\": \"*.github.com\","
+ " \"Protocol\": \"BOTH\", \"Action\": \"PROXY\", \"IsEnabled\": false, \"ProxyConfigId\": 2 },\n"
+ " { \"ProcessName\": \"x\", \"Protocol\": \"UDP\", \"Action\": \"BLOCK\" }\n"
+ " ],\n"
+ " \"LogFilters\": [ { \"Mode\": \"Hide\", \"ProcessName\": \"x\" } ] }\n";
+
+static int parse(const char *s, struct pbp_profile *p, char *err)
+{
+ return pbp_parse(s, strlen(s), p, err, 256);
+}
+
+static void test_windows_sample(void)
+{
+ struct pbp_profile p;
+ char err[256];
+ CHECK(parse(WINDOWS_SAMPLE, &p, err) == 0);
+ CHECK(p.nproxies == 2 && p.nrules == 3 && p.logging);
+ CHECK(p.proxies[0].type == 1 && !strcmp(p.proxies[0].host, "127.0.0.1") && p.proxies[0].port == 1080);
+ CHECK(!strcmp(p.proxies[0].name, "proxy1"));
+ CHECK(p.proxies[1].type == 0 && !strcmp(p.proxies[1].name, "corp") && !strcmp(p.proxies[1].pass, "p\"w"));
+ CHECK(!strcmp(p.rules[0].process, "chrome.exe") && p.rules[0].proxy_id == 1 && p.rules[0].enabled);
+ CHECK(!strcmp(p.rules[1].hosts, "192.168.*.*;*.github.com")); // domains join the host list
+ CHECK(!strcmp(p.rules[1].ports, "80;443") && p.rules[1].protocol == 2 && !p.rules[1].enabled);
+ CHECK(p.rules[2].protocol == 1 && p.rules[2].action == 2 && p.rules[2].proxy_id == 0 && p.rules[2].enabled);
+ CHECK(!strcmp(p.rules[2].hosts, "*") && !strcmp(p.rules[2].ports, "*"));
+ pbp_free(&p);
+}
+
+static void test_roundtrip(void)
+{
+ struct pbp_profile a, b;
+ char err[256];
+ CHECK(parse(WINDOWS_SAMPLE, &a, err) == 0);
+ a.name = strdup("Work \"é\"");
+ a.default_proxy_id = 2;
+ a.dns_via_proxy = false;
+ char *json = pbp_serialize(&a);
+ CHECK(json && strstr(json, "\"TargetDomains\": \"*.github.com\"") && strstr(json, "\"TargetHosts\": \"192.168.*.*\""));
+ CHECK(pbp_parse(json, strlen(json), &b, err, sizeof err) == 0);
+ CHECK(b.nproxies == a.nproxies && b.nrules == a.nrules && b.default_proxy_id == 2 && !b.dns_via_proxy);
+ CHECK(b.name && !strcmp(b.name, a.name));
+ for (size_t i = 0; i < a.nrules && i < b.nrules; i++) {
+ CHECK(!strcmp(a.rules[i].hosts, b.rules[i].hosts) && !strcmp(a.rules[i].process, b.rules[i].process));
+ CHECK(a.rules[i].protocol == b.rules[i].protocol && a.rules[i].action == b.rules[i].action);
+ CHECK(a.rules[i].enabled == b.rules[i].enabled && a.rules[i].proxy_id == b.rules[i].proxy_id);
+ }
+ for (size_t i = 0; i < a.nproxies && i < b.nproxies; i++)
+ CHECK(!strcmp(a.proxies[i].pass, b.proxies[i].pass) && a.proxies[i].port == b.proxies[i].port && a.proxies[i].id == b.proxies[i].id);
+ free(json);
+ pbp_free(&a);
+ pbp_free(&b);
+}
+
+static void expect_error(const char *json, const char *needle)
+{
+ struct pbp_profile p;
+ char err[256] = "";
+ int rc = parse(json, &p, err);
+ CHECK(rc == -1 && p.nproxies == 0 && p.nrules == 0 && !p.proxies && !p.rules);
+ if (needle && !strstr(err, needle)) { fails++; printf("FAIL error '%s' lacks '%s'\n", err, needle); }
+}
+
+static void test_errors(void)
+{
+ expect_error("", NULL);
+ expect_error("[]", "JSON object");
+ expect_error("{", NULL);
+ expect_error("{\"ProxyRules\": 5}", "arrays");
+ expect_error("{} trailing", "after the profile");
+ expect_error("{\"Name\": \"abc}", "unterminated");
+ expect_error("{\"Name\": \"\\q\"}", "escape");
+ expect_error("{\"Name\": \"\\ud800\"}", "surrogate");
+ expect_error("{\"Name\": \"\\u0000\"}", "NUL");
+ expect_error("{\"ProxyConfigs\":[{\"Type\":\"socks5\",\"Host\":\"h\",\"Port\":\"0\"}]}", "Port");
+ expect_error("{\"ProxyConfigs\":[{\"Type\":\"socks5\",\"Host\":\"\",\"Port\":\"1\"}]}", "Host");
+ expect_error("{\"ProxyConfigs\":[{\"Type\":\"ftp\",\"Host\":\"h\",\"Port\":\"1\"}]}", "Type");
+ expect_error("{\"ProxyConfigs\":[5]}", "not an object");
+ expect_error("{\"ProxyRules\":[{\"Protocol\":\"ICMP\"}]}", "Protocol");
+ expect_error("{\"ProxyRules\":[{\"Action\":\"ALLOW\"}]}", "Action");
+ expect_error("{\"ProxyRules\":[{\"ProxyConfigId\":7}]}", "does not match");
+ expect_error("{\"ProxyRules\":[{\"ProxyConfigId\":-1}]}", "does not match");
+ expect_error("{\"DefaultProxyId\":9}", "DefaultProxyId");
+
+ char deep[400]; // nesting beyond the limit must not recurse without bound
+ memset(deep, '[', 300);
+ deep[300] = 0;
+ expect_error(deep, "deeply");
+}
+
+static void test_leniency(void)
+{
+ struct pbp_profile p;
+ char err[256];
+ CHECK(parse("\xEF\xBB\xBF{\"Name\":\"bom\"}", &p, err) == 0 && !strcmp(p.name, "bom"));
+ pbp_free(&p);
+ CHECK(parse("{\"Name\":\"\\u00e9\\ud83d\\ude00\"}", &p, err) == 0 && !strcmp(p.name, "\xC3\xA9\xF0\x9F\x98\x80"));
+ pbp_free(&p);
+ // numbers where strings are expected, mixed key case, duplicate ids and names
+ CHECK(parse("{\"proxyconfigs\":[{\"Id\":3,\"Name\":\"a\",\"Type\":\"SOCKS5\",\"Host\":\"h\",\"Port\":1080},"
+ "{\"Id\":3,\"Name\":\"a\",\"Type\":\"HTTP\",\"Host\":\"h2\",\"Port\":\"8080\"}],"
+ "\"ProxyRules\":[{\"ProxyConfigId\":\"3\"}]}", &p, err) == 0);
+ CHECK(p.nproxies == 2 && p.proxies[0].port == 1080 && p.proxies[0].id == 3 && p.proxies[1].id == 4);
+ CHECK(strcmp(p.proxies[0].name, p.proxies[1].name) != 0);
+ CHECK(p.nrules == 1 && p.rules[0].proxy_id == 3);
+ pbp_free(&p);
+ CHECK(parse("{}", &p, err) == 0 && p.nproxies == 0 && p.nrules == 0 && p.logging && p.dns_via_proxy);
+ pbp_free(&p);
+}
+
+static void check_split(const char *in, const char *ips, const char *doms)
+{
+ char *a, *d;
+ pbp_split_hosts(in, &a, &d);
+ CHECK(!strcmp(a, ips) && !strcmp(d, doms));
+ if (strcmp(a, ips) || strcmp(d, doms)) printf(" split(%s) = [%s] [%s], wanted [%s] [%s]\n", in, a, d, ips, doms);
+ free(a);
+ free(d);
+}
+
+static void test_hosts(void)
+{
+ check_split("*", "*", "");
+ check_split("", "", "");
+ check_split("10.0.0.0/8; 192.168.*.*", "10.0.0.0/8;192.168.*.*", "");
+ check_split("1.2.3.4-1.2.3.9,10.1-5.*.*", "1.2.3.4-1.2.3.9;10.1-5.*.*", "");
+ check_split("github.com;*.github.com", "", "github.com;*.github.com");
+ check_split("fe80::1;2001:db8::/32", "fe80::1;2001:db8::/32", "");
+ check_split("10.0.0.1;example.org;::1;bad.cafe", "10.0.0.1;::1", "example.org;bad.cafe");
+ check_split("a?.example.com", "", "a?.example.com");
+
+ char *m = pbp_merge_hosts("*", "x.com");
+ CHECK(!strcmp(m, "x.com")); free(m);
+ m = pbp_merge_hosts("", "");
+ CHECK(!strcmp(m, "*")); free(m);
+ m = pbp_merge_hosts("10.0.0.0/8", "x.com;y.org");
+ CHECK(!strcmp(m, "10.0.0.0/8;x.com;y.org")); free(m);
+ m = pbp_merge_hosts(NULL, NULL);
+ CHECK(!strcmp(m, "*")); free(m);
+}
+
+static void test_names(void)
+{
+ const char *names[] = { "Default", "My Work", "a/b", "..", ".hidden", "100%", "tab\tname", "日本語", "x.y.z", "a:b*c?" };
+ for (size_t i = 0; i < sizeof names / sizeof *names; i++) {
+ char *f = pbp_filename_for(names[i]);
+ CHECK(f && !strchr(f, '/') && f[0] != '.');
+ char *back = f ? pbp_name_from_filename(f) : NULL;
+ CHECK(back && !strcmp(back, names[i]));
+ free(f);
+ free(back);
+ }
+ CHECK(pbp_filename_for("") == NULL && pbp_filename_for(NULL) == NULL);
+ char longname[300];
+ memset(longname, 'a', 299);
+ longname[299] = 0;
+ CHECK(pbp_filename_for(longname) == NULL);
+ CHECK(pbp_name_from_filename("x.txt") == NULL && pbp_name_from_filename(".pbprofile") == NULL);
+ CHECK(pbp_name_from_filename("bad%zz.pbprofile") == NULL && pbp_name_from_filename("trunc%4.pbprofile") == NULL);
+ CHECK(pbp_name_from_filename("nul%00.pbprofile") == NULL);
+}
+
+static void test_files(void)
+{
+ char dir[] = "/tmp/pbp_test_XXXXXX";
+ CHECK(mkdtemp(dir) != NULL);
+ char path[300], err[256];
+ snprintf(path, sizeof path, "%s/a.pbprofile", dir);
+
+ struct pbp_profile p, q;
+ CHECK(parse(WINDOWS_SAMPLE, &p, err) == 0);
+ CHECK(pbp_save_file(path, &p, err, sizeof err) == 0);
+ struct stat st;
+ CHECK(stat(path, &st) == 0 && (st.st_mode & 0777) == 0600); // the file holds credentials
+ CHECK(pbp_load_file(path, &q, err, sizeof err) == 0 && q.nrules == p.nrules);
+ pbp_free(&q);
+ CHECK(pbp_save_file(path, &p, err, sizeof err) == 0); // overwrite
+ char leftovers[400];
+ snprintf(leftovers, sizeof leftovers, "ls %s | grep -c tmp > /dev/null", dir);
+ CHECK(system(leftovers) != 0); // no temporary files remain
+ pbp_free(&p);
+
+ CHECK(pbp_load_file("/nonexistent/x.pbprofile", &q, err, sizeof err) == -1 && strstr(err, "cannot open"));
+ CHECK(pbp_load_file(dir, &q, err, sizeof err) == -1 && strstr(err, "regular"));
+ snprintf(path, sizeof path, "%s/empty.pbprofile", dir);
+ FILE *f = fopen(path, "w");
+ fclose(f);
+ CHECK(pbp_load_file(path, &q, err, sizeof err) == -1 && strstr(err, "empty"));
+ snprintf(path, sizeof path, "%s/huge.pbprofile", dir);
+ f = fopen(path, "w");
+ CHECK(fseek(f, (long)PBP_MAX_FILE + 10, SEEK_SET) == 0 && fputc('x', f) != EOF);
+ fclose(f);
+ CHECK(pbp_load_file(path, &q, err, sizeof err) == -1 && strstr(err, "too large"));
+
+ char *r = pbp_resolve("/etc/proxybridge", "Work");
+ CHECK(r && !strcmp(r, "/etc/proxybridge/profiles/Work.pbprofile")); free(r);
+ r = pbp_resolve("/etc/proxybridge", "/tmp/x.pbprofile");
+ CHECK(r && !strcmp(r, "/tmp/x.pbprofile")); free(r);
+ r = pbp_resolve("/etc/proxybridge", "Work.pbprofile"); // no such file in the cwd: treated as the name
+ CHECK(r && !strcmp(r, "/etc/proxybridge/profiles/Work.pbprofile")); free(r);
+ r = pbp_resolve("/etc/proxybridge", "..");
+ CHECK(r && strstr(r, "..") == NULL ? 1 : r && !strstr(r, "/../")); free(r);
+
+ char cmd[400];
+ snprintf(cmd, sizeof cmd, "rm -rf %s", dir);
+ CHECK(system(cmd) == 0);
+}
+
+// Mutated and truncated inputs must be rejected or accepted, never crash or leak (run under ASan/UBSan).
+static void test_fuzz(void)
+{
+ size_t n = strlen(WINDOWS_SAMPLE);
+ unsigned seed = 12345;
+ int accepted = 0;
+ for (int it = 0; it < 40000; it++) {
+ char *buf = malloc(n + 1);
+ memcpy(buf, WINDOWS_SAMPLE, n + 1);
+ size_t len = n;
+ seed = seed * 1103515245u + 12345u;
+ int flips = 1 + (int)((seed >> 16) % 4);
+ for (int k = 0; k < flips; k++) {
+ seed = seed * 1103515245u + 12345u;
+ size_t pos = (seed >> 8) % n;
+ seed = seed * 1103515245u + 12345u;
+ buf[pos] = (char)(seed >> 16);
+ }
+ seed = seed * 1103515245u + 12345u;
+ if ((seed >> 20) % 4 == 0) len = (seed >> 8) % n;
+ struct pbp_profile p;
+ char err[256];
+ if (pbp_parse(buf, len, &p, err, sizeof err) == 0) {
+ accepted++;
+ char *out = pbp_serialize(&p);
+ struct pbp_profile q;
+ CHECK(out && pbp_parse(out, strlen(out), &q, err, sizeof err) == 0); // anything accepted must survive a round trip
+ if (out) pbp_free(&q);
+ free(out);
+ pbp_free(&p);
+ }
+ free(buf);
+ }
+ CHECK(accepted > 0);
+}
+
+int main(void)
+{
+ test_windows_sample();
+ test_roundtrip();
+ test_errors();
+ test_leniency();
+ test_hosts();
+ test_names();
+ test_files();
+ test_fuzz();
+ printf("profile_test: %d checks, %d failed\n", checks, fails);
+ return fails ? 1 : 0;
+}
diff --git a/Linux/profile/tests/run_tests.sh b/Linux/profile/tests/run_tests.sh
new file mode 100755
index 0000000..da3a528
--- /dev/null
+++ b/Linux/profile/tests/run_tests.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+# Builds profile_test with ASan+UBSan (and plain, warnings as errors) and runs it. Output goes to a temp dir.
+set -euo pipefail
+cd "$(dirname "$0")"
+OUT=$(mktemp -d)
+trap 'rm -rf "$OUT"' EXIT
+CFLAGS="-std=gnu11 -O1 -g -Wall -Wextra -Werror"
+gcc $CFLAGS -o "$OUT/plain" profile_test.c ../pb_profile.c
+gcc $CFLAGS -fsanitize=address,undefined -fno-sanitize-recover=undefined -o "$OUT/asan" profile_test.c ../pb_profile.c
+"$OUT/plain"
+ASAN_OPTIONS=detect_leaks=1 "$OUT/asan"
diff --git a/Linux/tests/e2e_profile.sh b/Linux/tests/e2e_profile.sh
new file mode 100755
index 0000000..4903fc7
--- /dev/null
+++ b/Linux/tests/e2e_profile.sh
@@ -0,0 +1,117 @@
+#!/bin/bash
+# End-to-end test of `ProxyBridge --profile`: a profile in the Windows/macOS .pbprofile format drives the real datapath.
+# sudo Linux/tests/e2e_profile.sh
+set -u
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+ROOT="$(dirname "$HERE")"
+PB_DIR="${PB_DIR:-$ROOT/output}"
+[ -x "$PB_DIR/ProxyBridge" ] && [ -f "$PB_DIR/libproxybridge.so" ] || { echo "Build first (Linux/build.sh) or set PB_DIR"; exit 1; }
+[ "$(id -u)" = 0 ] || { echo "run as root"; exit 1; }
+WORK="$(mktemp -d)"
+LOG="$WORK/proxy.log"; : > "$LOG"
+PASS=0; FAIL=0
+ok() { echo " PASS $1"; PASS=$((PASS+1)); }
+bad() { echo " FAIL $1"; FAIL=$((FAIL+1)); }
+has() { if [[ "$2" == *"$3"* ]]; then ok "$1"; else bad "$1 (got: ${2:0:300})"; fi; }
+PB_PID=""; FAKE_PID=""
+cleanup() { [ -n "$PB_PID" ] && kill "$PB_PID" 2>/dev/null; [ -n "$FAKE_PID" ] && kill "$FAKE_PID" 2>/dev/null; wait 2>/dev/null; rm -rf "$WORK"; }
+trap cleanup EXIT
+export LD_LIBRARY_PATH="$PB_DIR"
+export PROXYBRIDGE_CONFIG_DIR="$WORK/cfg"
+mkdir -p "$WORK/cfg/profiles"
+
+python3 "$HERE/fake_proxies.py" "$LOG" > "$WORK/fake.out" 2>&1 & FAKE_PID=$!
+sleep 1
+
+start_pb() { # args...; leaves PB_PID set and waits for start-up
+ stdbuf -oL "$PB_DIR/ProxyBridge" "$@" > "$WORK/pb.out" 2>&1 & PB_PID=$!
+ for _ in $(seq 40); do grep -q "ProxyBridge started" "$WORK/pb.out" && return 0; kill -0 "$PB_PID" 2>/dev/null || return 1; sleep 0.25; done
+ return 1
+}
+stop_pb() { kill -INT "$PB_PID" 2>/dev/null; wait "$PB_PID" 2>/dev/null; PB_PID=""; }
+
+# What the Windows GUI exports: numeric ids, no proxy names on the first entry, domains in TargetDomains, a disabled rule.
+cat > "$WORK/win.pbprofile" <<'JSON'
+{
+ "Version": "1.0",
+ "LocalhostViaProxy": false,
+ "IsTrafficLoggingEnabled": true,
+ "ProxyConfigs": [
+ { "Id": 1, "Type": "socks5", "Host": "127.0.0.1", "Port": "19080", "Username": "", "Password": "", "SendDomainToProxy": true },
+ { "Id": 2, "Name": "bobby", "Type": "SOCKS5", "Host": "127.0.0.1", "Port": "19081", "Username": "bob", "Password": "pw" }
+ ],
+ "ProxyRules": [
+ { "ProcessName": "curl", "TargetHosts": "192.0.2.0/24", "TargetPorts": "*", "TargetDomains": "", "Protocol": "TCP", "Action": "PROXY", "IsEnabled": true, "ProxyConfigId": 1 },
+ { "ProcessName": "curl", "TargetHosts": "198.51.100.0/24", "TargetPorts": "80;8080", "Protocol": "TCP", "Action": "PROXY", "IsEnabled": true, "ProxyConfigId": 2 },
+ { "ProcessName": "curl", "TargetHosts": "203.0.113.0/24", "TargetPorts": "*", "Protocol": "TCP", "Action": "PROXY", "IsEnabled": false, "ProxyConfigId": 1 },
+ { "ProcessName": "curl", "TargetHosts": "*", "TargetPorts": "*", "TargetDomains": "*.profile-test.invalid", "Protocol": "TCP", "Action": "PROXY", "IsEnabled": true, "ProxyConfigId": 2 },
+ { "ProcessName": "curl", "TargetHosts": "203.0.114.0/24", "TargetPorts": "*", "Protocol": "BOTH", "Action": "BLOCK", "IsEnabled": true }
+ ]
+}
+JSON
+chmod 600 "$WORK/win.pbprofile"
+
+echo "== a profile file (Windows format) by path"
+if start_pb --verbose 3 --profile "$WORK/win.pbprofile"; then ok "ProxyBridge starts from a profile"; else bad "start"; cat "$WORK/pb.out"; fi
+out=$(cat "$WORK/pb.out")
+has "profile path is reported" "$out" "Profile: $WORK/win.pbprofile"
+has "both proxies loaded" "$out" "Proxies: 2"
+has "unnamed proxy gets a stable name" "$out" "proxy1"
+has "named proxy keeps its name" "$out" "bobby"
+has "the disabled rule is skipped" "$out" "Rules: 4"
+out=$(curl -s -m 5 http://192.0.2.7/); has "ProxyConfigId 1 -> first proxy" "$out" "hello-from-A dst=192.0.2.7:80"
+out=$(curl -s -m 5 http://198.51.100.7:8080/); has "ProxyConfigId 2 -> authenticated proxy" "$out" "hello-from-B dst=198.51.100.7:8080"
+out=$(curl -s -m 3 http://203.0.113.7/ 2>&1; echo "rc=$?"); has "disabled rule does not route" "$out" "rc=28"
+out=$(curl -s -m 5 http://203.0.114.7/ 2>&1; echo "rc=$?"); has "BLOCK action from the profile" "$out" "rc=7"
+stop_pb
+
+echo "== a profile saved by the GUI, by name (also with spaces)"
+cp "$WORK/win.pbprofile" "$WORK/cfg/profiles/Work Profile.pbprofile"
+out=$("$PB_DIR/ProxyBridge" --list-profiles 2>&1)
+has "--list-profiles shows the name" "$out" "Work Profile"
+if start_pb --profile "Work Profile"; then ok "starts by profile name"; else bad "start by name"; cat "$WORK/pb.out"; fi
+out=$(curl -s -m 5 http://192.0.2.9/); has "rules from the named profile apply" "$out" "hello-from-A dst=192.0.2.9:80"
+stop_pb
+
+echo "== default proxy, combining with --proxy/--rule, DNS flag"
+cat > "$WORK/dflt.pbprofile" <<'JSON'
+{ "Version": "1.0", "DnsViaProxy": false, "DefaultProxyId": 2,
+ "ProxyConfigs": [
+ { "Id": 1, "Name": "one", "Type": "socks5", "Host": "127.0.0.1", "Port": "19080" },
+ { "Id": 2, "Name": "two", "Type": "http", "Host": "127.0.0.1", "Port": "19082" } ],
+ "ProxyRules": [ { "ProcessName": "curl", "TargetHosts": "192.0.2.0/24", "Protocol": "TCP", "Action": "PROXY" } ] }
+JSON
+chmod 600 "$WORK/dflt.pbprofile"
+start_pb --profile "$WORK/dflt.pbprofile" --proxy extra=socks5://127.0.0.1:19080 --rule "curl:198.51.100.0/24:*:TCP:PROXY=extra"
+out=$(cat "$WORK/pb.out")
+has "DefaultProxyId is honoured by rules without a proxy" "$(curl -s -m 5 http://192.0.2.5/)" "hello-from-C dst=192.0.2.5:80"
+has "--rule works after --profile" "$(curl -s -m 5 http://198.51.100.5/)" "hello-from-A dst=198.51.100.5:80"
+has "profile DnsViaProxy=false is applied" "$out" "DNS via Proxy: Disabled"
+stop_pb
+start_pb --profile "$WORK/dflt.pbprofile" --dns-via-proxy true
+has "explicit --dns-via-proxy wins" "$(cat "$WORK/pb.out")" "DNS via Proxy: Enabled"
+stop_pb
+
+echo "== bad input is rejected before anything is attached"
+expect_fail() { # name expected-text args...
+ local name="$1" want="$2"; shift 2
+ out=$("$PB_DIR/ProxyBridge" "$@" 2>&1); rc=$?
+ if [ $rc -ne 0 ] && [[ "$out" == *"$want"* ]]; then ok "$name"; else bad "$name (rc=$rc: ${out:0:300})"; fi
+}
+expect_fail "missing file" "cannot open" --profile "$WORK/nope.pbprofile"
+expect_fail "unknown profile name" "cannot open" --profile "no such profile"
+echo '{ "ProxyRules": [ { "ProxyConfigId": 9 } ] }' > "$WORK/badref.pbprofile"
+expect_fail "rule referring to a missing proxy" "does not match any proxy" --profile "$WORK/badref.pbprofile"
+echo 'not json' > "$WORK/junk.pbprofile"
+expect_fail "malformed JSON" "not a valid profile" --profile "$WORK/junk.pbprofile"
+echo '{ "ProxyRules": [ { "TargetHosts": "999.1.1.1" } ] }' > "$WORK/badhost.pbprofile"
+expect_fail "rule the engine rejects" "ERROR" --profile "$WORK/badhost.pbprofile"
+expect_fail "--profile without a value" "Unknown option" --profile
+
+echo "== credentials in a world-readable profile trigger a warning"
+cp "$WORK/win.pbprofile" "$WORK/open.pbprofile"; chmod 644 "$WORK/open.pbprofile"
+out=$(timeout 3 "$PB_DIR/ProxyBridge" --profile "$WORK/open.pbprofile" 2>&1)
+has "permission warning" "$out" "other users can read it"
+
+echo; echo "passed=$PASS failed=$FAIL"
+[ "$FAIL" = 0 ]