]> git.stg.codes - stg.git/blob - projects/rscriptd/listener.cpp
a1193527b9bc3d7c9f4f9969e6bcf31655c6b8bd
[stg.git] / projects / rscriptd / listener.cpp
1 /*
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.
6  *
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.
11  *
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
15  */
16
17 /*
18  *    Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
19  *    Author : Maxim Mamontov <faust@stargazer.dp.ua>
20  */
21
22 #include "listener.h"
23
24 #include "stg/scriptexecuter.h"
25 #include "stg/locker.h"
26 #include "stg/common.h"
27 #include "stg/const.h"
28
29 #include <sstream>
30 #include <algorithm>
31 #include <chrono>
32 #include <csignal>
33 #include <cerrno>
34 #include <ctime>
35 #include <cstring>
36
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>
42 #include <unistd.h>
43
44 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
45
46 //-----------------------------------------------------------------------------
47 LISTENER::LISTENER()
48     : WriteServLog(STG::Logger::get()),
49       port(0),
50       receiverStopped(true),
51       processorStopped(true),
52       userTimeout(0),
53       listenSocket(0),
54       version("rscriptd listener v.1.2")
55 {
56 }
57 //-----------------------------------------------------------------------------
58 void LISTENER::SetPassword(const std::string & p)
59 {
60 password = p;
61 printfd(__FILE__, "Encryption initiated with password \'%s\'\n", password.c_str());
62 InitEncrypt(&ctxS, password);
63 }
64 //-----------------------------------------------------------------------------
65 bool LISTENER::Start()
66 {
67 printfd(__FILE__, "LISTENER::Start()\n");
68
69 if (PrepareNet())
70     {
71     return true;
72     }
73
74 if (!m_receiverThread.joinable())
75     m_receiverThread = std::jthread([this](auto token){ Run(std::move(token)); });
76
77 if (!m_processorThread.joinable())
78     m_processorThread = std::jthread([this](auto token){ RunProcessor(std::move(token)); });
79
80 errorStr = "";
81
82 return false;
83 }
84 //-----------------------------------------------------------------------------
85 bool LISTENER::Stop()
86 {
87 m_receiverThread.request_stop();
88 m_processorThread.request_stop();
89
90 printfd(__FILE__, "LISTENER::Stop()\n");
91
92 std::this_thread::sleep_for(std::chrono::milliseconds(500));
93
94 if (!processorStopped)
95     {
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));
99
100     //after 5 seconds waiting thread still running. now killing it
101     if (!processorStopped)
102         {
103         //TODO pthread_cancel()
104         m_processorThread.detach();
105         printfd(__FILE__, "LISTENER killed Timeouter\n");
106         }
107     }
108
109 if (!receiverStopped)
110     {
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));
114
115     //after 5 seconds waiting thread still running. now killing it
116     if (!receiverStopped)
117         {
118         //TODO pthread_cancel()
119         m_receiverThread.detach();
120         printfd(__FILE__, "LISTENER killed Run\n");
121         }
122     }
123
124 if (receiverStopped)
125     m_receiverThread.join();
126 if (processorStopped)
127     m_processorThread.join();
128
129 FinalizeNet();
130
131 for (const auto& user : users)
132     Disconnect(user);
133
134 printfd(__FILE__, "LISTENER::Stoped successfully.\n");
135
136 return false;
137 }
138 //-----------------------------------------------------------------------------
139 void LISTENER::Run(std::stop_token token)
140 {
141 receiverStopped = false;
142
143 while (!token.stop_requested())
144     RecvPacket(token);
145
146 receiverStopped = true;
147 }
148 //-----------------------------------------------------------------------------
149 void LISTENER::RunProcessor(std::stop_token token)
150 {
151 processorStopped = false;
152
153 while (!token.stop_requested())
154 {
155     std::this_thread::sleep_for(std::chrono::milliseconds(500));
156     if (!pending.empty())
157         ProcessPending();
158     ProcessTimeouts();
159 }
160
161 processorStopped = true;
162 }
163 //-----------------------------------------------------------------------------
164 bool LISTENER::PrepareNet()
165 {
166 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
167
168 if (listenSocket < 0)
169     {
170     errorStr = "Cannot create socket.";
171     return true;
172     }
173
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");
178
179 if (bind(listenSocket, reinterpret_cast<sockaddr*>(&listenAddr), sizeof(listenAddr)) < 0)
180     {
181     errorStr = "LISTENER: Bind failed.";
182     return true;
183     }
184
185 printfd(__FILE__, "LISTENER::PrepareNet() >>>> Start successfull.\n");
186
187 return false;
188 }
189 //-----------------------------------------------------------------------------
190 bool LISTENER::FinalizeNet()
191 {
192 close(listenSocket);
193
194 return false;
195 }
196 //-----------------------------------------------------------------------------
197 bool LISTENER::RecvPacket(const std::stop_token& token)
198 {
199 struct iovec iov[2];
200
201 char buffer[RS_MAX_PACKET_LEN];
202 STG::RS::PACKET_HEADER packetHead;
203
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);
208
209 size_t dataLen = 0;
210 while (dataLen < sizeof(buffer))
211     {
212     if (!WaitPackets(listenSocket))
213         {
214         if (token.stop_requested())
215             return false;
216         continue;
217         }
218     int portion = readv(listenSocket, iov, 2);
219     if (portion < 0)
220         {
221         return true;
222         }
223     dataLen += portion;
224     }
225
226 if (CheckHeader(packetHead))
227     {
228     printfd(__FILE__, "Invalid packet or incorrect protocol version!\n");
229     return true;
230     }
231
232 std::string userLogin(reinterpret_cast<const char*>(packetHead.login));
233 PendingData pd;
234 pd.data.login = userLogin;
235 pd.data.ip = ntohl(packetHead.ip);
236 pd.data.id = ntohl(packetHead.id);
237
238 if (packetHead.packetType == RS_ALIVE_PACKET)
239     {
240     pd.type = PendingData::ALIVE;
241     }
242 else if (packetHead.packetType == RS_CONNECT_PACKET)
243     {
244     pd.type = PendingData::CONNECT;
245     if (GetParams(buffer, pd.data))
246         {
247         return true;
248         }
249     }
250 else if (packetHead.packetType == RS_DISCONNECT_PACKET)
251     {
252     pd.type = PendingData::DISCONNECT;
253     if (GetParams(buffer, pd.data))
254         {
255         return true;
256         }
257     }
258 else
259     return true;
260
261 std::lock_guard lock(m_mutex);
262 pending.push_back(pd);
263
264 return false;
265 }
266 //-----------------------------------------------------------------------------
267 bool LISTENER::GetParams(char * buffer, UserData & data)
268 {
269 STG::RS::PACKET_TAIL packetTail;
270
271 DecryptString(&packetTail, buffer, sizeof(packetTail), &ctxS);
272
273 if (strncmp(reinterpret_cast<const char*>(packetTail.magic), RS_ID, RS_MAGIC_LEN))
274     {
275     printfd(__FILE__, "Invalid crypto magic\n");
276     return true;
277     }
278
279 std::ostringstream params;
280 params << "\"" << data.login << "\" "
281        << inet_ntostring(data.ip) << " "
282        << data.id << " "
283        << reinterpret_cast<const char*>(packetTail.params);
284
285 data.params = params.str();
286
287 return false;
288 }
289 //-----------------------------------------------------------------------------
290 void LISTENER::ProcessPending()
291 {
292 auto it = pending.begin();
293 size_t count = 0;
294 printfd(__FILE__, "Pending: %d\n", pending.size());
295 while (it != pending.end() && count < 256)
296     {
297     auto uit = std::lower_bound(users.begin(), users.end(), it->data.login);
298     if (it->type == PendingData::CONNECT)
299         {
300         printfd(__FILE__, "Connect packet\n");
301         if (uit == users.end() || uit->data.login != it->data.login)
302             {
303             printfd(__FILE__, "Connect new user '%s'\n", it->data.login.c_str());
304             // Add new user
305             Connect(*it);
306             users.insert(uit, AliveData(it->data));
307             }
308         else
309             {
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;
314             }
315         }
316     else if (it->type == PendingData::ALIVE)
317         {
318         printfd(__FILE__, "Alive packet\n");
319         if (uit != users.end() && uit->data.login == it->data.login)
320             {
321             printfd(__FILE__, "Alive user '%s'\n", it->data.login.c_str());
322             // Update existing user
323             time(&uit->lastAlive);
324             }
325         else
326             {
327             printfd(__FILE__, "Alive user '%s' is not found\n", it->data.login.c_str());
328             }
329         }
330     else if (it->type == PendingData::DISCONNECT)
331         {
332         printfd(__FILE__, "Disconnect packet\n");
333         if (uit != users.end() && uit->data.login == it->data.login.c_str())
334             {
335             printfd(__FILE__, "Disconnect user '%s'\n", it->data.login.c_str());
336             // Disconnect existing user
337             uit->data.params = it->data.params;
338             Disconnect(*uit);
339             users.erase(uit);
340             }
341         else
342             {
343             printfd(__FILE__, "Cannot find user '%s' for disconnect\n", it->data.login.c_str());
344             }
345         }
346     else
347         {
348         printfd(__FILE__, "Unknown packet type\n");
349         }
350     ++it;
351     ++count;
352     }
353 std::lock_guard lock(m_mutex);
354 pending.erase(pending.begin(), it);
355 }
356 //-----------------------------------------------------------------------------
357 void LISTENER::ProcessTimeouts()
358 {
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; });
361
362 if (it != users.end())
363     {
364     printfd(__FILE__, "Total users: %d, users to disconnect: %d\n", users.size(), std::distance(it, users.end()));
365
366     std::for_each(it, users.end(), [this](const auto& user){ Disconnect(user);});
367
368     users.erase(it, users.end());
369     }
370 }
371 //-----------------------------------------------------------------------------
372 bool LISTENER::Connect(const PendingData & pd) const
373 {
374 printfd(__FILE__, "Connect %s\n", pd.data.login.c_str());
375 if (access(scriptOnConnect.c_str(), X_OK) == 0)
376     {
377     if (ScriptExec((scriptOnConnect + " " + pd.data.params).c_str()))
378         {
379         WriteServLog("Script %s cannot be executed for an unknown reason.", scriptOnConnect.c_str());
380         return true;
381         }
382     }
383 else
384     {
385     WriteServLog("Script %s cannot be executed. File not found.", scriptOnConnect.c_str());
386     return true;
387     }
388 return false;
389 }
390 //-----------------------------------------------------------------------------
391 bool LISTENER::Disconnect(const AliveData& ad) const
392 {
393 printfd(__FILE__, "Disconnect %s\n", ad.data.login.c_str());
394 if (access(scriptOnDisconnect.c_str(), X_OK) == 0)
395     {
396     if (ScriptExec((scriptOnDisconnect + " " + ad.data.params).c_str()))
397         {
398         WriteServLog("Script %s cannot be executed for an unknown reson.", scriptOnDisconnect.c_str());
399         return true;
400         }
401     }
402 else
403     {
404     WriteServLog("Script %s cannot be executed. File not found.", scriptOnDisconnect.c_str());
405     return true;
406     }
407 return false;
408 }
409 //-----------------------------------------------------------------------------
410 bool LISTENER::CheckHeader(const STG::RS::PACKET_HEADER & header) const
411 {
412 if (strncmp(reinterpret_cast<const char*>(header.magic), RS_ID, RS_MAGIC_LEN))
413     return true;
414 if (strncmp(reinterpret_cast<const char*>(header.protoVer), "02", RS_PROTO_VER_LEN))
415     return true;
416 return false;
417 }
418 //-----------------------------------------------------------------------------
419 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
420 {
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);
425 }
426 //-----------------------------------------------------------------------------