From c5621f845445553f628269c533799f712df7778c Mon Sep 17 00:00:00 2001
From: root <root@ip-10-0-3-195.ec2.internal>
Date: Sun, 11 Feb 2024 11:48:32 +0000
Subject: [PATCH] core/tcp: reject new tcp connections if reject_new_tcp_conn
 is enabled

---
 src/core/core_cmd.c    |  1 +
 src/core/tcp_main.c    | 10 ++++++++++
 src/core/tcp_options.c |  2 ++
 src/core/tcp_options.h |  1 +
 4 files changed, 14 insertions(+)

diff --git a/src/core/core_cmd.c b/src/core/core_cmd.c
index 3fb2e6d8d7..37481332de 100644
--- a/src/core/core_cmd.c
+++ b/src/core/core_cmd.c
@@ -742,6 +742,7 @@ static void core_tcp_options(rpc_t* rpc, void* c)
 			"max_connections(soft)", t.max_connections,
 			"max_tls_connections(soft)", t.max_tls_connections,
 			"no_connect",	t.no_connect,
+			"reject_new_tcp_conn",	t.reject_new_tcp_conn,
 			"fd_cache",		t.fd_cache,
 			"async",		t.async,
 			"connect_wait",	t.tcp_connect_wait,
diff --git a/src/core/tcp_main.c b/src/core/tcp_main.c
index 97e849d724..b4b93a1a0c 100644
--- a/src/core/tcp_main.c
+++ b/src/core/tcp_main.c
@@ -4223,6 +4223,16 @@ static inline int handle_new_connect(struct socket_info* si)
 		LM_ERR("error while accepting connection(%d): %s\n", errno, strerror(errno));
 		return -1;
 	}
+
+	/* check if reject_new_tcp_conn is enabled */
+	LM_ERR("doing reject_new_tcp_conn check now\n");
+	if ( cfg_get(tcp, tcp_cfg, reject_new_tcp_conn) ) {
+		LM_DBG("reject_new_tcp_conn is enabled, rejecting SYN\n");
+		tcp_safe_close(new_sock);
+		TCP_STATS_LOCAL_REJECT();
+		return 0; /* no success, because we rejected */
+	}
+
 	if (unlikely(*tcp_connections_no>=cfg_get(tcp, tcp_cfg, max_connections))){
 		LM_ERR("maximum number of connections exceeded: %d/%d\n",
 					*tcp_connections_no,
diff --git a/src/core/tcp_options.c b/src/core/tcp_options.c
index 8929c04ca4..e690018a16 100644
--- a/src/core/tcp_options.c
+++ b/src/core/tcp_options.c
@@ -66,6 +66,8 @@ static cfg_def_t tcp_cfg_def[] = {
 		"maximum tls connections number, soft limit"},
 	{ "no_connect",   CFG_VAR_INT | CFG_ATOMIC,      0,   1,      0,         0,
 		"if set only accept new connections, never actively open new ones"},
+	{ "reject_new_tcp_conn",   CFG_VAR_INT | CFG_ATOMIC,      0,   1,      0,         0,
+		"if set we will reject all new conenctions"},
 	{ "fd_cache",     CFG_VAR_INT | CFG_READONLY,    0,   1,      0,         0,
 		"file descriptor cache for tcp_send"},
 	/* tcp async options */
diff --git a/src/core/tcp_options.h b/src/core/tcp_options.h
index 61d5828c27..a31a8f24d9 100644
--- a/src/core/tcp_options.h
+++ b/src/core/tcp_options.h
@@ -114,6 +114,7 @@ struct cfg_group_tcp{
 	int max_connections; /* max tcp connections (includes tls connections) */
 	int max_tls_connections; /* max tls connections */
 	int no_connect; /* do not open any new tcp connection (but accept them) */
+	int reject_new_tcp_conn; /* rejeect new connections */
 	int fd_cache; /* on /off */
 	/* tcp async options */
 	int async; /* on / off */
-- 
2.30.2

