From 7a386256b6e80520637583268b9e9fef5fe0f743 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ond=C5=99ej=20Sur=C3=BD?= <ondrej@isc.org>
Date: Thu, 10 Mar 2022 13:58:58 +0100
Subject: [PATCH] On shutdown, reset the established TCP connections

Previously, the established TCP connections (both client and server)
would be gracefully closed waiting for the write timeout.

Don't wait for TCP connections to gracefully shutdown, but directly
reset them for faster shutdown.

(cherry picked from commit 6ddac2d56de980717aaba7fc0ad73af0f3890399)
Conflict: NA
Reference: https://gitlab.isc.org/isc-projects/bind9/-/commit/7a386256b6e80520637583268b9e9fef5fe0f743
---
 lib/isc/netmgr/netmgr.c | 27 +++++++++++++++++++++++----
 1 file changed, 23 insertions(+), 4 deletions(-)

diff --git a/lib/isc/netmgr/netmgr.c b/lib/isc/netmgr/netmgr.c
index 41e4bce616..24947a562a 100644
--- a/lib/isc/netmgr/netmgr.c
+++ b/lib/isc/netmgr/netmgr.c
@@ -2686,6 +2686,7 @@ reset_shutdown(uv_handle_t *handle) {
 	isc_nmsocket_t *sock = uv_handle_get_data(handle);
 
 	isc__nmsocket_shutdown(sock);
+	isc__nmsocket_detach(&sock);
 }
 
 void
@@ -2706,14 +2707,19 @@ isc__nmsocket_reset(isc_nmsocket_t *sock) {
 		break;
 	}
 
-	if (!uv_is_closing(&sock->uv_handle.handle)) {
+	if (!uv_is_closing(&sock->uv_handle.handle) &&
+	    uv_is_active(&sock->uv_handle.handle))
+	{
 		/*
 		 * The real shutdown will be handled in the respective
 		 * close functions.
 		 */
+		isc__nmsocket_attach(sock, &(isc_nmsocket_t *){ NULL });
 		int r = uv_tcp_close_reset(&sock->uv_handle.tcp,
 					   reset_shutdown);
 		UV_RUNTIME_CHECK(uv_tcp_close_reset, r);
+	} else {
+		isc__nmsocket_shutdown(sock);
 	}
 }
 
@@ -2751,13 +2757,26 @@ shutdown_walk_cb(uv_handle_t *handle, void *arg) {
 
 	switch (handle->type) {
 	case UV_UDP:
+		isc__nmsocket_shutdown(sock);
+		return;
 	case UV_TCP:
-		break;
+		switch (sock->type) {
+		case isc_nm_tcpsocket:
+		case isc_nm_tcpdnssocket:
+			if (sock->parent == NULL) {
+				/* Reset the TCP connections on shutdown */
+				isc__nmsocket_reset(sock);
+				return;
+			}
+			/* FALLTHROUGH */
+		default:
+			isc__nmsocket_shutdown(sock);
+		}
+
+		return;
 	default:
 		return;
 	}
-
-	isc__nmsocket_shutdown(sock);
 }
 
 void
-- 
2.23.0

