Solution of long standing Emacs and GTK problem #emacs #gtk #c #programming

🕑︎ - 2026-11-07 - 🟊 14 - ♺ 5
A picture cute beagle sitting on a lawn looking into the camera. He was called Fidel.

16 years ago I went for a walk with the family dog. When I returned home my computer's disk was full.

I reported the problem on the Emacs development mailing list, because what happened was that I had Emacs running on my computer, and I had it open a window on my phone, when suddenly I had to walk the dog. As my phone lost wifi access, the connection to the display on the phone broke, and so did Emacs.

It spectacularly logged a warning over and over filling up my disk, 42 GB in total.

The Emacs developers saw this as a problem and avoided it by killing Emacs instead of going into the warning loop.

That is arguably better than filling up the disk, but not a very nice outcome - network connections come and go, so if you are opening windows on other machines, you'll hit this abrupt exit sooner or later, and lose your state in the original Emacs. Annoying when you are using Emacs to read email, RSS etc.

Since 2011 Emacs has pointed to an old GTK issue from 2002 in its documentation and crash message in these cases, which did not affect the attitude of the GTK/GNOME/Glib developers in a positive way.

Anyway, in 2020 I got inspired by the mention of the old problem to look into a related problem: Log out hanging after X-forwarded emacsclient. What followed was more digging: Re: Log out hanging after X-forwarded emacsclient - and it turned out that the two problems are intertwined.

Here is the mailing list post from 2020 where I finally found out what is going on: Re: long-standing GTK bug - basically if the display disappears while GTK is in control, X11 calls an error handler which has to longjmp() out at the end - because otherwise X11 will call _exit() after returning from the error handler - and control never returns to GTK, so it isn't able to decrease an internal counter

My hack was to change Emacs to change the counter in the internal GTK structure from the error handler, which is not a sustainable solution because it means that when GTKs internals change, Emacs must be updated.

commit 3e567677c2c4c2194b19bb54f9b2d98f27494f70
Author: Adam Sjøgren <asjo@koldfront.dk>
Date:   Sun May 17 00:08:31 2020 +0200

    Reset GMainContext in_check_or_prepare when a display disappears
    
    To prevent an endless stream of warnings from GLib being printed.
    
    This solves the long standing GTK problem with X displays
    disappearing (e.g. due to a network error).
    
    This change includes the definition of the struct _GMainContext copied
    from glib/gmain.c, which I do not think is the correct solution.

diff --git a/src/xterm.c b/src/xterm.c
index a7be710426e..8cfe08af8bc 100644
--- a/src/xterm.c
+++ b/src/xterm.c
@@ -26707,6 +26707,50 @@ x_try_restore_frame (void)
 /* Handle the loss of connection to display DPY.  ERROR_MESSAGE is
    the text of an error message that lead to the connection loss.  */
 
+// XXX These definitions are stolen from glib/gmain.c:
+typedef struct _GPollRec GPollRec;
+typedef struct _GWakeup GWakeup;
+
+struct _GMainContext
+{
+  /* The following lock is used for both the list of sources
+   * and the list of poll records
+   */
+  GMutex mutex;
+  GCond cond;
+  GThread *owner;
+  guint owner_count;
+  GSList *waiters;
+
+  volatile gint ref_count;
+
+  GHashTable *sources;              /* guint -> GSource */
+
+  GPtrArray *pending_dispatches;
+  gint timeout;                        /* Timeout for current iteration */
+
+  guint next_id;
+  GList *source_lists;
+  gint in_check_or_prepare;
+
+  GPollRec *poll_records;
+  guint n_poll_records;
+  GPollFD *cached_poll_array;
+  guint cached_poll_array_size;
+
+  GWakeup *wakeup;
+
+  GPollFD wake_up_rec;
+
+/* Flag indicating whether the set of fd's changed during a poll */
+  gboolean poll_changed;
+
+  GPollFunc poll_func;
+
+  gint64   time;
+  gboolean time_is_fresh;
+};
+
 static void
 x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
 {
@@ -26728,6 +26772,7 @@ x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
     return;
 
   current_display = dpy;
+  Display *disappeared_display = NULL;
 
   dpyinfo = x_display_info_for_display (dpy);
   error_msg = alloca (strlen (error_message) + 1);
@@ -26818,6 +26863,10 @@ x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
       if (ioerror)
        dpyinfo->display = 0;
     }
+  if (ioerror) {
+    disappeared_display = dpyinfo->display;
+    dpyinfo->display = 0;
+  }
 
   /* delete_frame can still try to read async input (even though we
      tell pass `noelisp'), because looking up the `delete-before'
@@ -26871,17 +26920,13 @@ x_connection_closed (Display *dpy, const char *error_message, bool ioerror)
          XSync inside the error handler apparently hangs Emacs.  On
          current Xt versions, this isn't needed either.  */
 #ifdef USE_GTK
-      /* A long-standing GTK bug prevents proper disconnect handling
-        <https://gitlab.gnome.org/GNOME/gtk/issues/221>.  Once,
-        the resulting Glib error message loop filled a user's disk.
-        To avoid this, kill Emacs unconditionally on disconnect.  */
-      shut_down_emacs (0, Qnil);
-      fprintf (stderr, "%s\n\
-When compiled with GTK, Emacs cannot recover from X disconnects.\n\
-This is a GTK bug: https://gitlab.gnome.org/GNOME/gtk/issues/221\n\
-For details, see etc/PROBLEMS.\n",
-              error_msg);
-      emacs_abort ();
+      if (disappeared_display) {
+        GMainContext *context;
+        context = g_main_context_default();
+        // Try resetting recursion prevention counter:
+        context->in_check_or_prepare = 0;
+        xg_display_close (disappeared_display);
+      }
 #endif /* USE_GTK */
 
       /* Indicate that this display is dead.  */

This hack is not sufficient, though, because Emacs will try and close a disappeared display if it is the last, so I also have been carrying this patch around:

commit 60980ae616ca38748e7c5ce0525e960d06bc4046
Author: Adam Sjøgren <asjo@koldfront.dk>
Date:   Mon May 18 22:06:36 2020 +0200

    Don't close the last display, as it is the default
    
    Closing the default display results in a segfault.

diff --git a/src/gtkutil.c b/src/gtkutil.c
index f8e2d524688..df087e1e646 100644
--- a/src/gtkutil.c
+++ b/src/gtkutil.c
@@ -316,7 +316,7 @@ xg_display_close (GdkDisplay *gdpy)
 
       /* Find another display.  */
       for (dpyinfo = x_display_list; dpyinfo; dpyinfo = dpyinfo->next)
-        if (dpyinfo->display != dpy)
+        if (dpyinfo->display != 0 && dpyinfo->display != dpy)
           {
            gdpy_new = gdk_x11_lookup_xdisplay (dpyinfo->display);
            gdk_display_manager_set_default_display (gdk_display_manager_get (),
@@ -326,7 +326,11 @@ xg_display_close (GdkDisplay *gdpy)
       gdpy_def = gdpy_new;
     }
 
-  gdk_display_close (gdpy);
+  /* We can't close the default display (the result is a segfault),
+     and if it's the last display, we can't make another display the
+     default: */
+  if (gdpy_def != NULL)
+    gdk_display_close (gdpy);
 
 #else
 

Furthermore we want the x terminal closed when the last frame is closed, otherwise you get the effect that you close emacsclient, but you can't close the terminal it was started from - and if you Control-C it, your Emacs crashes.

commit 4e06f6085c33379376410d325cf142bc8760e636
Author: Adam Sjøgren <asjo@koldfront.dk>
Date:   Thu Dec 8 15:51:34 2022 +0100

    Close x terminal when last frame is closed with GTK
    
    The workaround originally introduced for GTK was expanded to cover
    Lucid and Motif as well due to other problems; this only removes the
    workaround for GTK.

diff --git a/src/frame.c b/src/frame.c
index ff5e55bb7af..c9a78e7e294 100644
--- a/src/frame.c
+++ b/src/frame.c
@@ -2976,10 +2976,12 @@ delete_frame (Lisp_Object frame, Lisp_Object force)
     /* Since a similar behavior was observed on the Lucid and Motif
        builds (see Bug#5802, Bug#21509, Bug#23499, Bug#27816), we now
        don't delete the terminal for these builds either.  */
+#ifndef USE_GTK
     if (terminal->reference_count == 0
        && (terminal->type == output_x_window
            || terminal->type == output_pgtk))
       terminal->reference_count = 1;
+#endif /* USE_GTK */
 #endif /* USE_X_TOOLKIT || USE_GTK */
 
     if (terminal->reference_count == 0)

I added the information to the GTK issue from 2019 after mentioning it on the Emacs development mailing list, but nothing more came of it.

I have been using this hack locally since 2020, and only remember it when I recompile Emacs and something in the affected areas has changed (which is rarely).

Yesterday I got a notification from the GTK issue, where somebody asked if I was still following along, because a new solution was brewing.

The story of the new solution, which might be acceptable in Emacs, is in an Emacs bug created in the summer of 2026, and it seems to be very close to being done now, in november 2026.

Colour me amazed!

If I understand it correctly, it changes the error handler to make a note of the display disappearing, and then when control returns to Emacs, it then closes the display and effectively tells GTK about it, solving the problem of not returning to GTK from the error handler and having the count be wrong.

It will be fun to try when/if it lands.

rndc: 'reload' failed: out of range #dns

🕡︎ - 2026-11-02

A while back I made a note for myself: when reloading a zone on a BIND 9 name server, eg: rndc reload koldfront.dk IN internet fails with the error message rndc: 'reload' failed: out of range, one solution is to simply ask it to sync and clean by running rndc sync -clean.

Hopefully I will look here the next time I encounter that problem.

Attack of the crawlers #net #fail2ban

🕓︎ - 2026-10-17 - 🟊 1 - ♺ 1

Like everybody else who has a server online, I have noticed the increase in crawling since the generative AI wave started.

Yesterday my network connection was very slow - IPv6 had 70% packet loss and both IPv4 and 6 had suddenly average ping times of 300+ ms, where it's usually around 10-30ms for nearby servers.

It didn't look good:

Smokeping graph showing latency to wikipedia.org being horrible for long periods of time Friday and Saturday

I tried restarting the ISP router - it runs an old, modified OpenWrt, and I thought it might be having problems keeping up. That gave a short drop, but the the problem swiftly returned.

I suspected my ISP had a problem, so I changed my computers to prefer IPv4 over IPv6 (same latency, but no packet loss), and I thought my guess was correct when I saw this morning that normality had returned around 7AM. Maybe somebody got to work and fixed something?

But then this afternoon the problem returned, and as I took a look at Munin again, I noticed that the "Apache volume" graph seemed to corrolate with the Smokeping graph:

Graph of bytes/second sent by Apache

So I tried stopping Apache. Ping fell to normal levels. Started it again. Ping back up to 300ms.

Aha!

iftop confirmed that my outbound bandwidth was saturated - I'm on an ancient copper 40/10 Mbps ADSL line, so it is not that hard to do. In fact the tail I have on the webserver logs moved so slowly, that I didn't even consider that to be the problem.

Now I have enabled mod_ratelimit in Apache and configured it aggressively on the pictures on asjo.org that the crawlers were saturating my connection by fetching, and I have added a couple of new patterns to my fail2ban filters, matching "Reflectionbot" and "Applebot" and a funky one that identifies itself just as "Mozilla 5.0 (compatible; crawler)".

I have been running a webserver on my home connection for the past 25+ years - never needed this before. Thanks for ruining one more thing, sloppists.

Student Assistant, Novonesis R&D IT, Lyngby #novonesis #job

🕒︎ - 2026-10-15 - ♺ 2
Novonesis

The Operations team in Lyngby, Denmark is looking for a student assistant; you will be on premise, as are [most of] the Linux servers you will be looking after. Plenty of racks, cooling, UPS, backup tapes, distributed storage, virtual machines, automation, monitoring, and tasks to do → take a look at the posting and apply if it sounds interesting to you.

Organisational Dysfunction of the Day

🕣︎ - 2026-10-04
The cover of Organisational Dysfunctions - Open Systems Theory Explains, by Trond Hjorteland.

I stumbled over a long thread of Organisational Dysfunction of the Day-posts on the fediverse recently. Some stood out:

The organisation has values. […] the output was synthesised into five words: Courage, Trust, Impact, Collaboration, Excellence. They are on the website, in the onboarding deck, framed in reception. Leadership references them in all-hands. […] Most people cannot name all five without looking.

· The values on the wall

The company has a solid sustainability certification. […] Meanwhile, every developer on every team now runs an AI coding assistant constantly: […] Nobody tracks how much compute this consumes, or where.

· The adaptation plan nobody owns

Every team has one. The person who remembers why the architecture is the way it is, who onboards new people without being asked, who spots the misunderstanding between two colleagues before it becomes a conflict, who writes the documentation nobody else gets around to. They are rarely the loudest voice in the room. Their work is invisible precisely because it works. Then they leave, or they are cut in a restructuring because their output is hard to measure. The team notices immediately. Things that used to happen automatically now fall through the gaps.

· When the glue leaves

The explanation sections are are little heavy on abbreviations and references you apparently Just Know™, but the thread is interesting nonetheless - and to be fair, it is advertising a book.

A couple of toots by Rob Pike on LLMs #programming #ai

🕣︎ - 2026-10-04 - ♺ 1

Rob Pike has some choice words on LLMs:

I like calculators, I like maps. But I worry every day about what LLMs are doing to people's brains.

It's why I won't touch the damn things. I like my ability to think.

The context is in the start of the thread.

AkaRank return #net

🕡︎ - 2026-08-31 - ♺ 1
Plot of Akarank for asjo.org (and a couple of competing domains).

Back in March I learned that one of my domains asjo.org was in the top 1000 in Akamai's AkaRank DNS ranking.

I set up graphing of the ranking, to be able to follow along. I also looked up the earliest ranking I could find in The Internet Archive (446 on 2025-11-13 - above wikipedia.org!), and added it to my dataset.

A couple of months after the discovery the ranking dropped significantly - suddenly my little domain was only listed in the top ~150K.

It stayed around there for another couple of months, and then it suddenly dropped to top ~900K.

I was half expecting that somebody noticed they had misconfigured something and fixed it, but still, none of my other domains are in the top 1 million.

Some weeks went by, then the ranking jumped up, and then up again, so now asjo.org is at 1268! That means that Akamai sees more DNS lookups for asjo.org than they do for domains such as messenger.com, samsungmobile.com, twitch.tv, visa.com, mastercard.com, amazon.it, and kaspersky.com just to mention a few.

The mystery lives on.

Lille langebro

Today

Kristallnacht (88).

Larry Wall announces "patch" (42).

The Berlin Wall came down (37).

Tomorrow

NSCA Mosaic 2.0 released (33).

Wednesday

Toddy (32).

Thursday

Neil Young (81).

Friday

World Kindness Day (29).

Novozymes (26).

Saturday

Claude Monet (186).

World Diabetes Day (20).

Sunday

Microprocessors (55).

2026-11-16

Rasmus (36).

2026-11-17

Sigurd (32).

2026-11-19

International Men's Day.

2026-11-21

Speed of light discovered by Ole Rømer (350).

Rene Magritte (128).

2026-11-22

DNA lounge (41).

2026-11-23

Sri Sathya Sai Baba (100).

szn.dk (25).

2026-11-26

NPC (27).

2026-11-29

Grethe Jørgensen (103).

Hilda Nalwanga (39).