8fa458
From b2929ff50a7676563177bc52a372ddcae48cb002 Mon Sep 17 00:00:00 2001
8fa458
From: Petr Mensik <pemensik@redhat.com>
8fa458
Date: Wed, 24 Apr 2019 20:09:07 +0200
8fa458
Subject: [PATCH] 5200.   [security]      tcp-clients settings could be
8fa458
 exceeded in some cases,                         which could lead to
8fa458
 exhaustion of file descriptors.                         (CVE-2018-5743) [GL
8fa458
 #615]
8fa458
8fa458
---
8fa458
 bin/named/client.c                     | 421 +++++++++++++++++++------
8fa458
 bin/named/include/named/client.h       |  13 +-
8fa458
 bin/named/include/named/interfacemgr.h |  13 +-
8fa458
 bin/named/interfacemgr.c               |   9 +-
8fa458
 lib/isc/include/isc/quota.h            |   7 +
8fa458
 lib/isc/quota.c                        |  33 +-
8fa458
 6 files changed, 385 insertions(+), 111 deletions(-)
8fa458
8fa458
diff --git a/bin/named/client.c b/bin/named/client.c
8fa458
index b7d8a98..e1acaf1 100644
8fa458
--- a/bin/named/client.c
8fa458
+++ b/bin/named/client.c
8fa458
@@ -243,7 +243,7 @@ static void ns_client_dumpmessage(ns_client_t *client, const char *reason);
8fa458
 static isc_result_t get_client(ns_clientmgr_t *manager, ns_interface_t *ifp,
8fa458
 			       dns_dispatch_t *disp, isc_boolean_t tcp);
8fa458
 static isc_result_t get_worker(ns_clientmgr_t *manager, ns_interface_t *ifp,
8fa458
-			       isc_socket_t *sock);
8fa458
+			       isc_socket_t *sock, ns_client_t *oldclient);
8fa458
 static inline isc_boolean_t
8fa458
 allowed(isc_netaddr_t *addr, dns_name_t *signer, isc_netaddr_t *ecs_addr,
8fa458
 	isc_uint8_t ecs_addrlen, isc_uint8_t *ecs_scope, dns_acl_t *acl);
8fa458
@@ -295,6 +295,119 @@ ns_client_settimeout(ns_client_t *client, unsigned int seconds) {
8fa458
 	}
8fa458
 }
8fa458
 
8fa458
+/*%
8fa458
+ * Allocate a reference-counted object that will maintain a single pointer to
8fa458
+ * the (also reference-counted) TCP client quota, shared between all the
8fa458
+ * clients processing queries on a single TCP connection, so that all
8fa458
+ * clients sharing the one socket will together consume only one slot in
8fa458
+ * the 'tcp-clients' quota.
8fa458
+ */
8fa458
+static isc_result_t
8fa458
+tcpconn_init(ns_client_t *client, isc_boolean_t force) {
8fa458
+	isc_result_t result;
8fa458
+	isc_quota_t *quota = NULL;
8fa458
+	ns_tcpconn_t *tconn = NULL;
8fa458
+
8fa458
+	REQUIRE(client->tcpconn == NULL);
8fa458
+
8fa458
+	/*
8fa458
+	 * Try to attach to the quota first, so we won't pointlessly
8fa458
+	 * allocate memory for a tcpconn object if we can't get one.
8fa458
+	 */
8fa458
+	if (force) {
8fa458
+		result = isc_quota_force(&ns_g_server->tcpquota, "a;;
8fa458
+	} else {
8fa458
+		result = isc_quota_attach(&ns_g_server->tcpquota, "a;;
8fa458
+	}
8fa458
+	if (result != ISC_R_SUCCESS) {
8fa458
+		return (result);
8fa458
+	}
8fa458
+
8fa458
+	/*
8fa458
+	 * A global memory context is used for the allocation as different
8fa458
+	 * client structures may have different memory contexts assigned and a
8fa458
+	 * reference counter allocated here might need to be freed by a
8fa458
+	 * different client.  The performance impact caused by memory context
8fa458
+	 * contention here is expected to be negligible, given that this code
8fa458
+	 * is only executed for TCP connections.
8fa458
+	 */
8fa458
+	tconn = isc_mem_allocate(ns_g_mctx, sizeof(*tconn));
8fa458
+
8fa458
+	isc_refcount_init(&tconn->refs, 1);
8fa458
+	tconn->tcpquota = quota;
8fa458
+	quota = NULL;
8fa458
+	tconn->pipelined = ISC_FALSE;
8fa458
+
8fa458
+	client->tcpconn = tconn;
8fa458
+
8fa458
+	return (ISC_R_SUCCESS);
8fa458
+}
8fa458
+
8fa458
+/*%
8fa458
+ * Increase the count of client structures sharing the TCP connection
8fa458
+ * that 'source' is associated with; add a pointer to the same tcpconn
8fa458
+ * to 'target', thus associating it with the same TCP connection.
8fa458
+ */
8fa458
+static void
8fa458
+tcpconn_attach(ns_client_t *source, ns_client_t *target) {
8fa458
+	int refs;
8fa458
+
8fa458
+	REQUIRE(source->tcpconn != NULL);
8fa458
+	REQUIRE(target->tcpconn == NULL);
8fa458
+	REQUIRE(source->tcpconn->pipelined);
8fa458
+
8fa458
+	isc_refcount_increment(&source->tcpconn->refs, &refs);
8fa458
+	INSIST(refs > 1);
8fa458
+	target->tcpconn = source->tcpconn;
8fa458
+}
8fa458
+
8fa458
+/*%
8fa458
+ * Decrease the count of client structures sharing the TCP connection that
8fa458
+ * 'client' is associated with.  If this is the last client using this TCP
8fa458
+ * connection, we detach from the TCP quota and free the tcpconn
8fa458
+ * object. Either way, client->tcpconn is set to NULL.
8fa458
+ */
8fa458
+static void
8fa458
+tcpconn_detach(ns_client_t *client) {
8fa458
+	ns_tcpconn_t *tconn = NULL;
8fa458
+	int refs;
8fa458
+
8fa458
+	REQUIRE(client->tcpconn != NULL);
8fa458
+
8fa458
+	tconn = client->tcpconn;
8fa458
+	client->tcpconn = NULL;
8fa458
+
8fa458
+	isc_refcount_decrement(&tconn->refs, &refs);
8fa458
+	if (refs == 0) {
8fa458
+		isc_quota_detach(&tconn->tcpquota);
8fa458
+		isc_mem_free(ns_g_mctx, tconn);
8fa458
+	}
8fa458
+}
8fa458
+
8fa458
+/*%
8fa458
+ * Mark a client as active and increment the interface's 'ntcpactive'
8fa458
+ * counter, as a signal that there is at least one client servicing
8fa458
+ * TCP queries for the interface. If we reach the TCP client quota at
8fa458
+ * some point, this will be used to determine whether a quota overrun
8fa458
+ * should be permitted.
8fa458
+ *
8fa458
+ * Marking the client active with the 'tcpactive' flag ensures proper
8fa458
+ * accounting, by preventing us from incrementing or decrementing
8fa458
+ * 'ntcpactive' more than once per client.
8fa458
+ */
8fa458
+static void
8fa458
+mark_tcp_active(ns_client_t *client, isc_boolean_t active) {
8fa458
+	if (active && !client->tcpactive) {
8fa458
+		isc_atomic_xadd(&client->interface->ntcpactive, 1);
8fa458
+		client->tcpactive = active;
8fa458
+	} else if (!active && client->tcpactive) {
8fa458
+		uint32_t old =
8fa458
+			isc_atomic_xadd(&client->interface->ntcpactive, -1);
8fa458
+		INSIST(old > 0);
8fa458
+		client->tcpactive = active;
8fa458
+	}
8fa458
+}
8fa458
+
8fa458
 /*%
8fa458
  * Check for a deactivation or shutdown request and take appropriate
8fa458
  * action.  Returns ISC_TRUE if either is in progress; in this case
8fa458
@@ -384,7 +497,8 @@ exit_check(ns_client_t *client) {
8fa458
 		INSIST(client->recursionquota == NULL);
8fa458
 
8fa458
 		if (NS_CLIENTSTATE_READING == client->newstate) {
8fa458
-			if (!client->pipelined) {
8fa458
+			INSIST(client->tcpconn != NULL);
8fa458
+			if (!client->tcpconn->pipelined) {
8fa458
 				client_read(client);
8fa458
 				client->newstate = NS_CLIENTSTATE_MAX;
8fa458
 				return (ISC_TRUE); /* We're done. */
8fa458
@@ -402,10 +516,13 @@ exit_check(ns_client_t *client) {
8fa458
 		 */
8fa458
 		INSIST(client->recursionquota == NULL);
8fa458
 		INSIST(client->newstate <= NS_CLIENTSTATE_READY);
8fa458
-		if (client->nreads > 0)
8fa458
+
8fa458
+		if (client->nreads > 0) {
8fa458
 			dns_tcpmsg_cancelread(&client->tcpmsg);
8fa458
-		if (client->nreads != 0) {
8fa458
-			/* Still waiting for read cancel completion. */
8fa458
+		}
8fa458
+
8fa458
+		/* Still waiting for read cancel completion. */
8fa458
+		if (client->nreads > 0) {
8fa458
 			return (ISC_TRUE);
8fa458
 		}
8fa458
 
8fa458
@@ -413,14 +530,49 @@ exit_check(ns_client_t *client) {
8fa458
 			dns_tcpmsg_invalidate(&client->tcpmsg);
8fa458
 			client->tcpmsg_valid = ISC_FALSE;
8fa458
 		}
8fa458
+
8fa458
+		/*
8fa458
+		 * Soon the client will be ready to accept a new TCP
8fa458
+		 * connection or UDP request, but we may have enough
8fa458
+		 * clients doing that already.  Check whether this client
8fa458
+		 * needs to remain active and allow it go inactive if
8fa458
+		 * not.
8fa458
+		 *
8fa458
+		 * UDP clients always go inactive at this point, but a TCP
8fa458
+		 * client may need to stay active and return to READY
8fa458
+		 * state if no other clients are available to listen
8fa458
+		 * for TCP requests on this interface.
8fa458
+		 *
8fa458
+		 * Regardless, if we're going to FREED state, that means
8fa458
+		 * the system is shutting down and we don't need to
8fa458
+		 * retain clients.
8fa458
+		 */
8fa458
+		if (client->mortal && TCP_CLIENT(client) &&
8fa458
+		    client->newstate != NS_CLIENTSTATE_FREED &&
8fa458
+		    !ns_g_clienttest &&
8fa458
+		    isc_atomic_xadd(&client->interface->ntcpaccepting, 0) == 0)
8fa458
+		{
8fa458
+			/* Nobody else is accepting */
8fa458
+			client->mortal = ISC_FALSE;
8fa458
+			client->newstate = NS_CLIENTSTATE_READY;
8fa458
+		}
8fa458
+
8fa458
+		/*
8fa458
+		 * Detach from TCP connection and TCP client quota,
8fa458
+		 * if appropriate. If this is the last reference to
8fa458
+		 * the TCP connection in our pipeline group, the
8fa458
+		 * TCP quota slot will be released.
8fa458
+		 */
8fa458
+		if (client->tcpconn) {
8fa458
+			tcpconn_detach(client);
8fa458
+		}
8fa458
+
8fa458
 		if (client->tcpsocket != NULL) {
8fa458
 			CTRACE("closetcp");
8fa458
 			isc_socket_detach(&client->tcpsocket);
8fa458
+			mark_tcp_active(client, ISC_FALSE);
8fa458
 		}
8fa458
 
8fa458
-		if (client->tcpquota != NULL)
8fa458
-			isc_quota_detach(&client->tcpquota);
8fa458
-
8fa458
 		if (client->timerset) {
8fa458
 			(void)isc_timer_reset(client->timer,
8fa458
 					      isc_timertype_inactive,
8fa458
@@ -428,45 +580,26 @@ exit_check(ns_client_t *client) {
8fa458
 			client->timerset = ISC_FALSE;
8fa458
 		}
8fa458
 
8fa458
-		client->pipelined = ISC_FALSE;
8fa458
-
8fa458
 		client->peeraddr_valid = ISC_FALSE;
8fa458
 
8fa458
 		client->state = NS_CLIENTSTATE_READY;
8fa458
-		INSIST(client->recursionquota == NULL);
8fa458
-
8fa458
-		/*
8fa458
-		 * Now the client is ready to accept a new TCP connection
8fa458
-		 * or UDP request, but we may have enough clients doing
8fa458
-		 * that already.  Check whether this client needs to remain
8fa458
-		 * active and force it to go inactive if not.
8fa458
-		 *
8fa458
-		 * UDP clients go inactive at this point, but TCP clients
8fa458
-		 * may remain active if we have fewer active TCP client
8fa458
-		 * objects than desired due to an earlier quota exhaustion.
8fa458
-		 */
8fa458
-		if (client->mortal && TCP_CLIENT(client) && !ns_g_clienttest) {
8fa458
-			LOCK(&client->interface->lock);
8fa458
-			if (client->interface->ntcpcurrent <
8fa458
-				    client->interface->ntcptarget)
8fa458
-				client->mortal = ISC_FALSE;
8fa458
-			UNLOCK(&client->interface->lock);
8fa458
-		}
8fa458
 
8fa458
 		/*
8fa458
 		 * We don't need the client; send it to the inactive
8fa458
 		 * queue for recycling.
8fa458
 		 */
8fa458
 		if (client->mortal) {
8fa458
-			if (client->newstate > NS_CLIENTSTATE_INACTIVE)
8fa458
+			if (client->newstate > NS_CLIENTSTATE_INACTIVE) {
8fa458
 				client->newstate = NS_CLIENTSTATE_INACTIVE;
8fa458
+			}
8fa458
 		}
8fa458
 
8fa458
 		if (NS_CLIENTSTATE_READY == client->newstate) {
8fa458
 			if (TCP_CLIENT(client)) {
8fa458
 				client_accept(client);
8fa458
-			} else
8fa458
+			} else {
8fa458
 				client_udprecv(client);
8fa458
+			}
8fa458
 			client->newstate = NS_CLIENTSTATE_MAX;
8fa458
 			return (ISC_TRUE);
8fa458
 		}
8fa458
@@ -478,41 +611,51 @@ exit_check(ns_client_t *client) {
8fa458
 		/*
8fa458
 		 * We are trying to enter the inactive state.
8fa458
 		 */
8fa458
-		if (client->naccepts > 0)
8fa458
+		if (client->naccepts > 0) {
8fa458
 			isc_socket_cancel(client->tcplistener, client->task,
8fa458
 					  ISC_SOCKCANCEL_ACCEPT);
8fa458
+		}
8fa458
 
8fa458
 		/* Still waiting for accept cancel completion. */
8fa458
-		if (! (client->naccepts == 0))
8fa458
+		if (client->naccepts > 0) {
8fa458
 			return (ISC_TRUE);
8fa458
+		}
8fa458
 
8fa458
 		/* Accept cancel is complete. */
8fa458
-		if (client->nrecvs > 0)
8fa458
+		if (client->nrecvs > 0) {
8fa458
 			isc_socket_cancel(client->udpsocket, client->task,
8fa458
 					  ISC_SOCKCANCEL_RECV);
8fa458
+		}
8fa458
 
8fa458
 		/* Still waiting for recv cancel completion. */
8fa458
-		if (! (client->nrecvs == 0))
8fa458
+		if (client->nrecvs > 0) {
8fa458
 			return (ISC_TRUE);
8fa458
+		}
8fa458
 
8fa458
 		/* Still waiting for control event to be delivered */
8fa458
-		if (client->nctls > 0)
8fa458
+		if (client->nctls > 0) {
8fa458
 			return (ISC_TRUE);
8fa458
-
8fa458
-		/* Deactivate the client. */
8fa458
-		if (client->interface)
8fa458
-			ns_interface_detach(&client->interface);
8fa458
+		}
8fa458
 
8fa458
 		INSIST(client->naccepts == 0);
8fa458
 		INSIST(client->recursionquota == NULL);
8fa458
-		if (client->tcplistener != NULL)
8fa458
+		if (client->tcplistener != NULL) {
8fa458
 			isc_socket_detach(&client->tcplistener);
8fa458
+			mark_tcp_active(client, ISC_FALSE);
8fa458
+		}
8fa458
 
8fa458
-		if (client->udpsocket != NULL)
8fa458
+		if (client->udpsocket != NULL) {
8fa458
 			isc_socket_detach(&client->udpsocket);
8fa458
+		}
8fa458
 
8fa458
-		if (client->dispatch != NULL)
8fa458
+		/* Deactivate the client. */
8fa458
+		if (client->interface != NULL) {
8fa458
+			ns_interface_detach(&client->interface);
8fa458
+		}
8fa458
+
8fa458
+		if (client->dispatch != NULL) {
8fa458
 			dns_dispatch_detach(&client->dispatch);
8fa458
+		}
8fa458
 
8fa458
 		client->attributes = 0;
8fa458
 		client->mortal = ISC_FALSE;
8fa458
@@ -537,10 +680,13 @@ exit_check(ns_client_t *client) {
8fa458
 			client->newstate = NS_CLIENTSTATE_MAX;
8fa458
 			if (!ns_g_clienttest && manager != NULL &&
8fa458
 			    !manager->exiting)
8fa458
+			{
8fa458
 				ISC_QUEUE_PUSH(manager->inactive, client,
8fa458
 					       ilink);
8fa458
-			if (client->needshutdown)
8fa458
+			}
8fa458
+			if (client->needshutdown) {
8fa458
 				isc_task_shutdown(client->task);
8fa458
+			}
8fa458
 			return (ISC_TRUE);
8fa458
 		}
8fa458
 	}
8fa458
@@ -650,7 +796,7 @@ client_start(isc_task_t *task, isc_event_t *event) {
8fa458
 		return;
8fa458
 
8fa458
 	if (TCP_CLIENT(client)) {
8fa458
-		if (client->pipelined) {
8fa458
+		if (client->tcpconn != NULL) {
8fa458
 			client_read(client);
8fa458
 		} else {
8fa458
 			client_accept(client);
8fa458
@@ -660,7 +806,6 @@ client_start(isc_task_t *task, isc_event_t *event) {
8fa458
 	}
8fa458
 }
8fa458
 
8fa458
-
8fa458
 /*%
8fa458
  * The client's task has received a shutdown event.
8fa458
  */
8fa458
@@ -2301,6 +2446,7 @@ client_request(isc_task_t *task, isc_event_t *event) {
8fa458
 		client->nrecvs--;
8fa458
 	} else {
8fa458
 		INSIST(TCP_CLIENT(client));
8fa458
+		INSIST(client->tcpconn != NULL);
8fa458
 		REQUIRE(event->ev_type == DNS_EVENT_TCPMSG);
8fa458
 		REQUIRE(event->ev_sender == &client->tcpmsg);
8fa458
 		buffer = &client->tcpmsg.buffer;
8fa458
@@ -2484,18 +2630,27 @@ client_request(isc_task_t *task, isc_event_t *event) {
8fa458
 	/*
8fa458
 	 * Pipeline TCP query processing.
8fa458
 	 */
8fa458
-	if (client->message->opcode != dns_opcode_query)
8fa458
-		client->pipelined = ISC_FALSE;
8fa458
-	if (TCP_CLIENT(client) && client->pipelined) {
8fa458
-		result = isc_quota_reserve(&ns_g_server->tcpquota);
8fa458
-		if (result == ISC_R_SUCCESS)
8fa458
-			result = ns_client_replace(client);
8fa458
+	if (TCP_CLIENT(client) &&
8fa458
+	    client->message->opcode != dns_opcode_query)
8fa458
+	{
8fa458
+		client->tcpconn->pipelined = ISC_FALSE;
8fa458
+	}
8fa458
+	if (TCP_CLIENT(client) && client->tcpconn->pipelined) {
8fa458
+		/*
8fa458
+		 * We're pipelining. Replace the client; the
8fa458
+		 * replacement can read the TCP socket looking
8fa458
+		 * for new messages and this one can process the
8fa458
+		 * current message asynchronously.
8fa458
+		 *
8fa458
+		 * There will now be at least three clients using this
8fa458
+		 * TCP socket - one accepting new connections,
8fa458
+		 * one reading an existing connection to get new
8fa458
+		 * messages, and one answering the message already
8fa458
+		 * received.
8fa458
+		 */
8fa458
+		result = ns_client_replace(client);
8fa458
 		if (result != ISC_R_SUCCESS) {
8fa458
-			ns_client_log(client, NS_LOGCATEGORY_CLIENT,
8fa458
-				      NS_LOGMODULE_CLIENT, ISC_LOG_WARNING,
8fa458
-				      "no more TCP clients(read): %s",
8fa458
-				      isc_result_totext(result));
8fa458
-			client->pipelined = ISC_FALSE;
8fa458
+			client->tcpconn->pipelined = ISC_FALSE;
8fa458
 		}
8fa458
 	}
8fa458
 
8fa458
@@ -3051,8 +3206,7 @@ client_create(ns_clientmgr_t *manager, ns_client_t **clientp) {
8fa458
 	client->signer = NULL;
8fa458
 	dns_name_init(&client->signername, NULL);
8fa458
 	client->mortal = ISC_FALSE;
8fa458
-	client->pipelined = ISC_FALSE;
8fa458
-	client->tcpquota = NULL;
8fa458
+	client->tcpconn = NULL;
8fa458
 	client->recursionquota = NULL;
8fa458
 	client->interface = NULL;
8fa458
 	client->peeraddr_valid = ISC_FALSE;
8fa458
@@ -3062,6 +3216,7 @@ client_create(ns_clientmgr_t *manager, ns_client_t **clientp) {
8fa458
 	client->filter_aaaa = dns_aaaa_ok;
8fa458
 #endif
8fa458
 	client->needshutdown = ns_g_clienttest;
8fa458
+	client->tcpactive = ISC_FALSE;
8fa458
 
8fa458
 	ISC_EVENT_INIT(&client->ctlevent, sizeof(client->ctlevent), 0, NULL,
8fa458
 		       NS_EVENT_CLIENTCONTROL, client_start, client, client,
8fa458
@@ -3156,9 +3311,10 @@ client_read(ns_client_t *client) {
8fa458
 
8fa458
 static void
8fa458
 client_newconn(isc_task_t *task, isc_event_t *event) {
8fa458
+	isc_result_t result;
8fa458
 	ns_client_t *client = event->ev_arg;
8fa458
 	isc_socket_newconnev_t *nevent = (isc_socket_newconnev_t *)event;
8fa458
-	isc_result_t result;
8fa458
+	uint32_t old;
8fa458
 
8fa458
 	REQUIRE(event->ev_type == ISC_SOCKEVENT_NEWCONN);
8fa458
 	REQUIRE(NS_CLIENT_VALID(client));
8fa458
@@ -3168,13 +3324,18 @@ client_newconn(isc_task_t *task, isc_event_t *event) {
8fa458
 
8fa458
 	INSIST(client->state == NS_CLIENTSTATE_READY);
8fa458
 
8fa458
+	/*
8fa458
+	 * The accept() was successful and we're now establishing a new
8fa458
+	 * connection. We need to make note of it in the client and
8fa458
+	 * interface objects so client objects can do the right thing
8fa458
+	 * when going inactive in exit_check() (see comments in
8fa458
+	 * client_accept() for details).
8fa458
+	 */
8fa458
 	INSIST(client->naccepts == 1);
8fa458
 	client->naccepts--;
8fa458
 
8fa458
-	LOCK(&client->interface->lock);
8fa458
-	INSIST(client->interface->ntcpcurrent > 0);
8fa458
-	client->interface->ntcpcurrent--;
8fa458
-	UNLOCK(&client->interface->lock);
8fa458
+	old = isc_atomic_xadd(&client->interface->ntcpaccepting, -1);
8fa458
+	INSIST(old > 0);
8fa458
 
8fa458
 	/*
8fa458
 	 * We must take ownership of the new socket before the exit
8fa458
@@ -3207,6 +3368,7 @@ client_newconn(isc_task_t *task, isc_event_t *event) {
8fa458
 			      NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(3),
8fa458
 			      "accept failed: %s",
8fa458
 			      isc_result_totext(nevent->result));
8fa458
+		tcpconn_detach(client);
8fa458
 	}
8fa458
 
8fa458
 	if (exit_check(client))
8fa458
@@ -3244,20 +3406,13 @@ client_newconn(isc_task_t *task, isc_event_t *event) {
8fa458
 		 * telnetting to port 53 (once per CPU) will
8fa458
 		 * deny service to legitimate TCP clients.
8fa458
 		 */
8fa458
-		client->pipelined = ISC_FALSE;
8fa458
-		result = isc_quota_attach(&ns_g_server->tcpquota,
8fa458
-					  &client->tcpquota);
8fa458
-		if (result == ISC_R_SUCCESS)
8fa458
-			result = ns_client_replace(client);
8fa458
-		if (result != ISC_R_SUCCESS) {
8fa458
-			ns_client_log(client, NS_LOGCATEGORY_CLIENT,
8fa458
-				      NS_LOGMODULE_CLIENT, ISC_LOG_WARNING,
8fa458
-				      "no more TCP clients(accept): %s",
8fa458
-				      isc_result_totext(result));
8fa458
-		} else if (ns_g_server->keepresporder == NULL ||
8fa458
-			   !allowed(&netaddr, NULL, NULL, 0, NULL,
8fa458
-				    ns_g_server->keepresporder)) {
8fa458
-			client->pipelined = ISC_TRUE;
8fa458
+		result = ns_client_replace(client);
8fa458
+		if (result == ISC_R_SUCCESS &&
8fa458
+		    (ns_g_server->keepresporder == NULL ||
8fa458
+		     !allowed(&netaddr, NULL, NULL, 0, NULL,
8fa458
+			      ns_g_server->keepresporder)))
8fa458
+		{
8fa458
+			client->tcpconn->pipelined = ISC_TRUE;
8fa458
 		}
8fa458
 
8fa458
 		client_read(client);
8fa458
@@ -3273,12 +3428,66 @@ client_accept(ns_client_t *client) {
8fa458
 
8fa458
 	CTRACE("accept");
8fa458
 
8fa458
+	/*
8fa458
+	 * Set up a new TCP connection. This means try to attach to the
8fa458
+	 * TCP client quota (tcp-clients), but fail if we're over quota.
8fa458
+	 */
8fa458
+	result = tcpconn_init(client, ISC_FALSE);
8fa458
+	if (result != ISC_R_SUCCESS) {
8fa458
+		isc_boolean_t exit;
8fa458
+
8fa458
+		ns_client_log(client, NS_LOGCATEGORY_CLIENT,
8fa458
+			      NS_LOGMODULE_CLIENT, ISC_LOG_WARNING,
8fa458
+			      "TCP client quota reached: %s",
8fa458
+			      isc_result_totext(result));
8fa458
+
8fa458
+		/*
8fa458
+		 * We have exceeded the system-wide TCP client quota.  But,
8fa458
+		 * we can't just block this accept in all cases, because if
8fa458
+		 * we did, a heavy TCP load on other interfaces might cause
8fa458
+		 * this interface to be starved, with no clients able to
8fa458
+		 * accept new connections.
8fa458
+		 *
8fa458
+		 * So, we check here to see if any other clients are
8fa458
+		 * already servicing TCP queries on this interface (whether
8fa458
+		 * accepting, reading, or processing). If we find that at
8fa458
+		 * least one client other than this one is active, then
8fa458
+		 * it's okay *not* to call accept - we can let this
8fa458
+		 * client go inactive and another will take over when it's
8fa458
+		 * done.
8fa458
+		 *
8fa458
+		 * If there aren't enough active clients on the interface,
8fa458
+		 * then we can be a little bit flexible about the quota.
8fa458
+		 * We'll allow *one* extra client through to ensure we're
8fa458
+		 * listening on every interface; we do this by setting the
8fa458
+		 * 'force' option to tcpconn_init().
8fa458
+		 *
8fa458
+		 * (Note: In practice this means that the real TCP client
8fa458
+		 * quota is tcp-clients plus the number of listening
8fa458
+		 * interfaces plus 1.)
8fa458
+		 */
8fa458
+		exit = (isc_atomic_xadd(&client->interface->ntcpactive, 0) >
8fa458
+			(client->tcpactive ? 1 : 0));
8fa458
+		if (exit) {
8fa458
+			client->newstate = NS_CLIENTSTATE_INACTIVE;
8fa458
+			(void)exit_check(client);
8fa458
+			return;
8fa458
+		}
8fa458
+
8fa458
+		result = tcpconn_init(client, ISC_TRUE);
8fa458
+		RUNTIME_CHECK(result == ISC_R_SUCCESS);
8fa458
+	}
8fa458
+
8fa458
+	/*
8fa458
+	 * If this client was set up using get_client() or get_worker(),
8fa458
+	 * then TCP is already marked active. However, if it was restarted
8fa458
+	 * from exit_check(), it might not be, so we take care of it now.
8fa458
+	 */
8fa458
+	mark_tcp_active(client, ISC_TRUE);
8fa458
+
8fa458
 	result = isc_socket_accept(client->tcplistener, client->task,
8fa458
 				   client_newconn, client);
8fa458
 	if (result != ISC_R_SUCCESS) {
8fa458
-		UNEXPECTED_ERROR(__FILE__, __LINE__,
8fa458
-				 "isc_socket_accept() failed: %s",
8fa458
-				 isc_result_totext(result));
8fa458
 		/*
8fa458
 		 * XXXRTH  What should we do?  We're trying to accept but
8fa458
 		 *	   it didn't work.  If we just give up, then TCP
8fa458
@@ -3286,13 +3495,37 @@ client_accept(ns_client_t *client) {
8fa458
 		 *
8fa458
 		 *	   For now, we just go idle.
8fa458
 		 */
8fa458
+		UNEXPECTED_ERROR(__FILE__, __LINE__,
8fa458
+				 "isc_socket_accept() failed: %s",
8fa458
+				 isc_result_totext(result));
8fa458
+
8fa458
+		tcpconn_detach(client);
8fa458
+		mark_tcp_active(client, ISC_FALSE);
8fa458
 		return;
8fa458
 	}
8fa458
+
8fa458
+	/*
8fa458
+	 * The client's 'naccepts' counter indicates that this client has
8fa458
+	 * called accept() and is waiting for a new connection. It should
8fa458
+	 * never exceed 1.
8fa458
+	 */
8fa458
 	INSIST(client->naccepts == 0);
8fa458
 	client->naccepts++;
8fa458
-	LOCK(&client->interface->lock);
8fa458
-	client->interface->ntcpcurrent++;
8fa458
-	UNLOCK(&client->interface->lock);
8fa458
+
8fa458
+	/*
8fa458
+	 * The interface's 'ntcpaccepting' counter is incremented when
8fa458
+	 * any client calls accept(), and decremented in client_newconn()
8fa458
+	 * once the connection is established.
8fa458
+	 *
8fa458
+	 * When the client object is shutting down after handling a TCP
8fa458
+	 * request (see exit_check()), if this value is at least one, that
8fa458
+	 * means another client has called accept() and is waiting to
8fa458
+	 * establish the next connection. That means the client may be
8fa458
+	 * be free to become inactive; otherwise it may need to start
8fa458
+	 * listening for connections itself to prevent the interface
8fa458
+	 * going dead.
8fa458
+	 */
8fa458
+	isc_atomic_xadd(&client->interface->ntcpaccepting, 1);
8fa458
 }
8fa458
 
8fa458
 static void
8fa458
@@ -3363,15 +3596,17 @@ ns_client_replace(ns_client_t *client) {
8fa458
 	REQUIRE(client->manager != NULL);
8fa458
 
8fa458
 	tcp = TCP_CLIENT(client);
8fa458
-	if (tcp && client->pipelined) {
8fa458
+	if (tcp && client->tcpconn != NULL && client->tcpconn->pipelined) {
8fa458
 		result = get_worker(client->manager, client->interface,
8fa458
-				    client->tcpsocket);
8fa458
+				    client->tcpsocket, client);
8fa458
 	} else {
8fa458
 		result = get_client(client->manager, client->interface,
8fa458
 				    client->dispatch, tcp);
8fa458
+
8fa458
 	}
8fa458
-	if (result != ISC_R_SUCCESS)
8fa458
+	if (result != ISC_R_SUCCESS) {
8fa458
 		return (result);
8fa458
+	}
8fa458
 
8fa458
 	/*
8fa458
 	 * The responsibility for listening for new requests is hereby
8fa458
@@ -3557,9 +3792,12 @@ get_client(ns_clientmgr_t *manager, ns_interface_t *ifp,
8fa458
 	client->dscp = ifp->dscp;
8fa458
 
8fa458
 	if (tcp) {
8fa458
+		mark_tcp_active(client, ISC_TRUE);
8fa458
+
8fa458
 		client->attributes |= NS_CLIENTATTR_TCP;
8fa458
 		isc_socket_attach(ifp->tcpsocket,
8fa458
 				  &client->tcplistener);
8fa458
+
8fa458
 	} else {
8fa458
 		isc_socket_t *sock;
8fa458
 
8fa458
@@ -3577,7 +3815,8 @@ get_client(ns_clientmgr_t *manager, ns_interface_t *ifp,
8fa458
 }
8fa458
 
8fa458
 static isc_result_t
8fa458
-get_worker(ns_clientmgr_t *manager, ns_interface_t *ifp, isc_socket_t *sock)
8fa458
+get_worker(ns_clientmgr_t *manager, ns_interface_t *ifp, isc_socket_t *sock,
8fa458
+	   ns_client_t *oldclient)
8fa458
 {
8fa458
 	isc_result_t result = ISC_R_SUCCESS;
8fa458
 	isc_event_t *ev;
8fa458
@@ -3585,6 +3824,7 @@ get_worker(ns_clientmgr_t *manager, ns_interface_t *ifp, isc_socket_t *sock)
8fa458
 	MTRACE("get worker");
8fa458
 
8fa458
 	REQUIRE(manager != NULL);
8fa458
+	REQUIRE(oldclient != NULL);
8fa458
 
8fa458
 	if (manager->exiting)
8fa458
 		return (ISC_R_SHUTTINGDOWN);
8fa458
@@ -3617,14 +3857,15 @@ get_worker(ns_clientmgr_t *manager, ns_interface_t *ifp, isc_socket_t *sock)
8fa458
 	ns_interface_attach(ifp, &client->interface);
8fa458
 	client->newstate = client->state = NS_CLIENTSTATE_WORKING;
8fa458
 	INSIST(client->recursionquota == NULL);
8fa458
-	client->tcpquota = &ns_g_server->tcpquota;
8fa458
 
8fa458
 	client->dscp = ifp->dscp;
8fa458
 
8fa458
 	client->attributes |= NS_CLIENTATTR_TCP;
8fa458
-	client->pipelined = ISC_TRUE;
8fa458
 	client->mortal = ISC_TRUE;
8fa458
 
8fa458
+	tcpconn_attach(oldclient, client);
8fa458
+	mark_tcp_active(client, ISC_TRUE);
8fa458
+
8fa458
 	isc_socket_attach(ifp->tcpsocket, &client->tcplistener);
8fa458
 	isc_socket_attach(sock, &client->tcpsocket);
8fa458
 	isc_socket_setname(client->tcpsocket, "worker-tcp", NULL);
8fa458
diff --git a/bin/named/include/named/client.h b/bin/named/include/named/client.h
8fa458
index 262b906..0f54d22 100644
8fa458
--- a/bin/named/include/named/client.h
8fa458
+++ b/bin/named/include/named/client.h
8fa458
@@ -9,8 +9,6 @@
8fa458
  * information regarding copyright ownership.
8fa458
  */
8fa458
 
8fa458
-/* $Id: client.h,v 1.96 2012/01/31 23:47:31 tbox Exp $ */
8fa458
-
8fa458
 #ifndef NAMED_CLIENT_H
8fa458
 #define NAMED_CLIENT_H 1
8fa458
 
8fa458
@@ -77,6 +75,13 @@
8fa458
  *** Types
8fa458
  ***/
8fa458
 
8fa458
+/*% reference-counted TCP connection object */
8fa458
+typedef struct ns_tcpconn {
8fa458
+	isc_refcount_t		refs;
8fa458
+	isc_quota_t		*tcpquota;
8fa458
+	isc_boolean_t		pipelined;
8fa458
+} ns_tcpconn_t;
8fa458
+
8fa458
 /*% nameserver client structure */
8fa458
 struct ns_client {
8fa458
 	unsigned int		magic;
8fa458
@@ -91,6 +96,7 @@ struct ns_client {
8fa458
 	int			nupdates;
8fa458
 	int			nctls;
8fa458
 	int			references;
8fa458
+	isc_boolean_t		tcpactive;
8fa458
 	isc_boolean_t		needshutdown; 	/*
8fa458
 						 * Used by clienttest to get
8fa458
 						 * the client to go from
8fa458
@@ -129,8 +135,7 @@ struct ns_client {
8fa458
 	dns_name_t		signername;   /*%< [T]SIG key name */
8fa458
 	dns_name_t *		signer;	      /*%< NULL if not valid sig */
8fa458
 	isc_boolean_t		mortal;	      /*%< Die after handling request */
8fa458
-	isc_boolean_t		pipelined;   /*%< TCP queries not in sequence */
8fa458
-	isc_quota_t		*tcpquota;
8fa458
+	ns_tcpconn_t		*tcpconn;
8fa458
 	isc_quota_t		*recursionquota;
8fa458
 	ns_interface_t		*interface;
8fa458
 
8fa458
diff --git a/bin/named/include/named/interfacemgr.h b/bin/named/include/named/interfacemgr.h
8fa458
index 36870f3..d9ac90f 100644
8fa458
--- a/bin/named/include/named/interfacemgr.h
8fa458
+++ b/bin/named/include/named/interfacemgr.h
8fa458
@@ -9,8 +9,6 @@
8fa458
  * information regarding copyright ownership.
8fa458
  */
8fa458
 
8fa458
-/* $Id: interfacemgr.h,v 1.35 2011/07/28 23:47:58 tbox Exp $ */
8fa458
-
8fa458
 #ifndef NAMED_INTERFACEMGR_H
8fa458
 #define NAMED_INTERFACEMGR_H 1
8fa458
 
8fa458
@@ -75,9 +73,14 @@ struct ns_interface {
8fa458
 						/*%< UDP dispatchers. */
8fa458
 	isc_socket_t *		tcpsocket;	/*%< TCP socket. */
8fa458
 	isc_dscp_t		dscp;		/*%< "listen-on" DSCP value */
8fa458
-	int			ntcptarget;	/*%< Desired number of concurrent
8fa458
-						     TCP accepts */
8fa458
-	int			ntcpcurrent;	/*%< Current ditto, locked */
8fa458
+	int32_t			ntcpaccepting;	/*%< Number of clients
8fa458
+						     ready to accept new
8fa458
+						     TCP connections on this
8fa458
+						     interface */
8fa458
+	int32_t			ntcpactive;	/*%< Number of clients
8fa458
+						     servicing TCP queries
8fa458
+						     (whether accepting or
8fa458
+						     connected) */
8fa458
 	int			nudpdispatch;	/*%< Number of UDP dispatches */
8fa458
 	ns_clientmgr_t *	clientmgr;	/*%< Client manager. */
8fa458
 	ISC_LINK(ns_interface_t) link;
8fa458
diff --git a/bin/named/interfacemgr.c b/bin/named/interfacemgr.c
8fa458
index d8c7188..96c080b 100644
8fa458
--- a/bin/named/interfacemgr.c
8fa458
+++ b/bin/named/interfacemgr.c
8fa458
@@ -384,8 +384,9 @@ ns_interface_create(ns_interfacemgr_t *mgr, isc_sockaddr_t *addr,
8fa458
 	 * connections will be handled in parallel even though there is
8fa458
 	 * only one client initially.
8fa458
 	 */
8fa458
-	ifp->ntcptarget = 1;
8fa458
-	ifp->ntcpcurrent = 0;
8fa458
+	ifp->ntcpaccepting = 0;
8fa458
+	ifp->ntcpactive = 0;
8fa458
+
8fa458
 	ifp->nudpdispatch = 0;
8fa458
 
8fa458
 	ifp->dscp = -1;
8fa458
@@ -520,9 +521,7 @@ ns_interface_accepttcp(ns_interface_t *ifp) {
8fa458
 	 */
8fa458
 	(void)isc_socket_filter(ifp->tcpsocket, "dataready");
8fa458
 
8fa458
-	result = ns_clientmgr_createclients(ifp->clientmgr,
8fa458
-					    ifp->ntcptarget, ifp,
8fa458
-					    ISC_TRUE);
8fa458
+	result = ns_clientmgr_createclients(ifp->clientmgr, 1, ifp, ISC_TRUE);
8fa458
 	if (result != ISC_R_SUCCESS) {
8fa458
 		UNEXPECTED_ERROR(__FILE__, __LINE__,
8fa458
 				 "TCP ns_clientmgr_createclients(): %s",
8fa458
diff --git a/lib/isc/include/isc/quota.h b/lib/isc/include/isc/quota.h
8fa458
index b9bf598..36c5830 100644
8fa458
--- a/lib/isc/include/isc/quota.h
8fa458
+++ b/lib/isc/include/isc/quota.h
8fa458
@@ -100,6 +100,13 @@ isc_quota_attach(isc_quota_t *quota, isc_quota_t **p);
8fa458
  * quota if successful (ISC_R_SUCCESS or ISC_R_SOFTQUOTA).
8fa458
  */
8fa458
 
8fa458
+isc_result_t
8fa458
+isc_quota_force(isc_quota_t *quota, isc_quota_t **p);
8fa458
+/*%<
8fa458
+ * Like isc_quota_attach, but will attach '*p' to the quota
8fa458
+ * even if the hard quota has been exceeded.
8fa458
+ */
8fa458
+
8fa458
 void
8fa458
 isc_quota_detach(isc_quota_t **p);
8fa458
 /*%<
8fa458
diff --git a/lib/isc/quota.c b/lib/isc/quota.c
8fa458
index 3ddff0d..20976a4 100644
8fa458
--- a/lib/isc/quota.c
8fa458
+++ b/lib/isc/quota.c
8fa458
@@ -74,20 +74,39 @@ isc_quota_release(isc_quota_t *quota) {
8fa458
 	UNLOCK(&quota->lock);
8fa458
 }
8fa458
 
8fa458
-isc_result_t
8fa458
-isc_quota_attach(isc_quota_t *quota, isc_quota_t **p)
8fa458
-{
8fa458
+static isc_result_t
8fa458
+doattach(isc_quota_t *quota, isc_quota_t **p, isc_boolean_t force) {
8fa458
 	isc_result_t result;
8fa458
-	INSIST(p != NULL && *p == NULL);
8fa458
+	REQUIRE(p != NULL && *p == NULL);
8fa458
+
8fa458
 	result = isc_quota_reserve(quota);
8fa458
-	if (result == ISC_R_SUCCESS || result == ISC_R_SOFTQUOTA)
8fa458
+	if (result == ISC_R_SUCCESS || result == ISC_R_SOFTQUOTA) {
8fa458
+		*p = quota;
8fa458
+	} else if (result == ISC_R_QUOTA && force) {
8fa458
+		/* attach anyway */
8fa458
+		LOCK(&quota->lock);
8fa458
+		quota->used++;
8fa458
+		UNLOCK(&quota->lock);
8fa458
+
8fa458
 		*p = quota;
8fa458
+		result = ISC_R_SUCCESS;
8fa458
+	}
8fa458
+
8fa458
 	return (result);
8fa458
 }
8fa458
 
8fa458
+isc_result_t
8fa458
+isc_quota_attach(isc_quota_t *quota, isc_quota_t **p) {
8fa458
+	return (doattach(quota, p, ISC_FALSE));
8fa458
+}
8fa458
+
8fa458
+isc_result_t
8fa458
+isc_quota_force(isc_quota_t *quota, isc_quota_t **p) {
8fa458
+	return (doattach(quota, p, ISC_TRUE));
8fa458
+}
8fa458
+
8fa458
 void
8fa458
-isc_quota_detach(isc_quota_t **p)
8fa458
-{
8fa458
+isc_quota_detach(isc_quota_t **p) {
8fa458
 	INSIST(p != NULL && *p != NULL);
8fa458
 	isc_quota_release(*p);
8fa458
 	*p = NULL;
8fa458
-- 
8fa458
2.20.1
8fa458