]> git.stg.codes - stg.git/blob - projects/rscriptd/listener.cpp
Переіменовано пару змінних для збереження семантики, виправлено розмір
[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 <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 "listener.h"
37 #include "script_executer.h"
38 #include "stg_locker.h"
39 #include "common.h"
40
41 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
42 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
43
44 //-----------------------------------------------------------------------------
45 LISTENER::LISTENER()
46     : WriteServLog(GetStgLogger()),
47       port(0),
48       running(false),
49       receiverStopped(true),
50       processorStopped(true),
51       userTimeout(0),
52       listenSocket(0)
53 {
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 usleep(500000);
106
107 if (!processorStopped)
108     {
109     //5 seconds to thread stops itself
110     for (int i = 0; i < 25 && !processorStopped; i++)
111         {
112         usleep(200000);
113         }
114
115     //after 5 seconds waiting thread still running. now killing it
116     if (!processorStopped)
117         {
118         //TODO pthread_cancel()
119         if (pthread_kill(processorThread, SIGINT))
120             {
121             errorStr = "Cannot kill thread.";
122             return true;
123             }
124         printfd(__FILE__, "LISTENER killed Timeouter\n");
125         }
126     }
127
128 if (!receiverStopped)
129     {
130     //5 seconds to thread stops itself
131     for (int i = 0; i < 25 && !receiverStopped; i++)
132         {
133         usleep(200000);
134         }
135
136     //after 5 seconds waiting thread still running. now killing it
137     if (!receiverStopped)
138         {
139         //TODO pthread_cancel()
140         if (pthread_kill(receiverThread, SIGINT))
141             {
142             errorStr = "Cannot kill thread.";
143             return true;
144             }
145         printfd(__FILE__, "LISTENER killed Run\n");
146         }
147     }
148
149 pthread_join(receiverThread, NULL);
150 pthread_join(processorThread, NULL);
151
152 pthread_mutex_destroy(&mutex);
153
154 FinalizeNet();
155
156 std::for_each(users.begin(), users.end(), DisconnectUser(*this));
157
158 printfd(__FILE__, "LISTENER::Stoped successfully.\n");
159
160 return false;
161 }
162 //-----------------------------------------------------------------------------
163 void * LISTENER::Run(void * d)
164 {
165 LISTENER * listener = static_cast<LISTENER *>(d);
166
167 listener->Runner();
168
169 return NULL;
170 }
171 //-----------------------------------------------------------------------------
172 void LISTENER::Runner()
173 {
174 receiverStopped = false;
175
176 while (running)
177     {
178     RecvPacket();
179     }
180
181 receiverStopped = true;
182 }
183 //-----------------------------------------------------------------------------
184 void * LISTENER::RunProcessor(void * d)
185 {
186 LISTENER * listener = static_cast<LISTENER *>(d);
187
188 listener->ProcessorRunner();
189
190 return NULL;
191 }
192 //-----------------------------------------------------------------------------
193 void LISTENER::ProcessorRunner()
194 {
195 processorStopped = false;
196
197 while (running)
198     {
199     usleep(500000);
200     if (!pending.empty())
201         ProcessPending();
202     ProcessTimeouts();
203     }
204
205 processorStopped = true;
206 }
207 //-----------------------------------------------------------------------------
208 bool LISTENER::PrepareNet()
209 {
210 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
211
212 if (listenSocket < 0)
213     {
214     errorStr = "Cannot create socket.";
215     return true;
216     }
217
218 struct sockaddr_in listenAddr;
219 listenAddr.sin_family = AF_INET;
220 listenAddr.sin_port = htons(port);
221 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
222
223 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
224     {
225     errorStr = "LISTENER: Bind failed.";
226     return true;
227     }
228
229 printfd(__FILE__, "LISTENER::PrepareNet() >>>> Start successfull.\n");
230
231 return false;
232 }
233 //-----------------------------------------------------------------------------
234 bool LISTENER::FinalizeNet()
235 {
236 close(listenSocket);
237
238 return false;
239 }
240 //-----------------------------------------------------------------------------
241 bool LISTENER::RecvPacket()
242 {
243 struct iovec iov[2];
244
245 char buffer[RS_MAX_PACKET_LEN];
246 RS_PACKET_HEADER packetHead;
247
248 iov[0].iov_base = reinterpret_cast<char *>(&packetHead);
249 iov[0].iov_len = sizeof(packetHead);
250 iov[1].iov_base = buffer;
251 iov[1].iov_len = sizeof(buffer) - sizeof(packetHead);
252
253 size_t dataLen = 0;
254 while (dataLen < sizeof(buffer))
255     {
256     if (!WaitPackets(listenSocket))
257         {
258         if (!running)
259             return false;
260         continue;
261         }
262     int portion = readv(listenSocket, iov, 2);
263     if (portion < 0)
264         {
265         return true;
266         }
267     dataLen += portion;
268     }
269
270 if (CheckHeader(packetHead))
271     {
272     printfd(__FILE__, "Invalid packet or incorrect protocol version!\n");
273     return true;
274     }
275
276 std::string userLogin((char *)packetHead.login);
277 PendingData data;
278 data.login = userLogin;
279 data.ip = ntohl(packetHead.ip);
280 data.id = ntohl(packetHead.id);
281
282 if (packetHead.packetType == RS_ALIVE_PACKET)
283     {
284     data.type = PendingData::ALIVE;
285     }
286 else if (packetHead.packetType == RS_CONNECT_PACKET)
287     {
288     data.type = PendingData::CONNECT;
289     if (GetParams(buffer, data))
290         {
291         return true;
292         }
293     }
294 else if (packetHead.packetType == RS_DISCONNECT_PACKET)
295     {
296     data.type = PendingData::DISCONNECT;
297     if (GetParams(buffer, data))
298         {
299         return true;
300         }
301     }
302
303 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
304 pending.push_back(data);
305
306 return false;
307 }
308 //-----------------------------------------------------------------------------
309 bool LISTENER::GetParams(char * buffer, UserData & data)
310 {
311 RS_PACKET_TAIL packetTail;
312
313 Decrypt(&ctxS, (char *)&packetTail, buffer, sizeof(packetTail) / 8);
314
315 if (strncmp((char *)packetTail.magic, RS_ID, RS_MAGIC_LEN))
316     {
317     printfd(__FILE__, "Invalid crypto magic\n");
318     return true;
319     }
320
321 std::stringstream params;
322 params << "\"" << data.login << "\" "
323        << inet_ntostring(data.ip) << " "
324        << data.id << " "
325        << (char *)packetTail.params;
326
327 data.params = params.str();
328
329 return false;
330 }
331 //-----------------------------------------------------------------------------
332 void LISTENER::ProcessPending()
333 {
334 std::list<PendingData> localPending;
335
336     {
337     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
338     printfd(__FILE__, "Pending data size: %d\n", pending.size());
339     localPending.swap(pending);
340     }
341
342 std::list<PendingData>::iterator it(localPending.begin());
343 while (it != localPending.end())
344     {
345     std::vector<AliveData>::iterator uit(
346             std::lower_bound(
347                 users.begin(),
348                 users.end(),
349                 it->login)
350             );
351     if (it->type == PendingData::CONNECT)
352         {
353         if (uit == users.end() || uit->login != it->login)
354             {
355             // Add new user
356             Connect(*it);
357             users.insert(uit, AliveData(static_cast<UserData>(*it)));
358             }
359         else if (uit->login == it->login)
360             {
361             // Update already existing user
362             time(&uit->lastAlive);
363             uit->params = it->params;
364             }
365         }
366     else if (it->type == PendingData::ALIVE)
367         {
368         if (uit != users.end() && uit->login == it->login)
369             {
370             // Update existing user
371             time(&uit->lastAlive);
372             }
373         }
374     else if (it->type == PendingData::DISCONNECT)
375         {
376         if (uit != users.end() && uit->login == it->login.c_str())
377             {
378             // Disconnect existing user
379             Disconnect(*uit);
380             users.erase(uit);
381             }
382         }
383     ++it;
384     }
385 }
386 //-----------------------------------------------------------------------------
387 void LISTENER::ProcessTimeouts()
388 {
389 const std::vector<AliveData>::iterator it(
390         std::stable_partition(
391             users.begin(),
392             users.end(),
393             IsNotTimedOut(userTimeout)
394         )
395     );
396
397 if (it != users.end())
398     {
399     printfd(__FILE__, "Total users: %d, users to disconnect: %d\n", users.size(), std::distance(it, users.end()));
400
401     std::for_each(
402             it,
403             users.end(),
404             DisconnectUser(*this)
405         );
406
407     users.erase(it, users.end());
408     }
409 }
410 //-----------------------------------------------------------------------------
411 bool LISTENER::Connect(const UserData & data) const
412 {
413 printfd(__FILE__, "Connect %s\n", data.login.c_str());
414 if (access(scriptOnConnect.c_str(), X_OK) == 0)
415     {
416     if (ScriptExec(scriptOnConnect + " " + data.params))
417         {
418         WriteServLog("Script %s cannot be executed for an unknown reason.", scriptOnConnect.c_str());
419         return true;
420         }
421     }
422 else
423     {
424     WriteServLog("Script %s cannot be executed. File not found.", scriptOnConnect.c_str());
425     return true;
426     }
427 return false;
428 }
429 //-----------------------------------------------------------------------------
430 bool LISTENER::Disconnect(const UserData & data) const
431 {
432 printfd(__FILE__, "Disconnect %s\n", data.login.c_str());
433 if (access(scriptOnDisconnect.c_str(), X_OK) == 0)
434     {
435     if (ScriptExec(scriptOnDisconnect + " " + data.params))
436         {
437         WriteServLog("Script %s cannot be executed for an unknown reson.", scriptOnDisconnect.c_str());
438         return true;
439         }
440     }
441 else
442     {
443     WriteServLog("Script %s cannot be executed. File not found.", scriptOnDisconnect.c_str());
444     return true;
445     }
446 return false;
447 }
448 //-----------------------------------------------------------------------------
449 bool LISTENER::CheckHeader(const RS_PACKET_HEADER & header) const
450 {
451 if (strncmp((char *)header.magic, RS_ID, RS_MAGIC_LEN))
452     {
453     return true;
454     }
455 if (strncmp((char *)header.protoVer, "02", RS_PROTO_VER_LEN))
456     {
457     return true;
458     }
459 return false;
460 }
461 //-----------------------------------------------------------------------------
462 bool LISTENER::WaitPackets(int sd) const
463 {
464 fd_set rfds;
465 FD_ZERO(&rfds);
466 FD_SET(sd, &rfds);
467
468 struct timeval tv;
469 tv.tv_sec = 0;
470 tv.tv_usec = 500000;
471
472 int res = select(sd + 1, &rfds, NULL, NULL, &tv);
473 if (res == -1) // Error
474     {
475     if (errno != EINTR)
476         {
477         printfd(__FILE__, "Error on select: '%s'\n", strerror(errno));
478         }
479     return false;
480     }
481
482 if (res == 0) // Timeout
483     {
484     return false;
485     }
486
487 return true;
488 }
489 //-----------------------------------------------------------------------------
490 inline
491 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
492 {
493 unsigned char keyL[PASSWD_LEN];
494 memset(keyL, 0, PASSWD_LEN);
495 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
496 Blowfish_Init(ctx, keyL, PASSWD_LEN);
497 }
498 //-----------------------------------------------------------------------------
499 inline
500 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
501 {
502 if (dst != src)
503     memcpy(dst, src, len8 * 8);
504
505 for (int i = 0; i < len8; i++)
506     Blowfish_Decrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
507 }
508 //-----------------------------------------------------------------------------