Skip to content

Commit 77d2b1c

Browse files
committed
Added cap on maximum simultaneous clients to prevent file descriptor exhaustion
1 parent 30f9097 commit 77d2b1c

File tree

4 files changed

+13
-0
lines changed

4 files changed

+13
-0
lines changed

src/HTTPMessage.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ enum Status {
7575

7676
// 4xx Client Error
7777
BAD_REQUEST = 400,
78+
METHOD_NOT_ALLOWED = 405,
7879
NOT_FOUND = 404,
7980

8081
// 5xx Server Error

src/HTTPResponse.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ void HTTPResponse::determineStatusCode() {
4545
status = Status(OK);
4646
} else if (reason.contains("Bad Request")) {
4747
status = Status(BAD_REQUEST);
48+
} else if (reason.contains("Method Not Allowed")) {
49+
status = Status(METHOD_NOT_ALLOWED);
4850
} else if (reason.contains("Not Found")) {
4951
status = Status(NOT_FOUND);
5052
} else if (reason.contains("Server Error")) {
@@ -70,6 +72,9 @@ void HTTPResponse::determineReasonStr() {
7072
case Status(BAD_REQUEST):
7173
reason = "Bad Request";
7274
break;
75+
case Status(METHOD_NOT_ALLOWED):
76+
reason = "Method Not Allowed";
77+
break;
7378
case Status(NOT_FOUND):
7479
reason = "Not Found";
7580
break;

src/HTTPServer.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,12 @@ void HTTPServer::acceptConnection() {
289289
if (clfd == INVALID_SOCKET)
290290
return;
291291

292+
// Reject the connection if the client limit has been reached to prevent file descriptor exhaustion
293+
if (clientMap.size() >= MAX_CLIENTS) {
294+
close(clfd);
295+
return;
296+
}
297+
292298
// Set socket as non-blocking; close and reject the connection if this fails
293299
if (fcntl(clfd, F_SETFL, O_NONBLOCK) == -1) {
294300
std::print("Failed to set client socket non-blocking, rejecting connection\n");

src/HTTPServer.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040

4141
constexpr int32_t INVALID_SOCKET = -1;
4242
constexpr uint32_t QUEUE_SIZE = 1024;
43+
constexpr uint32_t MAX_CLIENTS = 1024;
4344

4445
class HTTPServer {
4546
// Server Socket

0 commit comments

Comments
 (0)