seperated thread for each connection

This commit is contained in:
mrbesen 2023-01-15 18:33:33 +01:00
parent af4ad93292
commit 4135fe740b
Signed by: MrBesen
GPG Key ID: 596B2350DCD67504
1 changed files with 23 additions and 38 deletions

View File

@ -23,9 +23,7 @@ const static uint16_t PORT = 8956;
static bool run = true;
std::mutex lock;
std::condition_variable lock_cv; // not empty or eol
std::list<int> clients;
std::list<std::thread*> clients;
void sig_handler(int sig_num) {
std::cerr << "signalHandler triggered" << std::endl;
@ -138,6 +136,11 @@ void clientShell( int client ) {
int sockVal = 1;
::setsockopt( client, SOL_TCP, TCP_NODELAY, &sockVal, 4);
sendInstant(
"\033[90m╔═════════════╗\n"
"\033[90m║ \033[94mHacker 9000 \033[90m║\n"
"\033[90m╚═════════════╝\033[0m\n", client);
sendTyped("Bonjour Eliot!\n\nWhat is your target?\n", client);
const std::string target = read(client);
@ -197,26 +200,6 @@ void clientShell( int client ) {
::close( client );
}
void backgroundTask() {
while ( run ) {
int nextClient = -1;
{
std::unique_lock<std::mutex> guard(lock);
if( clients.empty() ) {
lock_cv.wait(guard);
}
if ( clients.empty() ) {
// no more clients
break;
}
nextClient = clients.front();
clients.pop_front();
}
clientShell( nextClient );
}
}
int main () {
// init rand seed
srand(time(NULL));
@ -244,10 +227,9 @@ int main () {
return 1;
}
std::thread backgroundThread( backgroundTask );
::signal(SIGINT, sig_handler);
::signal(SIGTERM, sig_handler);
::signal(SIGPIPE, SIG_IGN);
while ( run ) {
int status = pollSocket( sock );
@ -260,24 +242,27 @@ int main () {
inet_ntop(addr.sin6_family, &addr.sin6_addr, buffer, INET6_ADDRSTRLEN);
std::cout << "accepted Client: " << buffer << std::endl;
{
std::lock_guard<std::mutex> guard(lock);
clients.push_back( client );
clients.push_back( new std::thread(clientShell, client) );
}
if ( clients.size() > 1000 ) {
for ( uint32_t i = 0; i < 500; ++i ) {
std::thread* th = clients.front();
clients.pop_front();
if( th->joinable() ) {
th->join();
}
delete th;
}
lock_cv.notify_one();
}
}
}
// notify thread
{
std::lock_guard<std::mutex> guard(lock);
clients.clear();
}
lock_cv.notify_all();
if( backgroundThread.joinable() ) {
backgroundThread.join();
for ( std::thread* th : clients ) {
if( th->joinable() ) {
th->join();
}
delete th;
}
::close(sock);