From ac5952aee8a6dbe38717b637d8476a625d25d91a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ond=C5=99ej=20Sur=C3=BD?= <ondrej@isc.org>
Date: Mon, 28 Feb 2022 10:25:06 +0100
Subject: [PATCH] Handle TCP sockets in isc__nmsocket_reset()

The isc__nmsocket_reset() was missing a case for raw TCP sockets (used
by RNDC and DoH) which would case a assertion failure when write timeout
would be triggered.

TCP sockets are now also properly handled in isc__nmsocket_reset().

(cherry picked from commit b220fb32bdb3c70f80b95d3611807deceab2bd55)
Conflict: NA
Reference: https://gitlab.isc.org/isc-projects/bind9/-/commit/ac5952aee8a6dbe38717b637d8476a625d25d91a
---
 lib/isc/netmgr/netmgr.c | 38 +++++++++++++++++++++++++++++++++-----
 1 file changed, 33 insertions(+), 5 deletions(-)

diff --git a/lib/isc/netmgr/netmgr.c b/lib/isc/netmgr/netmgr.c
index 4829af52f9..b82ae64382 100644
--- a/lib/isc/netmgr/netmgr.c
+++ b/lib/isc/netmgr/netmgr.c
@@ -218,6 +218,9 @@ isc__nm_work_cb(uv_work_t *req);
 static void
 isc__nm_after_work_cb(uv_work_t *req, int status);
 
+void
+isc__nmsocket_reset(isc_nmsocket_t *sock);
+
 /*%<
  * Issue a 'handle closed' callback on the socket.
  */
@@ -1942,11 +1945,7 @@ isc__nmsocket_writetimeout_cb(uv_timer_t *timer) {
 	int r = uv_timer_stop(&sock->write_timer);
 	UV_RUNTIME_CHECK(uv_timer_stop, r);
 
-	/* The shutdown will be handled in the respective close functions */
-	r = uv_tcp_close_reset(&sock->uv_handle.tcp, NULL);
-	UV_RUNTIME_CHECK(uv_tcp_close_reset, r);
-
-	isc__nmsocket_shutdown(sock);
+	isc__nmsocket_reset(sock);
 }
 
 void
@@ -2674,6 +2673,35 @@ isc__nm_async_detach(isc__networker_t *worker, isc__netievent_t *ev0) {
 	nmhandle_detach_cb(&ievent->handle FLARG_PASS);
 }
 
+void
+isc__nmsocket_reset(isc_nmsocket_t *sock) {
+	REQUIRE(VALID_NMSOCK(sock));
+
+	switch (sock->type) {
+	case isc_nm_tcpsocket:
+	case isc_nm_tcpdnssocket:
+		/*
+		 * This can be called from the TCP write timeout.
+		 */
+		REQUIRE(sock->parent == NULL);
+		break;
+	default:
+		INSIST(0);
+		ISC_UNREACHABLE();
+		break;
+	}
+
+	if (!uv_is_closing(&sock->uv_handle.handle)) {
+		/*
+		 * The real shutdown will be handled in the respective
+		 * close functions.
+		 */
+		int r = uv_tcp_close_reset(&sock->uv_handle.tcp, NULL);
+		UV_RUNTIME_CHECK(uv_tcp_close_reset, r);
+	}
+	isc__nmsocket_shutdown(sock);
+}
+
 void
 isc__nmsocket_shutdown(isc_nmsocket_t *sock) {
 	REQUIRE(VALID_NMSOCK(sock));
-- 
2.23.0

