From 8607ac169bf5e0900ce4b2563545459862c49c66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20Villac=C3=ADs=20Lasso?= Date: Tue, 7 Sep 2021 15:02:21 -0500 Subject: [PATCH] Stop accept()-ing connections if already at max connection limit The constant CONFIG_LWIP_MAX_SOCKETS, if available, tells how many sockets can be opened at once. If already at this limit, and an attempt is made to accept() an additional incoming connection from a listening socket, the accept() call will fail. Fix this by checking the socket list and refusing to add the listening socket to the set of readable sockets to check in the select() call. This will cause connections to remain in the listening backlog until some other socket is closed. --- src/AsyncTCP.cpp | 11 +++++++++-- src/AsyncTCP.h | 4 ++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/AsyncTCP.cpp b/src/AsyncTCP.cpp index f106e2a..66acd2f 100644 --- a/src/AsyncTCP.cpp +++ b/src/AsyncTCP.cpp @@ -92,12 +92,19 @@ void _asynctcpsock_task(void *) FD_ZERO(&sockSet_r); FD_ZERO(&sockSet_w); for (it = _socketBaseList.begin(); it != _socketBaseList.end(); it++) { if ((*it)->_socket != -1) { - FD_SET((*it)->_socket, &sockSet_r); +#ifdef CONFIG_LWIP_MAX_SOCKETS + if (!(*it)->_isServer() || _socketBaseList.size() < CONFIG_LWIP_MAX_SOCKETS) { +#endif + FD_SET((*it)->_socket, &sockSet_r); + if (max_sock <= (*it)->_socket) max_sock = (*it)->_socket + 1; +#ifdef CONFIG_LWIP_MAX_SOCKETS + } +#endif if ((*it)->_pendingWrite()) { FD_SET((*it)->_socket, &sockSet_w); + if (max_sock <= (*it)->_socket) max_sock = (*it)->_socket + 1; } (*it)->_selected = true; - if (max_sock <= (*it)->_socket) max_sock = (*it)->_socket + 1; } } diff --git a/src/AsyncTCP.h b/src/AsyncTCP.h index 0b70a07..9660aac 100644 --- a/src/AsyncTCP.h +++ b/src/AsyncTCP.h @@ -71,6 +71,7 @@ protected: virtual void _sockDelayedConnect(void) {} // Action to take on DNS-resolve finished virtual bool _pendingWrite(void) { return false; } // Test if there is data pending to be written + virtual bool _isServer(void) { return false; } // Will a read from this socket result in one more client? public: AsyncSocketBase(void); @@ -239,6 +240,9 @@ class AsyncServer : public AsyncSocketBase // Listening socket is readable on incoming connection void _sockIsReadable(void); + + // Mark this class as a server + bool _isServer(void) { return true; } };