]> git.stg.codes - stg.git/blob - rscriptd/listener.cpp
Port to CMake, get rid of os_int.h.
[stg.git] / 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 <arpa/inet.h>
23 #include <sys/uio.h> // readv
24 #include <sys/types.h> // for historical versions of BSD
25 #include <sys/socket.h>
26 #include <netinet/in.h>
27 #include <unistd.h>
28
29 #include <csignal>
30 #include <cerrno>
31 #include <ctime>
32 #include <cstring>
33 #include <sstream>
34 #include <algorithm>
35
36 #include "stg/scriptexecuter.h"
37 #include "stg/locker.h"
38 #include "stg/common.h"
39 #include "stg/const.h"
40 #include "listener.h"
41
42 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
43 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
44
45 //-----------------------------------------------------------------------------
46 LISTENER::LISTENER()
47     : WriteServLog(GetStgLogger()),
48       port(0),
49       running(false),
50       receiverStopped(true),
51       processorStopped(true),
52       userTimeout(0),
53       listenSocket(0),
54       version("rscriptd listener v.1.2")
55 {
56 pthread_mutex_init(&mutex, NULL);
57 }
58 //-----------------------------------------------------------------------------
59 void LISTENER::SetPassword(const std::string & p)
60 {
61 password = p;
62 printfd(__FILE__, "Encryption initiated with password \'%s\'\n", password.c_str());
63 InitEncrypt(&ctxS, password);
64 }
65 //-----------------------------------------------------------------------------
66 bool LISTENER::Start()
67 {
68 printfd(__FILE__, "LISTENER::Start()\n");
69 running = true;
70
71 if (PrepareNet())
72     {
73     return true;
74     }
75
76 if (receiverStopped)
77     {
78     if (pthread_create(&receiverThread, NULL, Run, this))
79         {
80         errorStr = "Cannot create thread.";
81         return true;
82         }
83     }
84
85 if (processorStopped)
86     {
87     if (pthread_create(&processorThread, NULL, RunProcessor, this))
88         {
89         errorStr = "Cannot create thread.";
90         return true;
91         }
92     }
93
94 errorStr = "";
95
96 return false;
97 }
98 //-----------------------------------------------------------------------------
99 bool LISTENER::Stop()
100 {
101 running = false;
102
103 printfd(__FILE__, "LISTENER::Stop()\n");
104
105 struct timespec ts = {0, 500000000};
106 nanosleep(&ts, NULL);
107
108 if (!processorStopped)
109     {
110     //5 seconds to thread stops itself
111     for (int i = 0; i < 25 && !processorStopped; i++)
112         {
113         struct timespec ts = {0, 200000000};
114         nanosleep(&ts, NULL);
115         }
116
117     //after 5 seconds waiting thread still running. now killing it
118     if (!processorStopped)
119         {
120         //TODO pthread_cancel()
121         if (pthread_kill(processorThread, SIGINT))
122             {
123             errorStr = "Cannot kill thread.";
124             return true;
125             }
126         printfd(__FILE__, "LISTENER killed Timeouter\n");
127         }
128     }
129
130 if (!receiverStopped)
131     {
132     //5 seconds to thread stops itself
133     for (int i = 0; i < 25 && !receiverStopped; i++)
134         {
135         struct timespec ts = {0, 200000000};
136         nanosleep(&ts, NULL);
137         }
138
139     //after 5 seconds waiting thread still running. now killing it
140     if (!receiverStopped)
141         {
142         //TODO pthread_cancel()
143         if (pthread_kill(receiverThread, SIGINT))
144             {
145             errorStr = "Cannot kill thread.";
146             return true;
147             }
148         printfd(__FILE__, "LISTENER killed Run\n");
149         }
150     }
151
152 pthread_join(receiverThread, NULL);
153 pthread_join(processorThread, NULL);
154
155 pthread_mutex_destroy(&mutex);
156
157 FinalizeNet();
158
159 std::for_each(users.begin(), users.end(), DisconnectUser(*this));
160
161 printfd(__FILE__, "LISTENER::Stoped successfully.\n");
162
163 return false;
164 }
165 //-----------------------------------------------------------------------------
166 void * LISTENER::Run(void * d)
167 {
168 sigset_t signalSet;
169 sigfillset(&signalSet);
170 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
171
172 LISTENER * listener = static_cast<LISTENER *>(d);
173
174 listener->Runner();
175
176 return NULL;
177 }
178 //-----------------------------------------------------------------------------
179 void LISTENER::Runner()
180 {
181 receiverStopped = false;
182
183 while (running)
184     {
185     RecvPacket();
186     }
187
188 receiverStopped = true;
189 }
190 //-----------------------------------------------------------------------------
191 void * LISTENER::RunProcessor(void * d)
192 {
193 sigset_t signalSet;
194 sigfillset(&signalSet);
195 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
196
197 LISTENER * listener = static_cast<LISTENER *>(d);
198
199 listener->ProcessorRunner();
200
201 return NULL;
202 }
203 //-----------------------------------------------------------------------------
204 void LISTENER::ProcessorRunner()
205 {
206 processorStopped = false;
207
208 while (running)
209     {
210     struct timespec ts = {0, 500000000};
211     nanosleep(&ts, NULL);
212     if (!pending.empty())
213         ProcessPending();
214     ProcessTimeouts();
215     }
216
217 processorStopped = true;
218 }
219 //-----------------------------------------------------------------------------
220 bool LISTENER::PrepareNet()
221 {
222 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
223
224 if (listenSocket < 0)
225     {
226     errorStr = "Cannot create socket.";
227     return true;
228     }
229
230 struct sockaddr_in listenAddr;
231 listenAddr.sin_family = AF_INET;
232 listenAddr.sin_port = htons(port);
233 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
234
235 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
236     {
237     errorStr = "LISTENER: Bind failed.";
238     return true;
239     }
240
241 printfd(__FILE__, "LISTENER::PrepareNet() >>>> Start successfull.\n");
242
243 return false;
244 }
245 //-----------------------------------------------------------------------------
246 bool LISTENER::FinalizeNet()
247 {
248 close(listenSocket);
249
250 return false;
251 }
252 //-----------------------------------------------------------------------------
253 bool LISTENER::RecvPacket()
254 {
255 struct iovec iov[2];
256
257 char buffer[RS_MAX_PACKET_LEN];
258 RS::PACKET_HEADER packetHead;
259
260 iov[0].iov_base = reinterpret_cast<char *>(&packetHead);
261 iov[0].iov_len = sizeof(packetHead);
262 iov[1].iov_base = buffer;
263 iov[1].iov_len = sizeof(buffer) - sizeof(packetHead);
264
265 size_t dataLen = 0;
266 while (dataLen < sizeof(buffer))
267     {
268     if (!WaitPackets(listenSocket))
269         {
270         if (!running)
271             return false;
272         continue;
273         }
274     int portion = readv(listenSocket, iov, 2);
275     if (portion < 0)
276         {
277         return true;
278         }
279     dataLen += portion;
280     }
281
282 if (CheckHeader(packetHead))
283     {
284     printfd(__FILE__, "Invalid packet or incorrect protocol version!\n");
285     return true;
286     }
287
288 std::string userLogin((char *)packetHead.login);
289 PendingData data;
290 data.login = userLogin;
291 data.ip = ntohl(packetHead.ip);
292 data.id = ntohl(packetHead.id);
293
294 if (packetHead.packetType == RS_ALIVE_PACKET)
295     {
296     data.type = PendingData::ALIVE;
297     }
298 else if (packetHead.packetType == RS_CONNECT_PACKET)
299     {
300     data.type = PendingData::CONNECT;
301     if (GetParams(buffer, data))
302         {
303         return true;
304         }
305     }
306 else if (packetHead.packetType == RS_DISCONNECT_PACKET)
307     {
308     data.type = PendingData::DISCONNECT;
309     if (GetParams(buffer, data))
310         {
311         return true;
312         }
313     }
314
315 STG_LOCKER lock(&mutex);
316 pending.push_back(data);
317
318 return false;
319 }
320 //-----------------------------------------------------------------------------
321 bool LISTENER::GetParams(char * buffer, UserData & data)
322 {
323 RS::PACKET_TAIL packetTail;
324
325 Decrypt(&ctxS, (char *)&packetTail, buffer, sizeof(packetTail) / 8);
326
327 if (strncmp((char *)packetTail.magic, RS_ID, RS_MAGIC_LEN))
328     {
329     printfd(__FILE__, "Invalid crypto magic\n");
330     return true;
331     }
332
333 std::ostringstream params;
334 params << "\"" << data.login << "\" "
335        << inet_ntostring(data.ip) << " "
336        << data.id << " "
337        << (char *)packetTail.params;
338
339 data.params = params.str();
340
341 return false;
342 }
343 //-----------------------------------------------------------------------------
344 void LISTENER::ProcessPending()
345 {
346 std::list<PendingData>::iterator it(pending.begin());
347 size_t count = 0;
348 printfd(__FILE__, "Pending: %d\n", pending.size());
349 while (it != pending.end() && count < 256)
350     {
351     std::vector<AliveData>::iterator uit(
352             std::lower_bound(
353                 users.begin(),
354                 users.end(),
355                 it->login)
356             );
357     if (it->type == PendingData::CONNECT)
358         {
359         printfd(__FILE__, "Connect packet\n");
360         if (uit == users.end() || uit->login != it->login)
361             {
362             printfd(__FILE__, "Connect new user '%s'\n", it->login.c_str());
363             // Add new user
364             Connect(*it);
365             users.insert(uit, AliveData(static_cast<UserData>(*it)));
366             }
367         else if (uit->login == it->login)
368             {
369             printfd(__FILE__, "Update existing user '%s'\n", it->login.c_str());
370             // Update already existing user
371             time(&uit->lastAlive);
372             uit->params = it->params;
373             }
374         else
375             {
376             printfd(__FILE__, "Hmmm... Strange connect for '%s'\n", it->login.c_str());
377             }
378         }
379     else if (it->type == PendingData::ALIVE)
380         {
381         printfd(__FILE__, "Alive packet\n");
382         if (uit != users.end() && uit->login == it->login)
383             {
384             printfd(__FILE__, "Alive user '%s'\n", it->login.c_str());
385             // Update existing user
386             time(&uit->lastAlive);
387             }
388         else
389             {
390             printfd(__FILE__, "Alive user '%s' is not found\n", it->login.c_str());
391             }
392         }
393     else if (it->type == PendingData::DISCONNECT)
394         {
395         printfd(__FILE__, "Disconnect packet\n");
396         if (uit != users.end() && uit->login == it->login.c_str())
397             {
398             printfd(__FILE__, "Disconnect user '%s'\n", it->login.c_str());
399             // Disconnect existing user
400             uit->params = it->params;
401             Disconnect(*uit);
402             users.erase(uit);
403             }
404         else
405             {
406             printfd(__FILE__, "Cannot find user '%s' for disconnect\n", it->login.c_str());
407             }
408         }
409     else
410         {
411         printfd(__FILE__, "Unknown packet type\n");
412         }
413     ++it;
414     ++count;
415     }
416 STG_LOCKER lock(&mutex);
417 pending.erase(pending.begin(), it);
418 }
419 //-----------------------------------------------------------------------------
420 void LISTENER::ProcessTimeouts()
421 {
422 const std::vector<AliveData>::iterator it(
423         std::stable_partition(
424             users.begin(),
425             users.end(),
426             IsNotTimedOut(userTimeout)
427         )
428     );
429
430 if (it != users.end())
431     {
432     printfd(__FILE__, "Total users: %d, users to disconnect: %d\n", users.size(), std::distance(it, users.end()));
433
434     std::for_each(
435             it,
436             users.end(),
437             DisconnectUser(*this)
438         );
439
440     users.erase(it, users.end());
441     }
442 }
443 //-----------------------------------------------------------------------------
444 bool LISTENER::Connect(const UserData & data) const
445 {
446 printfd(__FILE__, "Connect %s\n", data.login.c_str());
447 if (access(scriptOnConnect.c_str(), X_OK) == 0)
448     {
449     if (ScriptExec((scriptOnConnect + " " + data.params).c_str()))
450         {
451         WriteServLog("Script %s cannot be executed for an unknown reason.", scriptOnConnect.c_str());
452         return true;
453         }
454     }
455 else
456     {
457     WriteServLog("Script %s cannot be executed. File not found.", scriptOnConnect.c_str());
458     return true;
459     }
460 return false;
461 }
462 //-----------------------------------------------------------------------------
463 bool LISTENER::Disconnect(const UserData & data) const
464 {
465 printfd(__FILE__, "Disconnect %s\n", data.login.c_str());
466 if (access(scriptOnDisconnect.c_str(), X_OK) == 0)
467     {
468     if (ScriptExec((scriptOnDisconnect + " " + data.params).c_str()))
469         {
470         WriteServLog("Script %s cannot be executed for an unknown reson.", scriptOnDisconnect.c_str());
471         return true;
472         }
473     }
474 else
475     {
476     WriteServLog("Script %s cannot be executed. File not found.", scriptOnDisconnect.c_str());
477     return true;
478     }
479 return false;
480 }
481 //-----------------------------------------------------------------------------
482 bool LISTENER::CheckHeader(const RS::PACKET_HEADER & header) const
483 {
484 if (strncmp((char *)header.magic, RS_ID, RS_MAGIC_LEN))
485     {
486     return true;
487     }
488 if (strncmp((char *)header.protoVer, "02", RS_PROTO_VER_LEN))
489     {
490     return true;
491     }
492 return false;
493 }
494 //-----------------------------------------------------------------------------
495 inline
496 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
497 {
498 unsigned char keyL[PASSWD_LEN];
499 memset(keyL, 0, PASSWD_LEN);
500 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
501 Blowfish_Init(ctx, keyL, PASSWD_LEN);
502 }
503 //-----------------------------------------------------------------------------
504 inline
505 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
506 {
507 if (dst != src)
508     memcpy(dst, src, len8 * 8);
509
510 for (int i = 0; i < len8; i++)
511     Blowfish_Decrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
512 }
513 //-----------------------------------------------------------------------------