272df6
From 05bf4fa9056d85782dad528bba3d0fa90946d4d8 Mon Sep 17 00:00:00 2001
272df6
From: Petr Mensik <pemensik@redhat.com>
272df6
Date: Wed, 24 Apr 2019 20:09:07 +0200
272df6
Subject: [PATCH] 5200. [security] tcp-clients settings could be exceeded in
272df6
 some cases, which could lead to exhaustion of file descriptors.
272df6
 (CVE-2018-5743) [GL #615]
272df6
---
272df6
 bin/named/client.c                     | 428 +++++++++++++++++++------
272df6
 bin/named/include/named/client.h       |  13 +-
272df6
 bin/named/include/named/interfacemgr.h |  13 +-
272df6
 bin/named/interfacemgr.c               |   9 +-
272df6
 lib/isc/include/isc/quota.h            |   7 +
272df6
 lib/isc/quota.c                        |  33 +-
272df6
 6 files changed, 389 insertions(+), 114 deletions(-)
272df6
272df6
diff --git a/bin/named/client.c b/bin/named/client.c
272df6
index f014b61..0ba383b 100644
272df6
--- a/bin/named/client.c
272df6
+++ b/bin/named/client.c
272df6
@@ -234,7 +234,9 @@ static void ns_client_dumpmessage(ns_client_t *client, const char *reason);
272df6
 static isc_result_t get_client(ns_clientmgr_t *manager, ns_interface_t *ifp,
272df6
 			       dns_dispatch_t *disp, isc_boolean_t tcp);
272df6
 static isc_result_t get_worker(ns_clientmgr_t *manager, ns_interface_t *ifp,
272df6
-			       isc_socket_t *socket);
272df6
+			       isc_socket_t *sock, ns_client_t *oldclient);
272df6
+static inline isc_boolean_t
272df6
+allowed(isc_netaddr_t *addr, dns_name_t *signer, dns_acl_t *acl);
272df6
 
272df6
 void
272df6
 ns_client_recursing(ns_client_t *client) {
272df6
@@ -280,6 +282,119 @@ ns_client_settimeout(ns_client_t *client, unsigned int seconds) {
272df6
 	}
272df6
 }
272df6
 
272df6
+/*%
272df6
+ * Allocate a reference-counted object that will maintain a single pointer to
272df6
+ * the (also reference-counted) TCP client quota, shared between all the
272df6
+ * clients processing queries on a single TCP connection, so that all
272df6
+ * clients sharing the one socket will together consume only one slot in
272df6
+ * the 'tcp-clients' quota.
272df6
+ */
272df6
+static isc_result_t
272df6
+tcpconn_init(ns_client_t *client, isc_boolean_t force) {
272df6
+	isc_result_t result;
272df6
+	isc_quota_t *quota = NULL;
272df6
+	ns_tcpconn_t *tconn = NULL;
272df6
+
272df6
+	REQUIRE(client->tcpconn == NULL);
272df6
+
272df6
+	/*
272df6
+	 * Try to attach to the quota first, so we won't pointlessly
272df6
+	 * allocate memory for a tcpconn object if we can't get one.
272df6
+	 */
272df6
+	if (force) {
272df6
+		result = isc_quota_force(&ns_g_server->tcpquota, "a;;
272df6
+	} else {
272df6
+		result = isc_quota_attach(&ns_g_server->tcpquota, "a;;
272df6
+	}
272df6
+	if (result != ISC_R_SUCCESS) {
272df6
+		return (result);
272df6
+	}
272df6
+
272df6
+	/*
272df6
+	 * A global memory context is used for the allocation as different
272df6
+	 * client structures may have different memory contexts assigned and a
272df6
+	 * reference counter allocated here might need to be freed by a
272df6
+	 * different client.  The performance impact caused by memory context
272df6
+	 * contention here is expected to be negligible, given that this code
272df6
+	 * is only executed for TCP connections.
272df6
+	 */
272df6
+	tconn = isc_mem_allocate(ns_g_mctx, sizeof(*tconn));
272df6
+
272df6
+	isc_refcount_init(&tconn->refs, 1);
272df6
+	tconn->tcpquota = quota;
272df6
+	quota = NULL;
272df6
+	tconn->pipelined = ISC_FALSE;
272df6
+
272df6
+	client->tcpconn = tconn;
272df6
+
272df6
+	return (ISC_R_SUCCESS);
272df6
+}
272df6
+
272df6
+/*%
272df6
+ * Increase the count of client structures sharing the TCP connection
272df6
+ * that 'source' is associated with; add a pointer to the same tcpconn
272df6
+ * to 'target', thus associating it with the same TCP connection.
272df6
+ */
272df6
+static void
272df6
+tcpconn_attach(ns_client_t *source, ns_client_t *target) {
272df6
+	int refs;
272df6
+
272df6
+	REQUIRE(source->tcpconn != NULL);
272df6
+	REQUIRE(target->tcpconn == NULL);
272df6
+	REQUIRE(source->tcpconn->pipelined);
272df6
+
272df6
+	isc_refcount_increment(&source->tcpconn->refs, &refs);
272df6
+	INSIST(refs > 1);
272df6
+	target->tcpconn = source->tcpconn;
272df6
+}
272df6
+
272df6
+/*%
272df6
+ * Decrease the count of client structures sharing the TCP connection that
272df6
+ * 'client' is associated with.  If this is the last client using this TCP
272df6
+ * connection, we detach from the TCP quota and free the tcpconn
272df6
+ * object. Either way, client->tcpconn is set to NULL.
272df6
+ */
272df6
+static void
272df6
+tcpconn_detach(ns_client_t *client) {
272df6
+	ns_tcpconn_t *tconn = NULL;
272df6
+	int refs;
272df6
+
272df6
+	REQUIRE(client->tcpconn != NULL);
272df6
+
272df6
+	tconn = client->tcpconn;
272df6
+	client->tcpconn = NULL;
272df6
+
272df6
+	isc_refcount_decrement(&tconn->refs, &refs);
272df6
+	if (refs == 0) {
272df6
+		isc_quota_detach(&tconn->tcpquota);
272df6
+		isc_mem_free(ns_g_mctx, tconn);
272df6
+	}
272df6
+}
272df6
+
272df6
+/*%
272df6
+ * Mark a client as active and increment the interface's 'ntcpactive'
272df6
+ * counter, as a signal that there is at least one client servicing
272df6
+ * TCP queries for the interface. If we reach the TCP client quota at
272df6
+ * some point, this will be used to determine whether a quota overrun
272df6
+ * should be permitted.
272df6
+ *
272df6
+ * Marking the client active with the 'tcpactive' flag ensures proper
272df6
+ * accounting, by preventing us from incrementing or decrementing
272df6
+ * 'ntcpactive' more than once per client.
272df6
+ */
272df6
+static void
272df6
+mark_tcp_active(ns_client_t *client, isc_boolean_t active) {
272df6
+	if (active && !client->tcpactive) {
272df6
+		isc_atomic_xadd(&client->interface->ntcpactive, 1);
272df6
+		client->tcpactive = active;
272df6
+	} else if (!active && client->tcpactive) {
272df6
+		uint32_t old =
272df6
+			isc_atomic_xadd(&client->interface->ntcpactive, -1);
272df6
+		INSIST(old > 0);
272df6
+		client->tcpactive = active;
272df6
+	}
272df6
+}
272df6
+
272df6
 /*%
272df6
  * Check for a deactivation or shutdown request and take appropriate
272df6
  * action.  Returns ISC_TRUE if either is in progress; in this case
272df6
@@ -369,7 +484,8 @@ exit_check(ns_client_t *client) {
272df6
 		INSIST(client->recursionquota == NULL);
272df6
 
272df6
 		if (NS_CLIENTSTATE_READING == client->newstate) {
272df6
-			if (!client->pipelined) {
272df6
+			INSIST(client->tcpconn != NULL);
272df6
+			if (!client->tcpconn->pipelined) {
272df6
 				client_read(client);
272df6
 				client->newstate = NS_CLIENTSTATE_MAX;
272df6
 				return (ISC_TRUE); /* We're done. */
272df6
@@ -386,10 +502,13 @@ exit_check(ns_client_t *client) {
272df6
 		 */
272df6
 		INSIST(client->recursionquota == NULL);
272df6
 		INSIST(client->newstate <= NS_CLIENTSTATE_READY);
272df6
-		if (client->nreads > 0)
272df6
+
272df6
+		if (client->nreads > 0) {
272df6
 			dns_tcpmsg_cancelread(&client->tcpmsg);
272df6
-		if (! client->nreads == 0) {
272df6
-			/* Still waiting for read cancel completion. */
272df6
+		}
272df6
+
272df6
+		/* Still waiting for read cancel completion. */
272df6
+		if (client->nreads > 0) {
272df6
 			return (ISC_TRUE);
272df6
 		}
272df6
 
272df6
@@ -397,14 +516,49 @@ exit_check(ns_client_t *client) {
272df6
 			dns_tcpmsg_invalidate(&client->tcpmsg);
272df6
 			client->tcpmsg_valid = ISC_FALSE;
272df6
 		}
272df6
+
272df6
+		/*
272df6
+		 * Soon the client will be ready to accept a new TCP
272df6
+		 * connection or UDP request, but we may have enough
272df6
+		 * clients doing that already.  Check whether this client
272df6
+		 * needs to remain active and allow it go inactive if
272df6
+		 * not.
272df6
+		 *
272df6
+		 * UDP clients always go inactive at this point, but a TCP
272df6
+		 * client may need to stay active and return to READY
272df6
+		 * state if no other clients are available to listen
272df6
+		 * for TCP requests on this interface.
272df6
+		 *
272df6
+		 * Regardless, if we're going to FREED state, that means
272df6
+		 * the system is shutting down and we don't need to
272df6
+		 * retain clients.
272df6
+		 */
272df6
+		if (client->mortal && TCP_CLIENT(client) &&
272df6
+		    client->newstate != NS_CLIENTSTATE_FREED &&
272df6
+		    !ns_g_clienttest &&
272df6
+		    isc_atomic_xadd(&client->interface->ntcpaccepting, 0) == 0)
272df6
+		{
272df6
+			/* Nobody else is accepting */
272df6
+			client->mortal = ISC_FALSE;
272df6
+			client->newstate = NS_CLIENTSTATE_READY;
272df6
+		}
272df6
+
272df6
+		/*
272df6
+		 * Detach from TCP connection and TCP client quota,
272df6
+		 * if appropriate. If this is the last reference to
272df6
+		 * the TCP connection in our pipeline group, the
272df6
+		 * TCP quota slot will be released.
272df6
+		 */
272df6
+		if (client->tcpconn) {
272df6
+			tcpconn_detach(client);
272df6
+		}
272df6
+
272df6
 		if (client->tcpsocket != NULL) {
272df6
 			CTRACE("closetcp");
272df6
 			isc_socket_detach(&client->tcpsocket);
272df6
+			mark_tcp_active(client, ISC_FALSE);
272df6
 		}
272df6
 
272df6
-		if (client->tcpquota != NULL)
272df6
-			isc_quota_detach(&client->tcpquota);
272df6
-
272df6
 		if (client->timerset) {
272df6
 			(void)isc_timer_reset(client->timer,
272df6
 					      isc_timertype_inactive,
272df6
@@ -412,45 +566,26 @@ exit_check(ns_client_t *client) {
272df6
 			client->timerset = ISC_FALSE;
272df6
 		}
272df6
 
272df6
-		client->pipelined = ISC_FALSE;
272df6
-
272df6
 		client->peeraddr_valid = ISC_FALSE;
272df6
 
272df6
 		client->state = NS_CLIENTSTATE_READY;
272df6
-		INSIST(client->recursionquota == NULL);
272df6
-
272df6
-		/*
272df6
-		 * Now the client is ready to accept a new TCP connection
272df6
-		 * or UDP request, but we may have enough clients doing
272df6
-		 * that already.  Check whether this client needs to remain
272df6
-		 * active and force it to go inactive if not.
272df6
-		 *
272df6
-		 * UDP clients go inactive at this point, but TCP clients
272df6
-		 * may remain active if we have fewer active TCP client
272df6
-		 * objects than desired due to an earlier quota exhaustion.
272df6
-		 */
272df6
-		if (client->mortal && TCP_CLIENT(client) && !ns_g_clienttest) {
272df6
-			LOCK(&client->interface->lock);
272df6
-			if (client->interface->ntcpcurrent <
272df6
-				    client->interface->ntcptarget)
272df6
-				client->mortal = ISC_FALSE;
272df6
-			UNLOCK(&client->interface->lock);
272df6
-		}
272df6
 
272df6
 		/*
272df6
 		 * We don't need the client; send it to the inactive
272df6
 		 * queue for recycling.
272df6
 		 */
272df6
 		if (client->mortal) {
272df6
-			if (client->newstate > NS_CLIENTSTATE_INACTIVE)
272df6
+			if (client->newstate > NS_CLIENTSTATE_INACTIVE) {
272df6
 				client->newstate = NS_CLIENTSTATE_INACTIVE;
272df6
+			}
272df6
 		}
272df6
 
272df6
 		if (NS_CLIENTSTATE_READY == client->newstate) {
272df6
 			if (TCP_CLIENT(client)) {
272df6
 				client_accept(client);
272df6
-			} else
272df6
+			} else {
272df6
 				client_udprecv(client);
272df6
+			}
272df6
 			client->newstate = NS_CLIENTSTATE_MAX;
272df6
 			return (ISC_TRUE);
272df6
 		}
272df6
@@ -462,41 +597,51 @@ exit_check(ns_client_t *client) {
272df6
 		/*
272df6
 		 * We are trying to enter the inactive state.
272df6
 		 */
272df6
-		if (client->naccepts > 0)
272df6
+		if (client->naccepts > 0) {
272df6
 			isc_socket_cancel(client->tcplistener, client->task,
272df6
 					  ISC_SOCKCANCEL_ACCEPT);
272df6
+		}
272df6
 
272df6
 		/* Still waiting for accept cancel completion. */
272df6
-		if (! (client->naccepts == 0))
272df6
+		if (client->naccepts > 0) {
272df6
 			return (ISC_TRUE);
272df6
+		}
272df6
 
272df6
 		/* Accept cancel is complete. */
272df6
-		if (client->nrecvs > 0)
272df6
+		if (client->nrecvs > 0) {
272df6
 			isc_socket_cancel(client->udpsocket, client->task,
272df6
 					  ISC_SOCKCANCEL_RECV);
272df6
+		}
272df6
 
272df6
 		/* Still waiting for recv cancel completion. */
272df6
-		if (! (client->nrecvs == 0))
272df6
+		if (client->nrecvs > 0) {
272df6
 			return (ISC_TRUE);
272df6
+		}
272df6
 
272df6
 		/* Still waiting for control event to be delivered */
272df6
-		if (client->nctls > 0)
272df6
+		if (client->nctls > 0) {
272df6
 			return (ISC_TRUE);
272df6
-
272df6
-		/* Deactivate the client. */
272df6
-		if (client->interface)
272df6
-			ns_interface_detach(&client->interface);
272df6
+		}
272df6
 
272df6
 		INSIST(client->naccepts == 0);
272df6
 		INSIST(client->recursionquota == NULL);
272df6
-		if (client->tcplistener != NULL)
272df6
+		if (client->tcplistener != NULL) {
272df6
 			isc_socket_detach(&client->tcplistener);
272df6
+			mark_tcp_active(client, ISC_FALSE);
272df6
+		}
272df6
 
272df6
-		if (client->udpsocket != NULL)
272df6
+		if (client->udpsocket != NULL) {
272df6
 			isc_socket_detach(&client->udpsocket);
272df6
+		}
272df6
 
272df6
-		if (client->dispatch != NULL)
272df6
+		/* Deactivate the client. */
272df6
+		if (client->interface != NULL) {
272df6
+			ns_interface_detach(&client->interface);
272df6
+		}
272df6
+
272df6
+		if (client->dispatch != NULL) {
272df6
 			dns_dispatch_detach(&client->dispatch);
272df6
+		}
272df6
 
272df6
 		client->attributes = 0;
272df6
 		client->mortal = ISC_FALSE;
272df6
@@ -515,10 +660,13 @@ exit_check(ns_client_t *client) {
272df6
 			client->newstate = NS_CLIENTSTATE_MAX;
272df6
 			if (!ns_g_clienttest && manager != NULL &&
272df6
 			    !manager->exiting)
272df6
+			{
272df6
 				ISC_QUEUE_PUSH(manager->inactive, client,
272df6
 					       ilink);
272df6
-			if (client->needshutdown)
272df6
+			}
272df6
+			if (client->needshutdown) {
272df6
 				isc_task_shutdown(client->task);
272df6
+			}
272df6
 			return (ISC_TRUE);
272df6
 		}
272df6
 	}
272df6
@@ -613,7 +761,7 @@ client_start(isc_task_t *task, isc_event_t *event) {
272df6
 		return;
272df6
 
272df6
 	if (TCP_CLIENT(client)) {
272df6
-		if (client->pipelined) {
272df6
+		if (client->tcpconn != NULL) {
272df6
 			client_read(client);
272df6
 		} else {
272df6
 			client_accept(client);
272df6
@@ -623,7 +771,6 @@ client_start(isc_task_t *task, isc_event_t *event) {
272df6
 	}
272df6
 }
272df6
 
272df6
-
272df6
 /*%
272df6
  * The client's task has received a shutdown event.
272df6
  */
272df6
@@ -1511,6 +1658,7 @@ client_request(isc_task_t *task, isc_event_t *event) {
272df6
 		client->nrecvs--;
272df6
 	} else {
272df6
 		INSIST(TCP_CLIENT(client));
272df6
+		INSIST(client->tcpconn != NULL);
272df6
 		REQUIRE(event->ev_type == DNS_EVENT_TCPMSG);
272df6
 		REQUIRE(event->ev_sender == &client->tcpmsg);
272df6
 		buffer = &client->tcpmsg.buffer;
272df6
@@ -1653,18 +1801,27 @@ client_request(isc_task_t *task, isc_event_t *event) {
272df6
 	/*
272df6
 	 * Pipeline TCP query processing.
272df6
 	 */
272df6
-	if (client->message->opcode != dns_opcode_query)
272df6
-		client->pipelined = ISC_FALSE;
272df6
-	if (TCP_CLIENT(client) && client->pipelined) {
272df6
-		result = isc_quota_reserve(&ns_g_server->tcpquota);
272df6
-		if (result == ISC_R_SUCCESS)
272df6
-			result = ns_client_replace(client);
272df6
+	if (TCP_CLIENT(client) &&
272df6
+	    client->message->opcode != dns_opcode_query)
272df6
+	{
272df6
+		client->tcpconn->pipelined = ISC_FALSE;
272df6
+	}
272df6
+	if (TCP_CLIENT(client) && client->tcpconn->pipelined) {
272df6
+		/*
272df6
+		 * We're pipelining. Replace the client; the
272df6
+		 * replacement can read the TCP socket looking
272df6
+		 * for new messages and this one can process the
272df6
+		 * current message asynchronously.
272df6
+		 *
272df6
+		 * There will now be at least three clients using this
272df6
+		 * TCP socket - one accepting new connections,
272df6
+		 * one reading an existing connection to get new
272df6
+		 * messages, and one answering the message already
272df6
+		 * received.
272df6
+		 */
272df6
+		result = ns_client_replace(client);
272df6
 		if (result != ISC_R_SUCCESS) {
272df6
-			ns_client_log(client, NS_LOGCATEGORY_CLIENT,
272df6
-				      NS_LOGMODULE_CLIENT, ISC_LOG_WARNING,
272df6
-				      "no more TCP clients(read): %s",
272df6
-				      isc_result_totext(result));
272df6
-			client->pipelined = ISC_FALSE;
272df6
+			client->tcpconn->pipelined = ISC_FALSE;
272df6
 		}
272df6
 	}
272df6
 
272df6
@@ -2168,8 +2325,7 @@ client_create(ns_clientmgr_t *manager, ns_client_t **clientp) {
272df6
 	client->signer = NULL;
272df6
 	dns_name_init(&client->signername, NULL);
272df6
 	client->mortal = ISC_FALSE;
272df6
-	client->pipelined = ISC_FALSE;
272df6
-	client->tcpquota = NULL;
272df6
+	client->tcpconn = NULL;
272df6
 	client->recursionquota = NULL;
272df6
 	client->interface = NULL;
272df6
 	client->peeraddr_valid = ISC_FALSE;
272df6
@@ -2177,6 +2333,7 @@ client_create(ns_clientmgr_t *manager, ns_client_t **clientp) {
272df6
 	client->filter_aaaa = dns_v4_aaaa_ok;
272df6
 #endif
272df6
 	client->needshutdown = ns_g_clienttest;
272df6
+	client->tcpactive = ISC_FALSE;
272df6
 
272df6
 	ISC_EVENT_INIT(&client->ctlevent, sizeof(client->ctlevent), 0, NULL,
272df6
 		       NS_EVENT_CLIENTCONTROL, client_start, client, client,
272df6
@@ -2269,9 +2426,10 @@ client_read(ns_client_t *client) {
272df6
 
272df6
 static void
272df6
 client_newconn(isc_task_t *task, isc_event_t *event) {
272df6
+	isc_result_t result;
272df6
 	ns_client_t *client = event->ev_arg;
272df6
 	isc_socket_newconnev_t *nevent = (isc_socket_newconnev_t *)event;
272df6
-	isc_result_t result;
272df6
+	uint32_t old;
272df6
 
272df6
 	REQUIRE(event->ev_type == ISC_SOCKEVENT_NEWCONN);
272df6
 	REQUIRE(NS_CLIENT_VALID(client));
272df6
@@ -2281,13 +2439,18 @@ client_newconn(isc_task_t *task, isc_event_t *event) {
272df6
 
272df6
 	INSIST(client->state == NS_CLIENTSTATE_READY);
272df6
 
272df6
+	/*
272df6
+	 * The accept() was successful and we're now establishing a new
272df6
+	 * connection. We need to make note of it in the client and
272df6
+	 * interface objects so client objects can do the right thing
272df6
+	 * when going inactive in exit_check() (see comments in
272df6
+	 * client_accept() for details).
272df6
+	 */
272df6
 	INSIST(client->naccepts == 1);
272df6
 	client->naccepts--;
272df6
 
272df6
-	LOCK(&client->interface->lock);
272df6
-	INSIST(client->interface->ntcpcurrent > 0);
272df6
-	client->interface->ntcpcurrent--;
272df6
-	UNLOCK(&client->interface->lock);
272df6
+	old = isc_atomic_xadd(&client->interface->ntcpaccepting, -1);
272df6
+	INSIST(old > 0);
272df6
 
272df6
 	/*
272df6
 	 * We must take ownership of the new socket before the exit
272df6
@@ -2320,6 +2483,7 @@ client_newconn(isc_task_t *task, isc_event_t *event) {
272df6
 			      NS_LOGMODULE_CLIENT, ISC_LOG_DEBUG(3),
272df6
 			      "accept failed: %s",
272df6
 			      isc_result_totext(nevent->result));
272df6
+		tcpconn_detach(client);
272df6
 	}
272df6
 
272df6
 	if (exit_check(client))
272df6
@@ -2357,20 +2521,13 @@ client_newconn(isc_task_t *task, isc_event_t *event) {
272df6
 		 * telnetting to port 53 (once per CPU) will
272df6
 		 * deny service to legitimate TCP clients.
272df6
 		 */
272df6
-		client->pipelined = ISC_FALSE;
272df6
-		result = isc_quota_attach(&ns_g_server->tcpquota,
272df6
-					  &client->tcpquota);
272df6
-		if (result == ISC_R_SUCCESS)
272df6
-			result = ns_client_replace(client);
272df6
-		if (result != ISC_R_SUCCESS) {
272df6
-			ns_client_log(client, NS_LOGCATEGORY_CLIENT,
272df6
-				      NS_LOGMODULE_CLIENT, ISC_LOG_WARNING,
272df6
-				      "no more TCP clients(accept): %s",
272df6
-				      isc_result_totext(result));
272df6
-		} else if (ns_g_server->keepresporder == NULL ||
272df6
-			   !allowed(&netaddr, NULL, NULL, 0, NULL,
272df6
-				    ns_g_server->keepresporder)) {
272df6
-			client->pipelined = ISC_TRUE;
272df6
+		result = ns_client_replace(client);
272df6
+		if (result == ISC_R_SUCCESS &&
272df6
+		    (ns_g_server->keepresporder == NULL ||
272df6
+		     !allowed(&netaddr, NULL,
272df6
+			      ns_g_server->keepresporder)))
272df6
+		{
272df6
+			client->tcpconn->pipelined = ISC_TRUE;
272df6
 		}
272df6
 
272df6
 		client_read(client);
272df6
@@ -2386,12 +2543,66 @@ client_accept(ns_client_t *client) {
272df6
 
272df6
 	CTRACE("accept");
272df6
 
272df6
+	/*
272df6
+	 * Set up a new TCP connection. This means try to attach to the
272df6
+	 * TCP client quota (tcp-clients), but fail if we're over quota.
272df6
+	 */
272df6
+	result = tcpconn_init(client, ISC_FALSE);
272df6
+	if (result != ISC_R_SUCCESS) {
272df6
+		isc_boolean_t exit;
272df6
+
272df6
+		ns_client_log(client, NS_LOGCATEGORY_CLIENT,
272df6
+			      NS_LOGMODULE_CLIENT, ISC_LOG_WARNING,
272df6
+			      "TCP client quota reached: %s",
272df6
+			      isc_result_totext(result));
272df6
+
272df6
+		/*
272df6
+		 * We have exceeded the system-wide TCP client quota.  But,
272df6
+		 * we can't just block this accept in all cases, because if
272df6
+		 * we did, a heavy TCP load on other interfaces might cause
272df6
+		 * this interface to be starved, with no clients able to
272df6
+		 * accept new connections.
272df6
+		 *
272df6
+		 * So, we check here to see if any other clients are
272df6
+		 * already servicing TCP queries on this interface (whether
272df6
+		 * accepting, reading, or processing). If we find that at
272df6
+		 * least one client other than this one is active, then
272df6
+		 * it's okay *not* to call accept - we can let this
272df6
+		 * client go inactive and another will take over when it's
272df6
+		 * done.
272df6
+		 *
272df6
+		 * If there aren't enough active clients on the interface,
272df6
+		 * then we can be a little bit flexible about the quota.
272df6
+		 * We'll allow *one* extra client through to ensure we're
272df6
+		 * listening on every interface; we do this by setting the
272df6
+		 * 'force' option to tcpconn_init().
272df6
+		 *
272df6
+		 * (Note: In practice this means that the real TCP client
272df6
+		 * quota is tcp-clients plus the number of listening
272df6
+		 * interfaces plus 1.)
272df6
+		 */
272df6
+		exit = (isc_atomic_xadd(&client->interface->ntcpactive, 0) >
272df6
+			(client->tcpactive ? 1 : 0));
272df6
+		if (exit) {
272df6
+			client->newstate = NS_CLIENTSTATE_INACTIVE;
272df6
+			(void)exit_check(client);
272df6
+			return;
272df6
+		}
272df6
+
272df6
+		result = tcpconn_init(client, ISC_TRUE);
272df6
+		RUNTIME_CHECK(result == ISC_R_SUCCESS);
272df6
+	}
272df6
+
272df6
+	/*
272df6
+	 * If this client was set up using get_client() or get_worker(),
272df6
+	 * then TCP is already marked active. However, if it was restarted
272df6
+	 * from exit_check(), it might not be, so we take care of it now.
272df6
+	 */
272df6
+	mark_tcp_active(client, ISC_TRUE);
272df6
+
272df6
 	result = isc_socket_accept(client->tcplistener, client->task,
272df6
 				   client_newconn, client);
272df6
 	if (result != ISC_R_SUCCESS) {
272df6
-		UNEXPECTED_ERROR(__FILE__, __LINE__,
272df6
-				 "isc_socket_accept() failed: %s",
272df6
-				 isc_result_totext(result));
272df6
 		/*
272df6
 		 * XXXRTH  What should we do?  We're trying to accept but
272df6
 		 *	   it didn't work.  If we just give up, then TCP
272df6
@@ -2399,13 +2610,37 @@ client_accept(ns_client_t *client) {
272df6
 		 *
272df6
 		 *	   For now, we just go idle.
272df6
 		 */
272df6
+		UNEXPECTED_ERROR(__FILE__, __LINE__,
272df6
+				 "isc_socket_accept() failed: %s",
272df6
+				 isc_result_totext(result));
272df6
+
272df6
+		tcpconn_detach(client);
272df6
+		mark_tcp_active(client, ISC_FALSE);
272df6
 		return;
272df6
 	}
272df6
+
272df6
+	/*
272df6
+	 * The client's 'naccepts' counter indicates that this client has
272df6
+	 * called accept() and is waiting for a new connection. It should
272df6
+	 * never exceed 1.
272df6
+	 */
272df6
 	INSIST(client->naccepts == 0);
272df6
 	client->naccepts++;
272df6
-	LOCK(&client->interface->lock);
272df6
-	client->interface->ntcpcurrent++;
272df6
-	UNLOCK(&client->interface->lock);
272df6
+
272df6
+	/*
272df6
+	 * The interface's 'ntcpaccepting' counter is incremented when
272df6
+	 * any client calls accept(), and decremented in client_newconn()
272df6
+	 * once the connection is established.
272df6
+	 *
272df6
+	 * When the client object is shutting down after handling a TCP
272df6
+	 * request (see exit_check()), if this value is at least one, that
272df6
+	 * means another client has called accept() and is waiting to
272df6
+	 * establish the next connection. That means the client may be
272df6
+	 * be free to become inactive; otherwise it may need to start
272df6
+	 * listening for connections itself to prevent the interface
272df6
+	 * going dead.
272df6
+	 */
272df6
+	isc_atomic_xadd(&client->interface->ntcpaccepting, 1);
272df6
 }
272df6
 
272df6
 static void
272df6
@@ -2476,15 +2711,17 @@ ns_client_replace(ns_client_t *client) {
272df6
 	REQUIRE(client->manager != NULL);
272df6
 
272df6
 	tcp = TCP_CLIENT(client);
272df6
-	if (tcp && client->pipelined) {
272df6
+	if (tcp && client->tcpconn != NULL && client->tcpconn->pipelined) {
272df6
 		result = get_worker(client->manager, client->interface,
272df6
-				    client->tcpsocket);
272df6
+				    client->tcpsocket, client);
272df6
 	} else {
272df6
 		result = get_client(client->manager, client->interface,
272df6
 				    client->dispatch, tcp);
272df6
+
272df6
 	}
272df6
-	if (result != ISC_R_SUCCESS)
272df6
+	if (result != ISC_R_SUCCESS) {
272df6
 		return (result);
272df6
+	}
272df6
 
272df6
 	/*
272df6
 	 * The responsibility for listening for new requests is hereby
272df6
@@ -2668,9 +2905,12 @@ get_client(ns_clientmgr_t *manager, ns_interface_t *ifp,
272df6
 	INSIST(client->recursionquota == NULL);
272df6
 
272df6
 	if (tcp) {
272df6
+		mark_tcp_active(client, ISC_TRUE);
272df6
+
272df6
 		client->attributes |= NS_CLIENTATTR_TCP;
272df6
 		isc_socket_attach(ifp->tcpsocket,
272df6
 				  &client->tcplistener);
272df6
+
272df6
 	} else {
272df6
 		isc_socket_t *sock;
272df6
 
272df6
@@ -2688,7 +2928,8 @@ get_client(ns_clientmgr_t *manager, ns_interface_t *ifp,
272df6
 }
272df6
 
272df6
 static isc_result_t
272df6
-get_worker(ns_clientmgr_t *manager, ns_interface_t *ifp, isc_socket_t *socket)
272df6
+get_worker(ns_clientmgr_t *manager, ns_interface_t *ifp, isc_socket_t *sock,
272df6
+	   ns_client_t *oldclient)
272df6
 {
272df6
 	isc_result_t result = ISC_R_SUCCESS;
272df6
 	isc_event_t *ev;
272df6
@@ -2696,6 +2937,7 @@ get_worker(ns_clientmgr_t *manager, ns_interface_t *ifp, isc_socket_t *socket)
272df6
 	MTRACE("get worker");
272df6
 
272df6
 	REQUIRE(manager != NULL);
272df6
+	REQUIRE(oldclient != NULL);
272df6
 
272df6
 	if (manager->exiting)
272df6
 		return (ISC_R_SHUTTINGDOWN);
272df6
@@ -2728,15 +2970,15 @@ get_worker(ns_clientmgr_t *manager, ns_interface_t *ifp, isc_socket_t *socket)
272df6
 	ns_interface_attach(ifp, &client->interface);
272df6
 	client->newstate = client->state = NS_CLIENTSTATE_WORKING;
272df6
 	INSIST(client->recursionquota == NULL);
272df6
-	client->tcpquota = &ns_g_server->tcpquota;
272df6
-
272df6
-	client->dscp = ifp->dscp;
272df6
 
272df6
 	client->attributes |= NS_CLIENTATTR_TCP;
272df6
-	client->pipelined = ISC_TRUE;
272df6
+	client->mortal = ISC_TRUE;
272df6
+
272df6
+	tcpconn_attach(oldclient, client);
272df6
+	mark_tcp_active(client, ISC_TRUE);
272df6
 
272df6
 	isc_socket_attach(ifp->tcpsocket, &client->tcplistener);
272df6
-	isc_socket_attach(socket, &client->tcpsocket);
272df6
+	isc_socket_attach(sock, &client->tcpsocket);
272df6
 	isc_socket_setname(client->tcpsocket, "worker-tcp", NULL);
272df6
 	(void)isc_socket_getpeername(client->tcpsocket, &client->peeraddr);
272df6
 	client->peeraddr_valid = ISC_TRUE;
272df6
diff --git a/bin/named/include/named/client.h b/bin/named/include/named/client.h
272df6
index bf4d201..ef55a7a 100644
272df6
--- a/bin/named/include/named/client.h
272df6
+++ b/bin/named/include/named/client.h
272df6
@@ -15,8 +15,6 @@
272df6
  * PERFORMANCE OF THIS SOFTWARE.
272df6
  */
272df6
 
272df6
-/* $Id$ */
272df6
-
272df6
 #ifndef NAMED_CLIENT_H
272df6
 #define NAMED_CLIENT_H 1
272df6
 
272df6
@@ -83,6 +81,13 @@
272df6
  *** Types
272df6
  ***/
272df6
 
272df6
+/*% reference-counted TCP connection object */
272df6
+typedef struct ns_tcpconn {
272df6
+	isc_refcount_t		refs;
272df6
+	isc_quota_t		*tcpquota;
272df6
+	isc_boolean_t		pipelined;
272df6
+} ns_tcpconn_t;
272df6
+
272df6
 /*% nameserver client structure */
272df6
 struct ns_client {
272df6
 	unsigned int		magic;
272df6
@@ -133,8 +138,8 @@ struct ns_client {
272df6
 	dns_name_t		signername;   /*%< [T]SIG key name */
272df6
 	dns_name_t *		signer;	      /*%< NULL if not valid sig */
272df6
 	isc_boolean_t		mortal;	      /*%< Die after handling request */
272df6
-	isc_boolean_t		pipelined;   /*%< TCP queries not in sequence */
272df6
-	isc_quota_t		*tcpquota;
272df6
+	isc_boolean_t		tcpactive;
272df6
+	ns_tcpconn_t		*tcpconn;
272df6
 	isc_quota_t		*recursionquota;
272df6
 	ns_interface_t		*interface;
272df6
 	isc_sockaddr_t		peeraddr;
272df6
diff --git a/bin/named/include/named/interfacemgr.h b/bin/named/include/named/interfacemgr.h
272df6
index 380dbed..a342866 100644
272df6
--- a/bin/named/include/named/interfacemgr.h
272df6
+++ b/bin/named/include/named/interfacemgr.h
272df6
@@ -15,8 +15,6 @@
272df6
  * PERFORMANCE OF THIS SOFTWARE.
272df6
  */
272df6
 
272df6
-/* $Id: interfacemgr.h,v 1.35 2011/07/28 23:47:58 tbox Exp $ */
272df6
-
272df6
 #ifndef NAMED_INTERFACEMGR_H
272df6
 #define NAMED_INTERFACEMGR_H 1
272df6
 
272df6
@@ -80,9 +78,14 @@ struct ns_interface {
272df6
 	dns_dispatch_t *	udpdispatch[MAX_UDP_DISPATCH];
272df6
 						/*%< UDP dispatchers. */
272df6
 	isc_socket_t *		tcpsocket;	/*%< TCP socket. */
272df6
-	int			ntcptarget;	/*%< Desired number of concurrent
272df6
-						     TCP accepts */
272df6
-	int			ntcpcurrent;	/*%< Current ditto, locked */
272df6
+	int32_t			ntcpaccepting;	/*%< Number of clients
272df6
+						     ready to accept new
272df6
+						     TCP connections on this
272df6
+						     interface */
272df6
+	int32_t			ntcpactive;	/*%< Number of clients
272df6
+						     servicing TCP queries
272df6
+						     (whether accepting or
272df6
+						     connected) */
272df6
 	int			nudpdispatch;	/*%< Number of UDP dispatches */
272df6
 	ns_clientmgr_t *	clientmgr;	/*%< Client manager. */
272df6
 	ISC_LINK(ns_interface_t) link;
272df6
diff --git a/bin/named/interfacemgr.c b/bin/named/interfacemgr.c
272df6
index 4aee47a..ebec0c4 100644
272df6
--- a/bin/named/interfacemgr.c
272df6
+++ b/bin/named/interfacemgr.c
272df6
@@ -380,8 +380,9 @@ ns_interface_create(ns_interfacemgr_t *mgr, isc_sockaddr_t *addr,
272df6
 	 * connections will be handled in parallel even though there is
272df6
 	 * only one client initially.
272df6
 	 */
272df6
-	ifp->ntcptarget = 1;
272df6
-	ifp->ntcpcurrent = 0;
272df6
+	ifp->ntcpaccepting = 0;
272df6
+	ifp->ntcpactive = 0;
272df6
+
272df6
 	ifp->nudpdispatch = 0;
272df6
 
272df6
 	ISC_LINK_INIT(ifp, link);
272df6
@@ -510,9 +511,7 @@ ns_interface_accepttcp(ns_interface_t *ifp) {
272df6
 	 */
272df6
 	(void)isc_socket_filter(ifp->tcpsocket, "dataready");
272df6
 
272df6
-	result = ns_clientmgr_createclients(ifp->clientmgr,
272df6
-					    ifp->ntcptarget, ifp,
272df6
-					    ISC_TRUE);
272df6
+	result = ns_clientmgr_createclients(ifp->clientmgr, 1, ifp, ISC_TRUE);
272df6
 	if (result != ISC_R_SUCCESS) {
272df6
 		UNEXPECTED_ERROR(__FILE__, __LINE__,
272df6
 				 "TCP ns_clientmgr_createclients(): %s",
272df6
diff --git a/lib/isc/include/isc/quota.h b/lib/isc/include/isc/quota.h
272df6
index 7b0d0d9..bb1a927 100644
272df6
--- a/lib/isc/include/isc/quota.h
272df6
+++ b/lib/isc/include/isc/quota.h
272df6
@@ -107,6 +107,13 @@ isc_quota_attach(isc_quota_t *quota, isc_quota_t **p);
272df6
  * quota if successful (ISC_R_SUCCESS or ISC_R_SOFTQUOTA).
272df6
  */
272df6
 
272df6
+isc_result_t
272df6
+isc_quota_force(isc_quota_t *quota, isc_quota_t **p);
272df6
+/*%<
272df6
+ * Like isc_quota_attach, but will attach '*p' to the quota
272df6
+ * even if the hard quota has been exceeded.
272df6
+ */
272df6
+
272df6
 void
272df6
 isc_quota_detach(isc_quota_t **p);
272df6
 /*%<
272df6
diff --git a/lib/isc/quota.c b/lib/isc/quota.c
272df6
index 5e5c50c..ca4c478 100644
272df6
--- a/lib/isc/quota.c
272df6
+++ b/lib/isc/quota.c
272df6
@@ -81,20 +81,39 @@ isc_quota_release(isc_quota_t *quota) {
272df6
 	UNLOCK(&quota->lock);
272df6
 }
272df6
 
272df6
-isc_result_t
272df6
-isc_quota_attach(isc_quota_t *quota, isc_quota_t **p)
272df6
-{
272df6
+static isc_result_t
272df6
+doattach(isc_quota_t *quota, isc_quota_t **p, isc_boolean_t force) {
272df6
 	isc_result_t result;
272df6
-	INSIST(p != NULL && *p == NULL);
272df6
+	REQUIRE(p != NULL && *p == NULL);
272df6
+
272df6
 	result = isc_quota_reserve(quota);
272df6
-	if (result == ISC_R_SUCCESS || result == ISC_R_SOFTQUOTA)
272df6
+	if (result == ISC_R_SUCCESS || result == ISC_R_SOFTQUOTA) {
272df6
+		*p = quota;
272df6
+	} else if (result == ISC_R_QUOTA && force) {
272df6
+		/* attach anyway */
272df6
+		LOCK(&quota->lock);
272df6
+		quota->used++;
272df6
+		UNLOCK(&quota->lock);
272df6
+
272df6
 		*p = quota;
272df6
+		result = ISC_R_SUCCESS;
272df6
+	}
272df6
+
272df6
 	return (result);
272df6
 }
272df6
 
272df6
+isc_result_t
272df6
+isc_quota_attach(isc_quota_t *quota, isc_quota_t **p) {
272df6
+	return (doattach(quota, p, ISC_FALSE));
272df6
+}
272df6
+
272df6
+isc_result_t
272df6
+isc_quota_force(isc_quota_t *quota, isc_quota_t **p) {
272df6
+	return (doattach(quota, p, ISC_TRUE));
272df6
+}
272df6
+
272df6
 void
272df6
-isc_quota_detach(isc_quota_t **p)
272df6
-{
272df6
+isc_quota_detach(isc_quota_t **p) {
272df6
 	INSIST(p != NULL && *p != NULL);
272df6
 	isc_quota_release(*p);
272df6
 	*p = NULL;
272df6
-- 
272df6
2.20.1
272df6