From ce42ddedafa6e95355ff7817b019c5e18c18669e Mon Sep 17 00:00:00 2001
From: Jelte Fennema-Nio <postgres@jeltef.nl>
Date: Thu, 26 Nov 2026 14:27:33 +0100
Subject: [PATCH v2 5/5] POC: Add client_connection_linger_timeout to avoid
 lost errors at close

When a backend closes the connection while the client is still sending,
for instance a startup packet sent right after a TLS 1.3 handshake that
the server is about to reject, the server's OS answers that data with
an RST. On Windows the client's OS then discards everything the client
hasn't read yet, including the error explaining why the connection was
closed.

With this setting the backend sends a FIN, and then keeps reading and
discarding client data until the client closes its side or the timeout
expires, before closing the socket. Data the client sends in that
window no longer causes an RST. It's disabled by default, because it
can delay backend exit by up to the timeout when the client keeps the
connection open.
---
 src/backend/libpq/pqcomm.c                    | 87 +++++++++++++++++--
 src/backend/utils/misc/guc_parameters.dat     | 10 +++
 src/backend/utils/misc/postgresql.conf.sample |  3 +
 src/include/libpq/libpq.h                     |  1 +
 4 files changed, 94 insertions(+), 7 deletions(-)

diff --git a/src/backend/libpq/pqcomm.c b/src/backend/libpq/pqcomm.c
index 87de7ac1a1c..ab69ad3b65c 100644
--- a/src/backend/libpq/pqcomm.c
+++ b/src/backend/libpq/pqcomm.c
@@ -78,6 +78,7 @@
 #include "storage/latch.h"
 #include "utils/guc_hooks.h"
 #include "utils/memutils.h"
+#include "utils/timestamp.h"
 
 /*
  * Cope with the various platform-specific ways to spell TCP keepalive socket
@@ -103,6 +104,7 @@
  */
 int			Unix_socket_permissions;
 char	   *Unix_socket_group;
+int			client_connection_linger_timeout = 0;
 
 /* Where the Unix socket files are (list of palloc'd strings) */
 static List *sock_paths = NIL;
@@ -136,6 +138,7 @@ static bool PqCommReadingMsg;	/* in the middle of reading a message */
 /* Internal functions */
 static void socket_comm_reset(void);
 static void socket_close(int code, Datum arg);
+static void socket_linger(pgsocket sock);
 static void socket_set_nonblocking(bool nonblocking);
 static int	socket_flush(void);
 static int	socket_flush_if_writable(void);
@@ -394,20 +397,26 @@ socket_close(int code, Datum arg)
 		 * OpenSSL, closesocket() alone was observed to still lose messages
 		 * occasionally; why exactly was never determined.
 		 *
-		 * Even with a graceful shutdown, if the client sends anything after
-		 * we're gone, such as its next query, our side answers with an RST,
-		 * and the client can still lose the data we sent.  The client can
-		 * reduce that risk by reading any pending input before sending, but
-		 * it can't rule it out: our data might not have arrived yet when it
-		 * sends.
+		 * Even with a graceful shutdown, and on any platform, if the client
+		 * sends anything after we're gone, our side answers with an RST, and
+		 * a client on Windows can still lose the data we sent.  Lingering
+		 * (see socket_linger) avoids that for data the client sends shortly
+		 * after we close, such as during connection setup.  For later sends,
+		 * like an idle client's next query, only the client can reduce the
+		 * risk, by reading any pending input before sending.
 		 *
 		 * This code runs late enough during process shutdown that we should
 		 * have finished all externally-visible shutdown activities, so that
 		 * in principle it's good enough to act as a synchronous close on
 		 * Windows too.  But it's a lot more fragile than the other way.
 		 */
+		if (client_connection_linger_timeout > 0)
+			socket_linger(MyProcPort->sock);
+
 #ifdef WIN32
-		shutdown(MyProcPort->sock, SD_SEND);
+		/* If lingering is enabled, socket_linger() already called shutdown() */
+		if (client_connection_linger_timeout == 0)
+			shutdown(MyProcPort->sock, SD_SEND);
 		closesocket(MyProcPort->sock);
 #endif
 
@@ -416,6 +425,70 @@ socket_close(int code, Datum arg)
 	}
 }
 
+/*
+ * Send a FIN, then read and discard client data until the client closes its
+ * side too or client_connection_linger_timeout expires.
+ *
+ * Data arriving after we've closed the socket makes our OS answer with an
+ * RST, and some client OSes (notably Windows) then discard data the client
+ * hasn't read yet, such as our final error message.  This happens on any
+ * server OS, which is why this isn't Windows-specific.
+ *
+ * This runs very late during process exit, so use plain select() and recv().
+ */
+static void
+socket_linger(pgsocket sock)
+{
+	TimestampTz deadline;
+	char		buf[1024];
+
+#ifdef WIN32
+	shutdown(sock, SD_SEND);
+#else
+	shutdown(sock, SHUT_WR);
+#endif
+
+	deadline = TimestampTzPlusMilliseconds(GetCurrentTimestamp(),
+										   client_connection_linger_timeout);
+	for (;;)
+	{
+		long		timeout_ms;
+		fd_set		rfds;
+		struct timeval tv;
+		int			rc;
+		ssize_t		nread;
+
+		timeout_ms = TimestampDifferenceMilliseconds(GetCurrentTimestamp(),
+													 deadline);
+		if (timeout_ms <= 0)
+			break;
+
+		FD_ZERO(&rfds);
+		FD_SET(sock, &rfds);
+		tv.tv_sec = timeout_ms / 1000;
+		tv.tv_usec = (timeout_ms % 1000) * 1000;
+		rc = select((int) sock + 1, &rfds, NULL, NULL, &tv);
+		if (rc < 0)
+		{
+			if (errno == EINTR)
+				continue;
+			break;
+		}
+		if (rc == 0)
+			break;
+
+		nread = recv(sock, buf, sizeof(buf), 0);
+		if (nread == 0)
+			break;				/* client closed its side as well */
+		if (nread < 0)
+		{
+			if (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)
+				continue;
+			break;
+		}
+	}
+}
+
 
 
 /* --------------------------------
diff --git a/src/backend/utils/misc/guc_parameters.dat b/src/backend/utils/misc/guc_parameters.dat
index 8a8f1cca097..e3a3a721a38 100644
--- a/src/backend/utils/misc/guc_parameters.dat
+++ b/src/backend/utils/misc/guc_parameters.dat
@@ -449,6 +449,16 @@
   check_hook => 'check_client_connection_check_interval',
 },
 
+{ name => 'client_connection_linger_timeout', type => 'int', context => 'PGC_SIGHUP', group => 'CONN_AUTH_TCP',
+  short_desc => 'Sets how long to keep reading from the client after closing the connection.',
+  long_desc => 'This avoids the client losing the final error message, if it sends data while the connection is being closed. 0 disables lingering.',
+  flags => 'GUC_UNIT_MS',
+  variable => 'client_connection_linger_timeout',
+  boot_val => '0',
+  min => '0',
+  max => 'INT_MAX',
+},
+
 { name => 'client_encoding', type => 'string', context => 'PGC_USERSET', group => 'CLIENT_CONN_LOCALE',
   short_desc => 'Sets the client\'s character set encoding.',
   flags => 'GUC_IS_NAME | GUC_REPORT',
diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample
index b492b3af06c..336654fb821 100644
--- a/src/backend/utils/misc/postgresql.conf.sample
+++ b/src/backend/utils/misc/postgresql.conf.sample
@@ -92,6 +92,9 @@
 #client_connection_check_interval = 0   # time between checks for client
                                         # disconnection while running queries;
                                         # 0 for never
+#client_connection_linger_timeout = 0   # time to keep reading from the client
+                                        # after closing the connection;
+                                        # 0 to not linger
 
 # - Authentication -
 
diff --git a/src/include/libpq/libpq.h b/src/include/libpq/libpq.h
index d15073a0a93..96124100b5d 100644
--- a/src/include/libpq/libpq.h
+++ b/src/include/libpq/libpq.h
@@ -62,6 +62,7 @@ extern const PGDLLIMPORT PQcommMethods *PqCommMethods;
  * prototypes for functions in pqcomm.c
  */
 extern PGDLLIMPORT WaitEventSet *FeBeWaitSet;
+extern PGDLLIMPORT int client_connection_linger_timeout;
 
 #define FeBeWaitSetSocketPos 0
 #define FeBeWaitSetLatchPos 1
-- 
2.56.1

