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/common.h"
26 #include "stg/const.h"
36 #include <arpa/inet.h>
37 #include <sys/uio.h> // readv
38 #include <sys/types.h> // for historical versions of BSD
39 #include <sys/socket.h>
40 #include <netinet/in.h>
43 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
45 //-----------------------------------------------------------------------------
47 : WriteServLog(STG::Logger::get()),
49 receiverStopped(true),
50 processorStopped(true),
53 version("rscriptd listener v.1.2")
56 //-----------------------------------------------------------------------------
57 void LISTENER::SetPassword(const std::string & p)
60 printfd(__FILE__, "Encryption initiated with password \'%s\'\n", password.c_str());
61 InitEncrypt(&ctxS, password);
63 //-----------------------------------------------------------------------------
64 bool LISTENER::Start()
66 printfd(__FILE__, "LISTENER::Start()\n");
73 if (!m_receiverThread.joinable())
74 m_receiverThread = std::jthread([this](auto token){ Run(std::move(token)); });
76 if (!m_processorThread.joinable())
77 m_processorThread = std::jthread([this](auto token){ RunProcessor(std::move(token)); });
83 //-----------------------------------------------------------------------------
86 m_receiverThread.request_stop();
87 m_processorThread.request_stop();
89 printfd(__FILE__, "LISTENER::Stop()\n");
91 std::this_thread::sleep_for(std::chrono::milliseconds(500));
93 if (!processorStopped)
95 //5 seconds to thread stops itself
96 for (int i = 0; i < 25 && !processorStopped; i++)
97 std::this_thread::sleep_for(std::chrono::milliseconds(200));
99 //after 5 seconds waiting thread still running. now killing it
100 if (!processorStopped)
102 //TODO pthread_cancel()
103 m_processorThread.detach();
104 printfd(__FILE__, "LISTENER killed Timeouter\n");
108 if (!receiverStopped)
110 //5 seconds to thread stops itself
111 for (int i = 0; i < 25 && !receiverStopped; i++)
112 std::this_thread::sleep_for(std::chrono::milliseconds(200));
114 //after 5 seconds waiting thread still running. now killing it
115 if (!receiverStopped)
117 //TODO pthread_cancel()
118 m_receiverThread.detach();
119 printfd(__FILE__, "LISTENER killed Run\n");
124 m_receiverThread.join();
125 if (processorStopped)
126 m_processorThread.join();
130 for (const auto& user : users)
133 printfd(__FILE__, "LISTENER::Stoped successfully.\n");
137 //-----------------------------------------------------------------------------
138 void LISTENER::Run(std::stop_token token)
140 receiverStopped = false;
142 while (!token.stop_requested())
145 receiverStopped = true;
147 //-----------------------------------------------------------------------------
148 void LISTENER::RunProcessor(std::stop_token token)
150 processorStopped = false;
152 while (!token.stop_requested())
154 std::this_thread::sleep_for(std::chrono::milliseconds(500));
155 if (!pending.empty())
160 processorStopped = true;
162 //-----------------------------------------------------------------------------
163 bool LISTENER::PrepareNet()
165 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
167 if (listenSocket < 0)
169 errorStr = "Cannot create socket.";
173 struct sockaddr_in listenAddr;
174 listenAddr.sin_family = AF_INET;
175 listenAddr.sin_port = htons(port);
176 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
178 if (bind(listenSocket, reinterpret_cast<sockaddr*>(&listenAddr), sizeof(listenAddr)) < 0)
180 errorStr = "LISTENER: Bind failed.";
184 printfd(__FILE__, "LISTENER::PrepareNet() >>>> Start successfull.\n");
188 //-----------------------------------------------------------------------------
189 bool LISTENER::FinalizeNet()
195 //-----------------------------------------------------------------------------
196 bool LISTENER::RecvPacket(const std::stop_token& token)
200 char buffer[RS_MAX_PACKET_LEN];
201 STG::RS::PACKET_HEADER packetHead;
203 iov[0].iov_base = reinterpret_cast<char *>(&packetHead);
204 iov[0].iov_len = sizeof(packetHead);
205 iov[1].iov_base = buffer;
206 iov[1].iov_len = sizeof(buffer) - sizeof(packetHead);
209 while (dataLen < sizeof(buffer))
211 if (!WaitPackets(listenSocket))
213 if (token.stop_requested())
217 int portion = readv(listenSocket, iov, 2);
225 if (CheckHeader(packetHead))
227 printfd(__FILE__, "Invalid packet or incorrect protocol version!\n");
231 std::string userLogin(reinterpret_cast<const char*>(packetHead.login));
233 pd.data.login = userLogin;
234 pd.data.ip = ntohl(packetHead.ip);
235 pd.data.id = ntohl(packetHead.id);
237 if (packetHead.packetType == RS_ALIVE_PACKET)
239 pd.type = PendingData::ALIVE;
241 else if (packetHead.packetType == RS_CONNECT_PACKET)
243 pd.type = PendingData::CONNECT;
244 if (GetParams(buffer, pd.data))
249 else if (packetHead.packetType == RS_DISCONNECT_PACKET)
251 pd.type = PendingData::DISCONNECT;
252 if (GetParams(buffer, pd.data))
260 std::lock_guard lock(m_mutex);
261 pending.push_back(pd);
265 //-----------------------------------------------------------------------------
266 bool LISTENER::GetParams(char * buffer, UserData & data)
268 STG::RS::PACKET_TAIL packetTail;
270 DecryptString(&packetTail, buffer, sizeof(packetTail), &ctxS);
272 if (strncmp(reinterpret_cast<const char*>(packetTail.magic), RS_ID, RS_MAGIC_LEN))
274 printfd(__FILE__, "Invalid crypto magic\n");
278 std::ostringstream params;
279 params << "\"" << data.login << "\" "
280 << inet_ntostring(data.ip) << " "
282 << reinterpret_cast<const char*>(packetTail.params);
284 data.params = params.str();
288 //-----------------------------------------------------------------------------
289 void LISTENER::ProcessPending()
291 auto it = pending.begin();
293 printfd(__FILE__, "Pending: %d\n", pending.size());
294 while (it != pending.end() && count < 256)
296 auto uit = std::lower_bound(users.begin(), users.end(), it->data.login);
297 if (it->type == PendingData::CONNECT)
299 printfd(__FILE__, "Connect packet\n");
300 if (uit == users.end() || uit->data.login != it->data.login)
302 printfd(__FILE__, "Connect new user '%s'\n", it->data.login.c_str());
305 users.insert(uit, AliveData(it->data));
309 printfd(__FILE__, "Update existing user '%s'\n", it->data.login.c_str());
310 // Update already existing user
311 time(&uit->lastAlive);
312 uit->data.params = it->data.params;
315 else if (it->type == PendingData::ALIVE)
317 printfd(__FILE__, "Alive packet\n");
318 if (uit != users.end() && uit->data.login == it->data.login)
320 printfd(__FILE__, "Alive user '%s'\n", it->data.login.c_str());
321 // Update existing user
322 time(&uit->lastAlive);
326 printfd(__FILE__, "Alive user '%s' is not found\n", it->data.login.c_str());
329 else if (it->type == PendingData::DISCONNECT)
331 printfd(__FILE__, "Disconnect packet\n");
332 if (uit != users.end() && uit->data.login == it->data.login.c_str())
334 printfd(__FILE__, "Disconnect user '%s'\n", it->data.login.c_str());
335 // Disconnect existing user
336 uit->data.params = it->data.params;
342 printfd(__FILE__, "Cannot find user '%s' for disconnect\n", it->data.login.c_str());
347 printfd(__FILE__, "Unknown packet type\n");
352 std::lock_guard lock(m_mutex);
353 pending.erase(pending.begin(), it);
355 //-----------------------------------------------------------------------------
356 void LISTENER::ProcessTimeouts()
358 const auto now = time(nullptr);
359 const auto it = std::stable_partition(users.begin(), users.end(), [this, now](const auto& data){ return difftime(now, data.lastAlive) < userTimeout; });
361 if (it != users.end())
363 printfd(__FILE__, "Total users: %d, users to disconnect: %d\n", users.size(), std::distance(it, users.end()));
365 std::for_each(it, users.end(), [this](const auto& user){ Disconnect(user);});
367 users.erase(it, users.end());
370 //-----------------------------------------------------------------------------
371 bool LISTENER::Connect(const PendingData & pd) const
373 printfd(__FILE__, "Connect %s\n", pd.data.login.c_str());
374 if (access(scriptOnConnect.c_str(), X_OK) == 0)
376 if (ScriptExec((scriptOnConnect + " " + pd.data.params).c_str()))
378 WriteServLog("Script %s cannot be executed for an unknown reason.", scriptOnConnect.c_str());
384 WriteServLog("Script %s cannot be executed. File not found.", scriptOnConnect.c_str());
389 //-----------------------------------------------------------------------------
390 bool LISTENER::Disconnect(const AliveData& ad) const
392 printfd(__FILE__, "Disconnect %s\n", ad.data.login.c_str());
393 if (access(scriptOnDisconnect.c_str(), X_OK) == 0)
395 if (ScriptExec((scriptOnDisconnect + " " + ad.data.params).c_str()))
397 WriteServLog("Script %s cannot be executed for an unknown reson.", scriptOnDisconnect.c_str());
403 WriteServLog("Script %s cannot be executed. File not found.", scriptOnDisconnect.c_str());
408 //-----------------------------------------------------------------------------
409 bool LISTENER::CheckHeader(const STG::RS::PACKET_HEADER & header) const
411 if (strncmp(reinterpret_cast<const char*>(header.magic), RS_ID, RS_MAGIC_LEN))
413 if (strncmp(reinterpret_cast<const char*>(header.protoVer), "02", RS_PROTO_VER_LEN))
417 //-----------------------------------------------------------------------------
418 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
420 char keyL[PASSWD_LEN];
421 memset(keyL, 0, PASSWD_LEN);
422 strncpy(keyL, password.c_str(), PASSWD_LEN);
423 Blowfish_Init(ctx, keyL, PASSWD_LEN);
425 //-----------------------------------------------------------------------------