Skip to content

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

feat(linux/gui): proxy manager, profiles and per-rule proxy

anof-cybere3fea87988bf
diff --git a/Linux/gui/gui.h b/Linux/gui/gui.h
index 035c1ee..a1c0577 100644
--- a/Linux/gui/gui.h
+++ b/Linux/gui/gui.h
@@ -12,6 +12,7 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
+#include <stdarg.h>
#include "ProxyBridge.h"
typedef struct {
char *process_name;
@@ -26,13 +27,21 @@ 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
+ ProxyType type;
+ char *host;
+ uint16_t port;
+ char *username;
+ char *password;
+} ProxyData;
+
+// proxy manager dialog widgets
typedef struct {
GtkWidget *dialog;
- GtkWidget *ip_entry;
- GtkWidget *port_entry;
- GtkWidget *type_combo;
- GtkWidget *user_entry;
- GtkWidget *pass_entry;
+ GtkWidget *tree;
+ GtkListStore *store;
GtkWidget *test_host;
GtkWidget *test_port;
GtkTextBuffer *output_buffer;
@@ -46,14 +55,17 @@ typedef struct {
char *target_ports;
RuleProtocol protocol;
RuleAction action;
+ char *proxy_name; // NULL or "" = default proxy
bool enabled;
bool selected;
} RuleData;
struct TestRunnerData {
+ uint32_t proxy_id;
char *host;
uint16_t port;
- ConfigInfo *ui_info;
+ GtkTextBuffer *buffer; // referenced, released in the idle callback
+ GtkWidget *btn; // referenced, released in the idle callback
};
typedef struct {
@@ -68,11 +80,17 @@ extern GtkTextBuffer *log_buffer;
extern GtkWidget *status_bar;
extern guint status_context_id;
-extern char g_proxy_ip[256];
-extern uint16_t g_proxy_port;
-extern ProxyType g_proxy_type;
-extern char g_proxy_user[256];
-extern char g_proxy_pass[256];
+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_rules_list;
extern bool g_chk_logging;
@@ -85,18 +103,34 @@ char* get_current_time_str();
char *escape_json_string(const char *src);
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);
// config storage
void save_config();
void load_config();
+void profile_sync_active();
+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
+// settings / proxies
void on_proxy_configure(GtkWidget *widget, gpointer data);
+void on_profiles_clicked(GtkWidget *widget, gpointer data);
+ProxyData *find_proxy_by_name(const char *name);
+uint32_t resolve_proxy_id(const char *name);
+void free_proxy_data(ProxyData *p);
+void apply_proxies_to_lib();
// rules section
void on_proxy_rules_clicked(GtkWidget *widget, gpointer data);
+void free_rule_data(RuleData *rule);
+void apply_rules_to_lib();
+void refresh_rules_window();
// Logs
+void 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);
void on_search_conn_changed(GtkSearchEntry *entry, gpointer user_data);
diff --git a/Linux/gui/gui_config.c b/Linux/gui/gui_config.c
index 46c9571..433a182 100644
--- a/Linux/gui/gui_config.c
+++ b/Linux/gui/gui_config.c
@@ -1,24 +1,210 @@
#include "gui.h"
#include <fcntl.h>
-#define CONFIG_DIR "/etc/proxybridge"
-#define CONFIG_PATH "/etc/proxybridge/config.ini"
+#define CONFIG_DIR_DEFAULT "/etc/proxybridge"
+
+GList *g_profiles = NULL; // list of Profile
+char *g_active_profile = NULL; // name of the active profile
+
+// PROXYBRIDGE_CONFIG_DIR overrides the default dir (used for testing)
+static char *config_dir() {
+ const char *env = getenv("PROXYBRIDGE_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;
+}
+
+// ---- profiles ----
+
+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);
+ g_list_free(p->rules);
+ g_free(p->default_proxy);
+ g_free(p->name);
+ g_free(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;
+ }
+ return NULL;
+}
+
+// the working lists (g_proxies_list etc.) belong to the active profile, copy the heads back
+void profile_sync_active() {
+ Profile *p = profile_find(g_active_profile);
+ if (!p) return;
+ p->proxies = g_proxies_list;
+ p->rules = g_rules_list;
+ p->default_proxy = g_default_proxy;
+}
+
+static void load_globals_from(Profile *p) {
+ g_proxies_list = p->proxies;
+ g_rules_list = p->rules;
+ g_default_proxy = p->default_proxy;
+}
+
+static Profile *profile_new_empty(const char *name) {
+ Profile *p = g_malloc0(sizeof(Profile));
+ p->name = g_strdup(name);
+ g_profiles = g_list_append(g_profiles, p);
+ return p;
+}
+
+static ProxyData *copy_proxy(const ProxyData *src) {
+ ProxyData *d = g_malloc0(sizeof(ProxyData));
+ d->name = g_strdup(src->name);
+ d->type = src->type;
+ d->host = g_strdup(src->host);
+ d->port = src->port;
+ d->username = g_strdup(src->username ? src->username : "");
+ d->password = g_strdup(src->password ? src->password : "");
+ return d;
+}
+
+static RuleData *copy_rule(const RuleData *src) {
+ RuleData *d = g_malloc0(sizeof(RuleData));
+ d->process_name = g_strdup(src->process_name ? src->process_name : "");
+ d->target_hosts = g_strdup(src->target_hosts ? src->target_hosts : "");
+ 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->enabled = src->enabled;
+ return d;
+}
+
+// new profile (empty, or a copy of the active one). NULL if the name is empty or taken
+Profile *profile_create(const char *name, bool copy_active) {
+ if (!name || !*name || profile_find(name)) return NULL;
+ profile_sync_active();
+ Profile *src = copy_active ? profile_find(g_active_profile) : NULL;
+ Profile *p = profile_new_empty(name);
+ if (src) {
+ for (GList *l = src->proxies; l != NULL; l = l->next) p->proxies = g_list_append(p->proxies, copy_proxy((ProxyData *)l->data));
+ for (GList *l = src->rules; l != NULL; l = l->next) p->rules = g_list_append(p->rules, copy_rule((RuleData *)l->data));
+ p->default_proxy = g_strdup(src->default_proxy);
+ }
+ return p;
+}
+
+bool profile_rename(Profile *p, const char *new_name) {
+ if (!p || !new_name || !*new_name) return false;
+ if (strcmp(p->name, new_name) == 0) return true;
+ if (profile_find(new_name)) return false;
+ bool active = g_active_profile && strcmp(g_active_profile, p->name) == 0;
+ g_free(p->name);
+ p->name = g_strdup(new_name);
+ if (active) {
+ g_free(g_active_profile);
+ g_active_profile = g_strdup(new_name);
+ }
+ return true;
+}
+
+// makes the profile active (working lists swap). does not touch the library
+bool 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
+ char *copy = g_strdup(name);
+ g_free(g_active_profile);
+ g_active_profile = copy;
+ }
+ load_globals_from(p);
+ return true;
+}
+
+// last profile cannot be deleted. deleting the active one activates another first
+bool 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;
+ }
+ 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);
+ g_free(pn);
+ g_free(def_esc);
+
+ // proxies section, text fields are percent-encoded so '|' and newlines are safe
+ fprintf(f, "[PROXIES]\n");
+ 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);
+ }
+
+ // rules section
+ fprintf(f, "[RULES]\n");
+ 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);
+ }
+}
// save config
void save_config() {
+ profile_sync_active();
+
+ char *dir = config_dir();
+ char *path = config_path();
struct stat st = {0};
- if (stat(CONFIG_DIR, &st) == -1) {
- if (mkdir(CONFIG_DIR, 0700) != 0) {
+ 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;
}
- } else if (chmod(CONFIG_DIR, 0700) != 0) {
+ } else if (chmod(dir, 0700) != 0) {
perror("chmod config dir failed");
}
- int cfg_fd = open(CONFIG_PATH, O_WRONLY | O_CREAT | O_TRUNC, 0600);
+ int cfg_fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
if (cfg_fd < 0) {
- printf("failed to save config to %s\n", CONFIG_PATH);
+ printf("failed to save config to %s\n", path);
+ g_free(dir); g_free(path);
return;
}
// mode on open only hits create; tighten existing 0644 installs too
@@ -28,71 +214,126 @@ void save_config() {
FILE *f = fdopen(cfg_fd, "w");
if (!f) {
close(cfg_fd);
- printf("failed to save config to %s\n", CONFIG_PATH);
+ printf("failed to save config to %s\n", path);
+ g_free(dir); g_free(path);
return;
}
- // settings section
+ // settings section, global
+ char *act_esc = g_uri_escape_string(g_active_profile ? g_active_profile : "", NULL, FALSE);
fprintf(f, "[SETTINGS]\n");
- fprintf(f, "ip=%s\n", g_proxy_ip);
- fprintf(f, "port=%d\n", g_proxy_port);
- fprintf(f, "type=%d\n", g_proxy_type);
- fprintf(f, "user=%s\n", g_proxy_user);
- fprintf(f, "pass=%s\n", g_proxy_pass);
+ 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);
- // rules section
- fprintf(f, "[RULES]\n");
- for (GList *l = g_rules_list; l != NULL; l = l->next) {
- RuleData *rule = (RuleData *)l->data;
- // format: id|protocol|action|enabled|procname|hosts|ports
- fprintf(f, "%u|%d|%d|%d|%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 : ""
- );
- }
+ 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("");
+}
+
+static ProxyType proxy_type_from_int(int v) {
+ return v == PROXY_TYPE_HTTP ? PROXY_TYPE_HTTP : PROXY_TYPE_SOCKS5;
+}
+
+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;
+ }
+ return NULL;
}
-// load settings from file
+// load settings from file. old files (no profiles) end up in a profile called "Default"
void load_config() {
- chmod(CONFIG_PATH, 0600); // old installs might still be world readable
- FILE *f = fopen(CONFIG_PATH, "r");
- if (!f) return;
+ char *path = config_path();
+ chmod(path, 0600); // old installs might still be world readable
+ FILE *f = fopen(path, "r");
+ g_free(path);
+
+ char line[8192];
+ int section = 0; // 0=none, 1=settings, 2=rules, 3=proxies, 4=profile header
+ Profile *cur = NULL;
+ char *saved_active = NULL;
- char line[2048];
- int section = 0; // 0=none, 1=settings, 2=rules
+ // old single proxy config (pre multi-proxy), 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 (fgets(line, sizeof(line), f)) {
+ while (f && fgets(line, sizeof(line), f)) {
// trim newline
line[strcspn(line, "\r\n")] = 0;
if (strlen(line) == 0 || line[0] == '#') continue;
if (strcmp(line, "[SETTINGS]") == 0) { section = 1; continue; }
- if (strcmp(line, "[RULES]") == 0) { section = 2; 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);
+ g_free(pn);
+ section = cur ? 4 : 0;
+ continue;
+ }
- if (section == 1) {
+ if (section == 1 || section == 4) {
char *val = strchr(line, '=');
if (!val) continue;
*val = 0; val++;
- if (strcmp(line, "ip") == 0) strncpy(g_proxy_ip, val, sizeof(g_proxy_ip) - 1);
- else if (strcmp(line, "port") == 0) g_proxy_port = atoi(val);
- else if (strcmp(line, "type") == 0) g_proxy_type = atoi(val);
- else if (strcmp(line, "user") == 0) strncpy(g_proxy_user, val, sizeof(g_proxy_user) - 1);
- else if (strcmp(line, "pass") == 0) strncpy(g_proxy_pass, val, sizeof(g_proxy_pass) - 1);
- else if (strcmp(line, "logging") == 0) g_chk_logging = atoi(val);
- else if (strcmp(line, "dns") == 0) g_chk_dns = atoi(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]
+ 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);
+ }
+ 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 == 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);
}
- else if (section == 2) {
+ else if (section == 2 && cur) {
// parse rule line
RuleData *rule = g_malloc0(sizeof(RuleData));
char *p = line;
@@ -108,16 +349,59 @@ void load_config() {
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++;
}
- if (idx >= 4) {
- g_rules_list = g_list_append(g_rules_list, rule);
+ // 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 {
- g_free(rule);
+ free_rule_data(rule);
}
}
}
- fclose(f);
-}
\ No newline at end of file
+ if (f) fclose(f);
+
+ // migrate old single proxy config into the "Default" profile
+ if (old_ip[0] != '\0' && old_port >= 1 && old_port <= 65535) {
+ Profile *d = profile_find("Default");
+ if (!d) d = profile_new_empty("Default");
+ if (!d->proxies) {
+ ProxyData *px = g_malloc0(sizeof(ProxyData));
+ px->name = g_strdup("default");
+ px->type = proxy_type_from_int(old_type);
+ px->host = g_strdup(old_ip);
+ px->port = (uint16_t)old_port;
+ px->username = g_strdup(old_user);
+ px->password = g_strdup(old_pass);
+ d->proxies = g_list_append(d->proxies, px);
+ g_free(d->default_proxy);
+ d->default_proxy = g_strdup("default");
+ }
+ }
+
+ // always at least one profile
+ if (!g_profiles) profile_new_empty("Default");
+
+ // default points to nothing -> first proxy
+ for (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))) {
+ g_free(p->default_proxy);
+ p->default_proxy = g_strdup(((ProxyData *)p->proxies->data)->name);
+ }
+ }
+
+ Profile *act = profile_find(saved_active);
+ if (!act) act = (Profile *)g_profiles->data;
+ g_free(saved_active);
+ g_free(g_active_profile);
+ g_active_profile = g_strdup(act->name);
+ load_globals_from(act);
+}
diff --git a/Linux/gui/gui_logs.c b/Linux/gui/gui_logs.c
index 8fc8d2f..8b7520f 100644
--- a/Linux/gui/gui_logs.c
+++ b/Linux/gui/gui_logs.c
@@ -56,11 +56,11 @@ void on_clear_log_clicked(GtkButton *button, gpointer user_data) {
static void free_connection_data(ConnectionData *data) {
if (data) {
- free(data->process_name);
- free(data->dest_ip);
- free(data->proxy_info);
- free(data->timestamp);
- free(data);
+ g_free(data->process_name);
+ g_free(data->dest_ip);
+ g_free(data->proxy_info);
+ g_free(data->timestamp);
+ g_free(data);
}
}
@@ -69,20 +69,28 @@ static gboolean update_log_gui(gpointer user_data) {
LogData *data = (LogData *)user_data;
if (!data) return FALSE;
- GtkTextIter end;
- gtk_text_buffer_get_end_iter(log_buffer, &end);
+ if (log_buffer) {
+ GtkTextIter end;
+ gtk_text_buffer_get_end_iter(log_buffer, &end);
- char *time_str = get_current_time_str();
- char full_msg[1200];
- snprintf(full_msg, sizeof(full_msg), "%s %s\n", time_str, data->message);
- free(time_str);
+ char *time_str = get_current_time_str();
+ char *full_msg = g_strdup_printf("%s %s\n", time_str, data->message);
+ g_free(time_str);
- gtk_text_buffer_insert(log_buffer, &end, full_msg, -1);
+ // 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);
+ trim_buffer_lines(log_buffer, 100);
+ }
- free(data->message);
- free(data);
+ g_free(data->message);
+ g_free(data);
return FALSE; // done
}
@@ -95,11 +103,16 @@ static gboolean update_connection_gui_append(gpointer user_data) {
GtkTextIter end;
gtk_text_buffer_get_end_iter(conn_buffer, &end);
- char line_buffer[1024];
- snprintf(line_buffer, sizeof(line_buffer), "%s %s (PID:%u) -> %s:%u via %s\n",
+ 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);
}
@@ -109,18 +122,28 @@ static gboolean update_connection_gui_append(gpointer user_data) {
}
void lib_log_callback(const char *message) {
- LogData *data = malloc(sizeof(LogData));
- data->message = strdup(message);
+ LogData *data = g_malloc0(sizeof(LogData));
+ data->message = g_strdup(message ? message : "");
g_idle_add(update_log_gui, data);
}
+// log a message from the gui itself, same path as library logs
+void 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);
+}
+
void lib_connection_callback(const char *process_name, uint32_t pid, const char *dest_ip, uint16_t dest_port, const char *proxy_info) {
- ConnectionData *data = malloc(sizeof(ConnectionData));
- data->process_name = strdup(process_name);
+ ConnectionData *data = g_malloc0(sizeof(ConnectionData));
+ data->process_name = g_strdup(process_name ? process_name : "");
data->pid = pid;
- data->dest_ip = strdup(dest_ip);
+ data->dest_ip = g_strdup(dest_ip ? dest_ip : "");
data->dest_port = dest_port;
- data->proxy_info = strdup(proxy_info);
+ data->proxy_info = g_strdup(proxy_info ? proxy_info : "");
data->timestamp = get_current_time_str();
g_idle_add(update_connection_gui_append, data);
}
diff --git a/Linux/gui/gui_rules.c b/Linux/gui/gui_rules.c
index df625ed..685d50a 100644
--- a/Linux/gui/gui_rules.c
+++ b/Linux/gui/gui_rules.c
@@ -1,23 +1,56 @@
#include "gui.h"
+static GtkWidget *rules_window = NULL;
static GtkWidget *rules_list_box = NULL;
static GtkWidget *btn_select_all_header = NULL;
// forward
static void refresh_rules_ui();
-static void free_rule_data(RuleData *rule) {
+void free_rule_data(RuleData *rule) {
if (rule) {
- if (rule->process_name) free(rule->process_name);
- if (rule->target_hosts) free(rule->target_hosts);
- if (rule->target_ports) free(rule->target_ports);
- free(rule);
+ g_free(rule->process_name);
+ g_free(rule->target_hosts);
+ g_free(rule->target_ports);
+ g_free(rule->proxy_name);
+ g_free(rule);
+ }
+}
+
+// position of the rule in the library list. rules the library rejected (id 0) are not in it
+static 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;
+ if (((RuleData *)l->data)->id != 0) idx++;
+ }
+ return idx;
+}
+
+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_Start
+void 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);
}
}
static void on_rule_delete(GtkWidget *widget, gpointer data) {
RuleData *rule = (RuleData *)data;
- ProxyBridge_DeleteRule(rule->id);
+ if (rule->id != 0) ProxyBridge_DeleteRule(rule->id);
g_rules_list = g_list_remove(g_rules_list, rule);
free_rule_data(rule);
save_config();
@@ -27,53 +60,33 @@ static void on_rule_delete(GtkWidget *widget, gpointer data) {
static void on_rule_toggle(GtkToggleButton *btn, gpointer data) {
RuleData *rule = (RuleData *)data;
rule->enabled = gtk_toggle_button_get_active(btn);
- if (rule->enabled) ProxyBridge_EnableRule(rule->id);
- else ProxyBridge_DisableRule(rule->id);
+ if (rule->id != 0) {
+ if (rule->enabled) ProxyBridge_EnableRule(rule->id);
+ else ProxyBridge_DisableRule(rule->id);
+ }
save_config();
}
-static void on_save_rule(GtkWidget *widget, gpointer data) {
- GtkWidget **widgets = (GtkWidget **)data;
- GtkWidget *dialog = widgets[0];
- RuleData *edit_rule = (RuleData *)widgets[6]; // existing rule if present
-
- const char *proc = gtk_entry_get_text(GTK_ENTRY(widgets[1]));
- const char *hosts = gtk_entry_get_text(GTK_ENTRY(widgets[2]));
- const char *ports = gtk_entry_get_text(GTK_ENTRY(widgets[3]));
- RuleProtocol proto = gtk_combo_box_get_active(GTK_COMBO_BOX(widgets[4]));
- RuleAction action = gtk_combo_box_get_active(GTK_COMBO_BOX(widgets[5]));
+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;
+ if (!other) return;
- if (strlen(proc) == 0) return; // need process name
+ // swap the data pointers, keeps the list head valid
+ gpointer tmp = link->data;
+ link->data = other->data;
+ other->data = tmp;
- if (edit_rule) {
- // update backend and local copy
- ProxyBridge_EditRule(edit_rule->id, proc, hosts, ports, proto, action);
-
- free(edit_rule->process_name); edit_rule->process_name = strdup(proc);
- free(edit_rule->target_hosts); edit_rule->target_hosts = strdup(hosts);
- free(edit_rule->target_ports); edit_rule->target_ports = strdup(ports);
- edit_rule->protocol = proto;
- edit_rule->action = action;
- } else {
- // add new rule
- uint32_t new_id = ProxyBridge_AddRule(proc, hosts, ports, proto, action);
- RuleData *new_rule = malloc(sizeof(RuleData));
- new_rule->id = new_id;
- new_rule->process_name = strdup(proc);
- new_rule->target_hosts = strdup(hosts);
- new_rule->target_ports = strdup(ports);
- new_rule->protocol = proto;
- new_rule->action = action;
- new_rule->enabled = true;
- new_rule->selected = false;
- g_rules_list = g_list_append(g_rules_list, new_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);
save_config();
refresh_rules_ui();
- gtk_widget_destroy(dialog);
- free(widgets);
}
+static void on_rule_move_up(GtkWidget *widget, gpointer data) { on_rule_move((RuleData *)data, -1); }
+static 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",
@@ -84,18 +97,25 @@ static void on_browse_clicked(GtkWidget *widget, gpointer data) {
NULL);
if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) {
char *filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog));
- char *base = g_path_get_basename(filename);
- gtk_entry_set_text(GTK_ENTRY(entry), base);
- g_free(base);
- g_free(filename);
+ if (filename) {
+ char *base = g_path_get_basename(filename);
+ gtk_entry_set_text(GTK_ENTRY(entry), base);
+ g_free(base);
+ g_free(filename);
+ }
}
gtk_widget_destroy(dialog);
}
+// proxy combo only matters for PROXY rules
+static 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 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(window));
+ gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(rules_window ? rules_window : window));
gtk_window_set_modal(GTK_WINDOW(dialog), TRUE);
gtk_window_set_default_size(GTK_WINDOW(dialog), 500, 400);
@@ -112,6 +132,7 @@ static void open_rule_dialog(RuleData *rule) {
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();
@@ -128,6 +149,18 @@ static void open_rule_dialog(RuleData *rule) {
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");
+ 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;
+ }
+ 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);
@@ -153,7 +186,9 @@ static void open_rule_dialog(RuleData *rule) {
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.1-50; *");
+ 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++;
@@ -172,30 +207,92 @@ static void open_rule_dialog(RuleData *rule) {
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);
- GtkWidget *save_btn = gtk_button_new_with_label("Save");
- GtkWidget *cancel_btn = gtk_button_new_with_label("Cancel");
- gtk_dialog_add_action_widget(GTK_DIALOG(dialog), cancel_btn, GTK_RESPONSE_CANCEL);
- gtk_dialog_add_action_widget(GTK_DIALOG(dialog), save_btn, GTK_RESPONSE_ACCEPT);
-
- GtkWidget **data = malloc(7 * sizeof(GtkWidget*));
- data[0] = dialog;
- data[1] = proc_entry;
- data[2] = host_entry;
- data[3] = port_entry;
- data[4] = proto_combo;
- data[5] = action_combo;
- data[6] = (GtkWidget*)rule;
-
- g_signal_connect(save_btn, "clicked", G_CALLBACK(on_save_rule), data);
- g_signal_connect(cancel_btn, "clicked", G_CALLBACK(gtk_widget_destroy), NULL);
+ gtk_dialog_add_button(GTK_DIALOG(dialog), "Cancel", GTK_RESPONSE_CANCEL);
+ gtk_dialog_add_button(GTK_DIALOG(dialog), "Save", GTK_RESPONSE_ACCEPT);
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;
+ 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;
+ }
+
+ 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;
+ }
+
+ // 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);
}
static void on_rule_edit(GtkWidget *widget, gpointer data) {
- on_proxy_rules_clicked(NULL, NULL); // Re-open if closed? Usually modal.
- // Wait, on_rule_edit clicked from rules list already
open_rule_dialog((RuleData *)data);
}
@@ -227,16 +324,17 @@ static void on_rule_export_clicked(GtkWidget *widget, gpointer data) {
if (((RuleData *)l->data)->selected) { any_selected = true; break; }
}
if (!any_selected) {
- show_message(NULL, GTK_MESSAGE_WARNING, "Please select at least one rule to export.");
+ show_message(GTK_WINDOW(rules_window ? rules_window : window), GTK_MESSAGE_WARNING, "Please select at least one rule to export.");
return;
}
- GtkWidget *dialog = gtk_file_chooser_dialog_new("Export Rules", GTK_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", GTK_WINDOW(rules_window ? rules_window : 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 = fopen(filename, "w");
+ 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) {
@@ -246,63 +344,105 @@ static void on_rule_export_clicked(GtkWidget *widget, gpointer data) {
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 \"action\": \"%s\",\n \"enabled\": %s\n }", proc, host, port, proto, act, r->enabled ? "true" : "false");
- g_free(proc); g_free(host); g_free(port);
+ 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");
- fclose(f);
- show_message(NULL, GTK_MESSAGE_INFO, "Rules exported successfully.");
+ 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");
}
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;
+}
+
static void on_rule_import_clicked(GtkWidget *widget, gpointer data) {
- GtkWidget *dialog = gtk_file_chooser_dialog_new("Import Rules", GTK_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", GTK_WINDOW(rules_window ? rules_window : 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 (g_file_get_contents(filename, &content, &len, NULL)) {
+ if (filename && g_file_get_contents(filename, &content, &len, NULL)) {
char *curr = content;
- int imported = 0;
+ 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 = extract_sub_json_str(curr, "protocol");
- char *act_s = extract_sub_json_str(curr, "action");
- bool en = extract_sub_json_bool(curr, "enabled");
-
- if (proc && host && port && proto_s && act_s) {
+ 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 (strcmp(proto_s, "TCP") == 0) p = RULE_PROTOCOL_TCP;
- else if (strcmp(proto_s, "UDP") == 0) p = RULE_PROTOCOL_UDP;
+ 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 (strcmp(act_s, "DIRECT") == 0) a = RULE_ACTION_DIRECT;
- else if (strcmp(act_s, "BLOCK") == 0) a = RULE_ACTION_BLOCK;
-
- uint32_t nid = ProxyBridge_AddRule(proc, host, port, p, a);
- if (!en) ProxyBridge_DisableRule(nid);
- RuleData *nd = malloc(sizeof(RuleData));
- nd->id = nid; nd->process_name = strdup(proc); nd->target_hosts = strdup(host);
- nd->target_ports = strdup(port); nd->protocol = p; nd->action = a; nd->enabled = en; nd->selected = false;
- g_rules_list = g_list_append(g_rules_list, nd);
- imported++;
+ 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(proc); g_free(host); g_free(port); g_free(proto_s); g_free(act_s); g_free(proxy_s);
*end = saved; curr = end + 1;
}
g_free(content);
- if (imported > 0) { refresh_rules_ui(); show_message(NULL, GTK_MESSAGE_INFO, "Imported %d rules.", imported); }
+
+ 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);
+ } else {
+ show_message(GTK_WINDOW(rules_window ? rules_window : window), GTK_MESSAGE_ERROR, "Could not read the selected file.");
}
g_free(filename);
}
@@ -321,11 +461,12 @@ static void on_bulk_delete_clicked(GtkWidget *widget, gpointer data) {
if (!to_delete) return;
for (GList *d = to_delete; d != NULL; d = d->next) {
RuleData *rule = (RuleData *)d->data;
- ProxyBridge_DeleteRule(rule->id);
+ if (rule->id != 0) ProxyBridge_DeleteRule(rule->id);
g_rules_list = g_list_remove(g_rules_list, rule);
free_rule_data(rule);
}
g_list_free(to_delete);
+ save_config();
refresh_rules_ui();
}
@@ -371,8 +512,9 @@ static void refresh_rules_ui() {
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, 8, 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) {
@@ -392,8 +534,19 @@ static void refresh_rules_ui() {
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);
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++);
@@ -408,26 +561,51 @@ static void refresh_rules_ui() {
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), gtk_label_new(proto_strs[r->protocol]), 6, 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]);
+ 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");
gtk_grid_attach(GTK_GRID(grid), l_act, 7, row, 1, 1);
+ // proxy only matters for PROXY rules
+ const 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, 8, 1); row++;
+ gtk_grid_attach(GTK_GRID(grid), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), 0, row, 9, 1); row++;
}
gtk_widget_show_all(rules_list_box);
}
+void refresh_rules_window() {
+ refresh_rules_ui();
+}
+
+// widgets are gone, refresh_rules_ui must not touch them any more
+static void on_rules_window_destroy(GtkWidget *widget, gpointer data) {
+ rules_window = NULL;
+ rules_list_box = NULL;
+ btn_select_all_header = NULL;
+}
+
void on_proxy_rules_clicked(GtkWidget *widget, gpointer data) {
+ if (rules_window) {
+ 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), 800, 500);
+ gtk_window_set_default_size(GTK_WINDOW(dialog), 1000, 500);
gtk_window_set_transient_for(GTK_WINDOW(dialog), GTK_WINDOW(window));
GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10);
gtk_container_set_border_width(GTK_CONTAINER(vbox), 20);
diff --git a/Linux/gui/gui_settings.c b/Linux/gui/gui_settings.c
index 3268f9c..6de7fac 100644
--- a/Linux/gui/gui_settings.c
+++ b/Linux/gui/gui_settings.c
@@ -1,57 +1,130 @@
#include "gui.h"
-// settings stuff
+// 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
+};
+
+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);
+ }
+ g_free(p);
+}
+
+ProxyData *find_proxy_by_name(const char *name) {
+ if (!name || !*name) return NULL;
+ for (GList *l = g_proxies_list; l != NULL; l = l->next) {
+ ProxyData *p = (ProxyData *)l->data;
+ if (p->name && strcmp(p->name, name) == 0) return p;
+ }
+ return NULL;
+}
+
+// name -> library id, 0 means 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_Start
+void apply_proxies_to_lib() {
+ ProxyBridge_ClearProxies();
+ for (GList *l = g_proxies_list; l != NULL; l = l->next) {
+ ProxyData *p = (ProxyData *)l->data;
+ char err[256] = "";
+ p->id = ProxyBridge_AddProxy(p->name, p->type, p->host, p->port, p->username, p->password, err, sizeof(err));
+ if (p->id == 0) gui_log("Proxy '%s' rejected: %s", p->name, err[0] ? err : "unknown error");
+ }
+ 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);
+ if (p < 1 || p > 65535) return false;
+ if (port_out) *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);
- free(data->result_text);
- free(data);
+ g_object_unref(data->buffer);
+ g_object_unref(data->btn);
+ g_free(data->result_text);
+ g_free(data);
return FALSE;
}
static gpointer run_test_thread(gpointer user_data) {
struct TestRunnerData *req = (struct TestRunnerData *)user_data;
- char *buffer = malloc(4096);
- memset(buffer, 0, 4096);
+ char *buffer = g_malloc0(4096);
// run test
- ProxyBridge_TestConnection(req->host, req->port, buffer, 4096);
+ 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 = malloc(sizeof(TestResultData));
+ TestResultData *res = g_malloc0(sizeof(TestResultData));
res->result_text = buffer;
- res->buffer = req->ui_info->output_buffer;
- res->btn = req->ui_info->test_btn;
+ res->buffer = req->buffer;
+ res->btn = req->btn;
g_idle_add(on_test_done, res);
- free(req->host);
- free(req);
+ g_free(req->host);
+ g_free(req);
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);
+ return (ProxyData *)ptr;
+}
+
static void on_start_test_clicked(GtkWidget *widget, gpointer data) {
ConfigInfo *info = (ConfigInfo *)data;
- // check inputs
- const char *ip_text = gtk_entry_get_text(GTK_ENTRY(info->ip_entry));
- const char *port_text = gtk_entry_get_text(GTK_ENTRY(info->port_entry));
-
- if (!ip_text || strlen(ip_text) == 0 || strspn(port_text, "0123456789") != strlen(port_text) || strlen(port_text) == 0) {
- gtk_text_buffer_set_text(info->output_buffer, "Error: Invalid Proxy IP or Port.", -1);
+ 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);
return;
}
-
- // save config
- ProxyType type = (gtk_combo_box_get_active(GTK_COMBO_BOX(info->type_combo)) == 0) ? PROXY_TYPE_HTTP : PROXY_TYPE_SOCKS5;
- int port = (int)safe_strtol(port_text);
- const char *user = gtk_entry_get_text(GTK_ENTRY(info->user_entry));
- const char *pass = gtk_entry_get_text(GTK_ENTRY(info->pass_entry));
-
- ProxyBridge_SetProxyConfig(type, ip_text, port, user, pass);
// get target
const char *t_host = gtk_entry_get_text(GTK_ENTRY(info->test_host));
@@ -59,24 +132,303 @@ static void on_start_test_clicked(GtkWidget *widget, gpointer data) {
if (!t_host || strlen(t_host) == 0) t_host = "google.com";
int t_port = (int)safe_strtol(t_port_s);
- if (t_port <= 0) t_port = 80;
+ if (t_port <= 0 || t_port > 65535) t_port = 80;
// update gui
gtk_text_buffer_set_text(info->output_buffer, "Testing connection... Please wait...", -1);
gtk_widget_set_sensitive(info->test_btn, FALSE);
- // start thread
- struct TestRunnerData *req = malloc(sizeof(struct TestRunnerData));
- req->host = strdup(t_host);
- req->port = t_port;
- req->ui_info = info;
+ // 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);
}
+// ---- 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;
+ GtkTreeIter iter;
+ gtk_list_store_append(info->store, &iter);
+ gtk_list_store_set(info->store, &iter,
+ COL_NAME, p->name,
+ COL_TYPE, p->type == PROXY_TYPE_HTTP ? "HTTP" : "SOCKS5",
+ COL_ADDR, addr,
+ COL_AUTH, (p->username && *p->username) ? "Yes" : "No",
+ COL_DEFAULT, is_def ? "Yes" : "",
+ COL_PTR, p,
+ -1);
+ g_free(addr);
+ }
+}
+
+static void select_proxy_row(ConfigInfo *info, ProxyData *target) {
+ GtkTreeModel *model = GTK_TREE_MODEL(info->store);
+ GtkTreeIter iter;
+ if (!target || !gtk_tree_model_get_iter_first(model, &iter)) return;
+ do {
+ gpointer ptr = NULL;
+ gtk_tree_model_get(model, &iter, COL_PTR, &ptr, -1);
+ if (ptr == target) {
+ gtk_tree_selection_select_iter(gtk_tree_view_get_selection(GTK_TREE_VIEW(info->tree)), &iter);
+ return;
+ }
+ } 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 ProxyData *proxy_edit_dialog(GtkWindow *parent, ProxyData *existing) {
+ 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);
+ 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_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 *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);
+ gtk_grid_attach(GTK_GRID(grid), err_label, 0, 6, 2, 1);
+
+ if (existing) {
+ 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);
+ }
+ 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));
+ 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;
+ int port = 0;
+
+ 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;
+ }
+
+ // 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 (!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);
+ continue;
+ }
+
+ ProxyData *p = 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);
+ }
+ }
+ }
+ 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);
+ if (p->password) memset(p->password, 0, strlen(p->password));
+ g_free(p->password); p->password = g_strdup(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);
+ 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);
+ if (!p) return;
+ save_config();
+ refresh_proxy_store(info);
+ select_proxy_row(info, p);
+}
+
+static void on_proxy_edit(GtkWidget *widget, gpointer data) {
+ ConfigInfo *info = (ConfigInfo *)data;
+ ProxyData *sel = get_selected_proxy(info);
+ if (!sel) {
+ 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);
+}
+
+static void on_proxy_row_activated(GtkTreeView *tree, GtkTreePath *path, GtkTreeViewColumn *col, gpointer data) {
+ on_proxy_edit(NULL, data);
+}
+
+static void on_proxy_delete(GtkWidget *widget, gpointer data) {
+ ConfigInfo *info = (ConfigInfo *)data;
+ ProxyData *p = get_selected_proxy(info);
+ if (!p) {
+ show_message(GTK_WINDOW(info->dialog), GTK_MESSAGE_WARNING, "Select a proxy first.");
+ 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)
+ 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;
+ }
+ }
+
+ 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;
+ ProxyBridge_SetDefaultProxy(resolve_proxy_id(g_default_proxy));
+ }
+
+ save_config();
+ refresh_proxy_store(info);
+}
+
+static void on_proxy_set_default(GtkWidget *widget, gpointer data) {
+ ConfigInfo *info = (ConfigInfo *)data;
+ ProxyData *p = get_selected_proxy(info);
+ if (!p) {
+ 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);
+ ProxyBridge_SetDefaultProxy(p->id);
+ save_config();
+ refresh_proxy_store(info);
+ select_proxy_row(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);
+ g_free(status_msg);
+}
+
void on_proxy_configure(GtkWidget *widget, gpointer data) {
ConfigInfo info;
+ memset(&info, 0, sizeof(info));
GtkWidget *content_area;
GtkWidget *grid;
@@ -84,11 +436,10 @@ void on_proxy_configure(GtkWidget *widget, gpointer data) {
info.dialog = gtk_dialog_new_with_buttons("Proxy Settings",
GTK_WINDOW(window),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
- "Cancel", GTK_RESPONSE_CANCEL,
- "Save", GTK_RESPONSE_ACCEPT,
+ "Close", GTK_RESPONSE_CLOSE,
NULL);
// wider window
- gtk_window_set_default_size(GTK_WINDOW(info.dialog), 600, 500);
+ 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();
@@ -97,69 +448,69 @@ void on_proxy_configure(GtkWidget *widget, gpointer data) {
gtk_container_set_border_width(GTK_CONTAINER(grid), 10);
gtk_box_pack_start(GTK_BOX(content_area), grid, TRUE, TRUE, 0);
- // proxy type dropdown
- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Type:"), 0, 0, 1, 1);
- info.type_combo = gtk_combo_box_text_new();
- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(info.type_combo), "HTTP");
- gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(info.type_combo), "SOCKS5");
- gtk_combo_box_set_active(GTK_COMBO_BOX(info.type_combo), g_proxy_type == PROXY_TYPE_HTTP ? 0 : 1);
- gtk_grid_attach(GTK_GRID(grid), info.type_combo, 1, 0, 3, 1);
-
- // ip field
- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Host:"), 0, 1, 1, 1);
- info.ip_entry = gtk_entry_new();
- gtk_entry_set_text(GTK_ENTRY(info.ip_entry), g_proxy_ip);
- gtk_widget_set_hexpand(info.ip_entry, TRUE);
- gtk_grid_attach(GTK_GRID(grid), info.ip_entry, 1, 1, 3, 1);
-
- // port field
- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Port:"), 0, 2, 1, 1);
- info.port_entry = gtk_entry_new();
- if (g_proxy_port != 0) {
- char port_str[16];
- snprintf(port_str, sizeof(port_str), "%d", g_proxy_port);
- gtk_entry_set_text(GTK_ENTRY(info.port_entry), port_str);
- }
- gtk_grid_attach(GTK_GRID(grid), info.port_entry, 1, 2, 3, 1);
-
- // user field
- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Username:"), 0, 3, 1, 1);
- info.user_entry = gtk_entry_new();
- gtk_entry_set_text(GTK_ENTRY(info.user_entry), g_proxy_user);
- gtk_grid_attach(GTK_GRID(grid), info.user_entry, 1, 3, 3, 1);
-
- // password
- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Password:"), 0, 4, 1, 1);
- info.pass_entry = gtk_entry_new();
- gtk_entry_set_visibility(GTK_ENTRY(info.pass_entry), FALSE);
- gtk_entry_set_text(GTK_ENTRY(info.pass_entry), g_proxy_pass);
- gtk_grid_attach(GTK_GRID(grid), info.pass_entry, 1, 4, 3, 1);
+ // proxy list
+ info.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
+ 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);
+ gtk_tree_view_column_set_resizable(c, TRUE);
+ if (i == 2) gtk_tree_view_column_set_expand(c, TRUE);
+ 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 buttons
+ GtkWidget *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);
+ gtk_grid_attach(GTK_GRID(grid), btn_box, 0, 1, 4, 1);
// test section
- gtk_grid_attach(GTK_GRID(grid), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), 0, 5, 4, 1);
+ gtk_grid_attach(GTK_GRID(grid), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), 0, 2, 4, 1);
- GtkWidget *test_label = gtk_label_new("<b>Test Connection</b>");
+ GtkWidget *test_label = gtk_label_new("<b>Test Selected Proxy</b>");
gtk_label_set_use_markup(GTK_LABEL(test_label), TRUE);
gtk_widget_set_halign(test_label, GTK_ALIGN_START);
- gtk_grid_attach(GTK_GRID(grid), test_label, 0, 6, 4, 1);
+ gtk_grid_attach(GTK_GRID(grid), test_label, 0, 3, 4, 1);
// target
- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Target:"), 0, 7, 1, 1);
+ gtk_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_grid_attach(GTK_GRID(grid), info.test_host, 1, 7, 1, 1);
+ gtk_widget_set_hexpand(info.test_host, TRUE);
+ gtk_grid_attach(GTK_GRID(grid), info.test_host, 1, 4, 1, 1);
// target port
- gtk_grid_attach(GTK_GRID(grid), gtk_label_new("Port:"), 2, 7, 1, 1);
+ gtk_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, 7, 1, 1);
+ gtk_grid_attach(GTK_GRID(grid), info.test_port, 3, 4, 1, 1);
// test button
info.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, 8, 4, 1);
+ gtk_grid_attach(GTK_GRID(grid), info.test_btn, 0, 5, 4, 1);
// output log
GtkWidget *out_scroll = gtk_scrolled_window_new(NULL, NULL);
@@ -172,50 +523,217 @@ void on_proxy_configure(GtkWidget *widget, gpointer data) {
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, 9, 4, 1);
+ 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);
gtk_widget_show_all(info.dialog);
+ gtk_dialog_run(GTK_DIALOG(info.dialog));
+ gtk_widget_destroy(info.dialog);
+}
- while (TRUE) {
- if (gtk_dialog_run(GTK_DIALOG(info.dialog)) != GTK_RESPONSE_ACCEPT) break;
+// ---- profiles ----
- // check
- const char *ip_text = gtk_entry_get_text(GTK_ENTRY(info.ip_entry));
- const char *port_text = gtk_entry_get_text(GTK_ENTRY(info.port_entry));
+static void update_profile_ui() {
+ char *title = g_strdup_printf("ProxyBridge - %s", g_active_profile ? 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);
+}
- if (!ip_text || strlen(ip_text) == 0) {
- show_message(GTK_WINDOW(info.dialog), GTK_MESSAGE_ERROR, "Host (IP/Domain) cannot be empty.");
- continue;
- }
+// push the active profile to the running engine: no Stop/Start needed
+static void reapply_active_profile() {
+ ProxyBridge_ClearRules();
+ ProxyBridge_ClearProxies();
+ apply_proxies_to_lib();
+ apply_rules_to_lib();
+ save_config();
+ refresh_rules_window();
+ update_profile_ui();
+}
- if (strspn(port_text, "0123456789") != strlen(port_text) || strlen(port_text) == 0) {
- show_message(GTK_WINDOW(info.dialog), GTK_MESSAGE_ERROR, "Port must be a valid number.");
- continue;
- }
+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);
+ }
+}
+
+// name of the selected row, caller frees
+static 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);
+ return name;
+}
- int p = (int)safe_strtol(port_text);
- if (p < 1 || p > 65535) {
- show_message(GTK_WINDOW(info.dialog), GTK_MESSAGE_ERROR, "Port must be between 1 and 65535.");
- continue;
+// asks for a profile name, returns NULL on cancel. caller frees
+static char *ask_profile_name(GtkWindow *parent, const char *title, const char *initial) {
+ GtkWidget *d = gtk_dialog_new_with_buttons(title, parent, GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
+ "Cancel", GTK_RESPONSE_CANCEL, "OK", GTK_RESPONSE_ACCEPT, NULL);
+ GtkWidget *box = gtk_dialog_get_content_area(GTK_DIALOG(d));
+ gtk_container_set_border_width(GTK_CONTAINER(box), 10);
+ GtkWidget *entry = gtk_entry_new();
+ gtk_entry_set_activates_default(GTK_ENTRY(entry), TRUE);
+ gtk_entry_set_text(GTK_ENTRY(entry), initial ? 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) {
+ 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;
}
+ 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);
+}
- // save
- g_proxy_type = (gtk_combo_box_get_active(GTK_COMBO_BOX(info.type_combo)) == 0) ? PROXY_TYPE_HTTP : PROXY_TYPE_SOCKS5;
- g_strlcpy(g_proxy_ip, ip_text, sizeof(g_proxy_ip));
- g_proxy_port = p;
- g_strlcpy(g_proxy_user, gtk_entry_get_text(GTK_ENTRY(info.user_entry)), sizeof(g_proxy_user));
- g_strlcpy(g_proxy_pass, gtk_entry_get_text(GTK_ENTRY(info.pass_entry)), sizeof(g_proxy_pass));
+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);
+ g_free(name);
+}
- ProxyBridge_SetProxyConfig(g_proxy_type, g_proxy_ip, g_proxy_port, g_proxy_user, g_proxy_pass);
+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); }
+ g_free(name);
+}
+
+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 back
+ char *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);
+ }
+ g_free(name);
+ g_free(src);
+}
+static void on_profile_rename(GtkWidget *widget, gpointer data) {
+ ProfilesInfo *pi = (ProfilesInfo *)data;
+ char *old = selected_profile_name(pi);
+ if (!old) return;
+ char *name = ask_profile_name(GTK_WINDOW(pi->dialog), "Rename Profile", old);
+ if (name && profile_rename(profile_find(old), name)) {
save_config();
+ refresh_profile_store(pi);
+ update_profile_ui();
+ }
+ g_free(name);
+ g_free(old);
+}
- char status_msg[512];
- snprintf(status_msg, sizeof(status_msg), "Configuration updated: %s:%d", g_proxy_ip, g_proxy_port);
- gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, status_msg);
- break;
+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) {
+ 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;
+ if (profile_delete(profile_find(name))) {
+ if (was_active) reapply_active_profile();
+ else save_config();
+ refresh_profile_store(pi);
+ }
}
+ g_free(name);
+}
- gtk_widget_destroy(info.dialog);
+static void on_profile_row_activated(GtkTreeView *tree, GtkTreePath *path, GtkTreeViewColumn *col, gpointer data) {
+ on_profile_switch(NULL, data);
+}
+
+void on_profiles_clicked(GtkWidget *widget, gpointer data) {
+ ProfilesInfo pi;
+ memset(&pi, 0, sizeof(pi));
+ 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);
+ GtkWidget *box = gtk_dialog_get_content_area(GTK_DIALOG(pi.dialog));
+ gtk_container_set_border_width(GTK_CONTAINER(box), 10);
+
+ pi.store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_STRING);
+ pi.tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL(pi.store));
+ g_object_unref(pi.store);
+ 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_append_column(GTK_TREE_VIEW(pi.tree), c);
+ }
+ g_signal_connect(pi.tree, "row-activated", G_CALLBACK(on_profile_row_activated), &pi);
+ GtkWidget *scroll = gtk_scrolled_window_new(NULL, NULL);
+ gtk_container_add(GTK_CONTAINER(scroll), pi.tree);
+ gtk_box_pack_start(GTK_BOX(box), scroll, TRUE, TRUE, 0);
+
+ GtkWidget *btns = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
+ const char *labels[] = {"Switch", "New", "Duplicate", "Rename", "Delete"};
+ void (*cbs[])(GtkWidget *, gpointer) = {on_profile_switch, on_profile_new, on_profile_duplicate, on_profile_rename, on_profile_delete};
+ for (int i = 0; i < 5; i++) {
+ GtkWidget *b = gtk_button_new_with_label(labels[i]);
+ g_signal_connect(b, "clicked", G_CALLBACK(cbs[i]), &pi);
+ gtk_box_pack_start(GTK_BOX(btns), b, FALSE, FALSE, 0);
+ }
+ gtk_box_pack_start(GTK_BOX(box), btns, FALSE, FALSE, 5);
+
+ refresh_profile_store(&pi);
+ gtk_widget_show_all(pi.dialog);
+ gtk_dialog_run(GTK_DIALOG(pi.dialog));
+ gtk_widget_destroy(pi.dialog);
}
diff --git a/Linux/gui/gui_utils.c b/Linux/gui/gui_utils.c
index ae69d29..35d4a7c 100644
--- a/Linux/gui/gui_utils.c
+++ b/Linux/gui/gui_utils.c
@@ -40,40 +40,67 @@ void trim_buffer_lines(GtkTextBuffer *buffer, int max_lines) {
char* get_current_time_str() {
time_t rawtime;
struct tm *timeinfo;
- char *buffer = malloc(32);
+ char *buffer = g_malloc0(32);
time(&rawtime);
timeinfo = localtime(&rawtime);
- strftime(buffer, 32, "[%H:%M:%S]", timeinfo);
- return buffer;
+ if (!timeinfo || strftime(buffer, 32, "[%H:%M:%S]", timeinfo) == 0) buffer[0] = '\0';
+ return buffer; // free with g_free
}
// json stuff
char *escape_json_string(const char *src) {
- if (!src) return strdup("");
+ 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);
}
-// basic parser, good enough for valid inputs
+// 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);
- char *k = strstr(json, search_key);
+ const char *k = strstr(json, search_key);
if (!k) return NULL;
- char *colon = strchr(k, ':');
+ const char *colon = strchr(k + strlen(search_key), ':');
if (!colon) return NULL;
- char *val_start = strchr(colon, '"');
- if (!val_start) return NULL;
- val_start++;
- char *val_end = strchr(val_start, '"');
- if (!val_end) return NULL;
- return g_strndup(val_start, val_end - val_start);
+ 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);
+}
+
+// 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;
}
bool extract_sub_json_bool(const char *json, const char *key) {
@@ -85,7 +112,7 @@ bool extract_sub_json_bool(const char *json, const char *key) {
if (!colon) return false;
// skip whitespace
char *v = colon + 1;
- while(*v == ' ' || *v == '\t') v++;
+ while(*v == ' ' || *v == '\t' || *v == '\n' || *v == '\r') v++;
if (strncmp(v, "true", 4) == 0) return true;
return false;
}
diff --git a/Linux/gui/main.c b/Linux/gui/main.c
index 388622e..fc7d6b0 100644
--- a/Linux/gui/main.c
+++ b/Linux/gui/main.c
@@ -1,4 +1,5 @@
#include "gui.h"
+#include <glib-unix.h>
// widgets
GtkWidget *window;
@@ -9,13 +10,10 @@ GtkTextBuffer *log_buffer;
GtkWidget *status_bar;
guint status_context_id;
-// default config
-char g_proxy_ip[256] = "";
-uint16_t g_proxy_port = 0;
-ProxyType g_proxy_type = PROXY_TYPE_SOCKS5;
-char g_proxy_user[256] = "";
-char g_proxy_pass[256] = "";
+// config lives in gui_settings.c (proxies) and gui_rules.c (rules)
+static bool g_engine_running = false;
+// default config
GList *g_rules_list = NULL;
bool g_chk_logging = true;
bool g_chk_dns = true;
@@ -202,7 +200,8 @@ static void on_about(GtkWidget *widget, gpointer data) {
char *markup = g_strdup_printf(
"<span size='xx-large' weight='bold'>ProxyBridge</span>\n"
"<span color='gray'>Version %s</span>\n\n"
- "Universal proxy client for Linux applications\n\n"
+ "Universal proxy client for Linux applications\n"
+ "eBPF backend (needs root, kernel 5.8+ with BTF and cgroup v2)\n\n"
"Author: Sourav Kalal / InterceptSuite\n\n"
"Website: <a href=\"https://interceptsuite.com\">interceptsuite.com</a>\n"
"GitHub: <a href=\"https://github.com/InterceptSuite/ProxyBridge\">InterceptSuite/ProxyBridge</a>\n\n"
@@ -217,22 +216,40 @@ static void on_about(GtkWidget *widget, gpointer data) {
gtk_widget_destroy(dialog);
}
-static void signal_handler(int sig) {
- fprintf(stderr, "\nSignal %d received. Stopping ProxyBridge...\n", sig);
- ProxyBridge_Stop();
- exit(sig);
+// signal handlers run in the main loop (g_unix_signal_add), so no library calls from a real signal context
+static gboolean on_unix_signal(gpointer data) {
+ fprintf(stderr, "\nSignal received. Stopping ProxyBridge...\n");
+ gtk_main_quit();
+ return G_SOURCE_REMOVE;
}
static void on_window_destroy(GtkWidget *widget, gpointer data) {
- ProxyBridge_Stop();
- gtk_main_quit();
+ gtk_main_quit(); // engine is stopped once after gtk_main returns
}
-int main(int argc, char *argv[]) {
- signal(SIGINT, signal_handler);
- signal(SIGTERM, signal_handler);
- signal(SIGSEGV, signal_handler);
+// start the engine, config (proxies, rules) was already pushed to the library
+static 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");
+ gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, msg);
+ g_free(msg);
+ return true;
+ }
+ gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, "Failed to start ProxyBridge engine. See the Activity Logs tab.");
+ show_message(GTK_WINDOW(window), GTK_MESSAGE_ERROR,
+ "Failed to start the ProxyBridge engine.\n\n"
+ "Open the \"Activity Logs\" tab to see the reason.\n"
+ "The eBPF backend needs root, a kernel >= 5.8 with BTF and cgroup v2.");
+ return false;
+}
+
+static void on_start_engine(GtkWidget *widget, gpointer data) {
+ start_engine();
+}
+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; }
setenv("GSETTINGS_BACKEND", "memory", 1);
@@ -245,7 +262,9 @@ int main(int argc, char *argv[]) {
if (settings) g_object_set(settings, "gtk-application-prefer-dark-theme", TRUE, NULL);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
- gtk_window_set_title(GTK_WINDOW(window), "ProxyBridge");
+ char *win_title = g_strdup_printf("ProxyBridge - %s", g_active_profile ? g_active_profile : "Default");
+ gtk_window_set_title(GTK_WINDOW(window), win_title);
+ g_free(win_title);
gtk_window_set_default_size(GTK_WINDOW(window), 900, 600);
g_signal_connect(window, "destroy", G_CALLBACK(on_window_destroy), NULL);
@@ -256,8 +275,11 @@ int main(int argc, char *argv[]) {
GtkWidget *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 *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);
@@ -267,6 +289,9 @@ int main(int argc, char *argv[]) {
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);
@@ -275,10 +300,12 @@ int main(int argc, char *argv[]) {
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);
@@ -349,30 +376,25 @@ int main(int argc, char *argv[]) {
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);
- // start
+ // setup: callbacks, options, proxies, default proxy, rules, then start
ProxyBridge_SetLogCallback(lib_log_callback);
ProxyBridge_SetConnectionCallback(lib_connection_callback);
ProxyBridge_SetTrafficLoggingEnabled(g_chk_logging);
ProxyBridge_SetDnsViaProxy(g_chk_dns);
+ apply_proxies_to_lib();
+ apply_rules_to_lib();
- if (ProxyBridge_Start()) {
- // apply config
- ProxyBridge_SetProxyConfig(g_proxy_type, g_proxy_ip, g_proxy_port, g_proxy_user, g_proxy_pass);
-
- // restore rules
- for (GList *l = g_rules_list; l != NULL; l = l->next) {
- RuleData *r = (RuleData *)l->data;
- r->id = ProxyBridge_AddRule(r->process_name, r->target_hosts, r->target_ports, r->protocol, r->action);
- if (!r->enabled) ProxyBridge_DisableRule(r->id);
- }
-
- gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, "ProxyBridge Service Started.");
- } else {
- gtk_statusbar_push(GTK_STATUSBAR(status_bar), status_context_id, "Failed to start ProxyBridge engine.");
- }
+ g_unix_signal_add(SIGINT, on_unix_signal, NULL);
+ g_unix_signal_add(SIGTERM, on_unix_signal, NULL);
gtk_widget_show_all(window);
+ start_engine();
gtk_main();
+ if (g_engine_running) {
+ ProxyBridge_Stop();
+ g_engine_running = false;
+ }
+
return 0;
}
diff --git a/Linux/gui/tests/config_test.c b/Linux/gui/tests/config_test.c
new file mode 100644
index 0000000..bf02b71
--- /dev/null
+++ b/Linux/gui/tests/config_test.c
@@ -0,0 +1,107 @@
+// 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)
+#include "gui.h"
+
+GList *g_proxies_list = NULL;
+char *g_default_proxy = NULL;
+GList *g_rules_list = NULL;
+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);
+}
+
+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);
+
+ // 2. old single-proxy format
+ write_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_chk_logging);
+
+ // 3. profiles: create, add data, rename, switch, save, reload
+ CHECK(profile_create("Work", false) != NULL);
+ CHECK(profile_create("Work", false) == NULL);
+ CHECK(profile_create("", false) == NULL);
+ Profile *dup = profile_create("Copy", true);
+ CHECK(dup && g_list_length(dup->proxies) == 1 && g_list_length(dup->rules) == 1);
+ CHECK(profile_rename(profile_find("Copy"), "Home"));
+ 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);
+ g_chk_dns = false;
+ save_config();
+
+ char *path = g_strdup_printf("%s/config.ini", dir);
+ struct stat st;
+ CHECK(stat(path, &st) == 0 && (st.st_mode & 0777) == 0600);
+ g_free(path);
+
+ reset_state();
+ 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(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 refused
+ CHECK(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);
+
+ if (failures == 0) printf("config_test: all passed\n");
+ return failures ? 1 : 0;
+}