Force Proxy to any Windows/MacOS/Linux Application TCP and UDP traffic
C ccybersecurityhttp3httpproxylinuxlinux-proxymacosmacos-appmacos-proxyproxifierproxifier-alternativeproxyclienttcpthick-clientudpwindivertwindows
refactor(linux/gui): fix the exit leak, share helpers, move the rules JSON parser out
anof-cyber6c8e87aeddd0
diff --git a/Linux/gui/gui.h b/Linux/gui/gui.hindex a1c0577..653f671 100644--- a/Linux/gui/gui.h+++ b/Linux/gui/gui.h@@ -6,14 +6,11 @@#include <stdlib.h>#include <stdio.h>#include <string.h>-#include <time.h>-#include <pthread.h>-#include <signal.h>+#include <stdarg.h>#include <sys/types.h>#include <sys/stat.h>-#include <sys/wait.h>-#include <stdarg.h>#include "ProxyBridge.h"+typedef struct {char *process_name;uint32_t pid;@@ -24,12 +21,8 @@ typedef struct {} ConnectionData;typedef struct {- char *message;-} LogData;--typedef struct {- uint32_t id; // library proxy id, 0 = not registered with the library- char *name; // unique key, also what rules and the config refer to+ uint32_t id; // library id, 0 = not registered+ char *name; // unique key, rules and config refer to itProxyType type;char *host;uint16_t port;@@ -37,17 +30,6 @@ typedef struct {char *password;} ProxyData;-// proxy manager dialog widgets-typedef struct {- GtkWidget *dialog;- GtkWidget *tree;- GtkListStore *store;- GtkWidget *test_host;- GtkWidget *test_port;- GtkTextBuffer *output_buffer;- GtkWidget *test_btn;-} ConfigInfo;-typedef struct {uint32_t id;char *process_name;@@ -60,19 +42,15 @@ typedef struct {bool selected;} RuleData;-struct TestRunnerData {- uint32_t proxy_id;- char *host;- uint16_t port;- GtkTextBuffer *buffer; // referenced, released in the idle callback- GtkWidget *btn; // referenced, released in the idle callback-};-+// lists are only current while the profile is inactive, see profile_sync_activetypedef struct {- char *result_text;- GtkTextBuffer *buffer;- GtkWidget *btn;-} TestResultData;+ char *name;+ GList *proxies;+ char *default_proxy;+ GList *rules;+} Profile;++typedef void (*RuleImportCb)(const RuleData *rule, int index, void *ud);extern GtkWidget *window;extern GtkTextBuffer *conn_buffer;@@ -80,18 +58,10 @@ extern GtkTextBuffer *log_buffer;extern GtkWidget *status_bar;extern guint status_context_id;-typedef struct {- char *name;- GList *proxies; // ProxyData, only current while the profile is not active (see profile_sync_active)- char *default_proxy;- GList *rules; // RuleData-} Profile;--extern GList *g_profiles; // list of Profile-extern char *g_active_profile; // name of the active profile-extern GList *g_proxies_list; // list of ProxyData-extern char *g_default_proxy; // name of the default proxy, NULL if none-+extern GList *g_profiles;+extern char *g_active_profile;+extern GList *g_proxies_list; // working copy of the active profile+extern char *g_default_proxy;extern GList *g_rules_list;extern bool g_chk_logging;extern bool g_chk_dns;@@ -99,23 +69,25 @@ extern bool g_chk_dns;long safe_strtol(const char *nptr);void show_message(GtkWindow *parent, GtkMessageType type, const char *format, ...);void trim_buffer_lines(GtkTextBuffer *buffer, int max_lines);-char* get_current_time_str();-char *escape_json_string(const char *src);+char *get_current_time_str();+GtkWidget *combo_new(const char *first, ...) G_GNUC_NULL_TERMINATED;+GtkWidget *hint_label(const char *text);+void set_error_label(GtkWidget *label, const char *msg);+void grid_row(GtkWidget *grid, int row, const char *label, GtkWidget *widget);+char *extract_sub_json_str(const char *json, const char *key);-bool extract_sub_json_bool(const char *json, const char *key);-bool json_has_key(const char *json, const char *key);+int rules_from_json(const char *json, RuleImportCb cb, void *ud);+char *rules_to_json(GList *rules, bool only_selected);-// config storagevoid save_config();void load_config();-void profile_sync_active();+void config_free_all();Profile *profile_find(const char *name);Profile *profile_create(const char *name, bool copy_active);bool profile_rename(Profile *p, const char *new_name);bool profile_activate(const char *name);bool profile_delete(Profile *p);-// settings / proxiesvoid on_proxy_configure(GtkWidget *widget, gpointer data);void on_profiles_clicked(GtkWidget *widget, gpointer data);ProxyData *find_proxy_by_name(const char *name);@@ -123,13 +95,11 @@ uint32_t resolve_proxy_id(const char *name);void free_proxy_data(ProxyData *p);void apply_proxies_to_lib();-// rules sectionvoid on_proxy_rules_clicked(GtkWidget *widget, gpointer data);void free_rule_data(RuleData *rule);void apply_rules_to_lib();void refresh_rules_window();-// Logsvoid gui_log(const char *format, ...);void lib_log_callback(const char *message);void lib_connection_callback(const char *process_name, uint32_t pid, const char *dest_ip, uint16_t dest_port, const char *proxy_info);diff --git a/Linux/gui/gui_config.c b/Linux/gui/gui_config.cindex 433a182..75896f3 100644--- a/Linux/gui/gui_config.c+++ b/Linux/gui/gui_config.c@@ -3,8 +3,8 @@#define CONFIG_DIR_DEFAULT "/etc/proxybridge"-GList *g_profiles = NULL; // list of Profile-char *g_active_profile = NULL; // name of the active profile+GList *g_profiles = NULL;+char *g_active_profile = NULL;// PROXYBRIDGE_CONFIG_DIR overrides the default dir (used for testing)static char *config_dir() {@@ -12,17 +12,23 @@ static char *config_dir() {return g_strdup((env && *env) ? env : CONFIG_DIR_DEFAULT);}-static char *config_path() {- char *dir = config_dir();- char *path = g_strdup_printf("%s/config.ini", dir);- g_free(dir);- return path;+static char *esc(const char *s) {+ return g_uri_escape_string(s ? s : "", NULL, FALSE);+}++static char *unesc(const char *s) {+ char *out = g_uri_unescape_string(s ? s : "", NULL);+ return out ? out : g_strdup("");}-// ---- profiles ----+static void put_esc(FILE *f, const char *s, char sep) {+ char *e = esc(s);+ fputs(e, f);+ fputc(sep, f);+ g_free(e);+}static void free_profile(Profile *p) {- if (!p) return;for (GList *l = p->proxies; l != NULL; l = l->next) free_proxy_data((ProxyData *)l->data);for (GList *l = p->rules; l != NULL; l = l->next) free_rule_data((RuleData *)l->data);g_list_free(p->proxies);@@ -34,15 +40,13 @@ static void free_profile(Profile *p) {Profile *profile_find(const char *name) {if (!name) return NULL;- for (GList *l = g_profiles; l != NULL; l = l->next) {- Profile *p = (Profile *)l->data;- if (strcmp(p->name, name) == 0) return p;- }+ for (GList *l = g_profiles; l != NULL; l = l->next)+ if (strcmp(((Profile *)l->data)->name, name) == 0) return (Profile *)l->data;return NULL;}-// the working lists (g_proxies_list etc.) belong to the active profile, copy the heads back-void profile_sync_active() {+// the working lists belong to the active profile, copy the (possibly changed) heads back+static void profile_sync_active() {Profile *p = profile_find(g_active_profile);if (!p) return;p->proxies = g_proxies_list;@@ -56,6 +60,16 @@ static void load_globals_from(Profile *p) {g_default_proxy = p->default_proxy;}+void config_free_all() {+ profile_sync_active();+ g_list_free_full(g_profiles, (GDestroyNotify)free_profile);+ g_profiles = NULL;+ g_free(g_active_profile);+ g_active_profile = NULL;+ g_proxies_list = g_rules_list = NULL;+ g_default_proxy = NULL;+}+static Profile *profile_new_empty(const char *name) {Profile *p = g_malloc0(sizeof(Profile));p->name = g_strdup(name);@@ -81,12 +95,11 @@ static RuleData *copy_rule(const RuleData *src) {d->target_ports = g_strdup(src->target_ports ? src->target_ports : "");d->protocol = src->protocol;d->action = src->action;- d->proxy_name = src->proxy_name ? g_strdup(src->proxy_name) : NULL;+ d->proxy_name = g_strdup(src->proxy_name);d->enabled = src->enabled;return d;}-// new profile (empty, or a copy of the active one). NULL if the name is empty or takenProfile *profile_create(const char *name, bool copy_active) {if (!name || !*name || profile_find(name)) return NULL;profile_sync_active();@@ -114,12 +127,11 @@ bool profile_rename(Profile *p, const char *new_name) {return true;}-// makes the profile active (working lists swap). does not touch the librarybool profile_activate(const char *name) {Profile *p = profile_find(name);if (!p) return false;profile_sync_active();- if (g_active_profile != name) { // name may alias g_active_profile+ if (name != g_active_profile) {char *copy = g_strdup(name);g_free(g_active_profile);g_active_profile = copy;@@ -128,74 +140,59 @@ bool profile_activate(const char *name) {return true;}-// last profile cannot be deleted. deleting the active one activates another first+// the last profile stays; deleting the active one activates another firstbool profile_delete(Profile *p) {if (!p || !g_profiles || !g_profiles->next) return false;if (g_active_profile && strcmp(g_active_profile, p->name) == 0) {- Profile *other = NULL;- for (GList *l = g_profiles; l != NULL; l = l->next) if (l->data != p) { other = (Profile *)l->data; break; }- if (!other || !profile_activate(other->name)) return false;+ Profile *other = (Profile *)g_profiles->data;+ if (other == p) other = (Profile *)g_profiles->next->data;+ if (!profile_activate(other->name)) return false;}g_profiles = g_list_remove(g_profiles, p);free_profile(p);return true;}-// ---- save -----static void write_profile(FILE *f, Profile *prof) {- char *pn = g_uri_escape_string(prof->name, NULL, FALSE);- char *def_esc = g_uri_escape_string(prof->default_proxy ? prof->default_proxy : "", NULL, FALSE);- fprintf(f, "[PROFILE:%s]\n", pn);- fprintf(f, "defaultProxy=%s\n", def_esc);+ fputs("[PROFILE:", f);+ char *pn = esc(prof->name);+ fprintf(f, "%s]\ndefaultProxy=", pn);g_free(pn);- g_free(def_esc);+ put_esc(f, prof->default_proxy, '\n');- // proxies section, text fields are percent-encoded so '|' and newlines are safe- fprintf(f, "[PROXIES]\n");+ // fields are percent-encoded so '|' and newlines are safe: name|type|host|port|user|pass+ fputs("[PROXIES]\n", f);for (GList *l = prof->proxies; l != NULL; l = l->next) {ProxyData *p = (ProxyData *)l->data;- // format: name|type|host|port|user|pass- char *name = g_uri_escape_string(p->name ? p->name : "", NULL, FALSE);- char *host = g_uri_escape_string(p->host ? p->host : "", NULL, FALSE);- char *user = g_uri_escape_string(p->username ? p->username : "", NULL, FALSE);- char *pass = g_uri_escape_string(p->password ? p->password : "", NULL, FALSE);- fprintf(f, "%s|%d|%s|%u|%s|%s\n", name, p->type, host, p->port, user, pass);- g_free(name); g_free(host); g_free(user); g_free(pass);+ put_esc(f, p->name, '|');+ fprintf(f, "%d|", p->type);+ put_esc(f, p->host, '|');+ fprintf(f, "%u|", p->port);+ put_esc(f, p->username, '|');+ put_esc(f, p->password, '\n');}- // rules section- fprintf(f, "[RULES]\n");+ // id|protocol|action|enabled|procname|hosts|ports|proxyname+ fputs("[RULES]\n", f);for (GList *l = prof->rules; l != NULL; l = l->next) {- RuleData *rule = (RuleData *)l->data;- // format: id|protocol|action|enabled|procname|hosts|ports|proxyname- char *pname = g_uri_escape_string(rule->proxy_name ? rule->proxy_name : "", NULL, FALSE);- fprintf(f, "%u|%d|%d|%d|%s|%s|%s|%s\n",- rule->id,- rule->protocol,- rule->action,- rule->enabled,- rule->process_name ? rule->process_name : "",- rule->target_hosts ? rule->target_hosts : "",- rule->target_ports ? rule->target_ports : "",- pname- );- g_free(pname);+ RuleData *r = (RuleData *)l->data;+ fprintf(f, "%u|%d|%d|%d|%s|%s|%s|", r->id, r->protocol, r->action, r->enabled,+ r->process_name ? r->process_name : "", r->target_hosts ? r->target_hosts : "",+ r->target_ports ? r->target_ports : "");+ put_esc(f, r->proxy_name, '\n');}}-// save configvoid save_config() {profile_sync_active();char *dir = config_dir();- char *path = config_path();- struct stat st = {0};+ char *path = g_strdup_printf("%s/config.ini", dir);+ struct stat st;if (stat(dir, &st) == -1) {if (g_mkdir_with_parents(dir, 0700) != 0) {perror("failed to create config dir");- g_free(dir); g_free(path);- return;+ goto out;}} else if (chmod(dir, 0700) != 0) {perror("chmod config dir failed");@@ -203,40 +200,26 @@ void save_config() {int cfg_fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);if (cfg_fd < 0) {- printf("failed to save config to %s\n", path);- g_free(dir); g_free(path);- return;+ fprintf(stderr, "failed to save config to %s\n", path);+ goto out;}// mode on open only hits create; tighten existing 0644 installs too- if (fchmod(cfg_fd, 0600) != 0) {- perror("chmod config file failed");- }+ if (fchmod(cfg_fd, 0600) != 0) perror("chmod config file failed");FILE *f = fdopen(cfg_fd, "w");if (!f) {close(cfg_fd);- printf("failed to save config to %s\n", path);- g_free(dir); g_free(path);- return;+ fprintf(stderr, "failed to save config to %s\n", path);+ goto out;}- // settings section, global- char *act_esc = g_uri_escape_string(g_active_profile ? g_active_profile : "", NULL, FALSE);- fprintf(f, "[SETTINGS]\n");- fprintf(f, "activeProfile=%s\n", act_esc);- g_free(act_esc);- fprintf(f, "logging=%d\n", g_chk_logging);- fprintf(f, "dns=%d\n", g_chk_dns);-+ fputs("[SETTINGS]\nactiveProfile=", f);+ put_esc(f, g_active_profile, '\n');+ fprintf(f, "logging=%d\ndns=%d\n", g_chk_logging, g_chk_dns);for (GList *l = g_profiles; l != NULL; l = l->next) write_profile(f, (Profile *)l->data);-fclose(f);- g_free(dir); g_free(path);-}--// decode a percent-encoded field, never returns NULL-static char *unescape_field(const char *src) {- char *out = g_uri_unescape_string(src ? src : "", NULL);- return out ? out : g_strdup("");+out:+ g_free(dir);+ g_free(path);}static ProxyType proxy_type_from_int(int v) {@@ -244,43 +227,89 @@ static ProxyType proxy_type_from_int(int v) {}static ProxyData *find_in_list(GList *list, const char *name) {- for (GList *l = list; l != NULL; l = l->next) {- ProxyData *p = (ProxyData *)l->data;- if (p->name && strcmp(p->name, name) == 0) return p;- }+ for (GList *l = list; l != NULL; l = l->next)+ if (strcmp(((ProxyData *)l->data)->name, name) == 0) return (ProxyData *)l->data;return NULL;}-// load settings from file. old files (no profiles) end up in a profile called "Default"+static ProxyData *parse_proxy_line(char *line) {+ char *fields[6] = {NULL};+ int n = 0;+ char *tok;+ while (n < 6 && (tok = strsep(&line, "|")) != NULL) fields[n++] = tok;+ if (n < 4) return NULL;++ int port = atoi(fields[3]);+ ProxyData *px = g_malloc0(sizeof(ProxyData));+ px->name = unesc(fields[0]);+ px->type = proxy_type_from_int(atoi(fields[1]));+ px->host = unesc(fields[2]);+ px->port = (port >= 1 && port <= 65535) ? (uint16_t)port : 0;+ px->username = unesc(n > 4 ? fields[4] : "");+ px->password = unesc(n > 5 ? fields[5] : "");+ return px;+}++static RuleData *parse_rule_line(char *line) {+ RuleData *rule = g_malloc0(sizeof(RuleData));+ char *tok;+ int idx = 0;+ while ((tok = strsep(&line, "|")) != NULL) {+ switch (idx++) {+ case 1: rule->protocol = atoi(tok); break;+ case 2: rule->action = atoi(tok); break;+ case 3: rule->enabled = atoi(tok); break;+ case 4: rule->process_name = g_strdup(tok); break;+ case 5: rule->target_hosts = g_strdup(tok); break;+ case 6: rule->target_ports = g_strdup(tok); break;+ case 7: rule->proxy_name = unesc(tok); break;+ }+ }+ // old files can hold garbage, ids belong to the library and are assigned when the rule is added+ if (idx < 4 || rule->protocol > RULE_PROTOCOL_BOTH || rule->action > RULE_ACTION_BLOCK) {+ free_rule_data(rule);+ return NULL;+ }+ if (!rule->process_name) rule->process_name = g_strdup("");+ if (!rule->target_hosts) rule->target_hosts = g_strdup("");+ if (!rule->target_ports) rule->target_ports = g_strdup("");+ return rule;+}++// files without profile blocks (old format) end up in a profile called "Default"void load_config() {- char *path = config_path();- chmod(path, 0600); // old installs might still be world readable+ char *dir = config_dir();+ char *path = g_strdup_printf("%s/config.ini", dir);+ chmod(path, 0600);FILE *f = fopen(path, "r");+ g_free(dir);g_free(path);char line[8192];- int section = 0; // 0=none, 1=settings, 2=rules, 3=proxies, 4=profile header+ int section = 0; // 1=settings, 2=rules, 3=proxies, 4=profile headerProfile *cur = NULL;char *saved_active = NULL;- // old single proxy config (pre multi-proxy), migrated to a proxy called "default"+ // pre multi-proxy config, migrated to a proxy called "default"char old_ip[256] = "", old_user[256] = "", old_pass[256] = "";int old_port = 0, old_type = PROXY_TYPE_SOCKS5;while (f && fgets(line, sizeof(line), f)) {- // trim newlineline[strcspn(line, "\r\n")] = 0;-- if (strlen(line) == 0 || line[0] == '#') continue;+ if (!line[0] || line[0] == '#') continue;if (strcmp(line, "[SETTINGS]") == 0) { section = 1; continue; }- if (strcmp(line, "[RULES]") == 0) { section = 2; if (!cur) cur = profile_new_empty("Default"); continue; }- if (strcmp(line, "[PROXIES]") == 0) { section = 3; if (!cur) cur = profile_new_empty("Default"); continue; }- if (strncmp(line, "[PROFILE:", 9) == 0 && line[strlen(line) - 1] == ']') {- line[strlen(line) - 1] = 0;- char *pn = unescape_field(line + 9);- cur = (pn[0] != '\0') ? profile_find(pn) : NULL;- if (!cur && pn[0] != '\0') cur = profile_new_empty(pn);+ if (strcmp(line, "[RULES]") == 0 || strcmp(line, "[PROXIES]") == 0) {+ section = line[1] == 'R' ? 2 : 3;+ if (!cur) cur = profile_new_empty("Default");+ continue;+ }+ size_t len = strlen(line);+ if (strncmp(line, "[PROFILE:", 9) == 0 && line[len - 1] == ']') {+ line[len - 1] = 0;+ char *pn = unesc(line + 9);+ cur = pn[0] ? profile_find(pn) : NULL;+ if (!cur && pn[0]) cur = profile_new_empty(pn);g_free(pn);section = cur ? 4 : 0;continue;@@ -289,87 +318,37 @@ void load_config() {if (section == 1 || section == 4) {char *val = strchr(line, '=');if (!val) continue;- *val = 0; val++;-- if (section == 1 && strcmp(line, "ip") == 0) g_strlcpy(old_ip, val, sizeof(old_ip));- else if (section == 1 && strcmp(line, "port") == 0) old_port = atoi(val);- else if (section == 1 && strcmp(line, "type") == 0) old_type = atoi(val);- else if (section == 1 && strcmp(line, "user") == 0) g_strlcpy(old_user, val, sizeof(old_user));- else if (section == 1 && strcmp(line, "pass") == 0) g_strlcpy(old_pass, val, sizeof(old_pass));- else if (strcmp(line, "defaultProxy") == 0) {- // profile blocks own it, old files kept it in [SETTINGS]+ *val++ = 0;++ if (strcmp(line, "defaultProxy") == 0) {if (!cur) cur = profile_new_empty("Default");g_free(cur->default_proxy);- cur->default_proxy = unescape_field(val);- if (cur->default_proxy[0] == '\0') { g_free(cur->default_proxy); cur->default_proxy = NULL; }- }- else if (section == 1 && strcmp(line, "activeProfile") == 0) {- g_free(saved_active);- saved_active = unescape_field(val);+ cur->default_proxy = unesc(val);+ if (!cur->default_proxy[0]) { g_free(cur->default_proxy); cur->default_proxy = NULL; }}- else if (section == 1 && strcmp(line, "logging") == 0) g_chk_logging = atoi(val);- else if (section == 1 && strcmp(line, "dns") == 0) g_chk_dns = atoi(val);+ else if (section != 1) continue;+ else if (strcmp(line, "ip") == 0) g_strlcpy(old_ip, val, sizeof(old_ip));+ else if (strcmp(line, "port") == 0) old_port = atoi(val);+ else if (strcmp(line, "type") == 0) old_type = atoi(val);+ else if (strcmp(line, "user") == 0) g_strlcpy(old_user, val, sizeof(old_user));+ else if (strcmp(line, "pass") == 0) g_strlcpy(old_pass, val, sizeof(old_pass));+ else if (strcmp(line, "activeProfile") == 0) { g_free(saved_active); saved_active = unesc(val); }+ else if (strcmp(line, "logging") == 0) g_chk_logging = atoi(val);+ else if (strcmp(line, "dns") == 0) g_chk_dns = atoi(val);}else if (section == 3 && cur) {- // parse proxy line: name|type|host|port|user|pass- char *fields[6] = {NULL};- char *p = line;- int idx = 0;- char *token;- while (idx < 6 && (token = strsep(&p, "|")) != NULL) fields[idx++] = token;- if (idx < 4) continue;-- int port = atoi(fields[3]);- ProxyData *px = g_malloc0(sizeof(ProxyData));- px->name = unescape_field(fields[0]);- px->type = proxy_type_from_int(atoi(fields[1]));- px->host = unescape_field(fields[2]);- px->port = (port >= 1 && port <= 65535) ? (uint16_t)port : 0;- px->username = unescape_field(idx > 4 ? fields[4] : "");- px->password = unescape_field(idx > 5 ? fields[5] : "");- if (px->name[0] == '\0' || find_in_list(cur->proxies, px->name)) {- free_proxy_data(px);- continue;- }- cur->proxies = g_list_append(cur->proxies, px);+ ProxyData *px = parse_proxy_line(line);+ if (px && (!px->name[0] || find_in_list(cur->proxies, px->name))) { free_proxy_data(px); px = NULL; }+ if (px) cur->proxies = g_list_append(cur->proxies, px);}else if (section == 2 && cur) {- // parse rule line- RuleData *rule = g_malloc0(sizeof(RuleData));- char *p = line;- char *token;- int idx = 0;-- while ((token = strsep(&p, "|")) != NULL) {- switch(idx) {- case 0: rule->id = atoi(token); break;- case 1: rule->protocol = atoi(token); break;- case 2: rule->action = atoi(token); break;- case 3: rule->enabled = atoi(token); break;- case 4: rule->process_name = g_strdup(token); break;- case 5: rule->target_hosts = g_strdup(token); break;- case 6: rule->target_ports = g_strdup(token); break;- case 7: rule->proxy_name = unescape_field(token); break;- }- idx++;- }-- // old files can hold garbage, keep enums in range- if (idx >= 4 && rule->protocol <= RULE_PROTOCOL_BOTH && rule->action <= RULE_ACTION_BLOCK) {- if (!rule->process_name) rule->process_name = g_strdup("");- if (!rule->target_hosts) rule->target_hosts = g_strdup("");- if (!rule->target_ports) rule->target_ports = g_strdup("");- rule->id = 0; // ids belong to the library, assigned when the rule is added- cur->rules = g_list_append(cur->rules, rule);- } else {- free_rule_data(rule);- }+ RuleData *rule = parse_rule_line(line);+ if (rule) cur->rules = g_list_append(cur->rules, rule);}}if (f) fclose(f);- // migrate old single proxy config into the "Default" profile- if (old_ip[0] != '\0' && old_port >= 1 && old_port <= 65535) {+ if (old_ip[0] && old_port >= 1 && old_port <= 65535) {Profile *d = profile_find("Default");if (!d) d = profile_new_empty("Default");if (!d->proxies) {@@ -386,10 +365,8 @@ void load_config() {}}- // always at least one profileif (!g_profiles) profile_new_empty("Default");- // default points to nothing -> first proxyfor (GList *l = g_profiles; l != NULL; l = l->next) {Profile *p = (Profile *)l->data;if (p->proxies && (!p->default_proxy || !find_in_list(p->proxies, p->default_proxy))) {diff --git a/Linux/gui/gui_json.c b/Linux/gui/gui_json.cnew file mode 100644index 0000000..7742949--- /dev/null+++ b/Linux/gui/gui_json.c@@ -0,0 +1,140 @@+#include "gui.h"++static char *escape_json_string(const char *src) {+ GString *str = g_string_new("");+ for (const char *p = src ? src : ""; *p; p++) {+ switch (*p) {+ case '\\': g_string_append(str, "\\\\"); break;+ case '"': g_string_append(str, "\\\""); break;+ case '\n': g_string_append(str, "\\n"); break;+ case '\r': g_string_append(str, "\\r"); break;+ case '\t': g_string_append(str, "\\t"); break;+ default:+ if ((unsigned char)*p < 0x20) g_string_append_printf(str, "\\u%04x", (unsigned char)*p);+ else g_string_append_c(str, *p);+ }+ }+ return g_string_free(str, FALSE);+}++// returns NULL if the key is missing, its value is not a string, or the string is unterminated+char *extract_sub_json_str(const char *json, const char *key) {+ char *needle = g_strdup_printf("\"%s\"", key);+ const char *k = strstr(json, needle);+ const char *v = k ? strchr(k + strlen(needle), ':') : NULL;+ g_free(needle);+ if (!v) return NULL;+ v++;+ while (*v == ' ' || *v == '\t' || *v == '\n' || *v == '\r') v++;+ if (*v != '"') return NULL;+ v++;++ GString *out = g_string_new("");+ while (*v && *v != '"') {+ if (*v == '\\' && v[1]) {+ v++;+ g_string_append_c(out, *v == 'n' ? '\n' : *v == 'r' ? '\r' : *v == 't' ? '\t' : *v);+ } else {+ g_string_append_c(out, *v);+ }+ v++;+ }+ if (*v != '"') { g_string_free(out, TRUE); return NULL; }+ return g_string_free(out, FALSE);+}++static bool json_has_key(const char *json, const char *key) {+ char *needle = g_strdup_printf("\"%s\"", key);+ bool found = strstr(json, needle) != NULL;+ g_free(needle);+ return found;+}++static bool json_bool(const char *json, const char *key, bool def) {+ if (!json_has_key(json, key)) return def;+ char *needle = g_strdup_printf("\"%s\"", key);+ const char *colon = strchr(strstr(json, needle) + strlen(needle), ':');+ g_free(needle);+ if (!colon) return def;+ colon++;+ while (*colon == ' ' || *colon == '\t' || *colon == '\n' || *colon == '\r') colon++;+ return strncmp(colon, "true", 4) == 0;+}++// '}' closing the object that starts at p, skipping braces inside strings+static const char *object_end(const char *p) {+ bool in_str = false;+ for (p++; *p; p++) {+ if (in_str) {+ if (*p == '\\' && p[1]) p++;+ else if (*p == '"') in_str = false;+ } else if (*p == '"') {+ in_str = true;+ } else if (*p == '}') {+ return p;+ }+ }+ return NULL;+}++static char *first_str(const char *obj, const char *key, const char *alt) {+ char *s = extract_sub_json_str(obj, key);+ return s ? s : extract_sub_json_str(obj, alt);+}++static bool name_is(const char *s, const char *want) {+ return s && g_ascii_strcasecmp(s, want) == 0;+}++// accepts our keys and the macOS ones. unknown action strings (macOS stores a proxy id) mean PROXY+int rules_from_json(const char *json, RuleImportCb cb, void *ud) {+ int count = 0;+ for (const char *cur = json; (cur = strchr(cur, '{')) != NULL; ) {+ const char *end = object_end(cur);+ if (!end) break;+ char *obj = g_strndup(cur, end - cur + 1);+ cur = end + 1;++ RuleData r = {0};+ r.process_name = extract_sub_json_str(obj, "processNames");+ r.target_hosts = extract_sub_json_str(obj, "targetHosts");+ r.target_ports = extract_sub_json_str(obj, "targetPorts");+ char *proto = first_str(obj, "protocol", "ruleProtocol");+ char *act = first_str(obj, "action", "ruleAction");+ r.proxy_name = extract_sub_json_str(obj, "proxy");+ r.enabled = json_bool(obj, "enabled", true);+ if (!r.target_hosts) r.target_hosts = g_strdup("*");+ if (!r.target_ports) r.target_ports = g_strdup("*");+ r.protocol = name_is(proto, "TCP") ? RULE_PROTOCOL_TCP : name_is(proto, "UDP") ? RULE_PROTOCOL_UDP : RULE_PROTOCOL_BOTH;+ r.action = name_is(act, "DIRECT") ? RULE_ACTION_DIRECT : name_is(act, "BLOCK") ? RULE_ACTION_BLOCK : RULE_ACTION_PROXY;++ cb(&r, ++count, ud);++ g_free(r.process_name); g_free(r.target_hosts); g_free(r.target_ports); g_free(r.proxy_name);+ g_free(proto); g_free(act); g_free(obj);+ }+ return count;+}++char *rules_to_json(GList *rules, bool only_selected) {+ GString *out = g_string_new("[\n");+ bool first = true;+ for (GList *l = rules; l != NULL; l = l->next) {+ RuleData *r = (RuleData *)l->data;+ if (only_selected && !r->selected) continue;+ char *proc = escape_json_string(r->process_name);+ char *host = escape_json_string(r->target_hosts);+ char *port = escape_json_string(r->target_ports);+ char *pxy = escape_json_string(r->action == RULE_ACTION_PROXY ? r->proxy_name : NULL);+ const char *proto = r->protocol == RULE_PROTOCOL_TCP ? "TCP" : r->protocol == RULE_PROTOCOL_UDP ? "UDP" : "BOTH";+ const char *act = r->action == RULE_ACTION_PROXY ? "PROXY" : r->action == RULE_ACTION_DIRECT ? "DIRECT" : "BLOCK";+ g_string_append_printf(out, "%s {\n \"processNames\": \"%s\",\n \"targetHosts\": \"%s\",\n \"targetPorts\": \"%s\",\n"+ " \"protocol\": \"%s\",\n \"ruleProtocol\": \"%s\",\n \"action\": \"%s\",\n \"ruleAction\": \"%s\",\n"+ " \"proxy\": \"%s\",\n \"enabled\": %s\n }",+ first ? "" : ",\n", proc, host, port, proto, proto, act, act, pxy, r->enabled ? "true" : "false");+ g_free(proc); g_free(host); g_free(port); g_free(pxy);+ first = false;+ }+ g_string_append(out, "\n]\n");+ return g_string_free(out, FALSE);+}diff --git a/Linux/gui/gui_logs.c b/Linux/gui/gui_logs.cindex 8b7520f..b4d8055 100644--- a/Linux/gui/gui_logs.c+++ b/Linux/gui/gui_logs.c@@ -1,15 +1,16 @@#include "gui.h"-// filter logs based on search+#define MAX_LINES 100+static void filter_text_view(GtkTextBuffer *buffer, const char *text) {if (!buffer) return;GtkTextIter start, end;gtk_text_buffer_get_bounds(buffer, &start, &end);gtk_text_buffer_remove_tag_by_name(buffer, "hidden", &start, &end);+ if (!text || !*text) return;- if (!text || strlen(text) == 0) return;-+ char *lower_search = g_utf8_strdown(text, -1);GtkTextIter line_start = start;while (!gtk_text_iter_is_end(&line_start)) {GtkTextIter line_end = line_start;@@ -17,33 +18,25 @@ static void filter_text_view(GtkTextBuffer *buffer, const char *text) {gtk_text_iter_forward_to_line_end(&line_end);char *line_text = gtk_text_buffer_get_text(buffer, &line_start, &line_end, FALSE);-- // search case insensitivechar *lower_line = g_utf8_strdown(line_text, -1);- char *lower_search = g_utf8_strdown(text, -1);-if (!strstr(lower_line, lower_search)) {- GtkTextIter next_line = line_end;- gtk_text_iter_forward_char(&next_line); // include newline- gtk_text_buffer_apply_tag_by_name(buffer, "hidden", &line_start, &next_line);+ GtkTextIter next_line = line_end;+ gtk_text_iter_forward_char(&next_line);+ gtk_text_buffer_apply_tag_by_name(buffer, "hidden", &line_start, &next_line);}-g_free(lower_line);- g_free(lower_search);g_free(line_text);-gtk_text_iter_forward_line(&line_start);}+ g_free(lower_search);}void on_search_conn_changed(GtkSearchEntry *entry, gpointer user_data) {- const char *text = gtk_entry_get_text(GTK_ENTRY(entry));- filter_text_view(conn_buffer, text);+ filter_text_view(conn_buffer, gtk_entry_get_text(GTK_ENTRY(entry)));}void on_search_log_changed(GtkSearchEntry *entry, gpointer user_data) {- const char *text = gtk_entry_get_text(GTK_ENTRY(entry));- filter_text_view(log_buffer, text);+ filter_text_view(log_buffer, gtk_entry_get_text(GTK_ENTRY(entry)));}void on_clear_conn_clicked(GtkButton *button, gpointer user_data) {@@ -54,87 +47,52 @@ void on_clear_log_clicked(GtkButton *button, gpointer user_data) {if (log_buffer) gtk_text_buffer_set_text(log_buffer, "", 0);}-static void free_connection_data(ConnectionData *data) {- if (data) {- g_free(data->process_name);- g_free(data->dest_ip);- g_free(data->proxy_info);- g_free(data->timestamp);- g_free(data);+// library strings are not guaranteed utf8+static void append_line(GtkTextBuffer *buffer, char *line) {+ if (buffer) {+ if (!g_utf8_validate(line, -1, NULL)) {+ char *fixed = g_utf8_make_valid(line, -1);+ g_free(line);+ line = fixed;+ }+ GtkTextIter end;+ gtk_text_buffer_get_end_iter(buffer, &end);+ gtk_text_buffer_insert(buffer, &end, line, -1);+ trim_buffer_lines(buffer, MAX_LINES);}+ g_free(line);}-// update logs from main threadstatic gboolean update_log_gui(gpointer user_data) {- LogData *data = (LogData *)user_data;- if (!data) return FALSE;-- if (log_buffer) {- GtkTextIter end;- gtk_text_buffer_get_end_iter(log_buffer, &end);-- char *time_str = get_current_time_str();- char *full_msg = g_strdup_printf("%s %s\n", time_str, data->message);- g_free(time_str);-- // library strings are not guaranteed utf8- if (!g_utf8_validate(full_msg, -1, NULL)) {- char *fixed = g_utf8_make_valid(full_msg, -1);- g_free(full_msg);- full_msg = fixed;- }- gtk_text_buffer_insert(log_buffer, &end, full_msg, -1);- g_free(full_msg);-- trim_buffer_lines(log_buffer, 100);- }-- g_free(data->message);- g_free(data);- return FALSE; // done+ char *time_str = get_current_time_str();+ append_line(log_buffer, g_strdup_printf("%s %s\n", time_str, (char *)user_data));+ g_free(time_str);+ g_free(user_data);+ return FALSE;}-// update conn infostatic gboolean update_connection_gui_append(gpointer user_data) {- ConnectionData *data = (ConnectionData *)user_data;- if (!data) return FALSE;-- if (conn_buffer) {- GtkTextIter end;- gtk_text_buffer_get_end_iter(conn_buffer, &end);-- char *line_buffer = g_strdup_printf("%s %s (PID:%u) -> %s:%u via %s\n",- data->timestamp, data->process_name, data->pid, data->dest_ip, data->dest_port, data->proxy_info);- if (!g_utf8_validate(line_buffer, -1, NULL)) {- char *fixed = g_utf8_make_valid(line_buffer, -1);- g_free(line_buffer);- line_buffer = fixed;- }-- gtk_text_buffer_insert(conn_buffer, &end, line_buffer, -1);- g_free(line_buffer);-- trim_buffer_lines(conn_buffer, 100);- }-- free_connection_data(data);+ ConnectionData *d = (ConnectionData *)user_data;+ append_line(conn_buffer, g_strdup_printf("%s %s (PID:%u) -> %s:%u via %s\n",+ d->timestamp, d->process_name, d->pid, d->dest_ip, d->dest_port, d->proxy_info));+ g_free(d->process_name);+ g_free(d->dest_ip);+ g_free(d->proxy_info);+ g_free(d->timestamp);+ g_free(d);return FALSE;}void lib_log_callback(const char *message) {- LogData *data = g_malloc0(sizeof(LogData));- data->message = g_strdup(message ? message : "");- g_idle_add(update_log_gui, data);+ g_idle_add(update_log_gui, g_strdup(message ? message : ""));}-// log a message from the gui itself, same path as library logsvoid gui_log(const char *format, ...) {va_list args;va_start(args, format);char *msg = g_strdup_vprintf(format, args);va_end(args);- lib_log_callback(msg);- g_free(msg);+ g_idle_add(update_log_gui, msg);}void lib_connection_callback(const char *process_name, uint32_t pid, const char *dest_ip, uint16_t dest_port, const char *proxy_info) {diff --git a/Linux/gui/gui_rules.c b/Linux/gui/gui_rules.cindex 685d50a..435e9f4 100644--- a/Linux/gui/gui_rules.c+++ b/Linux/gui/gui_rules.c@@ -4,26 +4,26 @@ static GtkWidget *rules_window = NULL;static GtkWidget *rules_list_box = NULL;static GtkWidget *btn_select_all_header = NULL;-// forwardstatic void refresh_rules_ui();void free_rule_data(RuleData *rule) {- if (rule) {- g_free(rule->process_name);- g_free(rule->target_hosts);- g_free(rule->target_ports);- g_free(rule->proxy_name);- g_free(rule);- }+ if (!rule) return;+ g_free(rule->process_name);+ g_free(rule->target_hosts);+ g_free(rule->target_ports);+ g_free(rule->proxy_name);+ g_free(rule);+}++static GtkWindow *parent_window() {+ return GTK_WINDOW(rules_window ? rules_window : window);}-// position of the rule in the library list. rules the library rejected (id 0) are not in it+// position in the library list, rules it rejected (id 0) are not in itstatic int lib_index_of(RuleData *rule) {int idx = 0;- for (GList *l = g_rules_list; l != NULL; l = l->next) {- if (l->data == rule) break;+ for (GList *l = g_rules_list; l != NULL && l->data != rule; l = l->next)if (((RuleData *)l->data)->id != 0) idx++;- }return idx;}@@ -31,20 +31,15 @@ static uint32_t rule_proxy_id(RuleAction action, const char *proxy_name) {return action == RULE_ACTION_PROXY ? resolve_proxy_id(proxy_name) : 0;}-// push the stored rules to the library, call after the proxies were added and before ProxyBridge_Startvoid apply_rules_to_lib() {- ProxyBridge_ClearRules();int n = 1;for (GList *l = g_rules_list; l != NULL; l = l->next, n++) {RuleData *r = (RuleData *)l->data;char err[256] = "";r->id = ProxyBridge_AddRule(r->process_name, r->target_hosts, r->target_ports, r->protocol, r->action,rule_proxy_id(r->action, r->proxy_name), err, sizeof(err));- if (r->id == 0) {- gui_log("Rule #%d (%s) not loaded: %s", n, r->process_name, err[0] ? err : "rejected");- continue;- }- if (!r->enabled) ProxyBridge_DisableRule(r->id);+ if (r->id == 0) gui_log("Rule #%d (%s) not loaded: %s", n, r->process_name, err[0] ? err : "rejected");+ else if (!r->enabled) ProxyBridge_DisableRule(r->id);}}@@ -69,14 +64,12 @@ static void on_rule_toggle(GtkToggleButton *btn, gpointer data) {static void on_rule_move(RuleData *rule, int dir) {GList *link = g_list_find(g_rules_list, rule);- if (!link) return;- GList *other = dir < 0 ? link->prev : link->next;+ GList *other = link ? (dir < 0 ? link->prev : link->next) : NULL;if (!other) return;- // swap the data pointers, keeps the list head valid- gpointer tmp = link->data;+ // swap payloads so the list head stays validlink->data = other->data;- other->data = tmp;+ other->data = rule;if (rule->id != 0 && !ProxyBridge_MoveRule(rule->id, lib_index_of(rule)))gui_log("Could not reorder rule %u in the engine", rule->id);@@ -88,18 +81,13 @@ static void on_rule_move_up(GtkWidget *widget, gpointer data) { on_rule_move((Rustatic void on_rule_move_down(GtkWidget *widget, gpointer data) { on_rule_move((RuleData *)data, 1); }static void on_browse_clicked(GtkWidget *widget, gpointer data) {- GtkWidget *entry = (GtkWidget *)data;- GtkWidget *dialog = gtk_file_chooser_dialog_new("Select Application",- NULL,- GTK_FILE_CHOOSER_ACTION_OPEN,- "_Cancel", GTK_RESPONSE_CANCEL,- "_Select", GTK_RESPONSE_ACCEPT,- NULL);+ GtkWidget *dialog = gtk_file_chooser_dialog_new("Select Application", NULL, GTK_FILE_CHOOSER_ACTION_OPEN,+ "_Cancel", GTK_RESPONSE_CANCEL, "_Select", GTK_RESPONSE_ACCEPT, NULL);if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));if (filename) {char *base = g_path_get_basename(filename);- gtk_entry_set_text(GTK_ENTRY(entry), base);+ gtk_entry_set_text(GTK_ENTRY(data), base);g_free(base);g_free(filename);}@@ -107,187 +95,116 @@ static void on_browse_clicked(GtkWidget *widget, gpointer data) {gtk_widget_destroy(dialog);}-// proxy combo only matters for PROXY rulesstatic void on_action_changed(GtkComboBox *combo, gpointer data) {gtk_widget_set_sensitive(GTK_WIDGET(data), gtk_combo_box_get_active(combo) == RULE_ACTION_PROXY);}+static void set_str(char **dst, const char *src) {+ g_free(*dst);+ *dst = g_strdup(src);+}++// returns the saved rule, NULL while the engine rejects it (err filled)+static RuleData *save_rule(RuleData *rule, const char *proc, const char *hosts, const char *ports,+ RuleProtocol proto, RuleAction action, const char *proxy_name, char *err, size_t err_size) {+ if (!ProxyBridge_ValidateRule(proc, hosts, ports, err, err_size)) return NULL;+ uint32_t pid = rule_proxy_id(action, proxy_name);++ if (rule && rule->id != 0) {+ if (!ProxyBridge_EditRule(rule->id, proc, hosts, ports, proto, action, pid, err, err_size)) return NULL;+ } else {+ // new rule, or one the engine rejected at load time+ uint32_t id = ProxyBridge_AddRule(proc, hosts, ports, proto, action, pid, err, err_size);+ if (id == 0) return NULL;+ if (rule && !rule->enabled) ProxyBridge_DisableRule(id);+ if (!rule) {+ rule = g_malloc0(sizeof(RuleData));+ rule->enabled = true;+ g_rules_list = g_list_append(g_rules_list, rule);+ }+ rule->id = id;+ ProxyBridge_MoveRule(id, lib_index_of(rule));+ }+ set_str(&rule->process_name, proc);+ set_str(&rule->target_hosts, hosts);+ set_str(&rule->target_ports, ports);+ set_str(&rule->proxy_name, proxy_name);+ rule->protocol = proto;+ rule->action = action;+ return rule;+}+static void open_rule_dialog(RuleData *rule) {- GtkWidget *dialog = gtk_dialog_new();- gtk_window_set_title(GTK_WINDOW(dialog), rule ? "Edit Rule" : "Add Rule");- gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(rules_window ? rules_window : window));- gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);+ GtkWidget *dialog = gtk_dialog_new_with_buttons(rule ? "Edit Rule" : "Add Rule", parent_window(),+ GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,+ "Cancel", GTK_RESPONSE_CANCEL, "Save", GTK_RESPONSE_ACCEPT, NULL);gtk_window_set_default_size(GTK_WINDOW(dialog), 500, 400);-- GtkWidget *content = gtk_dialog_get_content_area(GTK_DIALOG(dialog));GtkWidget *grid = gtk_grid_new();gtk_grid_set_row_spacing(GTK_GRID(grid), 8);gtk_grid_set_column_spacing(GTK_GRID(grid), 10);gtk_container_set_border_width(GTK_CONTAINER(grid), 15);- // proc inputGtkWidget *proc_entry = gtk_entry_new();GtkWidget *browse_btn = gtk_button_new_with_label("Browse...");g_signal_connect(browse_btn, "clicked", G_CALLBACK(on_browse_clicked), proc_entry);GtkWidget *proc_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);gtk_box_pack_start(GTK_BOX(proc_box), proc_entry, TRUE, TRUE, 0);gtk_box_pack_start(GTK_BOX(proc_box), browse_btn, FALSE, FALSE, 0);- gtk_widget_set_hexpand(proc_box, TRUE);GtkWidget *host_entry = gtk_entry_new();GtkWidget *port_entry = gtk_entry_new();+ GtkWidget *proto_combo = combo_new("TCP", "UDP", "BOTH", NULL);+ GtkWidget *action_combo = combo_new("PROXY", "DIRECT", "BLOCK", NULL);- // protocol list- GtkWidget *proto_combo = gtk_combo_box_text_new();- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(proto_combo), "TCP");- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(proto_combo), "UDP");- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(proto_combo), "BOTH");-- // action list- GtkWidget *action_combo = gtk_combo_box_text_new();- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(action_combo), "PROXY");- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(action_combo), "DIRECT");- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(action_combo), "BLOCK");-- // proxy list: entry 0 = default proxy, then one per configured proxy (same order as g_proxies_list)- GtkWidget *proxy_combo = gtk_combo_box_text_new();- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(proxy_combo), "Default proxy");+ // entry 0 = default proxy, then one per proxy in g_proxies_list order+ GtkWidget *proxy_combo = combo_new("Default proxy", NULL);int proxy_sel = 0, pi = 1;for (GList *l = g_proxies_list; l != NULL; l = l->next, pi++) {ProxyData *p = (ProxyData *)l->data;gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(proxy_combo), p->name);- if (rule && rule->proxy_name && p->name && strcmp(rule->proxy_name, p->name) == 0) proxy_sel = pi;+ if (rule && rule->proxy_name && strcmp(rule->proxy_name, p->name) == 0) proxy_sel = pi;}gtk_combo_box_set_active(GTK_COMBO_BOX(proxy_combo), proxy_sel);g_signal_connect(action_combo, "changed", G_CALLBACK(on_action_changed), proxy_combo);- if (rule) {- gtk_entry_set_text(GTK_ENTRY(proc_entry), rule->process_name);- gtk_entry_set_text(GTK_ENTRY(host_entry), rule->target_hosts);- gtk_entry_set_text(GTK_ENTRY(port_entry), rule->target_ports);- gtk_combo_box_set_active(GTK_COMBO_BOX(proto_combo), rule->protocol);- gtk_combo_box_set_active(GTK_COMBO_BOX(action_combo), rule->action);- } else {- gtk_entry_set_text(GTK_ENTRY(port_entry), "*");- gtk_entry_set_text(GTK_ENTRY(host_entry), "*");- gtk_combo_box_set_active(GTK_COMBO_BOX(proto_combo), 2); // BOTH default- gtk_combo_box_set_active(GTK_COMBO_BOX(action_combo), 0); // PROXY default- }-- int row = 0;- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Process Name:"), 0, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), proc_box, 1, row, 1, 1); row++;-- GtkWidget *proc_hint = gtk_label_new("Example: firefox; chrome; /usr/bin/wget");- gtk_style_context_add_class(gtk_widget_get_style_context(proc_hint), "dim-label");- gtk_widget_set_halign(proc_hint, GTK_ALIGN_START);- gtk_grid_attach(GTK_GRID(grid), proc_hint, 1, row, 1, 1); row++;-- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Target Host:"), 0, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), host_entry, 1, row, 1, 1); row++;-- GtkWidget *host_hint = gtk_label_new("Example: 192.168.1.*; 10.0.0.0/8; 10.0.0.1-10.0.0.50; github.com; *.github.com; * (domains are matched via DNS answers)");- gtk_label_set_line_wrap(GTK_LABEL(host_hint), TRUE);- gtk_label_set_max_width_chars(GTK_LABEL(host_hint), 60);- gtk_style_context_add_class(gtk_widget_get_style_context(host_hint), "dim-label");- gtk_widget_set_halign(host_hint, GTK_ALIGN_START);- gtk_grid_attach(GTK_GRID(grid), host_hint, 1, row, 1, 1); row++;-- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Target Port:"), 0, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), port_entry, 1, row, 1, 1); row++;-- GtkWidget *port_hint = gtk_label_new("Example: 80; 443; 8000-8080; *");- gtk_style_context_add_class(gtk_widget_get_style_context(port_hint), "dim-label");- gtk_widget_set_halign(port_hint, GTK_ALIGN_START);- gtk_grid_attach(GTK_GRID(grid), port_hint, 1, row, 1, 1); row++;-- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Protocol:"), 0, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), proto_combo, 1, row, 1, 1); row++;-- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Action:"), 0, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), action_combo, 1, row, 1, 1); row++;-- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Proxy:"), 0, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), proxy_combo, 1, row, 1, 1); row++;-- // inline validation error- GtkWidget *err_label = gtk_label_new("");- gtk_widget_set_halign(err_label, GTK_ALIGN_START);- gtk_label_set_xalign(GTK_LABEL(err_label), 0);- gtk_label_set_line_wrap(GTK_LABEL(err_label), TRUE);- gtk_label_set_max_width_chars(GTK_LABEL(err_label), 60);- gtk_grid_attach(GTK_GRID(grid), err_label, 0, row, 2, 1); row++;-- gtk_container_add(GTK_CONTAINER(content), grid);-- gtk_dialog_add_button(GTK_DIALOG(dialog), "Cancel", GTK_RESPONSE_CANCEL);- gtk_dialog_add_button(GTK_DIALOG(dialog), "Save", GTK_RESPONSE_ACCEPT);+ gtk_entry_set_text(GTK_ENTRY(proc_entry), rule ? rule->process_name : "");+ gtk_entry_set_text(GTK_ENTRY(host_entry), rule ? rule->target_hosts : "*");+ gtk_entry_set_text(GTK_ENTRY(port_entry), rule ? rule->target_ports : "*");+ gtk_combo_box_set_active(GTK_COMBO_BOX(proto_combo), rule ? (int)rule->protocol : RULE_PROTOCOL_BOTH);+ gtk_combo_box_set_active(GTK_COMBO_BOX(action_combo), rule ? (int)rule->action : RULE_ACTION_PROXY);++ GtkWidget *err_label = hint_label("");+ grid_row(grid, 0, "Process Name:", proc_box);+ gtk_grid_attach(GTK_GRID(grid), hint_label("Example: firefox; chrome; /usr/bin/wget"), 1, 1, 1, 1);+ grid_row(grid, 2, "Target Host:", host_entry);+ gtk_grid_attach(GTK_GRID(grid), hint_label("Example: 192.168.1.*; 10.0.0.0/8; 10.0.0.1-10.0.0.50; github.com; *.github.com; * (domains are matched via DNS answers)"), 1, 3, 1, 1);+ grid_row(grid, 4, "Target Port:", port_entry);+ gtk_grid_attach(GTK_GRID(grid), hint_label("Example: 80; 443; 8000-8080; *"), 1, 5, 1, 1);+ grid_row(grid, 6, "Protocol:", proto_combo);+ grid_row(grid, 7, "Action:", action_combo);+ grid_row(grid, 8, "Proxy:", proxy_combo);+ gtk_grid_attach(GTK_GRID(grid), err_label, 0, 9, 2, 1);+ gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), grid);gtk_widget_show_all(dialog);on_action_changed(GTK_COMBO_BOX(action_combo), proxy_combo);- while (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {- const char *proc = gtk_entry_get_text(GTK_ENTRY(proc_entry));- const char *hosts = gtk_entry_get_text(GTK_ENTRY(host_entry));- const char *ports = gtk_entry_get_text(GTK_ENTRY(port_entry));- int proto_i = gtk_combo_box_get_active(GTK_COMBO_BOX(proto_combo));- int action_i = gtk_combo_box_get_active(GTK_COMBO_BOX(action_combo));- if (proto_i < 0) proto_i = RULE_PROTOCOL_BOTH;- if (action_i < 0) action_i = RULE_ACTION_PROXY;- RuleProtocol proto = (RuleProtocol)proto_i;- RuleAction action = (RuleAction)action_i;-- // proxy name from the combo, NULL = default- const char *proxy_name = NULL;+ bool saved = false;+ while (!saved && gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {+ int proto = gtk_combo_box_get_active(GTK_COMBO_BOX(proto_combo));+ int action = gtk_combo_box_get_active(GTK_COMBO_BOX(action_combo));int psel = gtk_combo_box_get_active(GTK_COMBO_BOX(proxy_combo));- if (action == RULE_ACTION_PROXY && psel > 0) {- ProxyData *pd = (ProxyData *)g_list_nth_data(g_proxies_list, psel - 1);- if (pd) proxy_name = pd->name;- }-+ ProxyData *pd = (action == RULE_ACTION_PROXY && psel > 0) ? g_list_nth_data(g_proxies_list, psel - 1) : NULL;char err[256] = "";- bool ok = ProxyBridge_ValidateRule(proc, hosts, ports, err, sizeof(err));- uint32_t pid = rule_proxy_id(action, proxy_name);-- if (ok) {- if (rule && rule->id != 0) {- ok = ProxyBridge_EditRule(rule->id, proc, hosts, ports, proto, action, pid, err, sizeof(err));- } else {- // new rule, or one the engine rejected when it was loaded- uint32_t new_id = ProxyBridge_AddRule(proc, hosts, ports, proto, action, pid, err, sizeof(err));- ok = (new_id != 0);- if (ok) {- if (rule && !rule->enabled) ProxyBridge_DisableRule(new_id);- if (rule) {- rule->id = new_id;- ProxyBridge_MoveRule(new_id, lib_index_of(rule));- } else {- RuleData *new_rule = g_malloc0(sizeof(RuleData));- new_rule->id = new_id;- new_rule->enabled = true;- g_rules_list = g_list_append(g_rules_list, new_rule);- rule = new_rule;- }- }- }- }- if (!ok) {- char *esc = g_markup_printf_escaped("<span foreground='#e5534b'>%s</span>", err[0] ? err : "Invalid rule.");- gtk_label_set_markup(GTK_LABEL(err_label), esc);- g_free(esc);- continue;+ saved = save_rule(rule, gtk_entry_get_text(GTK_ENTRY(proc_entry)), gtk_entry_get_text(GTK_ENTRY(host_entry)),+ gtk_entry_get_text(GTK_ENTRY(port_entry)), proto < 0 ? RULE_PROTOCOL_BOTH : (RuleProtocol)proto,+ action < 0 ? RULE_ACTION_PROXY : (RuleAction)action, pd ? pd->name : NULL, err, sizeof(err)) != NULL;+ if (saved) {+ save_config();+ refresh_rules_ui();+ } else {+ set_error_label(err_label, err[0] ? err : "Invalid rule.");}-- // update local copy- g_free(rule->process_name); rule->process_name = g_strdup(proc);- g_free(rule->target_hosts); rule->target_hosts = g_strdup(hosts);- g_free(rule->target_ports); rule->target_ports = g_strdup(ports);- g_free(rule->proxy_name); rule->proxy_name = proxy_name ? g_strdup(proxy_name) : NULL;- rule->protocol = proto;- rule->action = action;- save_config();- refresh_rules_ui();- break;}gtk_widget_destroy(dialog);}@@ -300,149 +217,104 @@ static void on_rule_add_clicked(GtkWidget *widget, gpointer data) {open_rule_dialog(NULL);}+static bool all_rules_selected() {+ if (!g_rules_list) return false;+ for (GList *l = g_rules_list; l != NULL; l = l->next)+ if (!((RuleData *)l->data)->selected) return false;+ return true;+}++static void update_select_all_label() {+ if (btn_select_all_header)+ gtk_button_set_label(GTK_BUTTON(btn_select_all_header), all_rules_selected() ? "Deselect All" : "Select All");+}+static void on_rule_select_toggle(GtkToggleButton *btn, gpointer data) {- RuleData *rule = (RuleData *)data;- rule->selected = gtk_toggle_button_get_active(btn);- if (btn_select_all_header) {- bool all_selected = (g_rules_list != NULL);- if (g_rules_list == NULL) all_selected = false;- for (GList *l = g_rules_list; l != NULL; l = l->next) {- RuleData *r = (RuleData *)l->data;- if (!r->selected) {- all_selected = false;- break;- }- }- gtk_button_set_label(GTK_BUTTON(btn_select_all_header), all_selected ? "Deselect All" : "Select All");- }+ ((RuleData *)data)->selected = gtk_toggle_button_get_active(btn);+ update_select_all_label();}static void on_rule_export_clicked(GtkWidget *widget, gpointer data) {- if (!g_rules_list) return;bool any_selected = false;- for (GList *l = g_rules_list; l != NULL; l = l->next) {- if (((RuleData *)l->data)->selected) { any_selected = true; break; }- }+ for (GList *l = g_rules_list; l != NULL; l = l->next) any_selected |= ((RuleData *)l->data)->selected;if (!any_selected) {- show_message(GTK_WINDOW(rules_window ? rules_window : window), GTK_MESSAGE_WARNING, "Please select at least one rule to export.");+ show_message(parent_window(), GTK_MESSAGE_WARNING, "Please select at least one rule to export.");return;}- GtkWidget *dialog = gtk_file_chooser_dialog_new("Export Rules", GTK_WINDOW(rules_window ? rules_window : window), GTK_FILE_CHOOSER_ACTION_SAVE, "_Cancel", GTK_RESPONSE_CANCEL, "_Save", GTK_RESPONSE_ACCEPT, NULL);+ GtkWidget *dialog = gtk_file_chooser_dialog_new("Export Rules", parent_window(), GTK_FILE_CHOOSER_ACTION_SAVE,+ "_Cancel", GTK_RESPONSE_CANCEL, "_Save", GTK_RESPONSE_ACCEPT, NULL);gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(dialog), TRUE);gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(dialog), "proxy_rules.json");if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));- FILE *f = filename ? fopen(filename, "w") : NULL;- if (f) {- // both our keys and the macOS ones (ruleProtocol/ruleAction), plus the proxy name- fprintf(f, "[\n");- bool first = true;- for (GList *l = g_rules_list; l != NULL; l = l->next) {- RuleData *r = (RuleData *)l->data;- if (!r->selected) continue;- if (!first) fprintf(f, ",\n");- char *proc = escape_json_string(r->process_name);- char *host = escape_json_string(r->target_hosts);- char *port = escape_json_string(r->target_ports);- char *pxy = escape_json_string(r->action == RULE_ACTION_PROXY ? r->proxy_name : NULL);- const char *proto = (r->protocol == RULE_PROTOCOL_TCP) ? "TCP" : (r->protocol == RULE_PROTOCOL_UDP ? "UDP" : "BOTH");- const char *act = (r->action == RULE_ACTION_PROXY) ? "PROXY" : (r->action == RULE_ACTION_DIRECT ? "DIRECT" : "BLOCK");- fprintf(f, " {\n \"processNames\": \"%s\",\n \"targetHosts\": \"%s\",\n \"targetPorts\": \"%s\",\n \"protocol\": \"%s\",\n \"ruleProtocol\": \"%s\",\n \"action\": \"%s\",\n \"ruleAction\": \"%s\",\n \"proxy\": \"%s\",\n \"enabled\": %s\n }", proc, host, port, proto, proto, act, act, pxy, r->enabled ? "true" : "false");- g_free(proc); g_free(host); g_free(port); g_free(pxy);- first = false;- }- fprintf(f, "\n]\n");- if (fclose(f) == 0) show_message(GTK_WINDOW(rules_window ? rules_window : window), GTK_MESSAGE_INFO, "Rules exported successfully.");- else show_message(GTK_WINDOW(rules_window ? rules_window : window), GTK_MESSAGE_ERROR, "Failed to write %s", filename);- } else {- show_message(GTK_WINDOW(rules_window ? rules_window : window), GTK_MESSAGE_ERROR, "Could not open %s for writing.", filename ? filename : "file");- }+ char *json = rules_to_json(g_rules_list, true);+ GError *err = NULL;+ if (filename && g_file_set_contents(filename, json, -1, &err))+ show_message(parent_window(), GTK_MESSAGE_INFO, "Rules exported successfully.");+ else+ show_message(parent_window(), GTK_MESSAGE_ERROR, "Could not write %s: %s", filename ? filename : "file", err ? err->message : "unknown error");+ if (err) g_error_free(err);+ g_free(json);g_free(filename);}gtk_widget_destroy(dialog);}-// first non-NULL of two (consumes both)-static char *pick_str(char *a, char *b) {- if (a) { g_free(b); return a; }- return b;+typedef struct {+ int imported, failed;+ GString *fail_msg;+} ImportCtx;++static void import_rule_cb(const RuleData *r, int index, void *ud) {+ ImportCtx *ctx = (ImportCtx *)ud;+ char err[256] = "";+ // unknown proxy name -> default proxy+ ProxyData *px = r->action == RULE_ACTION_PROXY ? find_proxy_by_name(r->proxy_name) : NULL;+ uint32_t id = r->process_name ? ProxyBridge_AddRule(r->process_name, r->target_hosts, r->target_ports, r->protocol,+ r->action, px ? px->id : 0, err, sizeof(err)) : 0;+ if (id == 0) {+ ctx->failed++;+ if (ctx->fail_msg->len < 3000)+ g_string_append_printf(ctx->fail_msg, "Rule #%d (%s): %s\n", index, r->process_name ? r->process_name : "?",+ !r->process_name ? "missing processNames" : err[0] ? err : "rejected");+ return;+ }+ if (!r->enabled) ProxyBridge_DisableRule(id);+ RuleData *nd = g_malloc0(sizeof(RuleData));+ nd->id = id;+ nd->process_name = g_strdup(r->process_name);+ nd->target_hosts = g_strdup(r->target_hosts);+ nd->target_ports = g_strdup(r->target_ports);+ nd->protocol = r->protocol;+ nd->action = r->action;+ nd->enabled = r->enabled;+ nd->proxy_name = px ? g_strdup(px->name) : NULL;+ g_rules_list = g_list_append(g_rules_list, nd);+ ctx->imported++;}static void on_rule_import_clicked(GtkWidget *widget, gpointer data) {- GtkWidget *dialog = gtk_file_chooser_dialog_new("Import Rules", GTK_WINDOW(rules_window ? rules_window : window), GTK_FILE_CHOOSER_ACTION_OPEN, "_Cancel", GTK_RESPONSE_CANCEL, "_Open", GTK_RESPONSE_ACCEPT, NULL);+ GtkWidget *dialog = gtk_file_chooser_dialog_new("Import Rules", parent_window(), GTK_FILE_CHOOSER_ACTION_OPEN,+ "_Cancel", GTK_RESPONSE_CANCEL, "_Open", GTK_RESPONSE_ACCEPT, NULL);if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));char *content = NULL;- gsize len;- if (filename && g_file_get_contents(filename, &content, &len, NULL)) {- char *curr = content;- int imported = 0, failed = 0, index = 0;- GString *fail_msg = g_string_new("");-- while ((curr = strchr(curr, '{')) != NULL) {- char *end = strchr(curr, '}');- if (!end) break;- char saved = *end; *end = '\0';- index++;-- // our keys first, macOS keys as fallback- char *proc = extract_sub_json_str(curr, "processNames");- char *host = extract_sub_json_str(curr, "targetHosts");- char *port = extract_sub_json_str(curr, "targetPorts");- char *proto_s = pick_str(extract_sub_json_str(curr, "protocol"), extract_sub_json_str(curr, "ruleProtocol"));- char *act_s = pick_str(extract_sub_json_str(curr, "action"), extract_sub_json_str(curr, "ruleAction"));- char *proxy_s = extract_sub_json_str(curr, "proxy");- bool en = json_has_key(curr, "enabled") ? extract_sub_json_bool(curr, "enabled") : true;-- if (!proc) {- failed++;- if (fail_msg->len < 3000) g_string_append_printf(fail_msg, "Rule #%d: missing processNames\n", index);- } else {- RuleProtocol p = RULE_PROTOCOL_BOTH;- if (proto_s && g_ascii_strcasecmp(proto_s, "TCP") == 0) p = RULE_PROTOCOL_TCP;- else if (proto_s && g_ascii_strcasecmp(proto_s, "UDP") == 0) p = RULE_PROTOCOL_UDP;- // anything that is not DIRECT/BLOCK is PROXY (macOS stores the proxy id there)- RuleAction a = RULE_ACTION_PROXY;- if (act_s && g_ascii_strcasecmp(act_s, "DIRECT") == 0) a = RULE_ACTION_DIRECT;- else if (act_s && g_ascii_strcasecmp(act_s, "BLOCK") == 0) a = RULE_ACTION_BLOCK;-- const char *h = host ? host : "*";- const char *po = port ? port : "*";- // unknown proxy name -> default proxy- ProxyData *px = (a == RULE_ACTION_PROXY) ? find_proxy_by_name(proxy_s) : NULL;-- char err[256] = "";- uint32_t nid = ProxyBridge_AddRule(proc, h, po, p, a, px ? px->id : 0, err, sizeof(err));- if (nid == 0) {- failed++;- if (fail_msg->len < 3000) g_string_append_printf(fail_msg, "Rule #%d (%s): %s\n", index, proc, err[0] ? err : "rejected");- } else {- if (!en) ProxyBridge_DisableRule(nid);- RuleData *nd = g_malloc0(sizeof(RuleData));- nd->id = nid; nd->process_name = g_strdup(proc); nd->target_hosts = g_strdup(h);- nd->target_ports = g_strdup(po); nd->protocol = p; nd->action = a; nd->enabled = en;- nd->proxy_name = px ? g_strdup(px->name) : NULL;- g_rules_list = g_list_append(g_rules_list, nd);- imported++;- }- }- g_free(proc); g_free(host); g_free(port); g_free(proto_s); g_free(act_s); g_free(proxy_s);- *end = saved; curr = end + 1;- }+ if (filename && g_file_get_contents(filename, &content, NULL, NULL)) {+ ImportCtx ctx = {0, 0, g_string_new("")};+ rules_from_json(content, import_rule_cb, &ctx);g_free(content);- if (imported > 0) { save_config(); refresh_rules_ui(); }- GtkWindow *parent = GTK_WINDOW(rules_window ? rules_window : window);- if (failed > 0) {- show_message(parent, GTK_MESSAGE_WARNING, "Imported %d rules, %d failed validation and were skipped:\n\n%s", imported, failed, fail_msg->str);- } else if (imported > 0) {- show_message(parent, GTK_MESSAGE_INFO, "Imported %d rules.", imported);- } else {- show_message(parent, GTK_MESSAGE_WARNING, "No rules found in the file.");- }- g_string_free(fail_msg, TRUE);+ if (ctx.imported > 0) { save_config(); refresh_rules_ui(); }+ if (ctx.failed > 0)+ show_message(parent_window(), GTK_MESSAGE_WARNING, "Imported %d rules, %d failed validation and were skipped:\n\n%s",+ ctx.imported, ctx.failed, ctx.fail_msg->str);+ else if (ctx.imported > 0)+ show_message(parent_window(), GTK_MESSAGE_INFO, "Imported %d rules.", ctx.imported);+ else+ show_message(parent_window(), GTK_MESSAGE_WARNING, "No rules found in the file.");+ g_string_free(ctx.fail_msg, TRUE);} else {- show_message(GTK_WINDOW(rules_window ? rules_window : window), GTK_MESSAGE_ERROR, "Could not read the selected file.");+ show_message(parent_window(), GTK_MESSAGE_ERROR, "Could not read the selected file.");}g_free(filename);}@@ -450,137 +322,108 @@ static void on_rule_import_clicked(GtkWidget *widget, gpointer data) {}static void on_bulk_delete_clicked(GtkWidget *widget, gpointer data) {- if (!g_rules_list) return;- GList *iter = g_rules_list;- GList *to_delete = NULL;- while (iter != NULL) {- RuleData *rule = (RuleData *)iter->data;- if (rule->selected) to_delete = g_list_append(to_delete, rule);- iter = iter->next;- }- if (!to_delete) return;- for (GList *d = to_delete; d != NULL; d = d->next) {- RuleData *rule = (RuleData *)d->data;- if (rule->id != 0) ProxyBridge_DeleteRule(rule->id);- g_rules_list = g_list_remove(g_rules_list, rule);- free_rule_data(rule);+ GList *l = g_rules_list;+ while (l != NULL) {+ GList *next = l->next;+ RuleData *rule = (RuleData *)l->data;+ if (rule->selected) {+ if (rule->id != 0) ProxyBridge_DeleteRule(rule->id);+ g_rules_list = g_list_delete_link(g_rules_list, l);+ free_rule_data(rule);+ }+ l = next;}- g_list_free(to_delete);save_config();refresh_rules_ui();}static void on_select_all_clicked(GtkWidget *widget, gpointer data) {- if (!g_rules_list) return;- bool all_selected = true;- for (GList *l = g_rules_list; l != NULL; l = l->next) {- if (!((RuleData *)l->data)->selected) { all_selected = false; break; }- }- bool new_state = !all_selected;+ bool new_state = !all_rules_selected();for (GList *l = g_rules_list; l != NULL; l = l->next) ((RuleData *)l->data)->selected = new_state;refresh_rules_ui();}+static GtkWidget *header_label(const char *text, bool expand) {+ GtkWidget *l = gtk_label_new(text);+ gtk_widget_set_halign(l, GTK_ALIGN_START);+ gtk_widget_set_hexpand(l, expand);+ return l;+}++static GtkWidget *cell_label(const char *text) {+ GtkWidget *l = header_label(text, false);+ gtk_label_set_ellipsize(GTK_LABEL(l), PANGO_ELLIPSIZE_END);+ return l;+}++static GtkWidget *small_button(GtkWidget *box, const char *label, const char *tip, bool sensitive, GCallback cb, gpointer data) {+ GtkWidget *b = gtk_button_new_with_label(label);+ if (tip) gtk_widget_set_tooltip_text(b, tip);+ gtk_widget_set_sensitive(b, sensitive);+ g_signal_connect(b, "clicked", cb, data);+ gtk_box_pack_start(GTK_BOX(box), b, FALSE, FALSE, 0);+ return b;+}++static GtkWidget *check_cell(GtkWidget *grid, int row, int col, bool active, GCallback cb, gpointer data) {+ GtkWidget *c = gtk_check_button_new();+ gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(c), active);+ g_signal_connect(c, "toggled", cb, data);+ gtk_grid_attach(GTK_GRID(grid), c, col, row, 1, 1);+ return c;+}+static void refresh_rules_ui() {if (!rules_list_box) return;GList *children = gtk_container_get_children(GTK_CONTAINER(rules_list_box));- for(GList *iter = children; iter != NULL; iter = g_list_next(iter)) gtk_widget_destroy(GTK_WIDGET(iter->data));+ for (GList *c = children; c != NULL; c = c->next) gtk_widget_destroy(GTK_WIDGET(c->data));g_list_free(children);-- if (btn_select_all_header) {- bool all_selected = (g_rules_list != NULL);- if (g_rules_list == NULL) all_selected = false;- for (GList *l = g_rules_list; l != NULL; l = l->next) {- if (!((RuleData *)l->data)->selected) { all_selected = false; break; }- }- gtk_button_set_label(GTK_BUTTON(btn_select_all_header), all_selected ? "Deselect All" : "Select All");- }+ update_select_all_label();GtkWidget *grid = gtk_grid_new();gtk_grid_set_row_spacing(GTK_GRID(grid), 10);gtk_grid_set_column_spacing(GTK_GRID(grid), 15);gtk_container_add(GTK_CONTAINER(rules_list_box), grid);- int row = 0;- gtk_grid_attach(GTK_GRID(grid), gtk_label_new(" "), 0, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Enable"), 1, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Actions"), 2, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("SR"), 3, row, 1, 1);- GtkWidget *h_proc = gtk_label_new("Process"); gtk_widget_set_halign(h_proc, GTK_ALIGN_START);- gtk_widget_set_hexpand(h_proc, TRUE); gtk_grid_attach(GTK_GRID(grid), h_proc, 4, row, 1, 1);- GtkWidget *h_host = gtk_label_new("Target Hosts"); gtk_widget_set_halign(h_host, GTK_ALIGN_START);- gtk_widget_set_hexpand(h_host, TRUE); gtk_grid_attach(GTK_GRID(grid), h_host, 5, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Protocol"), 6, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Action"), 7, row, 1, 1);- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Proxy"), 8, row, 1, 1);- row++;- gtk_grid_attach(GTK_GRID(grid), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), 0, row, 9, 1); row++;-- int sr_counter = 1;- for (GList *l = g_rules_list; l != NULL; l = l->next) {- RuleData *r = (RuleData *)l->data;- GtkWidget *chk_sel = gtk_check_button_new();- gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(chk_sel), r->selected);- g_signal_connect(chk_sel, "toggled", G_CALLBACK(on_rule_select_toggle), r);- gtk_grid_attach(GTK_GRID(grid), chk_sel, 0, row, 1, 1);+ const char *heads[] = {" ", "Enable", "Actions", "SR", "Process", "Target Hosts", "Protocol", "Action", "Proxy"};+ for (int c = 0; c < 9; c++)+ gtk_grid_attach(GTK_GRID(grid), header_label(heads[c], c == 4 || c == 5), c, 0, 1, 1);+ gtk_grid_attach(GTK_GRID(grid), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), 0, 1, 9, 1);- GtkWidget *chk = gtk_check_button_new();- gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(chk), r->enabled);- g_signal_connect(chk, "toggled", G_CALLBACK(on_rule_toggle), r);- gtk_grid_attach(GTK_GRID(grid), chk, 1, row, 1, 1);+ const char *proto_strs[] = {"TCP", "UDP", "BOTH"};+ const char *action_strs[] = {"PROXY", "DIRECT", "BLOCK"};+ const char *action_class[] = {"success", "info", "warning"};+ int row = 2, sr = 1;+ for (GList *l = g_rules_list; l != NULL; l = l->next, row += 2) {+ RuleData *r = (RuleData *)l->data;+ check_cell(grid, row, 0, r->selected, G_CALLBACK(on_rule_select_toggle), r);+ check_cell(grid, row, 1, r->enabled, G_CALLBACK(on_rule_toggle), r);- GtkWidget *act_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);- GtkWidget *btn_edit = gtk_button_new_with_label("Edit");- g_signal_connect(btn_edit, "clicked", G_CALLBACK(on_rule_edit), r);- GtkWidget *btn_del = gtk_button_new_with_label("Delete");- g_signal_connect(btn_del, "clicked", G_CALLBACK(on_rule_delete), r);// list position is the priority, first match wins- GtkWidget *btn_up = gtk_button_new_with_label("\u25B2");- gtk_widget_set_tooltip_text(btn_up, "Move up (higher priority)");- gtk_widget_set_sensitive(btn_up, l->prev != NULL);- g_signal_connect(btn_up, "clicked", G_CALLBACK(on_rule_move_up), r);- GtkWidget *btn_down = gtk_button_new_with_label("\u25BC");- gtk_widget_set_tooltip_text(btn_down, "Move down (lower priority)");- gtk_widget_set_sensitive(btn_down, l->next != NULL);- g_signal_connect(btn_down, "clicked", G_CALLBACK(on_rule_move_down), r);- gtk_box_pack_start(GTK_BOX(act_box), btn_edit, FALSE, FALSE, 0);- gtk_box_pack_start(GTK_BOX(act_box), btn_del, FALSE, FALSE, 0);- gtk_box_pack_start(GTK_BOX(act_box), btn_up, FALSE, FALSE, 0);- gtk_box_pack_start(GTK_BOX(act_box), btn_down, FALSE, FALSE, 0);+ GtkWidget *act_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2);+ small_button(act_box, "Edit", NULL, true, G_CALLBACK(on_rule_edit), r);+ small_button(act_box, "Delete", NULL, true, G_CALLBACK(on_rule_delete), r);+ small_button(act_box, "▲", "Move up (higher priority)", l->prev != NULL, G_CALLBACK(on_rule_move_up), r);+ small_button(act_box, "▼", "Move down (lower priority)", l->next != NULL, G_CALLBACK(on_rule_move_down), r);gtk_grid_attach(GTK_GRID(grid), act_box, 2, row, 1, 1);- char sr_str[16]; snprintf(sr_str, sizeof(sr_str), "%d", sr_counter++);+ char sr_str[16];+ snprintf(sr_str, sizeof(sr_str), "%d", sr++);gtk_grid_attach(GTK_GRID(grid), gtk_label_new(sr_str), 3, row, 1, 1);-- GtkWidget *l_proc = gtk_label_new(r->process_name); gtk_widget_set_halign(l_proc, GTK_ALIGN_START);- gtk_label_set_ellipsize(GTK_LABEL(l_proc), PANGO_ELLIPSIZE_END);- gtk_grid_attach(GTK_GRID(grid), l_proc, 4, row, 1, 1);-- GtkWidget *l_host = gtk_label_new(r->target_hosts); gtk_widget_set_halign(l_host, GTK_ALIGN_START);- gtk_label_set_ellipsize(GTK_LABEL(l_host), PANGO_ELLIPSIZE_END);- gtk_grid_attach(GTK_GRID(grid), l_host, 5, row, 1, 1);-- const char* proto_strs[] = {"TCP", "UDP", "BOTH"};+ gtk_grid_attach(GTK_GRID(grid), cell_label(r->process_name), 4, row, 1, 1);+ gtk_grid_attach(GTK_GRID(grid), cell_label(r->target_hosts), 5, row, 1, 1);gtk_grid_attach(GTK_GRID(grid), gtk_label_new(proto_strs[r->protocol <= RULE_PROTOCOL_BOTH ? r->protocol : RULE_PROTOCOL_BOTH]), 6, row, 1, 1);- const char* action_strs[] = {"PROXY", "DIRECT", "BLOCK"};- GtkWidget *l_act = gtk_label_new(action_strs[r->action <= RULE_ACTION_BLOCK ? r->action : RULE_ACTION_PROXY]);- GtkStyleContext *context = gtk_widget_get_style_context(l_act);- if (r->action == RULE_ACTION_PROXY) gtk_style_context_add_class(context, "success");- else if (r->action == RULE_ACTION_DIRECT) gtk_style_context_add_class(context, "info");- else gtk_style_context_add_class(context, "warning");+ int a = r->action <= RULE_ACTION_BLOCK ? r->action : RULE_ACTION_PROXY;+ GtkWidget *l_act = gtk_label_new(action_strs[a]);+ gtk_style_context_add_class(gtk_widget_get_style_context(l_act), action_class[a]);gtk_grid_attach(GTK_GRID(grid), l_act, 7, row, 1, 1);- // proxy only matters for PROXY rulesconst char *proxy_txt = "-";if (r->action == RULE_ACTION_PROXY)- proxy_txt = (r->proxy_name && *r->proxy_name && find_proxy_by_name(r->proxy_name)) ? r->proxy_name : "default";- GtkWidget *l_proxy = gtk_label_new(proxy_txt);- gtk_label_set_ellipsize(GTK_LABEL(l_proxy), PANGO_ELLIPSIZE_END);- gtk_grid_attach(GTK_GRID(grid), l_proxy, 8, row, 1, 1);-- row++;- gtk_grid_attach(GTK_GRID(grid), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), 0, row, 9, 1); row++;+ proxy_txt = (r->proxy_name && find_proxy_by_name(r->proxy_name)) ? r->proxy_name : "default";+ gtk_grid_attach(GTK_GRID(grid), cell_label(proxy_txt), 8, row, 1, 1);+ gtk_grid_attach(GTK_GRID(grid), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), 0, row + 1, 9, 1);}gtk_widget_show_all(rules_list_box);}@@ -589,7 +432,6 @@ void refresh_rules_window() {refresh_rules_ui();}-// widgets are gone, refresh_rules_ui must not touch them any morestatic void on_rules_window_destroy(GtkWidget *widget, gpointer data) {rules_window = NULL;rules_list_box = NULL;@@ -601,47 +443,41 @@ void on_proxy_rules_clicked(GtkWidget *widget, gpointer data) {gtk_window_present(GTK_WINDOW(rules_window));return;}- GtkWidget *dialog = gtk_window_new(GTK_WINDOW_TOPLEVEL);- rules_window = dialog;- g_signal_connect(dialog, "destroy", G_CALLBACK(on_rules_window_destroy), NULL);- gtk_window_set_title(GTK_WINDOW(dialog), "Process Rules");- gtk_window_set_default_size(GTK_WINDOW(dialog), 1000, 500);- gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(window));+ rules_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);+ g_signal_connect(rules_window, "destroy", G_CALLBACK(on_rules_window_destroy), NULL);+ gtk_window_set_title(GTK_WINDOW(rules_window), "Process Rules");+ gtk_window_set_default_size(GTK_WINDOW(rules_window), 1000, 500);+ gtk_window_set_transient_for(GTK_WINDOW(rules_window), GTK_WINDOW(window));GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);gtk_container_set_border_width(GTK_CONTAINER(vbox), 20);- gtk_container_add(GTK_CONTAINER(dialog), vbox);+ gtk_container_add(GTK_CONTAINER(rules_window), vbox);GtkWidget *header_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);GtkWidget *title = gtk_label_new(NULL);gtk_label_set_markup(GTK_LABEL(title), "<span size='x-large' weight='bold'>Process Rules</span>");+ gtk_box_pack_start(GTK_BOX(header_box), title, FALSE, FALSE, 0);+ GtkWidget *spacer = gtk_label_new("");+ gtk_box_pack_start(GTK_BOX(header_box), spacer, TRUE, TRUE, 0);++ btn_select_all_header = gtk_button_new_with_label("Select All");GtkWidget *add_btn = gtk_button_new_with_label("+ Add Rule");+ GtkWidget *del_btn = gtk_button_new_with_label("Delete Selected");+ GtkWidget *import_btn = gtk_button_new_with_label("Import");+ GtkWidget *export_btn = gtk_button_new_with_label("Export");g_signal_connect(add_btn, "clicked", G_CALLBACK(on_rule_add_clicked), NULL);- btn_select_all_header = gtk_button_new_with_label("Select All");g_signal_connect(btn_select_all_header, "clicked", G_CALLBACK(on_select_all_clicked), NULL);- GtkWidget *del_all_btn = gtk_button_new_with_label("Delete Selected");- g_signal_connect(del_all_btn, "clicked", G_CALLBACK(on_bulk_delete_clicked), NULL);- GtkWidget *import_btn = gtk_button_new_with_label("Import");+ g_signal_connect(del_btn, "clicked", G_CALLBACK(on_bulk_delete_clicked), NULL);g_signal_connect(import_btn, "clicked", G_CALLBACK(on_rule_import_clicked), NULL);- GtkWidget *export_btn = gtk_button_new_with_label("Export");g_signal_connect(export_btn, "clicked", G_CALLBACK(on_rule_export_clicked), NULL);-- gtk_box_pack_start(GTK_BOX(header_box), title, FALSE, FALSE, 0);- GtkWidget *spacer = gtk_label_new("");- gtk_widget_set_hexpand(spacer, TRUE);- gtk_box_pack_start(GTK_BOX(header_box), spacer, TRUE, TRUE, 0);- gtk_box_pack_end(GTK_BOX(header_box), add_btn, FALSE, FALSE, 5);- gtk_box_pack_end(GTK_BOX(header_box), btn_select_all_header, FALSE, FALSE, 5);- gtk_box_pack_end(GTK_BOX(header_box), del_all_btn, FALSE, FALSE, 5);- gtk_box_pack_end(GTK_BOX(header_box), export_btn, FALSE, FALSE, 5);- gtk_box_pack_end(GTK_BOX(header_box), import_btn, FALSE, FALSE, 5);+ GtkWidget *right[] = {add_btn, btn_select_all_header, del_btn, export_btn, import_btn};+ for (int i = 0; i < 5; i++) gtk_box_pack_end(GTK_BOX(header_box), right[i], FALSE, FALSE, 5);gtk_box_pack_start(GTK_BOX(vbox), header_box, FALSE, FALSE, 0);GtkWidget *scrolled = gtk_scrolled_window_new(NULL, NULL);- gtk_widget_set_vexpand(scrolled, TRUE);rules_list_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);gtk_container_add(GTK_CONTAINER(scrolled), rules_list_box);gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 0);refresh_rules_ui();- gtk_widget_show_all(dialog);+ gtk_widget_show_all(rules_window);}diff --git a/Linux/gui/gui_settings.c b/Linux/gui/gui_settings.cindex 6de7fac..22b11cb 100644--- a/Linux/gui/gui_settings.c+++ b/Linux/gui/gui_settings.c@@ -1,30 +1,37 @@#include "gui.h"-// settings stuff, proxy list manager-GList *g_proxies_list = NULL;char *g_default_proxy = NULL;-enum {- COL_NAME = 0,- COL_TYPE,- COL_ADDR,- COL_AUTH,- COL_DEFAULT,- COL_PTR,- N_COLS-};+enum { COL_NAME, COL_TYPE, COL_ADDR, COL_AUTH, COL_DEFAULT, COL_PTR, N_COLS };++typedef struct {+ GtkWidget *dialog;+ GtkWidget *tree;+ GtkListStore *store;+ GtkWidget *test_host;+ GtkWidget *test_port;+ GtkTextBuffer *output_buffer;+ GtkWidget *test_btn;+} ConfigInfo;++// refs on buffer/btn keep them valid if the dialog closes mid-test+typedef struct {+ uint32_t proxy_id;+ char *host;+ uint16_t port;+ GtkTextBuffer *buffer;+ GtkWidget *btn;+ char result[4096];+} TestJob;void free_proxy_data(ProxyData *p) {if (!p) return;g_free(p->name);g_free(p->host);g_free(p->username);- // dont leave passwords lying around in freed memory- if (p->password) {- memset(p->password, 0, strlen(p->password));- g_free(p->password);- }+ if (p->password) memset(p->password, 0, strlen(p->password));+ g_free(p->password);g_free(p);}@@ -37,13 +44,12 @@ ProxyData *find_proxy_by_name(const char *name) {return NULL;}-// name -> library id, 0 means default proxy (empty or unknown name)+// 0 = default proxy (empty or unknown name)uint32_t resolve_proxy_id(const char *name) {ProxyData *p = find_proxy_by_name(name);return p ? p->id : 0;}-// push the stored proxies to the library, call before ProxyBridge_Startvoid apply_proxies_to_lib() {ProxyBridge_ClearProxies();for (GList *l = g_proxies_list; l != NULL; l = l->next) {@@ -55,109 +61,89 @@ void apply_proxies_to_lib() {ProxyBridge_SetDefaultProxy(resolve_proxy_id(g_default_proxy));}-static bool port_text_valid(const char *port_text, int *port_out) {- if (!port_text || !*port_text || strspn(port_text, "0123456789") != strlen(port_text) || strlen(port_text) > 5) return false;- int p = (int)safe_strtol(port_text);+static bool confirm(GtkWindow *parent, const char *format, ...) {+ va_list args;+ va_start(args, format);+ char *msg = g_strdup_vprintf(format, args);+ va_end(args);+ GtkWidget *q = gtk_message_dialog_new(parent, GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, "%s", msg);+ int resp = gtk_dialog_run(GTK_DIALOG(q));+ gtk_widget_destroy(q);+ g_free(msg);+ return resp == GTK_RESPONSE_YES;+}++static bool port_text_valid(const char *text, int *port_out) {+ size_t n = strlen(text);+ if (n == 0 || n > 5 || strspn(text, "0123456789") != n) return false;+ int p = atoi(text);if (p < 1 || p > 65535) return false;- if (port_out) *port_out = p;+ *port_out = p;return true;}-// ---- test -----static gboolean on_test_done(gpointer user_data) {- TestResultData *data = (TestResultData *)user_data;- gtk_text_buffer_set_text(data->buffer, data->result_text, -1);- gtk_widget_set_sensitive(data->btn, TRUE);-- g_object_unref(data->buffer);- g_object_unref(data->btn);- g_free(data->result_text);- g_free(data);+ TestJob *job = (TestJob *)user_data;+ char *text = g_utf8_make_valid(job->result, -1);+ gtk_text_buffer_set_text(job->buffer, text, -1);+ gtk_widget_set_sensitive(job->btn, TRUE);+ g_free(text);+ g_object_unref(job->buffer);+ g_object_unref(job->btn);+ g_free(job->host);+ g_free(job);return FALSE;}static gpointer run_test_thread(gpointer user_data) {- struct TestRunnerData *req = (struct TestRunnerData *)user_data;-- char *buffer = g_malloc0(4096);-- // run test- ProxyBridge_TestProxy(req->proxy_id, req->host, req->port, buffer, 4096);- buffer[4095] = '\0';- if (!g_utf8_validate(buffer, -1, NULL)) {- char *fixed = g_utf8_make_valid(buffer, -1);- g_free(buffer);- buffer = fixed;- }-- TestResultData *res = g_malloc0(sizeof(TestResultData));- res->result_text = buffer;- res->buffer = req->buffer;- res->btn = req->btn;-- g_idle_add(on_test_done, res);-- g_free(req->host);- g_free(req);+ TestJob *job = (TestJob *)user_data;+ ProxyBridge_TestProxy(job->proxy_id, job->host, job->port, job->result, sizeof(job->result));+ job->result[sizeof(job->result) - 1] = '\0';+ g_idle_add(on_test_done, job);return NULL;}static ProxyData *get_selected_proxy(ConfigInfo *info) {- GtkTreeSelection *sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(info->tree));GtkTreeModel *model;GtkTreeIter iter;- if (!gtk_tree_selection_get_selected(sel, &model, &iter)) return NULL;gpointer ptr = NULL;- gtk_tree_model_get(model, &iter, COL_PTR, &ptr, -1);+ if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(info->tree)), &model, &iter))+ gtk_tree_model_get(model, &iter, COL_PTR, &ptr, -1);return (ProxyData *)ptr;}static void on_start_test_clicked(GtkWidget *widget, gpointer data) {ConfigInfo *info = (ConfigInfo *)data;-ProxyData *px = get_selected_proxy(info);- if (!px) {- gtk_text_buffer_set_text(info->output_buffer, "Error: Select a proxy to test.", -1);- return;- }- if (px->id == 0) {- gtk_text_buffer_set_text(info->output_buffer, "Error: This proxy was rejected by the engine, edit and save it again.", -1);+ const char *err = !px ? "Error: Select a proxy to test."+ : px->id == 0 ? "Error: This proxy was rejected by the engine, edit and save it again." : NULL;+ if (err) {+ gtk_text_buffer_set_text(info->output_buffer, err, -1);return;}- // get targetconst char *t_host = gtk_entry_get_text(GTK_ENTRY(info->test_host));- const char *t_port_s = gtk_entry_get_text(GTK_ENTRY(info->test_port));-- if (!t_host || strlen(t_host) == 0) t_host = "google.com";- int t_port = (int)safe_strtol(t_port_s);+ int t_port = (int)safe_strtol(gtk_entry_get_text(GTK_ENTRY(info->test_port)));if (t_port <= 0 || t_port > 65535) t_port = 80;- // update guigtk_text_buffer_set_text(info->output_buffer, "Testing connection... Please wait...", -1);gtk_widget_set_sensitive(info->test_btn, FALSE);- // start thread, widgets are ref'd because the dialog can close before the test ends- struct TestRunnerData *req = g_malloc0(sizeof(struct TestRunnerData));- req->proxy_id = px->id;- req->host = g_strdup(t_host);- req->port = (uint16_t)t_port;- req->buffer = g_object_ref(info->output_buffer);- req->btn = g_object_ref(info->test_btn);-- GThread *thread = g_thread_new("test_conn", run_test_thread, req);- g_thread_unref(thread);+ TestJob *job = g_malloc0(sizeof(TestJob));+ job->proxy_id = px->id;+ job->host = g_strdup(*t_host ? t_host : "google.com");+ job->port = (uint16_t)t_port;+ job->buffer = g_object_ref(info->output_buffer);+ job->btn = g_object_ref(info->test_btn);+ g_thread_unref(g_thread_new("test_conn", run_test_thread, job));}-// ---- list -----static void refresh_proxy_store(ConfigInfo *info) {gtk_list_store_clear(info->store);for (GList *l = g_proxies_list; l != NULL; l = l->next) {ProxyData *p = (ProxyData *)l->data;char *addr = g_strdup_printf("%s:%u", p->host, p->port);- bool is_def = g_default_proxy && p->name && strcmp(g_default_proxy, p->name) == 0;+ bool is_def = g_default_proxy && strcmp(g_default_proxy, p->name) == 0;GtkTreeIter iter;gtk_list_store_append(info->store, &iter);gtk_list_store_set(info->store, &iter,@@ -186,117 +172,95 @@ static void select_proxy_row(ConfigInfo *info, ProxyData *target) {} while (gtk_tree_model_iter_next(model, &iter));}-// add/edit dialog. existing == NULL adds a new one. returns the proxy that was saved or NULL+static void set_str(char **dst, const char *src) {+ g_free(*dst);+ *dst = g_strdup(src);+}++// renaming keeps the default proxy and the rules pointing at it+static void rename_proxy_refs(const char *old_name, const char *new_name) {+ if (g_default_proxy && strcmp(g_default_proxy, old_name) == 0) set_str(&g_default_proxy, new_name);+ for (GList *l = g_rules_list; l != NULL; l = l->next) {+ RuleData *r = (RuleData *)l->data;+ if (r->proxy_name && strcmp(r->proxy_name, old_name) == 0) set_str(&r->proxy_name, new_name);+ }+}++// existing == NULL adds. returns the saved proxy or NULLstatic ProxyData *proxy_edit_dialog(GtkWindow *parent, ProxyData *existing) {- GtkWidget *dialog = gtk_dialog_new_with_buttons(existing ? "Edit Proxy" : "Add Proxy",- parent,+ GtkWidget *dialog = gtk_dialog_new_with_buttons(existing ? "Edit Proxy" : "Add Proxy", parent,GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,- "Cancel", GTK_RESPONSE_CANCEL,- "Save", GTK_RESPONSE_ACCEPT,- NULL);+ "Cancel", GTK_RESPONSE_CANCEL, "Save", GTK_RESPONSE_ACCEPT, NULL);gtk_window_set_default_size(GTK_WINDOW(dialog), 420, -1);- GtkWidget *content_area = gtk_dialog_get_content_area(GTK_DIALOG(dialog));GtkWidget *grid = gtk_grid_new();gtk_grid_set_row_spacing(GTK_GRID(grid), 5);gtk_grid_set_column_spacing(GTK_GRID(grid), 10);gtk_container_set_border_width(GTK_CONTAINER(grid), 10);- gtk_box_pack_start(GTK_BOX(content_area), grid, TRUE, TRUE, 0);+ gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(dialog))), grid, TRUE, TRUE, 0);- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Name:"), 0, 0, 1, 1);GtkWidget *name_entry = gtk_entry_new();- gtk_widget_set_hexpand(name_entry, TRUE);- gtk_grid_attach(GTK_GRID(grid), name_entry, 1, 0, 1, 1);-- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Type:"), 0, 1, 1, 1);- GtkWidget *type_combo = gtk_combo_box_text_new();- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(type_combo), "HTTP");- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(type_combo), "SOCKS5");- gtk_combo_box_set_active(GTK_COMBO_BOX(type_combo), 1);- gtk_grid_attach(GTK_GRID(grid), type_combo, 1, 1, 1, 1);-- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Host:"), 0, 2, 1, 1);+ GtkWidget *type_combo = combo_new("HTTP", "SOCKS5", NULL);GtkWidget *ip_entry = gtk_entry_new();- gtk_grid_attach(GTK_GRID(grid), ip_entry, 1, 2, 1, 1);-- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Port:"), 0, 3, 1, 1);GtkWidget *port_entry = gtk_entry_new();- gtk_grid_attach(GTK_GRID(grid), port_entry, 1, 3, 1, 1);-- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Username:"), 0, 4, 1, 1);GtkWidget *user_entry = gtk_entry_new();- gtk_grid_attach(GTK_GRID(grid), user_entry, 1, 4, 1, 1);-- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Password:"), 0, 5, 1, 1);GtkWidget *pass_entry = gtk_entry_new();gtk_entry_set_visibility(GTK_ENTRY(pass_entry), FALSE);- gtk_grid_attach(GTK_GRID(grid), pass_entry, 1, 5, 1, 1);-- GtkWidget *err_label = gtk_label_new("");- gtk_widget_set_halign(err_label, GTK_ALIGN_START);- gtk_label_set_line_wrap(GTK_LABEL(err_label), TRUE);- gtk_label_set_xalign(GTK_LABEL(err_label), 0);+ grid_row(grid, 0, "Name:", name_entry);+ grid_row(grid, 1, "Type:", type_combo);+ grid_row(grid, 2, "Host:", ip_entry);+ grid_row(grid, 3, "Port:", port_entry);+ grid_row(grid, 4, "Username:", user_entry);+ grid_row(grid, 5, "Password:", pass_entry);+ GtkWidget *err_label = hint_label("");gtk_grid_attach(GTK_GRID(grid), err_label, 0, 6, 2, 1);+ gtk_combo_box_set_active(GTK_COMBO_BOX(type_combo), 1);if (existing) {+ char port_str[16];+ snprintf(port_str, sizeof(port_str), "%u", existing->port);gtk_entry_set_text(GTK_ENTRY(name_entry), existing->name);gtk_combo_box_set_active(GTK_COMBO_BOX(type_combo), existing->type == PROXY_TYPE_HTTP ? 0 : 1);gtk_entry_set_text(GTK_ENTRY(ip_entry), existing->host);- if (existing->port != 0) {- char port_str[16];- snprintf(port_str, sizeof(port_str), "%u", existing->port);- gtk_entry_set_text(GTK_ENTRY(port_entry), port_str);- }+ if (existing->port) gtk_entry_set_text(GTK_ENTRY(port_entry), port_str);gtk_entry_set_text(GTK_ENTRY(user_entry), existing->username ? existing->username : "");gtk_entry_set_text(GTK_ENTRY(pass_entry), existing->password ? existing->password : "");} else if (!g_proxies_list) {gtk_entry_set_text(GTK_ENTRY(name_entry), "default");}-gtk_widget_show_all(dialog);ProxyData *result = NULL;- while (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {- const char *name = gtk_entry_get_text(GTK_ENTRY(name_entry));- const char *ip_text = gtk_entry_get_text(GTK_ENTRY(ip_entry));+ while (!result && gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {const char *port_text = gtk_entry_get_text(GTK_ENTRY(port_entry));const char *user = gtk_entry_get_text(GTK_ENTRY(user_entry));const char *pass = gtk_entry_get_text(GTK_ENTRY(pass_entry));- ProxyType type = (gtk_combo_box_get_active(GTK_COMBO_BOX(type_combo)) == 0) ? PROXY_TYPE_HTTP : PROXY_TYPE_SOCKS5;+ ProxyType type = gtk_combo_box_get_active(GTK_COMBO_BOX(type_combo)) == 0 ? PROXY_TYPE_HTTP : PROXY_TYPE_SOCKS5;+ char *name = g_strstrip(g_strdup(gtk_entry_get_text(GTK_ENTRY(name_entry))));+ char *host = g_strstrip(g_strdup(gtk_entry_get_text(GTK_ENTRY(ip_entry))));+ ProxyData *dup = find_proxy_by_name(name);int port = 0;+ char err[256] = "";- char *name_t = g_strstrip(g_strdup(name));- char *host_t = g_strstrip(g_strdup(ip_text));- const char *msg = NULL;-- if (name_t[0] == '\0') msg = "Name cannot be empty.";- else if (find_proxy_by_name(name_t) && find_proxy_by_name(name_t) != existing) msg = "A proxy with this name already exists.";- else if (host_t[0] == '\0') msg = "Host (IP/Domain) cannot be empty.";- else if (!port_text_valid(port_text, &port)) msg = "Port must be a number between 1 and 65535.";-- if (msg) {- gtk_label_set_markup(GTK_LABEL(err_label), "");- char *esc = g_markup_printf_escaped("<span foreground='#e5534b'>%s</span>", msg);- gtk_label_set_markup(GTK_LABEL(err_label), esc);- g_free(esc);- g_free(name_t); g_free(host_t);- continue;- }+ const char *msg = !*name ? "Name cannot be empty."+ : (dup && dup != existing) ? "A proxy with this name already exists."+ : !*host ? "Host (IP/Domain) cannot be empty."+ : !port_text_valid(port_text, &port) ? "Port must be a number between 1 and 65535." : NULL;- // library validates too (and keeps the proxy list in sync)- char err[256] = "";uint32_t id = existing ? existing->id : 0;- bool ok;- if (id != 0) {- ok = ProxyBridge_EditProxy(id, name_t, type, host_t, (uint16_t)port, user, pass, err, sizeof(err));- } else {- id = ProxyBridge_AddProxy(name_t, type, host_t, (uint16_t)port, user, pass, err, sizeof(err));- ok = (id != 0);+ if (!msg) {+ bool ok;+ if (id) {+ ok = ProxyBridge_EditProxy(id, name, type, host, (uint16_t)port, user, pass, err, sizeof(err));+ } else {+ id = ProxyBridge_AddProxy(name, type, host, (uint16_t)port, user, pass, err, sizeof(err));+ ok = id != 0;+ }+ if (!ok) msg = err[0] ? err : "Engine rejected the proxy settings.";}- if (!ok) {- char *esc = g_markup_printf_escaped("<span foreground='#e5534b'>%s</span>", err[0] ? err : "Engine rejected the proxy settings.");- gtk_label_set_markup(GTK_LABEL(err_label), esc);- g_free(esc);- g_free(name_t); g_free(host_t);+ if (msg) {+ set_error_label(err_label, msg);+ g_free(name);+ g_free(host);continue;}@@ -304,52 +268,40 @@ static ProxyData *proxy_edit_dialog(GtkWindow *parent, ProxyData *existing) {if (!p) {p = g_malloc0(sizeof(ProxyData));g_proxies_list = g_list_append(g_proxies_list, p);- } else if (p->name && strcmp(p->name, name_t) != 0) {- // renamed, keep default and rules pointing at it- if (g_default_proxy && strcmp(g_default_proxy, p->name) == 0) {- g_free(g_default_proxy);- g_default_proxy = g_strdup(name_t);- }- for (GList *l = g_rules_list; l != NULL; l = l->next) {- RuleData *r = (RuleData *)l->data;- if (r->proxy_name && strcmp(r->proxy_name, p->name) == 0) {- g_free(r->proxy_name);- r->proxy_name = g_strdup(name_t);- }- }+ } else if (strcmp(p->name, name) != 0) {+ rename_proxy_refs(p->name, name);}p->id = id;- g_free(p->name); p->name = name_t;- g_free(p->host); p->host = host_t;- g_free(p->username); p->username = g_strdup(user);+ g_free(p->name); p->name = name;+ g_free(p->host); p->host = host;+ set_str(&p->username, user);if (p->password) memset(p->password, 0, strlen(p->password));- g_free(p->password); p->password = g_strdup(pass);+ set_str(&p->password, pass);p->type = type;p->port = (uint16_t)port;- // first proxy becomes the default- if (!g_default_proxy || !find_proxy_by_name(g_default_proxy)) {- g_free(g_default_proxy);- g_default_proxy = g_strdup(p->name);+ if (!find_proxy_by_name(g_default_proxy)) {+ set_str(&g_default_proxy, p->name);ProxyBridge_SetDefaultProxy(p->id);}result = p;- break;}-gtk_widget_destroy(dialog);return result;}-static void on_proxy_add(GtkWidget *widget, gpointer data) {- ConfigInfo *info = (ConfigInfo *)data;- ProxyData *p = proxy_edit_dialog(GTK_WINDOW(info->dialog), NULL);+static void commit_proxy_change(ConfigInfo *info, ProxyData *p) {if (!p) return;save_config();refresh_proxy_store(info);select_proxy_row(info, p);}+static void on_proxy_add(GtkWidget *widget, gpointer data) {+ ConfigInfo *info = (ConfigInfo *)data;+ commit_proxy_change(info, proxy_edit_dialog(GTK_WINDOW(info->dialog), NULL));+}+static void on_proxy_edit(GtkWidget *widget, gpointer data) {ConfigInfo *info = (ConfigInfo *)data;ProxyData *sel = get_selected_proxy(info);@@ -357,11 +309,7 @@ static void on_proxy_edit(GtkWidget *widget, gpointer data) {show_message(GTK_WINDOW(info->dialog), GTK_MESSAGE_WARNING, "Select a proxy first.");return;}- ProxyData *p = proxy_edit_dialog(GTK_WINDOW(info->dialog), sel);- if (!p) return;- save_config();- refresh_proxy_store(info);- select_proxy_row(info, p);+ commit_proxy_change(info, proxy_edit_dialog(GTK_WINDOW(info->dialog), sel));}static void on_proxy_row_activated(GtkTreeView *tree, GtkTreePath *path, GtkTreeViewColumn *col, gpointer data) {@@ -375,34 +323,21 @@ static void on_proxy_delete(GtkWidget *widget, gpointer data) {show_message(GTK_WINDOW(info->dialog), GTK_MESSAGE_WARNING, "Select a proxy first.");return;}+ if (!confirm(GTK_WINDOW(info->dialog), "Delete proxy '%s'?\nRules using it will fall back to the default proxy.", p->name)) return;- GtkWidget *q = gtk_message_dialog_new(GTK_WINDOW(info->dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION,- GTK_BUTTONS_YES_NO, "Delete proxy '%s'?\nRules using it will fall back to the default proxy.", p->name);- int resp = gtk_dialog_run(GTK_DIALOG(q));- gtk_widget_destroy(q);- if (resp != GTK_RESPONSE_YES) return;-- if (p->id != 0) ProxyBridge_DeleteProxy(p->id);-- // rules that used it now use the default proxy (library does the same)+ if (p->id) ProxyBridge_DeleteProxy(p->id);for (GList *l = g_rules_list; l != NULL; l = l->next) {RuleData *r = (RuleData *)l->data;- if (r->proxy_name && strcmp(r->proxy_name, p->name) == 0) {- g_free(r->proxy_name);- r->proxy_name = NULL;- }+ if (r->proxy_name && strcmp(r->proxy_name, p->name) == 0) set_str(&r->proxy_name, NULL);}bool was_default = g_default_proxy && strcmp(g_default_proxy, p->name) == 0;g_proxies_list = g_list_remove(g_proxies_list, p);free_proxy_data(p);-if (was_default) {- g_free(g_default_proxy);- g_default_proxy = g_proxies_list ? g_strdup(((ProxyData *)g_proxies_list->data)->name) : NULL;+ set_str(&g_default_proxy, g_proxies_list ? ((ProxyData *)g_proxies_list->data)->name : NULL);ProxyBridge_SetDefaultProxy(resolve_proxy_id(g_default_proxy));}-save_config();refresh_proxy_store(info);}@@ -414,12 +349,9 @@ static void on_proxy_set_default(GtkWidget *widget, gpointer data) {show_message(GTK_WINDOW(info->dialog), GTK_MESSAGE_WARNING, "Select a proxy first.");return;}- g_free(g_default_proxy);- g_default_proxy = g_strdup(p->name);+ set_str(&g_default_proxy, p->name);ProxyBridge_SetDefaultProxy(p->id);- save_config();- refresh_proxy_store(info);- select_proxy_row(info, p);+ commit_proxy_change(info, p);char *status_msg = g_strdup_printf("Default proxy: %s (%s:%u)", p->name, p->host, p->port);gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, status_msg);@@ -427,65 +359,45 @@ static void on_proxy_set_default(GtkWidget *widget, gpointer data) {}void on_proxy_configure(GtkWidget *widget, gpointer data) {- ConfigInfo info;- memset(&info, 0, sizeof(info));-- GtkWidget *content_area;- GtkWidget *grid;-- info.dialog = gtk_dialog_new_with_buttons("Proxy Settings",- GTK_WINDOW(window),+ ConfigInfo info = {0};+ info.dialog = gtk_dialog_new_with_buttons("Proxy Settings", GTK_WINDOW(window),GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,- "Close", GTK_RESPONSE_CLOSE,- NULL);- // wider window+ "Close", GTK_RESPONSE_CLOSE, NULL);gtk_window_set_default_size(GTK_WINDOW(info.dialog), 650, 560);- content_area = gtk_dialog_get_content_area(GTK_DIALOG(info.dialog));- grid = gtk_grid_new();+ GtkWidget *grid = gtk_grid_new();gtk_grid_set_row_spacing(GTK_GRID(grid), 5);gtk_grid_set_column_spacing(GTK_GRID(grid), 10);gtk_container_set_border_width(GTK_CONTAINER(grid), 10);- gtk_box_pack_start(GTK_BOX(content_area), grid, TRUE, TRUE, 0);+ gtk_box_pack_start(GTK_BOX(gtk_dialog_get_content_area(GTK_DIALOG(info.dialog))), grid, TRUE, TRUE, 0);- // proxy listinfo.store = gtk_list_store_new(N_COLS, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_POINTER);info.tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(info.store));- g_object_unref(info.store); // tree holds it now+ g_object_unref(info.store);const char *titles[] = {"Name", "Type", "Host:Port", "Auth", "Default"};for (int i = 0; i < 5; i++) {- GtkCellRenderer *r = gtk_cell_renderer_text_new();- GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes(titles[i], r, "text", i, NULL);+ GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes(titles[i], gtk_cell_renderer_text_new(), "text", i, NULL);gtk_tree_view_column_set_resizable(c, TRUE);- if (i == 2) gtk_tree_view_column_set_expand(c, TRUE);+ gtk_tree_view_column_set_expand(c, i == 2);gtk_tree_view_append_column(GTK_TREE_VIEW(info.tree), c);}g_signal_connect(info.tree, "row-activated", G_CALLBACK(on_proxy_row_activated), &info);GtkWidget *tree_scroll = gtk_scrolled_window_new(NULL, NULL);- gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(tree_scroll), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);gtk_widget_set_size_request(tree_scroll, -1, 180);gtk_widget_set_hexpand(tree_scroll, TRUE);gtk_widget_set_vexpand(tree_scroll, TRUE);gtk_container_add(GTK_CONTAINER(tree_scroll), info.tree);gtk_grid_attach(GTK_GRID(grid), tree_scroll, 0, 0, 4, 1);- // list buttonsGtkWidget *btn_box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);- GtkWidget *add_btn = gtk_button_new_with_label("Add");- GtkWidget *edit_btn = gtk_button_new_with_label("Edit");- GtkWidget *del_btn = gtk_button_new_with_label("Delete");- GtkWidget *def_btn = gtk_button_new_with_label("Set Default");- g_signal_connect(add_btn, "clicked", G_CALLBACK(on_proxy_add), &info);- g_signal_connect(edit_btn, "clicked", G_CALLBACK(on_proxy_edit), &info);- g_signal_connect(del_btn, "clicked", G_CALLBACK(on_proxy_delete), &info);- g_signal_connect(def_btn, "clicked", G_CALLBACK(on_proxy_set_default), &info);- gtk_box_pack_start(GTK_BOX(btn_box), add_btn, FALSE, FALSE, 0);- gtk_box_pack_start(GTK_BOX(btn_box), edit_btn, FALSE, FALSE, 0);- gtk_box_pack_start(GTK_BOX(btn_box), del_btn, FALSE, FALSE, 0);- gtk_box_pack_start(GTK_BOX(btn_box), def_btn, FALSE, FALSE, 0);+ const char *labels[] = {"Add", "Edit", "Delete", "Set Default"};+ void (*cbs[])(GtkWidget *, gpointer) = {on_proxy_add, on_proxy_edit, on_proxy_delete, on_proxy_set_default};+ for (int i = 0; i < 4; i++) {+ GtkWidget *b = gtk_button_new_with_label(labels[i]);+ g_signal_connect(b, "clicked", G_CALLBACK(cbs[i]), &info);+ gtk_box_pack_start(GTK_BOX(btn_box), b, FALSE, FALSE, 0);+ }gtk_grid_attach(GTK_GRID(grid), btn_box, 0, 1, 4, 1);-- // test sectiongtk_grid_attach(GTK_GRID(grid), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), 0, 2, 4, 1);GtkWidget *test_label = gtk_label_new("<b>Test Selected Proxy</b>");@@ -493,61 +405,58 @@ void on_proxy_configure(GtkWidget *widget, gpointer data) {gtk_widget_set_halign(test_label, GTK_ALIGN_START);gtk_grid_attach(GTK_GRID(grid), test_label, 0, 3, 4, 1);- // targetgtk_grid_attach(GTK_GRID(grid), gtk_label_new("Target:"), 0, 4, 1, 1);info.test_host = gtk_entry_new();gtk_entry_set_text(GTK_ENTRY(info.test_host), "google.com");gtk_widget_set_hexpand(info.test_host, TRUE);gtk_grid_attach(GTK_GRID(grid), info.test_host, 1, 4, 1, 1);-- // target portgtk_grid_attach(GTK_GRID(grid), gtk_label_new("Port:"), 2, 4, 1, 1);info.test_port = gtk_entry_new();gtk_entry_set_text(GTK_ENTRY(info.test_port), "80");gtk_widget_set_size_request(info.test_port, 80, -1);gtk_grid_attach(GTK_GRID(grid), info.test_port, 3, 4, 1, 1);- // test buttoninfo.test_btn = gtk_button_new_with_label("Start Test");g_signal_connect(info.test_btn, "clicked", G_CALLBACK(on_start_test_clicked), &info);gtk_grid_attach(GTK_GRID(grid), info.test_btn, 0, 5, 4, 1);- // output logGtkWidget *out_scroll = gtk_scrolled_window_new(NULL, NULL);gtk_widget_set_size_request(out_scroll, -1, 150);- gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(out_scroll), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);-GtkWidget *out_view = gtk_text_view_new();gtk_text_view_set_editable(GTK_TEXT_VIEW(out_view), FALSE);gtk_text_view_set_monospace(GTK_TEXT_VIEW(out_view), TRUE);info.output_buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(out_view));-gtk_container_add(GTK_CONTAINER(out_scroll), out_view);gtk_grid_attach(GTK_GRID(grid), out_scroll, 0, 6, 4, 1);refresh_proxy_store(&info);- if (g_proxies_list) select_proxy_row(&info, find_proxy_by_name(g_default_proxy) ? find_proxy_by_name(g_default_proxy) : (ProxyData *)g_proxies_list->data);+ ProxyData *def = find_proxy_by_name(g_default_proxy);+ if (!def && g_proxies_list) def = (ProxyData *)g_proxies_list->data;+ select_proxy_row(&info, def);gtk_widget_show_all(info.dialog);gtk_dialog_run(GTK_DIALOG(info.dialog));gtk_widget_destroy(info.dialog);}-// ---- profiles ----+typedef struct {+ GtkWidget *dialog;+ GtkWidget *tree;+ GtkListStore *store;+} ProfilesInfo;static void update_profile_ui() {- char *title = g_strdup_printf("ProxyBridge - %s", g_active_profile ? g_active_profile : "");+ char *title = g_strdup_printf("ProxyBridge - %s", g_active_profile);gtk_window_set_title(GTK_WINDOW(window), title);g_free(title);- char *msg = g_strdup_printf("Active profile: %s", g_active_profile ? g_active_profile : "");- gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, msg);- g_free(msg);+ title = g_strdup_printf("Active profile: %s", g_active_profile);+ gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, title);+ g_free(title);}-// push the active profile to the running engine: no Stop/Start needed+// engine keeps running, only its proxies and rules are replacedstatic void reapply_active_profile() {ProxyBridge_ClearRules();- ProxyBridge_ClearProxies();apply_proxies_to_lib();apply_rules_to_lib();save_config();@@ -555,34 +464,26 @@ static void reapply_active_profile() {update_profile_ui();}-typedef struct {- GtkWidget *dialog;- GtkWidget *tree;- GtkListStore *store;-} ProfilesInfo;-static void refresh_profile_store(ProfilesInfo *pi) {gtk_list_store_clear(pi->store);for (GList *l = g_profiles; l != NULL; l = l->next) {Profile *p = (Profile *)l->data;- bool act = g_active_profile && strcmp(p->name, g_active_profile) == 0;GtkTreeIter iter;gtk_list_store_append(pi->store, &iter);- gtk_list_store_set(pi->store, &iter, 0, p->name, 1, act ? "Active" : "", -1);+ gtk_list_store_set(pi->store, &iter, 0, p->name, 1, strcmp(p->name, g_active_profile) == 0 ? "Active" : "", -1);}}-// name of the selected row, caller freesstatic char *selected_profile_name(ProfilesInfo *pi) {GtkTreeModel *model;GtkTreeIter iter;- if (!gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(pi->tree)), &model, &iter)) return NULL;char *name = NULL;- gtk_tree_model_get(model, &iter, 0, &name, -1);+ if (gtk_tree_selection_get_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(pi->tree)), &model, &iter))+ gtk_tree_model_get(model, &iter, 0, &name, -1);return name;}-// asks for a profile name, returns NULL on cancel. caller frees+// NULL on cancelstatic char *ask_profile_name(GtkWindow *parent, const char *title, const char *initial) {GtkWidget *d = gtk_dialog_new_with_buttons(title, parent, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,"Cancel", GTK_RESPONSE_CANCEL, "OK", GTK_RESPONSE_ACCEPT, NULL);@@ -590,48 +491,41 @@ static char *ask_profile_name(GtkWindow *parent, const char *title, const char *gtk_container_set_border_width(GTK_CONTAINER(box), 10);GtkWidget *entry = gtk_entry_new();gtk_entry_set_activates_default(GTK_ENTRY(entry), TRUE);- gtk_entry_set_text(GTK_ENTRY(entry), initial ? initial : "");+ gtk_entry_set_text(GTK_ENTRY(entry), initial);gtk_box_pack_start(GTK_BOX(box), gtk_label_new("Profile name:"), FALSE, FALSE, 0);gtk_box_pack_start(GTK_BOX(box), entry, FALSE, FALSE, 5);gtk_dialog_set_default_response(GTK_DIALOG(d), GTK_RESPONSE_ACCEPT);gtk_widget_show_all(d);char *result = NULL;- while (gtk_dialog_run(GTK_DIALOG(d)) == GTK_RESPONSE_ACCEPT) {+ while (!result && gtk_dialog_run(GTK_DIALOG(d)) == GTK_RESPONSE_ACCEPT) {char *name = g_strstrip(g_strdup(gtk_entry_get_text(GTK_ENTRY(entry))));- if (name[0] == '\0') {- show_message(GTK_WINDOW(d), GTK_MESSAGE_ERROR, "Profile name cannot be empty.");- } else if (profile_find(name) && !(initial && strcmp(initial, name) == 0)) {- show_message(GTK_WINDOW(d), GTK_MESSAGE_ERROR, "A profile with this name already exists.");- } else {- result = name;- break;- }+ if (!*name) show_message(GTK_WINDOW(d), GTK_MESSAGE_ERROR, "Profile name cannot be empty.");+ else if (profile_find(name) && strcmp(initial, name) != 0) show_message(GTK_WINDOW(d), GTK_MESSAGE_ERROR, "A profile with this name already exists.");+ else { result = name; continue; }g_free(name);}gtk_widget_destroy(d);return result;}-static void do_switch(ProfilesInfo *pi, const char *name) {- if (!name || (g_active_profile && strcmp(name, g_active_profile) == 0)) return;- if (!profile_activate(name)) return;- reapply_active_profile();- refresh_profile_store(pi);-}-static void on_profile_switch(GtkWidget *widget, gpointer data) {ProfilesInfo *pi = (ProfilesInfo *)data;char *name = selected_profile_name(pi);- if (name) do_switch(pi, name);+ if (name && strcmp(name, g_active_profile) != 0 && profile_activate(name)) {+ reapply_active_profile();+ refresh_profile_store(pi);+ }g_free(name);}static void on_profile_new(GtkWidget *widget, gpointer data) {ProfilesInfo *pi = (ProfilesInfo *)data;char *name = ask_profile_name(GTK_WINDOW(pi->dialog), "New Profile", "");- if (!name) return;- if (profile_create(name, false)) { save_config(); refresh_profile_store(pi); }+ if (name && profile_create(name, false)) {+ save_config();+ refresh_profile_store(pi);+ }g_free(name);}@@ -639,22 +533,17 @@ static void on_profile_duplicate(GtkWidget *widget, gpointer data) {ProfilesInfo *pi = (ProfilesInfo *)data;char *src = selected_profile_name(pi);if (!src) return;- // duplicates the selected profile: make it active data-wise only for the copy, then switch backchar *initial = g_strdup_printf("%s copy", src);char *name = ask_profile_name(GTK_WINDOW(pi->dialog), "Duplicate Profile", initial);- g_free(initial);- if (name) {- char *prev = g_strdup(g_active_profile);- if (profile_activate(src)) {- profile_create(name, true);- profile_activate(prev); // library state was never touched- save_config();- refresh_profile_store(pi);- }- g_free(prev);+ char *prev = g_strdup(g_active_profile);+ // copies the active profile, so make the source active for a moment (library state is untouched)+ if (name && profile_activate(src)) {+ profile_create(name, true);+ profile_activate(prev);+ save_config();+ refresh_profile_store(pi);}- g_free(name);- g_free(src);+ g_free(prev); g_free(initial); g_free(name); g_free(src);}static void on_profile_rename(GtkWidget *widget, gpointer data) {@@ -675,17 +564,10 @@ static void on_profile_delete(GtkWidget *widget, gpointer data) {ProfilesInfo *pi = (ProfilesInfo *)data;char *name = selected_profile_name(pi);if (!name) return;- if (!g_profiles || !g_profiles->next) {+ if (!g_profiles->next) {show_message(GTK_WINDOW(pi->dialog), GTK_MESSAGE_WARNING, "The last profile cannot be deleted.");- g_free(name);- return;- }- GtkWidget *q = gtk_message_dialog_new(GTK_WINDOW(pi->dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_QUESTION,- GTK_BUTTONS_YES_NO, "Delete profile '%s' with all its proxies and rules?", name);- int resp = gtk_dialog_run(GTK_DIALOG(q));- gtk_widget_destroy(q);- if (resp == GTK_RESPONSE_YES) {- bool was_active = g_active_profile && strcmp(g_active_profile, name) == 0;+ } else if (confirm(GTK_WINDOW(pi->dialog), "Delete profile '%s' with all its proxies and rules?", name)) {+ bool was_active = strcmp(g_active_profile, name) == 0;if (profile_delete(profile_find(name))) {if (was_active) reapply_active_profile();else save_config();@@ -700,8 +582,7 @@ static void on_profile_row_activated(GtkTreeView *tree, GtkTreePath *path, GtkTr}void on_profiles_clicked(GtkWidget *widget, gpointer data) {- ProfilesInfo pi;- memset(&pi, 0, sizeof(pi));+ ProfilesInfo pi = {0};pi.dialog = gtk_dialog_new_with_buttons("Profiles", GTK_WINDOW(window), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,"Close", GTK_RESPONSE_CLOSE, NULL);gtk_window_set_default_size(GTK_WINDOW(pi.dialog), 420, 360);@@ -714,7 +595,7 @@ void on_profiles_clicked(GtkWidget *widget, gpointer data) {const char *titles[] = {"Profile", "Status"};for (int i = 0; i < 2; i++) {GtkTreeViewColumn *c = gtk_tree_view_column_new_with_attributes(titles[i], gtk_cell_renderer_text_new(), "text", i, NULL);- if (i == 0) gtk_tree_view_column_set_expand(c, TRUE);+ gtk_tree_view_column_set_expand(c, i == 0);gtk_tree_view_append_column(GTK_TREE_VIEW(pi.tree), c);}g_signal_connect(pi.tree, "row-activated", G_CALLBACK(on_profile_row_activated), &pi);diff --git a/Linux/gui/gui_utils.c b/Linux/gui/gui_utils.cindex 35d4a7c..a8c50b5 100644--- a/Linux/gui/gui_utils.c+++ b/Linux/gui/gui_utils.c@@ -1,32 +1,22 @@#include "gui.h"-// safer way to turn string to intlong safe_strtol(const char *nptr) {- if (!nptr) return 0; // null check- char *endptr;- long val = strtol(nptr, &endptr, 10);- if (endptr == nptr) return 0; // bad input- return val;+ return nptr ? strtol(nptr, NULL, 10) : 0;}-// show popup msgvoid show_message(GtkWindow *parent, GtkMessageType type, const char *format, ...) {va_list args;va_start(args, format);char *msg = g_strdup_vprintf(format, args);va_end(args);- GtkWidget *dialog = gtk_message_dialog_new(parent,- GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,- type,- GTK_BUTTONS_OK,- "%s", msg);+ GtkWidget *dialog = gtk_message_dialog_new(parent, GTK_DIALOG_DESTROY_WITH_PARENT | GTK_DIALOG_MODAL,+ type, GTK_BUTTONS_OK, "%s", msg);gtk_dialog_run(GTK_DIALOG(dialog));gtk_widget_destroy(dialog);g_free(msg);}-// keep log size under control so we dont use too much ramvoid trim_buffer_lines(GtkTextBuffer *buffer, int max_lines) {if (gtk_text_buffer_get_line_count(buffer) > max_lines) {GtkTextIter start, next;@@ -37,82 +27,43 @@ void trim_buffer_lines(GtkTextBuffer *buffer, int max_lines) {}}-char* get_current_time_str() {- time_t rawtime;- struct tm *timeinfo;- char *buffer = g_malloc0(32);- time(&rawtime);- timeinfo = localtime(&rawtime);- if (!timeinfo || strftime(buffer, 32, "[%H:%M:%S]", timeinfo) == 0) buffer[0] = '\0';- return buffer; // free with g_free+char *get_current_time_str() {+ GDateTime *now = g_date_time_new_now_local();+ char *s = g_date_time_format(now, "[%H:%M:%S]");+ g_date_time_unref(now);+ return s;}-// json stuff-char *escape_json_string(const char *src) {- if (!src) return g_strdup("");- GString *str = g_string_new("");- for (const char *p = src; *p; p++) {- if (*p == '\\') g_string_append(str, "\\\\");- else if (*p == '"') g_string_append(str, "\\\"");- else if (*p == '\n') g_string_append(str, "\\n");- else if (*p == '\r') g_string_append(str, "\\r");- else if (*p == '\t') g_string_append(str, "\\t");- else if ((unsigned char)*p < 0x20) g_string_append_printf(str, "\\u%04x", (unsigned char)*p);- else g_string_append_c(str, *p);- }- return g_string_free(str, FALSE);+GtkWidget *combo_new(const char *first, ...) {+ GtkWidget *combo = gtk_combo_box_text_new();+ va_list args;+ va_start(args, first);+ for (const char *s = first; s; s = va_arg(args, const char *))+ gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo), s);+ va_end(args);+ return combo;}-// basic parser, good enough for valid inputs. returns NULL if the key is missing or its value is not a string-char *extract_sub_json_str(const char *json, const char *key) {- char search_key[256];- snprintf(search_key, sizeof(search_key), "\"%s\"", key);- const char *k = strstr(json, search_key);- if (!k) return NULL;- const char *colon = strchr(k + strlen(search_key), ':');- if (!colon) return NULL;- const char *v = colon + 1;- while (*v == ' ' || *v == '\t' || *v == '\n' || *v == '\r') v++;- if (*v != '"') return NULL;- v++;-- // copy up to the closing quote, handling escapes- GString *out = g_string_new("");- while (*v && *v != '"') {- if (*v == '\\' && v[1]) {- v++;- switch (*v) {- case 'n': g_string_append_c(out, '\n'); break;- case 'r': g_string_append_c(out, '\r'); break;- case 't': g_string_append_c(out, '\t'); break;- default: g_string_append_c(out, *v); break; // \\ \" \/- }- } else {- g_string_append_c(out, *v);- }- v++;- }- if (*v != '"') { g_string_free(out, TRUE); return NULL; }- return g_string_free(out, FALSE);+GtkWidget *hint_label(const char *text) {+ GtkWidget *l = gtk_label_new(text);+ gtk_style_context_add_class(gtk_widget_get_style_context(l), "dim-label");+ gtk_widget_set_halign(l, GTK_ALIGN_START);+ gtk_label_set_xalign(GTK_LABEL(l), 0);+ gtk_label_set_line_wrap(GTK_LABEL(l), TRUE);+ gtk_label_set_max_width_chars(GTK_LABEL(l), 60);+ return l;}-// true if the key is present at all (extract_sub_json_bool cant tell false from missing)-bool json_has_key(const char *json, const char *key) {- char search_key[256];- snprintf(search_key, sizeof(search_key), "\"%s\"", key);- return strstr(json, search_key) != NULL;+void set_error_label(GtkWidget *label, const char *msg) {+ char *m = g_markup_printf_escaped("<span foreground='#e5534b'>%s</span>", msg);+ gtk_label_set_markup(GTK_LABEL(label), m);+ g_free(m);}-bool extract_sub_json_bool(const char *json, const char *key) {- char search_key[256];- snprintf(search_key, sizeof(search_key), "\"%s\"", key);- char *k = strstr(json, search_key);- if (!k) return false;- char *colon = strchr(k, ':');- if (!colon) return false;- // skip whitespace- char *v = colon + 1;- while(*v == ' ' || *v == '\t' || *v == '\n' || *v == '\r') v++;- if (strncmp(v, "true", 4) == 0) return true;- return false;+void grid_row(GtkWidget *grid, int row, const char *label, GtkWidget *widget) {+ GtkWidget *l = gtk_label_new(label);+ gtk_widget_set_halign(l, GTK_ALIGN_START);+ gtk_grid_attach(GTK_GRID(grid), l, 0, row, 1, 1);+ gtk_widget_set_hexpand(widget, TRUE);+ gtk_grid_attach(GTK_GRID(grid), widget, 1, row, 1, 1);}diff --git a/Linux/gui/main.c b/Linux/gui/main.cindex 9887cc0..f2b8cc8 100644--- a/Linux/gui/main.c+++ b/Linux/gui/main.c@@ -1,19 +1,15 @@#include "gui.h"#include <glib-unix.h>+#include <signal.h>-// widgetsGtkWidget *window;-GtkTextView *conn_view;GtkTextBuffer *conn_buffer;-GtkTextView *log_view;GtkTextBuffer *log_buffer;GtkWidget *status_bar;guint status_context_id;-// config lives in gui_settings.c (proxies) and gui_rules.c (rules)static bool g_engine_running = false;-// default configGList *g_rules_list = NULL;bool g_chk_logging = true;bool g_chk_dns = true;@@ -116,7 +112,6 @@ static void on_check_update(GtkWidget *widget, gpointer data) {GError *spawn_err = NULL;int exit_code = 0;- // feed only, no deploy.sh. open the linux download/notes url in the browserif (!g_spawn_sync(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,&json, &curl_err, &exit_code, &spawn_err)) {show_message(GTK_WINDOW(window), GTK_MESSAGE_ERROR, "Update check failed: %s",@@ -227,12 +222,11 @@ static void on_window_destroy(GtkWidget *widget, gpointer data) {gtk_main_quit(); // engine is stopped once after gtk_main returns}-// start the engine, config (proxies, rules) was already pushed to the librarystatic bool start_engine() {if (g_engine_running) return true;if (ProxyBridge_Start()) {g_engine_running = true;- char *msg = g_strdup_printf("ProxyBridge Service Started (eBPF). Active profile: %s", g_active_profile ? g_active_profile : "Default");+ char *msg = g_strdup_printf("ProxyBridge Service Started (eBPF). Active profile: %s", g_active_profile);gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, msg);g_free(msg);return true;@@ -249,20 +243,72 @@ static void on_start_engine(GtkWidget *widget, gpointer data) {start_engine();}+static GtkWidget *add_menu_item(GtkWidget *menu, const char *label, GCallback cb) {+ GtkWidget *item = gtk_menu_item_new_with_label(label);+ g_signal_connect(item, "activate", cb, NULL);+ gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);+ return item;+}++static void add_check_item(GtkWidget *menu, const char *label, bool active, GCallback cb) {+ GtkWidget *item = gtk_check_menu_item_new_with_label(label);+ gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(item), active);+ g_signal_connect(item, "toggled", cb, NULL);+ gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);+}++static void add_separator(GtkWidget *menu) {+ gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());+}++static GtkWidget *add_submenu(GtkWidget *menubar, const char *label) {+ GtkWidget *item = gtk_menu_item_new_with_label(label);+ GtkWidget *menu = gtk_menu_new();+ gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), menu);+ gtk_menu_shell_append(GTK_MENU_SHELL(menubar), item);+ return menu;+}++static GtkTextBuffer *add_text_tab(GtkWidget *notebook, const char *title, const char *placeholder, GCallback on_search, GCallback on_clear) {+ GtkWidget *tab = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);+ gtk_container_set_border_width(GTK_CONTAINER(tab), 5);+ GtkWidget *toolbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);+ GtkWidget *search = gtk_search_entry_new();+ gtk_entry_set_placeholder_text(GTK_ENTRY(search), placeholder);+ g_signal_connect(search, "search-changed", on_search, NULL);+ GtkWidget *clear_btn = gtk_button_new_with_label("Clear Logs");+ g_signal_connect(clear_btn, "clicked", on_clear, NULL);+ gtk_box_pack_start(GTK_BOX(toolbar), search, TRUE, TRUE, 0);+ gtk_box_pack_start(GTK_BOX(toolbar), clear_btn, FALSE, FALSE, 0);+ gtk_box_pack_start(GTK_BOX(tab), toolbar, FALSE, FALSE, 0);++ GtkWidget *view = gtk_text_view_new();+ gtk_text_view_set_editable(GTK_TEXT_VIEW(view), FALSE);+ gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(view), FALSE);+ GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(view));+ gtk_text_buffer_create_tag(buffer, "hidden", "invisible", TRUE, NULL);+ GtkWidget *scrolled = gtk_scrolled_window_new(NULL, NULL);+ gtk_container_add(GTK_CONTAINER(scrolled), view);+ gtk_box_pack_start(GTK_BOX(tab), scrolled, TRUE, TRUE, 0);+ gtk_notebook_append_page(GTK_NOTEBOOK(notebook), tab, gtk_label_new(title));+ return buffer;+}+int main(int argc, char *argv[]) {- if (getuid() != 0) { gtk_init(&argc, &argv); show_message(NULL, GTK_MESSAGE_ERROR, "ProxyBridge must be run as root (sudo)."); return 1; }+ if (getuid() != 0) {+ gtk_init(&argc, &argv);+ show_message(NULL, GTK_MESSAGE_ERROR, "ProxyBridge must be run as root (sudo).");+ return 1;+ }setenv("GSETTINGS_BACKEND", "memory", 1);-- // load config from fileload_config();-gtk_init(&argc, &argv);GtkSettings *settings = gtk_settings_get_default();if (settings) g_object_set(settings, "gtk-application-prefer-dark-theme", TRUE, NULL);window = gtk_window_new(GTK_WINDOW_TOPLEVEL);- char *win_title = g_strdup_printf("ProxyBridge - %s", g_active_profile ? g_active_profile : "Default");+ char *win_title = g_strdup_printf("ProxyBridge - %s", g_active_profile);gtk_window_set_title(GTK_WINDOW(window), win_title);g_free(win_title);gtk_window_set_default_size(GTK_WINDOW(window), 900, 600);@@ -271,112 +317,31 @@ int main(int argc, char *argv[]) {GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);gtk_container_add(GTK_CONTAINER(window), vbox);- // setup menuGtkWidget *menubar = gtk_menu_bar_new();- GtkWidget *proxy_menu_item = gtk_menu_item_new_with_label("Proxy");- GtkWidget *proxy_menu = gtk_menu_new();- GtkWidget *config_item = gtk_menu_item_new_with_label("Proxy Settings...");- GtkWidget *rules_item = gtk_menu_item_new_with_label("Proxy Rules...");-- GtkWidget *profiles_item = gtk_menu_item_new_with_label("Profiles...");- g_signal_connect(profiles_item, "activate", G_CALLBACK(on_profiles_clicked), NULL);-- GtkWidget *log_check_item = gtk_check_menu_item_new_with_label("Enable Traffic Logging");- gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(log_check_item), g_chk_logging);- g_signal_connect(log_check_item, "toggled", G_CALLBACK(on_log_traffic_toggled), NULL);-- GtkWidget *dns_check_item = gtk_check_menu_item_new_with_label("DNS via Proxy");- gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(dns_check_item), g_chk_dns);- g_signal_connect(dns_check_item, "toggled", G_CALLBACK(on_dns_proxy_toggled), NULL);-- GtkWidget *start_item = gtk_menu_item_new_with_label("Start Engine");- g_signal_connect(start_item, "activate", G_CALLBACK(on_start_engine), NULL);-- GtkWidget *exit_item = gtk_menu_item_new_with_label("Exit");-- g_signal_connect(config_item, "activate", G_CALLBACK(on_proxy_configure), NULL);- g_signal_connect(rules_item, "activate", G_CALLBACK(on_proxy_rules_clicked), NULL);- g_signal_connect(exit_item, "activate", G_CALLBACK(on_window_destroy), NULL);-- gtk_menu_shell_append(GTK_MENU_SHELL(proxy_menu), config_item);- gtk_menu_shell_append(GTK_MENU_SHELL(proxy_menu), rules_item);- gtk_menu_shell_append(GTK_MENU_SHELL(proxy_menu), profiles_item);- gtk_menu_shell_append(GTK_MENU_SHELL(proxy_menu), gtk_separator_menu_item_new());- gtk_menu_shell_append(GTK_MENU_SHELL(proxy_menu), log_check_item);- gtk_menu_shell_append(GTK_MENU_SHELL(proxy_menu), dns_check_item);- gtk_menu_shell_append(GTK_MENU_SHELL(proxy_menu), gtk_separator_menu_item_new());- gtk_menu_shell_append(GTK_MENU_SHELL(proxy_menu), start_item);- gtk_menu_shell_append(GTK_MENU_SHELL(proxy_menu), exit_item);- gtk_menu_item_set_submenu(GTK_MENU_ITEM(proxy_menu_item), proxy_menu);-- GtkWidget *about_menu_item = gtk_menu_item_new_with_label("About");- GtkWidget *about_menu = gtk_menu_new();- GtkWidget *about_child_item = gtk_menu_item_new_with_label("About");- g_signal_connect(about_child_item, "activate", G_CALLBACK(on_about), NULL);- GtkWidget *update_item = gtk_menu_item_new_with_label("Check for Updates");- g_signal_connect(update_item, "activate", G_CALLBACK(on_check_update), NULL);- gtk_menu_shell_append(GTK_MENU_SHELL(about_menu), about_child_item);- gtk_menu_shell_append(GTK_MENU_SHELL(about_menu), update_item);- gtk_menu_item_set_submenu(GTK_MENU_ITEM(about_menu_item), about_menu);-- gtk_menu_shell_append(GTK_MENU_SHELL(menubar), proxy_menu_item);- gtk_menu_shell_append(GTK_MENU_SHELL(menubar), about_menu_item);+ GtkWidget *proxy_menu = add_submenu(menubar, "Proxy");+ add_menu_item(proxy_menu, "Proxy Settings...", G_CALLBACK(on_proxy_configure));+ add_menu_item(proxy_menu, "Proxy Rules...", G_CALLBACK(on_proxy_rules_clicked));+ add_menu_item(proxy_menu, "Profiles...", G_CALLBACK(on_profiles_clicked));+ add_separator(proxy_menu);+ add_check_item(proxy_menu, "Enable Traffic Logging", g_chk_logging, G_CALLBACK(on_log_traffic_toggled));+ add_check_item(proxy_menu, "DNS via Proxy", g_chk_dns, G_CALLBACK(on_dns_proxy_toggled));+ add_separator(proxy_menu);+ add_menu_item(proxy_menu, "Start Engine", G_CALLBACK(on_start_engine));+ add_menu_item(proxy_menu, "Exit", G_CALLBACK(on_window_destroy));+ GtkWidget *about_menu = add_submenu(menubar, "About");+ add_menu_item(about_menu, "About", G_CALLBACK(on_about));+ add_menu_item(about_menu, "Check for Updates", G_CALLBACK(on_check_update));gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, FALSE, 0);- // tabsGtkWidget *notebook = gtk_notebook_new();gtk_box_pack_start(GTK_BOX(vbox), notebook, TRUE, TRUE, 0);+ conn_buffer = add_text_tab(notebook, "Connections", "Search connections...", G_CALLBACK(on_search_conn_changed), G_CALLBACK(on_clear_conn_clicked));+ log_buffer = add_text_tab(notebook, "Activity Logs", "Search logs...", G_CALLBACK(on_search_log_changed), G_CALLBACK(on_clear_log_clicked));- // connections tab- GtkWidget *conn_vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);- gtk_container_set_border_width(GTK_CONTAINER(conn_vbox), 5);- GtkWidget *conn_toolbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);- GtkWidget *conn_search = gtk_search_entry_new();- gtk_entry_set_placeholder_text(GTK_ENTRY(conn_search), "Search connections...");- g_signal_connect(conn_search, "search-changed", G_CALLBACK(on_search_conn_changed), NULL);- GtkWidget *conn_clear_btn = gtk_button_new_with_label("Clear Logs");- g_signal_connect(conn_clear_btn, "clicked", G_CALLBACK(on_clear_conn_clicked), NULL);- gtk_box_pack_start(GTK_BOX(conn_toolbar), conn_search, TRUE, TRUE, 0);- gtk_box_pack_start(GTK_BOX(conn_toolbar), conn_clear_btn, FALSE, FALSE, 0);- gtk_box_pack_start(GTK_BOX(conn_vbox), conn_toolbar, FALSE, FALSE, 0);- conn_view = GTK_TEXT_VIEW(gtk_text_view_new());- gtk_text_view_set_editable(conn_view, FALSE);- gtk_text_view_set_cursor_visible(conn_view, FALSE);- conn_buffer = gtk_text_view_get_buffer(conn_view);- gtk_text_buffer_create_tag(conn_buffer, "hidden", "invisible", TRUE, NULL);- GtkWidget *scrolled_window = gtk_scrolled_window_new(NULL, NULL);- gtk_container_add(GTK_CONTAINER(scrolled_window), GTK_WIDGET(conn_view));- gtk_box_pack_start(GTK_BOX(conn_vbox), scrolled_window, TRUE, TRUE, 0);- gtk_notebook_append_page(GTK_NOTEBOOK(notebook), conn_vbox, gtk_label_new("Connections"));-- // logs tab- GtkWidget *log_vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);- gtk_container_set_border_width(GTK_CONTAINER(log_vbox), 5);- GtkWidget *log_toolbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);- GtkWidget *log_search = gtk_search_entry_new();- gtk_entry_set_placeholder_text(GTK_ENTRY(log_search), "Search logs...");- g_signal_connect(log_search, "search-changed", G_CALLBACK(on_search_log_changed), NULL);- GtkWidget *log_clear_btn = gtk_button_new_with_label("Clear Logs");- g_signal_connect(log_clear_btn, "clicked", G_CALLBACK(on_clear_log_clicked), NULL);- gtk_box_pack_start(GTK_BOX(log_toolbar), log_search, TRUE, TRUE, 0);- gtk_box_pack_start(GTK_BOX(log_toolbar), log_clear_btn, FALSE, FALSE, 0);- gtk_box_pack_start(GTK_BOX(log_vbox), log_toolbar, FALSE, FALSE, 0);- log_view = GTK_TEXT_VIEW(gtk_text_view_new());- gtk_text_view_set_editable(log_view, FALSE);- gtk_text_view_set_cursor_visible(log_view, FALSE);- log_buffer = gtk_text_view_get_buffer(log_view);- gtk_text_buffer_create_tag(log_buffer, "hidden", "invisible", TRUE, NULL);- GtkWidget *log_scroll = gtk_scrolled_window_new(NULL, NULL);- gtk_container_add(GTK_CONTAINER(log_scroll), GTK_WIDGET(log_view));- gtk_box_pack_start(GTK_BOX(log_vbox), log_scroll, TRUE, TRUE, 0);- gtk_notebook_append_page(GTK_NOTEBOOK(notebook), log_vbox, gtk_label_new("Activity Logs"));-- // status barstatus_bar = gtk_statusbar_new();status_context_id = gtk_statusbar_get_context_id(GTK_STATUSBAR(status_bar), "Status");gtk_box_pack_start(GTK_BOX(vbox), status_bar, FALSE, FALSE, 0);- // setup: callbacks, options, proxies, default proxy, rules, then startProxyBridge_SetLogCallback(lib_log_callback);ProxyBridge_SetConnectionCallback(lib_connection_callback);ProxyBridge_SetTrafficLoggingEnabled(g_chk_logging);@@ -391,10 +356,7 @@ int main(int argc, char *argv[]) {start_engine();gtk_main();- if (g_engine_running) {- ProxyBridge_Stop();- g_engine_running = false;- }-+ if (g_engine_running) ProxyBridge_Stop();+ config_free_all();return 0;}diff --git a/Linux/gui/tests/config_test.c b/Linux/gui/tests/config_test.cindex bf02b71..ffd6659 100644--- a/Linux/gui/tests/config_test.c+++ b/Linux/gui/tests/config_test.c@@ -1,6 +1,7 @@-// root-free test of gui_config.c (profiles, migration, round trip)-// build: gcc -I../../src -I.. -D_GNU_SOURCE $(pkg-config --cflags gtk+-3.0) config_test.c ../gui_config.c -o config_test $(pkg-config --libs gtk+-3.0)+// root-free test of gui_config.c: profiles, migration, round trip, leak/heap stress+// build: see run_tests.sh#include "gui.h"+#include <malloc.h>GList *g_proxies_list = NULL;char *g_default_proxy = NULL;@@ -9,54 +10,58 @@ bool g_chk_logging = true;bool g_chk_dns = true;void free_proxy_data(ProxyData *p) {- if (!p) return;g_free(p->name); g_free(p->host); g_free(p->username); g_free(p->password); g_free(p);}+void free_rule_data(RuleData *r) {- if (!r) return;g_free(r->process_name); g_free(r->target_hosts); g_free(r->target_ports); g_free(r->proxy_name); g_free(r);}static int failures = 0;#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); failures++; } } while (0)-static void reset_state() {- g_profiles = NULL; g_active_profile = NULL;- g_proxies_list = NULL; g_rules_list = NULL; g_default_proxy = NULL;- g_chk_logging = true; g_chk_dns = true;-}-static void write_file(const char *dir, const char *content) {char *path = g_strdup_printf("%s/config.ini", dir);g_file_set_contents(path, content, -1, NULL);g_free(path);}+// 0 when the allocator is intercepted (ASan), LeakSanitizer covers that case+static size_t heap_used() {+ return mallinfo2().uordblks;+}++static void add_content(const char *proxy_name) {+ ProxyData *px = g_malloc0(sizeof(ProxyData));+ px->name = g_strdup(proxy_name); px->host = g_strdup("github.com"); px->port = 8080;+ px->username = g_strdup(""); px->password = g_strdup("s3cr|et");+ g_proxies_list = g_list_append(g_proxies_list, px);+ g_default_proxy = g_strdup(proxy_name);+ RuleData *r = g_malloc0(sizeof(RuleData));+ r->process_name = g_strdup("curl"); r->target_hosts = g_strdup("*.github.com"); r->target_ports = g_strdup("*");+ r->action = RULE_ACTION_PROXY; r->proxy_name = g_strdup(proxy_name); r->enabled = true;+ g_rules_list = g_list_append(g_rules_list, r);+}+int main() {char *dir = g_dir_make_tmp("pbcfg-XXXXXX", NULL);CHECK(dir != NULL);setenv("PROXYBRIDGE_CONFIG_DIR", dir, 1);- // 1. no file -> one "Default" profile- reset_state();load_config();- CHECK(g_list_length(g_profiles) == 1);- CHECK(strcmp(g_active_profile, "Default") == 0);+ CHECK(g_list_length(g_profiles) == 1 && strcmp(g_active_profile, "Default") == 0);+ config_free_all();- // 2. old single-proxy format+ // old single-proxy formatwrite_file(dir, "[SETTINGS]\nip=1.2.3.4\nport=1080\ntype=1\nuser=u\npass=p|w\nlogging=0\ndns=1\n[RULES]\n3|2|0|1|firefox|*|443;80|\n");- reset_state();load_config();CHECK(strcmp(g_active_profile, "Default") == 0);CHECK(g_list_length(g_proxies_list) == 1);- CHECK(strcmp(((ProxyData *)g_proxies_list->data)->name, "default") == 0);CHECK(strcmp(((ProxyData *)g_proxies_list->data)->host, "1.2.3.4") == 0);CHECK(strcmp(g_default_proxy, "default") == 0);- CHECK(g_list_length(g_rules_list) == 1);- CHECK(strcmp(((RuleData *)g_rules_list->data)->target_ports, "443;80") == 0);+ CHECK(g_list_length(g_rules_list) == 1 && strcmp(((RuleData *)g_rules_list->data)->target_ports, "443;80") == 0);CHECK(!g_chk_logging);- // 3. profiles: create, add data, rename, switch, save, reloadCHECK(profile_create("Work", false) != NULL);CHECK(profile_create("Work", false) == NULL);CHECK(profile_create("", false) == NULL);@@ -66,15 +71,7 @@ int main() {CHECK(!profile_rename(profile_find("Home"), "Work"));CHECK(profile_activate("Work"));CHECK(g_proxies_list == NULL && g_rules_list == NULL);- ProxyData *px = g_malloc0(sizeof(ProxyData));- px->name = g_strdup("p 1|x"); px->host = g_strdup("github.com"); px->port = 8080;- px->username = g_strdup(""); px->password = g_strdup("s3cr|et");- g_proxies_list = g_list_append(g_proxies_list, px);- g_default_proxy = g_strdup("p 1|x");- RuleData *r = g_malloc0(sizeof(RuleData));- r->process_name = g_strdup("curl"); r->target_hosts = g_strdup("*.github.com"); r->target_ports = g_strdup("*");- r->protocol = RULE_PROTOCOL_BOTH; r->action = RULE_ACTION_PROXY; r->proxy_name = g_strdup("p 1|x"); r->enabled = true;- g_rules_list = g_list_append(g_rules_list, r);+ add_content("p 1|x");g_chk_dns = false;save_config();@@ -83,25 +80,54 @@ int main() {CHECK(stat(path, &st) == 0 && (st.st_mode & 0777) == 0600);g_free(path);- reset_state();+ config_free_all();load_config();- CHECK(g_list_length(g_profiles) == 3);- CHECK(strcmp(g_active_profile, "Work") == 0);- CHECK(g_list_length(g_proxies_list) == 1);+ CHECK(g_list_length(g_profiles) == 3 && strcmp(g_active_profile, "Work") == 0);CHECK(strcmp(((ProxyData *)g_proxies_list->data)->name, "p 1|x") == 0);CHECK(strcmp(((ProxyData *)g_proxies_list->data)->password, "s3cr|et") == 0);CHECK(strcmp(((RuleData *)g_rules_list->data)->target_hosts, "*.github.com") == 0);- CHECK(strcmp(((RuleData *)g_rules_list->data)->proxy_name, "p 1|x") == 0);CHECK(!g_chk_dns && !g_chk_logging);CHECK(profile_find("Home") && g_list_length(profile_find("Home")->rules) == 1);- // 4. delete: non-last allowed, active one falls back, last refusedCHECK(profile_delete(profile_find("Work")));CHECK(strcmp(g_active_profile, "Default") == 0 && g_list_length(g_rules_list) == 1);CHECK(profile_delete(profile_find("Home")));CHECK(!profile_delete(profile_find("Default")));CHECK(g_list_length(g_profiles) == 1);+ save_config();+ config_free_all();++ // stress: heap must return to baseline+ load_config();+ for (int i = 0; i < 200; i++) { // warm up allocator caches+ Profile *p = profile_create("w", true);+ if (p) profile_delete(p);+ }+ size_t base = heap_used();+ for (int i = 0; i < 20000; i++) {+ char *a = g_strdup_printf("p%d", i), *b = g_strdup_printf("q%d", i), *c = g_strdup_printf("c%d", i);+ CHECK(profile_create(a, false) != NULL);+ CHECK(profile_activate(a));+ add_content("px");+ CHECK(profile_rename(profile_find(a), b));+ CHECK(profile_create(c, true) != NULL);+ save_config();+ if (i % 1000 == 0) {+ config_free_all();+ load_config();+ }+ CHECK(profile_activate("Default"));+ CHECK(profile_delete(profile_find(b)));+ CHECK(profile_delete(profile_find(c)));+ g_free(a); g_free(b); g_free(c);+ }+ size_t after = heap_used();+ printf("heap before=%zu after=%zu\n", base, after);+ CHECK(base == 0 || after < base + 64 * 1024);+ CHECK(g_list_length(g_profiles) == 1);- if (failures == 0) printf("config_test: all passed\n");+ config_free_all();+ g_free(dir);+ if (!failures) printf("config_test: all passed\n");return failures ? 1 : 0;}diff --git a/Linux/gui/tests/json_test.c b/Linux/gui/tests/json_test.cnew file mode 100644index 0000000..e1d0ef0--- /dev/null+++ b/Linux/gui/tests/json_test.c@@ -0,0 +1,83 @@+// hostile-input test of the rules json parser/writer (gui_json.c)+#include "gui.h"++void free_rule_data(RuleData *r) {+ g_free(r->process_name); g_free(r->target_hosts); g_free(r->target_ports); g_free(r->proxy_name); g_free(r);+}++static int failures = 0;+#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); failures++; } } while (0)++typedef struct { int n, named, disabled; RuleAction last_action; RuleProtocol last_proto; size_t max_len; } Stats;++static void cb(const RuleData *r, int index, void *ud) {+ Stats *s = (Stats *)ud;+ s->n++;+ if (r->process_name) {+ s->named++;+ if (strlen(r->process_name) > s->max_len) s->max_len = strlen(r->process_name);+ }+ if (!r->enabled) s->disabled++;+ s->last_action = r->action;+ s->last_proto = r->protocol;+}++static Stats parse(const char *json) {+ Stats s = {0};+ rules_from_json(json, cb, &s);+ return s;+}++int main() {+ Stats s = parse("[{\"processNames\":\"a\",\"action\":\"DIRECT\",\"protocol\":\"udp\",\"enabled\":false}]");+ CHECK(s.n == 1 && s.named == 1 && s.disabled == 1 && s.last_action == RULE_ACTION_DIRECT && s.last_proto == RULE_PROTOCOL_UDP);++ // macOS style: proxy uuid as action, ruleProtocol/ruleAction keys+ s = parse("{\"processNames\":\"a\",\"ruleAction\":\"6F1C-uuid\",\"ruleProtocol\":\"TCP\"}");+ CHECK(s.n == 1 && s.last_action == RULE_ACTION_PROXY && s.last_proto == RULE_PROTOCOL_TCP && s.disabled == 0);++ // hostile small inputs must not crash+ const char *bad[] = {"", "{", "}", "{{{{", "{\"processNames\":", "{\"processNames\":\"unterminated", "{\"processNames\":5}",+ "{\"processNames\":null,\"enabled\":\"yes\"}", "{\"a\":\"}\"}", "[{\"processNames\":\"x\\", "{\"processNames\":\"x\\\"}", NULL};+ for (int i = 0; bad[i]; i++) parse(bad[i]);+ s = parse("{\"processNames\":\"a}b\"}");+ CHECK(s.n == 1 && s.max_len == 3);+ s = parse("{\"processNames\":5}");+ CHECK(s.n == 1 && s.named == 0);++ // huge string+ size_t big = 20 * 1024 * 1024;+ char *json = g_malloc(big + 64);+ strcpy(json, "[{\"processNames\":\"");+ memset(json + strlen(json), 'A', big);+ strcpy(json + 18 + big, "\"}]");+ s = parse(json);+ CHECK(s.n == 1 && s.max_len == big);+ g_free(json);++ GString *deep = g_string_new("");+ for (int i = 0; i < 1000000; i++) g_string_append_c(deep, '{');+ parse(deep->str);+ g_string_free(deep, TRUE);++ // 100k rules round trip through the writer+ GList *rules = NULL;+ for (int i = 0; i < 100000; i++) {+ RuleData *r = g_malloc0(sizeof(RuleData));+ r->process_name = g_strdup_printf("proc\"%d\\", i);+ r->target_hosts = g_strdup("*.example.com;10.0.0.0/8");+ r->target_ports = g_strdup("80;443");+ r->protocol = i % 3; r->action = i % 3; r->enabled = i % 2;+ r->proxy_name = i % 3 == 0 ? g_strdup("px") : NULL;+ r->selected = true;+ rules = g_list_append(rules, r);+ }+ char *out = rules_to_json(rules, true);+ s = parse(out);+ CHECK(s.n == 100000 && s.named == 100000 && s.disabled == 50000);+ g_free(out);+ g_list_free_full(rules, (GDestroyNotify)free_rule_data);++ if (!failures) printf("json_test: all passed\n");+ return failures ? 1 : 0;+}diff --git a/Linux/gui/tests/run_tests.sh b/Linux/gui/tests/run_tests.shnew file mode 100755index 0000000..a950ef9--- /dev/null+++ b/Linux/gui/tests/run_tests.sh@@ -0,0 +1,13 @@+#!/bin/bash+# usage: tests/run_tests.sh [outdir] (root-free)+set -e+cd "$(dirname "$0")/.."+OUT="${1:-$(mktemp -d)}"+CF="-Wall -Wextra -Wno-unused-parameter -g -fsanitize=address,undefined -I../src -I. -D_GNU_SOURCE $(pkg-config --cflags gtk+-3.0)"+LF="$(pkg-config --libs gtk+-3.0)"+gcc $CF tests/config_test.c gui_config.c -o "$OUT/config_test" $LF+gcc $CF tests/json_test.c gui_json.c -o "$OUT/json_test" $LF+gcc -O1 -I../src -I. -D_GNU_SOURCE $(pkg-config --cflags gtk+-3.0) tests/config_test.c gui_config.c -o "$OUT/config_plain" $LF+"$OUT/config_plain"+ASAN_OPTIONS=detect_leaks=1 "$OUT/config_test"+ASAN_OPTIONS=detect_leaks=1 "$OUT/json_test"