From b3dfb49f78d78373743030ddc743e6e570bc90ef Mon Sep 17 00:00:00 2001
From: classabbyamp <dev@placeviolette.net>
Date: Sat, 10 Aug 2024 20:05:29 -0400
Subject: [PATCH] src/fe-gtk/fe-gtk.c: handle % in URLs better

1. don't let g_uri_escape_string escape %s, this often leads to %25%xx
   because many urls are pre-escaped.
2. use some regex heuristics to escape any %s that aren't part of an
   existing % escape sequence (% with two hexadecimal digits after)

this prevents glib/gtk2 from crashing hexchat when trying to open links
containing bare %s:

* https://gitlab.gnome.org/GNOME/glib/-/issues/2860
* https://gitlab.gnome.org/GNOME/glib/-/issues/2385

and prevents hexchat/glib from overeagerly escaping % sequences.
---
 src/fe-gtk/fe-gtk.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/fe-gtk/fe-gtk.c b/src/fe-gtk/fe-gtk.c
index 125ab5779..15fee8aaf 100644
--- a/src/fe-gtk/fe-gtk.c
+++ b/src/fe-gtk/fe-gtk.c
@@ -1057,7 +1057,11 @@ osx_show_uri (const char *url)
 static inline char *
 escape_uri (const char *uri)
 {
-	return g_uri_escape_string(uri, G_URI_RESERVED_CHARS_GENERIC_DELIMITERS G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS, FALSE);
+	gchar *esc;
+	GRegex *regex;
+	esc = g_uri_escape_string(uri, G_URI_RESERVED_CHARS_GENERIC_DELIMITERS G_URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS "%", FALSE);
+	regex = g_regex_new("\%(?![0-9a-fA-F][0-9a-fA-F])", G_REGEX_OPTIMIZE, 0, NULL);
+	return g_regex_replace(regex, esc, -1, 0, "%25", 0, NULL);
 }
 
 static inline gboolean
