2  *    This program is free software; you can redistribute it and/or modify
 
   3  *    it under the terms of the GNU General Public License as published by
 
   4  *    the Free Software Foundation; either version 2 of the License, or
 
   5  *    (at your option) any later version.
 
   7  *    This program is distributed in the hope that it will be useful,
 
   8  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
   9  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  10  *    GNU General Public License for more details.
 
  12  *    You should have received a copy of the GNU General Public License
 
  13  *    along with this program; if not, write to the Free Software
 
  14  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
  18  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
 
  19  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
 
  24 #include "stg/scriptexecuter.h"
 
  25 #include "stg/locker.h"
 
  26 #include "stg/common.h"
 
  27 #include "stg/const.h"
 
  37 #include <arpa/inet.h>
 
  38 #include <sys/uio.h> // readv
 
  39 #include <sys/types.h> // for historical versions of BSD
 
  40 #include <sys/socket.h>
 
  41 #include <netinet/in.h>
 
  44 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
 
  46 //-----------------------------------------------------------------------------
 
  48     : WriteServLog(STG::Logger::get()),
 
  50       receiverStopped(true),
 
  51       processorStopped(true),
 
  54       version("rscriptd listener v.1.2")
 
  57 //-----------------------------------------------------------------------------
 
  58 void LISTENER::SetPassword(const std::string & p)
 
  61 printfd(__FILE__, "Encryption initiated with password \'%s\'\n", password.c_str());
 
  62 InitEncrypt(&ctxS, password);
 
  64 //-----------------------------------------------------------------------------
 
  65 bool LISTENER::Start()
 
  67 printfd(__FILE__, "LISTENER::Start()\n");
 
  74 if (!m_receiverThread.joinable())
 
  75     m_receiverThread = std::jthread([this](auto token){ Run(std::move(token)); });
 
  77 if (!m_processorThread.joinable())
 
  78     m_processorThread = std::jthread([this](auto token){ RunProcessor(std::move(token)); });
 
  84 //-----------------------------------------------------------------------------
 
  87 m_receiverThread.request_stop();
 
  88 m_processorThread.request_stop();
 
  90 printfd(__FILE__, "LISTENER::Stop()\n");
 
  92 std::this_thread::sleep_for(std::chrono::milliseconds(500));
 
  94 if (!processorStopped)
 
  96     //5 seconds to thread stops itself
 
  97     for (int i = 0; i < 25 && !processorStopped; i++)
 
  98         std::this_thread::sleep_for(std::chrono::milliseconds(200));
 
 100     //after 5 seconds waiting thread still running. now killing it
 
 101     if (!processorStopped)
 
 103         //TODO pthread_cancel()
 
 104         m_processorThread.detach();
 
 105         printfd(__FILE__, "LISTENER killed Timeouter\n");
 
 109 if (!receiverStopped)
 
 111     //5 seconds to thread stops itself
 
 112     for (int i = 0; i < 25 && !receiverStopped; i++)
 
 113         std::this_thread::sleep_for(std::chrono::milliseconds(200));
 
 115     //after 5 seconds waiting thread still running. now killing it
 
 116     if (!receiverStopped)
 
 118         //TODO pthread_cancel()
 
 119         m_receiverThread.detach();
 
 120         printfd(__FILE__, "LISTENER killed Run\n");
 
 125     m_receiverThread.join();
 
 126 if (processorStopped)
 
 127     m_processorThread.join();
 
 131 for (const auto& user : users)
 
 134 printfd(__FILE__, "LISTENER::Stoped successfully.\n");
 
 138 //-----------------------------------------------------------------------------
 
 139 void LISTENER::Run(std::stop_token token)
 
 141 receiverStopped = false;
 
 143 while (!token.stop_requested())
 
 146 receiverStopped = true;
 
 148 //-----------------------------------------------------------------------------
 
 149 void LISTENER::RunProcessor(std::stop_token token)
 
 151 processorStopped = false;
 
 153 while (!token.stop_requested())
 
 155     std::this_thread::sleep_for(std::chrono::milliseconds(500));
 
 156     if (!pending.empty())
 
 161 processorStopped = true;
 
 163 //-----------------------------------------------------------------------------
 
 164 bool LISTENER::PrepareNet()
 
 166 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
 
 168 if (listenSocket < 0)
 
 170     errorStr = "Cannot create socket.";
 
 174 struct sockaddr_in listenAddr;
 
 175 listenAddr.sin_family = AF_INET;
 
 176 listenAddr.sin_port = htons(port);
 
 177 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
 
 179 if (bind(listenSocket, reinterpret_cast<sockaddr*>(&listenAddr), sizeof(listenAddr)) < 0)
 
 181     errorStr = "LISTENER: Bind failed.";
 
 185 printfd(__FILE__, "LISTENER::PrepareNet() >>>> Start successfull.\n");
 
 189 //-----------------------------------------------------------------------------
 
 190 bool LISTENER::FinalizeNet()
 
 196 //-----------------------------------------------------------------------------
 
 197 bool LISTENER::RecvPacket(const std::stop_token& token)
 
 201 char buffer[RS_MAX_PACKET_LEN];
 
 202 RS::PACKET_HEADER packetHead;
 
 204 iov[0].iov_base = reinterpret_cast<char *>(&packetHead);
 
 205 iov[0].iov_len = sizeof(packetHead);
 
 206 iov[1].iov_base = buffer;
 
 207 iov[1].iov_len = sizeof(buffer) - sizeof(packetHead);
 
 210 while (dataLen < sizeof(buffer))
 
 212     if (!WaitPackets(listenSocket))
 
 214         if (token.stop_requested())
 
 218     int portion = readv(listenSocket, iov, 2);
 
 226 if (CheckHeader(packetHead))
 
 228     printfd(__FILE__, "Invalid packet or incorrect protocol version!\n");
 
 232 std::string userLogin(reinterpret_cast<const char*>(packetHead.login));
 
 234 pd.data.login = userLogin;
 
 235 pd.data.ip = ntohl(packetHead.ip);
 
 236 pd.data.id = ntohl(packetHead.id);
 
 238 if (packetHead.packetType == RS_ALIVE_PACKET)
 
 240     pd.type = PendingData::ALIVE;
 
 242 else if (packetHead.packetType == RS_CONNECT_PACKET)
 
 244     pd.type = PendingData::CONNECT;
 
 245     if (GetParams(buffer, pd.data))
 
 250 else if (packetHead.packetType == RS_DISCONNECT_PACKET)
 
 252     pd.type = PendingData::DISCONNECT;
 
 253     if (GetParams(buffer, pd.data))
 
 261 std::lock_guard lock(m_mutex);
 
 262 pending.push_back(pd);
 
 266 //-----------------------------------------------------------------------------
 
 267 bool LISTENER::GetParams(char * buffer, UserData & data)
 
 269 RS::PACKET_TAIL packetTail;
 
 271 DecryptString(&packetTail, buffer, sizeof(packetTail), &ctxS);
 
 273 if (strncmp(reinterpret_cast<const char*>(packetTail.magic), RS_ID, RS_MAGIC_LEN))
 
 275     printfd(__FILE__, "Invalid crypto magic\n");
 
 279 std::ostringstream params;
 
 280 params << "\"" << data.login << "\" "
 
 281        << inet_ntostring(data.ip) << " "
 
 283        << reinterpret_cast<const char*>(packetTail.params);
 
 285 data.params = params.str();
 
 289 //-----------------------------------------------------------------------------
 
 290 void LISTENER::ProcessPending()
 
 292 auto it = pending.begin();
 
 294 printfd(__FILE__, "Pending: %d\n", pending.size());
 
 295 while (it != pending.end() && count < 256)
 
 297     auto uit = std::lower_bound(users.begin(), users.end(), it->data.login);
 
 298     if (it->type == PendingData::CONNECT)
 
 300         printfd(__FILE__, "Connect packet\n");
 
 301         if (uit == users.end() || uit->data.login != it->data.login)
 
 303             printfd(__FILE__, "Connect new user '%s'\n", it->data.login.c_str());
 
 306             users.insert(uit, AliveData(it->data));
 
 310             printfd(__FILE__, "Update existing user '%s'\n", it->data.login.c_str());
 
 311             // Update already existing user
 
 312             time(&uit->lastAlive);
 
 313             uit->data.params = it->data.params;
 
 316     else if (it->type == PendingData::ALIVE)
 
 318         printfd(__FILE__, "Alive packet\n");
 
 319         if (uit != users.end() && uit->data.login == it->data.login)
 
 321             printfd(__FILE__, "Alive user '%s'\n", it->data.login.c_str());
 
 322             // Update existing user
 
 323             time(&uit->lastAlive);
 
 327             printfd(__FILE__, "Alive user '%s' is not found\n", it->data.login.c_str());
 
 330     else if (it->type == PendingData::DISCONNECT)
 
 332         printfd(__FILE__, "Disconnect packet\n");
 
 333         if (uit != users.end() && uit->data.login == it->data.login.c_str())
 
 335             printfd(__FILE__, "Disconnect user '%s'\n", it->data.login.c_str());
 
 336             // Disconnect existing user
 
 337             uit->data.params = it->data.params;
 
 343             printfd(__FILE__, "Cannot find user '%s' for disconnect\n", it->data.login.c_str());
 
 348         printfd(__FILE__, "Unknown packet type\n");
 
 353 std::lock_guard lock(m_mutex);
 
 354 pending.erase(pending.begin(), it);
 
 356 //-----------------------------------------------------------------------------
 
 357 void LISTENER::ProcessTimeouts()
 
 359 const auto now = time(nullptr);
 
 360 const auto it = std::stable_partition(users.begin(), users.end(), [this, now](const auto& data){ return difftime(now, data.lastAlive) < userTimeout; });
 
 362 if (it != users.end())
 
 364     printfd(__FILE__, "Total users: %d, users to disconnect: %d\n", users.size(), std::distance(it, users.end()));
 
 366     std::for_each(it, users.end(), [this](const auto& user){ Disconnect(user);});
 
 368     users.erase(it, users.end());
 
 371 //-----------------------------------------------------------------------------
 
 372 bool LISTENER::Connect(const PendingData & pd) const
 
 374 printfd(__FILE__, "Connect %s\n", pd.data.login.c_str());
 
 375 if (access(scriptOnConnect.c_str(), X_OK) == 0)
 
 377     if (ScriptExec((scriptOnConnect + " " + pd.data.params).c_str()))
 
 379         WriteServLog("Script %s cannot be executed for an unknown reason.", scriptOnConnect.c_str());
 
 385     WriteServLog("Script %s cannot be executed. File not found.", scriptOnConnect.c_str());
 
 390 //-----------------------------------------------------------------------------
 
 391 bool LISTENER::Disconnect(const AliveData& ad) const
 
 393 printfd(__FILE__, "Disconnect %s\n", ad.data.login.c_str());
 
 394 if (access(scriptOnDisconnect.c_str(), X_OK) == 0)
 
 396     if (ScriptExec((scriptOnDisconnect + " " + ad.data.params).c_str()))
 
 398         WriteServLog("Script %s cannot be executed for an unknown reson.", scriptOnDisconnect.c_str());
 
 404     WriteServLog("Script %s cannot be executed. File not found.", scriptOnDisconnect.c_str());
 
 409 //-----------------------------------------------------------------------------
 
 410 bool LISTENER::CheckHeader(const RS::PACKET_HEADER & header) const
 
 412 if (strncmp(reinterpret_cast<const char*>(header.magic), RS_ID, RS_MAGIC_LEN))
 
 414 if (strncmp(reinterpret_cast<const char*>(header.protoVer), "02", RS_PROTO_VER_LEN))
 
 418 //-----------------------------------------------------------------------------
 
 419 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
 
 421 char keyL[PASSWD_LEN];
 
 422 memset(keyL, 0, PASSWD_LEN);
 
 423 strncpy(keyL, password.c_str(), PASSWD_LEN);
 
 424 Blowfish_Init(ctx, keyL, PASSWD_LEN);
 
 426 //-----------------------------------------------------------------------------