X-Git-Url: https://git.stg.codes/stg.git/blobdiff_plain/641204dfbdb9fc870cdd2e7f9e3169a44693e7bf..2574a28cbf000603bc31f61593dbf061ff56c1d5:/projects/rscriptd/listener.cpp diff --git a/projects/rscriptd/listener.cpp b/projects/rscriptd/listener.cpp index 87a85ebb..e4f1e2cd 100644 --- a/projects/rscriptd/listener.cpp +++ b/projects/rscriptd/listener.cpp @@ -19,6 +19,20 @@ * Author : Maxim Mamontov */ +#include "listener.h" + +#include "stg/scriptexecuter.h" +#include "stg/common.h" +#include "stg/const.h" + +#include +#include +#include +#include +#include +#include +#include + #include #include // readv #include // for historical versions of BSD @@ -26,33 +40,21 @@ #include #include -#include -#include -#include -#include -#include - -#include "listener.h" -#include "script_executer.h" -#include "stg_locker.h" -#include "common.h" +void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password); //----------------------------------------------------------------------------- LISTENER::LISTENER() - : WriteServLog(GetStgLogger()), + : WriteServLog(STG::Logger::get()), port(0), - running(false), receiverStopped(true), processorStopped(true), userTimeout(0), - listenSocket(0) + listenSocket(0), + version("rscriptd listener v.1.2") { -version = "rscriptd listener v.1.2"; - -pthread_mutex_init(&mutex, NULL); } //----------------------------------------------------------------------------- -void LISTENER::SetPassword(const string & p) +void LISTENER::SetPassword(const std::string & p) { password = p; printfd(__FILE__, "Encryption initiated with password \'%s\'\n", password.c_str()); @@ -62,30 +64,17 @@ InitEncrypt(&ctxS, password); bool LISTENER::Start() { printfd(__FILE__, "LISTENER::Start()\n"); -running = true; if (PrepareNet()) { return true; } -if (receiverStopped) - { - if (pthread_create(&receiverThread, NULL, Run, this)) - { - errorStr = "Cannot create thread."; - return true; - } - } +if (!m_receiverThread.joinable()) + m_receiverThread = std::jthread([this](auto token){ Run(std::move(token)); }); -if (processorStopped) - { - if (pthread_create(&processorThread, NULL, RunProcessor, this)) - { - errorStr = "Cannot create thread."; - return true; - } - } +if (!m_processorThread.joinable()) + m_processorThread = std::jthread([this](auto token){ RunProcessor(std::move(token)); }); errorStr = ""; @@ -94,29 +83,24 @@ return false; //----------------------------------------------------------------------------- bool LISTENER::Stop() { -running = false; +m_receiverThread.request_stop(); +m_processorThread.request_stop(); printfd(__FILE__, "LISTENER::Stop()\n"); -usleep(500000); +std::this_thread::sleep_for(std::chrono::milliseconds(500)); if (!processorStopped) { //5 seconds to thread stops itself for (int i = 0; i < 25 && !processorStopped; i++) - { - usleep(200000); - } + std::this_thread::sleep_for(std::chrono::milliseconds(200)); //after 5 seconds waiting thread still running. now killing it if (!processorStopped) { //TODO pthread_cancel() - if (pthread_kill(processorThread, SIGINT)) - { - errorStr = "Cannot kill thread."; - return true; - } + m_processorThread.detach(); printfd(__FILE__, "LISTENER killed Timeouter\n"); } } @@ -125,78 +109,53 @@ if (!receiverStopped) { //5 seconds to thread stops itself for (int i = 0; i < 25 && !receiverStopped; i++) - { - usleep(200000); - } + std::this_thread::sleep_for(std::chrono::milliseconds(200)); //after 5 seconds waiting thread still running. now killing it if (!receiverStopped) { //TODO pthread_cancel() - if (pthread_kill(receiverThread, SIGINT)) - { - errorStr = "Cannot kill thread."; - return true; - } + m_receiverThread.detach(); printfd(__FILE__, "LISTENER killed Run\n"); } } -pthread_join(receiverThread, NULL); -pthread_join(processorThread, NULL); - -pthread_mutex_destroy(&mutex); +if (receiverStopped) + m_receiverThread.join(); +if (processorStopped) + m_processorThread.join(); FinalizeNet(); -std::for_each(users.begin(), users.end(), DisconnectUser(*this)); +for (const auto& user : users) + Disconnect(user); printfd(__FILE__, "LISTENER::Stoped successfully.\n"); return false; } //----------------------------------------------------------------------------- -void * LISTENER::Run(void * d) -{ -LISTENER * ia = static_cast(d); - -ia->Runner(); - -return NULL; -} -//----------------------------------------------------------------------------- -void LISTENER::Runner() +void LISTENER::Run(std::stop_token token) { receiverStopped = false; -while (running) - { - RecvPacket(); - } +while (!token.stop_requested()) + RecvPacket(token); receiverStopped = true; } //----------------------------------------------------------------------------- -void * LISTENER::RunProcessor(void * d) -{ -LISTENER * ia = static_cast(d); - -ia->ProcessorRunner(); - -return NULL; -} -//----------------------------------------------------------------------------- -void LISTENER::ProcessorRunner() +void LISTENER::RunProcessor(std::stop_token token) { processorStopped = false; -while (running) - { - usleep(500000); +while (!token.stop_requested()) +{ + std::this_thread::sleep_for(std::chrono::milliseconds(500)); if (!pending.empty()) ProcessPending(); ProcessTimeouts(); - } +} processorStopped = true; } @@ -211,14 +170,12 @@ if (listenSocket < 0) return true; } -printfd(__FILE__, "Port: %d\n", port); - struct sockaddr_in listenAddr; listenAddr.sin_family = AF_INET; listenAddr.sin_port = htons(port); listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0"); -if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0) +if (bind(listenSocket, reinterpret_cast(&listenAddr), sizeof(listenAddr)) < 0) { errorStr = "LISTENER: Bind failed."; return true; @@ -236,24 +193,24 @@ close(listenSocket); return false; } //----------------------------------------------------------------------------- -bool LISTENER::RecvPacket() +bool LISTENER::RecvPacket(const std::stop_token& token) { struct iovec iov[2]; char buffer[RS_MAX_PACKET_LEN]; -RS_PACKET_HEADER packetHead; +STG::RS::PACKET_HEADER packetHead; iov[0].iov_base = reinterpret_cast(&packetHead); iov[0].iov_len = sizeof(packetHead); iov[1].iov_base = buffer; -iov[1].iov_len = sizeof(buffer); +iov[1].iov_len = sizeof(buffer) - sizeof(packetHead); size_t dataLen = 0; while (dataLen < sizeof(buffer)) { if (!WaitPackets(listenSocket)) { - if (!running) + if (token.stop_requested()) return false; continue; } @@ -271,56 +228,58 @@ if (CheckHeader(packetHead)) return true; } -std::string userLogin((char *)packetHead.login); -PendingData data; -data.login = userLogin; -data.ip = ntohl(packetHead.ip); -data.id = ntohl(packetHead.id); +std::string userLogin(reinterpret_cast(packetHead.login)); +PendingData pd; +pd.data.login = userLogin; +pd.data.ip = ntohl(packetHead.ip); +pd.data.id = ntohl(packetHead.id); if (packetHead.packetType == RS_ALIVE_PACKET) { - data.type = PendingData::ALIVE; + pd.type = PendingData::ALIVE; } else if (packetHead.packetType == RS_CONNECT_PACKET) { - data.type = PendingData::CONNECT; - if (GetParams(buffer, data)) + pd.type = PendingData::CONNECT; + if (GetParams(buffer, pd.data)) { return true; } } else if (packetHead.packetType == RS_DISCONNECT_PACKET) { - data.type = PendingData::DISCONNECT; - if (GetParams(buffer, data)) + pd.type = PendingData::DISCONNECT; + if (GetParams(buffer, pd.data)) { return true; } } +else + return true; -STG_LOCKER lock(&mutex, __FILE__, __LINE__); -pending.push_back(data); +std::lock_guard lock(m_mutex); +pending.push_back(pd); return false; } //----------------------------------------------------------------------------- bool LISTENER::GetParams(char * buffer, UserData & data) { -RS_PACKET_TAIL packetTail; +STG::RS::PACKET_TAIL packetTail; -Decrypt(&ctxS, (char *)&packetTail, buffer, sizeof(packetTail) / 8); +DecryptString(&packetTail, buffer, sizeof(packetTail), &ctxS); -if (strncmp((char *)packetTail.magic, RS_ID, RS_MAGIC_LEN)) +if (strncmp(reinterpret_cast(packetTail.magic), RS_ID, RS_MAGIC_LEN)) { printfd(__FILE__, "Invalid crypto magic\n"); return true; } -std::stringstream params; -params << data.login << " " +std::ostringstream params; +params << "\"" << data.login << "\" " << inet_ntostring(data.ip) << " " - << ntohl(data.id) << " " - << (char *)packetTail.params; + << data.id << " " + << reinterpret_cast(packetTail.params); data.params = params.str(); @@ -329,84 +288,92 @@ return false; //----------------------------------------------------------------------------- void LISTENER::ProcessPending() { -printfd(__FILE__, "Pending data size: %d\n", pending.size()); -std::list::iterator it(pending.begin()); -while (it != pending.end()) +auto it = pending.begin(); +size_t count = 0; +printfd(__FILE__, "Pending: %d\n", pending.size()); +while (it != pending.end() && count < 256) { - std::vector::iterator uit( - std::lower_bound( - users.begin(), - users.end(), - it->login) - ); + auto uit = std::lower_bound(users.begin(), users.end(), it->data.login); if (it->type == PendingData::CONNECT) { - if (uit == users.end() || uit->login != it->login) + printfd(__FILE__, "Connect packet\n"); + if (uit == users.end() || uit->data.login != it->data.login) { + printfd(__FILE__, "Connect new user '%s'\n", it->data.login.c_str()); // Add new user Connect(*it); - users.insert(uit, AliveData(static_cast(*it))); + users.insert(uit, AliveData(it->data)); } - else if (uit->login == it->login) + else { + printfd(__FILE__, "Update existing user '%s'\n", it->data.login.c_str()); // Update already existing user time(&uit->lastAlive); - uit->params = it->params; + uit->data.params = it->data.params; } } else if (it->type == PendingData::ALIVE) { - if (uit != users.end() && uit->login == it->login) + printfd(__FILE__, "Alive packet\n"); + if (uit != users.end() && uit->data.login == it->data.login) { + printfd(__FILE__, "Alive user '%s'\n", it->data.login.c_str()); // Update existing user time(&uit->lastAlive); } + else + { + printfd(__FILE__, "Alive user '%s' is not found\n", it->data.login.c_str()); + } } else if (it->type == PendingData::DISCONNECT) { - if (uit != users.end() && uit->login == it->login.c_str()) + printfd(__FILE__, "Disconnect packet\n"); + if (uit != users.end() && uit->data.login == it->data.login.c_str()) { + printfd(__FILE__, "Disconnect user '%s'\n", it->data.login.c_str()); // Disconnect existing user + uit->data.params = it->data.params; Disconnect(*uit); users.erase(uit); } + else + { + printfd(__FILE__, "Cannot find user '%s' for disconnect\n", it->data.login.c_str()); + } } - - STG_LOCKER lock(&mutex, __FILE__, __LINE__); - pending.erase(it++); + else + { + printfd(__FILE__, "Unknown packet type\n"); + } + ++it; + ++count; } +std::lock_guard lock(m_mutex); +pending.erase(pending.begin(), it); } //----------------------------------------------------------------------------- void LISTENER::ProcessTimeouts() { -const std::vector::iterator it( - std::stable_partition( - users.begin(), - users.end(), - IsNotTimedOut(userTimeout) - ) - ); +const auto now = time(nullptr); +const auto it = std::stable_partition(users.begin(), users.end(), [this, now](const auto& data){ return difftime(now, data.lastAlive) < userTimeout; }); if (it != users.end()) { printfd(__FILE__, "Total users: %d, users to disconnect: %d\n", users.size(), std::distance(it, users.end())); - std::for_each( - it, - users.end(), - DisconnectUser(*this) - ); + std::for_each(it, users.end(), [this](const auto& user){ Disconnect(user);}); users.erase(it, users.end()); } } //----------------------------------------------------------------------------- -bool LISTENER::Connect(const UserData & data) const +bool LISTENER::Connect(const PendingData & pd) const { -printfd(__FILE__, "Connect %s\n", data.login.c_str()); +printfd(__FILE__, "Connect %s\n", pd.data.login.c_str()); if (access(scriptOnConnect.c_str(), X_OK) == 0) { - if (ScriptExec(scriptOnConnect + " " + data.params)) + if (ScriptExec((scriptOnConnect + " " + pd.data.params).c_str())) { WriteServLog("Script %s cannot be executed for an unknown reason.", scriptOnConnect.c_str()); return true; @@ -420,12 +387,12 @@ else return false; } //----------------------------------------------------------------------------- -bool LISTENER::Disconnect(const UserData & data) const +bool LISTENER::Disconnect(const AliveData& ad) const { -printfd(__FILE__, "Disconnect %s\n", data.login.c_str()); +printfd(__FILE__, "Disconnect %s\n", ad.data.login.c_str()); if (access(scriptOnDisconnect.c_str(), X_OK) == 0) { - if (ScriptExec(scriptOnDisconnect + " " + data.params)) + if (ScriptExec((scriptOnDisconnect + " " + ad.data.params).c_str())) { WriteServLog("Script %s cannot be executed for an unknown reson.", scriptOnDisconnect.c_str()); return true; @@ -439,61 +406,20 @@ else return false; } //----------------------------------------------------------------------------- -void LISTENER::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) +bool LISTENER::CheckHeader(const STG::RS::PACKET_HEADER & header) const { -unsigned char keyL[PASSWD_LEN]; -memset(keyL, 0, PASSWD_LEN); -strncpy((char *)keyL, password.c_str(), PASSWD_LEN); -Blowfish_Init(ctx, keyL, PASSWD_LEN); -} -//----------------------------------------------------------------------------- -void LISTENER::Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8) -{ -if (dst != src) - memcpy(dst, src, len8 * 8); - -for (int i = 0; i < len8; i++) - Blowfish_Decrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4)); -} -//----------------------------------------------------------------------------- -bool LISTENER::CheckHeader(const RS_PACKET_HEADER & header) const -{ -if (strncmp((char *)header.magic, RS_ID, RS_MAGIC_LEN)) - { +if (strncmp(reinterpret_cast(header.magic), RS_ID, RS_MAGIC_LEN)) return true; - } -if (strncmp((char *)header.protoVer, "02", RS_PROTO_VER_LEN)) - { +if (strncmp(reinterpret_cast(header.protoVer), "02", RS_PROTO_VER_LEN)) return true; - } return false; } //----------------------------------------------------------------------------- -bool LISTENER::WaitPackets(int sd) const +void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) { -fd_set rfds; -FD_ZERO(&rfds); -FD_SET(sd, &rfds); - -struct timeval tv; -tv.tv_sec = 0; -tv.tv_usec = 500000; - -int res = select(sd + 1, &rfds, NULL, NULL, &tv); -if (res == -1) // Error - { - if (errno != EINTR) - { - printfd(__FILE__, "Error on select: '%s'\n", strerror(errno)); - } - return false; - } - -if (res == 0) // Timeout - { - return false; - } - -return true; +char keyL[PASSWD_LEN]; +memset(keyL, 0, PASSWD_LEN); +strncpy(keyL, password.c_str(), PASSWD_LEN); +Blowfish_Init(ctx, keyL, PASSWD_LEN); } //-----------------------------------------------------------------------------