]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/other/rscript/rscript.cpp
Merge remote-tracking branch 'github/master'
[stg.git] / projects / stargazer / plugins / other / rscript / rscript.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 "rscript.h"
23
24 #include "ur_functor.h"
25 #include "send_functor.h"
26
27 #include "stg/common.h"
28 #include "stg/locker.h"
29 #include "stg/users.h"
30 #include "stg/user_property.h"
31 #include "stg/logger.h"
32
33 #include <algorithm>
34
35 #include <csignal>
36 #include <cassert>
37 #include <cstdlib>
38 #include <cerrno>
39 #include <cstring>
40
41 #include <sys/time.h>
42 #include <netinet/ip.h>
43
44 #define RS_DEBUG (1)
45 #define MAX_SHORT_PCKT  (3)
46
47 extern volatile time_t stgTime;
48
49 using RS::REMOTE_SCRIPT;
50
51 namespace {
52
53 template<typename T>
54 struct USER_IS
55 {
56     explicit USER_IS(RS::UserPtr u) : user(u) {}
57     bool operator()(const T & notifier) { return notifier.GetUser() == user; }
58
59     RS::UserPtr user;
60 };
61
62 } // namespace anonymous
63
64 extern "C" STG::Plugin* GetPlugin()
65 {
66     static REMOTE_SCRIPT plugin;
67     return &plugin;
68 }
69 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
71 //-----------------------------------------------------------------------------
72 RS::SETTINGS::SETTINGS()
73     : sendPeriod(0),
74       port(0)
75 {
76 }
77 //-----------------------------------------------------------------------------
78 int RS::SETTINGS::ParseSettings(const STG::ModuleSettings & s)
79 {
80 int p;
81 STG::ParamValue pv;
82 std::vector<STG::ParamValue>::const_iterator pvi;
83 netRouters.clear();
84 ///////////////////////////
85 pv.param = "Port";
86 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
87 if (pvi == s.moduleParams.end() || pvi->value.empty())
88     {
89     errorStr = "Parameter \'Port\' not found.";
90     printfd(__FILE__, "Parameter 'Port' not found\n");
91     return -1;
92     }
93 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
94     {
95     errorStr = "Cannot parse parameter \'Port\': " + errorStr;
96     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
97     return -1;
98     }
99 port = static_cast<uint16_t>(p);
100 ///////////////////////////
101 pv.param = "SendPeriod";
102 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
103 if (pvi == s.moduleParams.end() || pvi->value.empty())
104     {
105     errorStr = "Parameter \'SendPeriod\' not found.";
106     printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
107     return -1;
108     }
109
110 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod))
111     {
112     errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
113     printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
114     return -1;
115     }
116 ///////////////////////////
117 pv.param = "UserParams";
118 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
119 if (pvi == s.moduleParams.end() || pvi->value.empty())
120     {
121     errorStr = "Parameter \'UserParams\' not found.";
122     printfd(__FILE__, "Parameter 'UserParams' not found\n");
123     return -1;
124     }
125 userParams = pvi->value;
126 ///////////////////////////
127 pv.param = "Password";
128 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
129 if (pvi == s.moduleParams.end() || pvi->value.empty())
130     {
131     errorStr = "Parameter \'Password\' not found.";
132     printfd(__FILE__, "Parameter 'Password' not found\n");
133     return -1;
134     }
135 password = pvi->value[0];
136 ///////////////////////////
137 pv.param = "SubnetFile";
138 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
139 if (pvi == s.moduleParams.end() || pvi->value.empty())
140     {
141     errorStr = "Parameter \'SubnetFile\' not found.";
142     printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
143     return -1;
144     }
145 subnetFile = pvi->value[0];
146
147 NRMapParser nrMapParser;
148
149 if (!nrMapParser.ReadFile(subnetFile))
150     {
151     netRouters = nrMapParser.GetMap();
152     }
153 else
154     {
155         STG::PluginLogger::get("rscript")("mod_rscript: error opening subnets file '%s'", subnetFile.c_str());
156     }
157
158 return 0;
159 }
160 //-----------------------------------------------------------------------------
161 //-----------------------------------------------------------------------------
162 //-----------------------------------------------------------------------------
163 REMOTE_SCRIPT::REMOTE_SCRIPT()
164     : sendPeriod(15),
165       halfPeriod(8),
166       nonstop(false),
167       isRunning(false),
168       users(NULL),
169       sock(0),
170       onAddUserNotifier(*this),
171       onDelUserNotifier(*this),
172       logger(STG::PluginLogger::get("rscript"))
173 {
174 pthread_mutex_init(&mutex, NULL);
175 }
176 //-----------------------------------------------------------------------------
177 REMOTE_SCRIPT::~REMOTE_SCRIPT()
178 {
179 pthread_mutex_destroy(&mutex);
180 }
181 //-----------------------------------------------------------------------------
182 void * REMOTE_SCRIPT::Run(void * d)
183 {
184 sigset_t signalSet;
185 sigfillset(&signalSet);
186 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
187
188 REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
189
190 rs->isRunning = true;
191
192 while (rs->nonstop)
193     {
194     rs->PeriodicSend();
195     sleep(2);
196     }
197
198 rs->isRunning = false;
199 return NULL;
200 }
201 //-----------------------------------------------------------------------------
202 int REMOTE_SCRIPT::ParseSettings()
203 {
204 int ret = rsSettings.ParseSettings(settings);
205 if (ret)
206     errorStr = rsSettings.GetStrError();
207
208 sendPeriod = rsSettings.GetSendPeriod();
209 halfPeriod = sendPeriod / 2;
210
211 return ret;
212 }
213 //-----------------------------------------------------------------------------
214 int REMOTE_SCRIPT::Start()
215 {
216 netRouters = rsSettings.GetSubnetsMap();
217
218 InitEncrypt(&ctx, rsSettings.GetPassword());
219
220 users->AddNotifierUserAdd(&onAddUserNotifier);
221 users->AddNotifierUserDel(&onDelUserNotifier);
222
223 nonstop = true;
224
225 if (GetUsers())
226     {
227     return -1;
228     }
229
230 if (PrepareNet())
231     {
232     return -1;
233     }
234
235 if (!isRunning)
236     {
237     if (pthread_create(&thread, NULL, Run, this))
238         {
239         errorStr = "Cannot create thread.";
240         logger("Cannot create thread.");
241         printfd(__FILE__, "Cannot create thread\n");
242         return -1;
243         }
244     }
245
246 errorStr = "";
247 return 0;
248 }
249 //-----------------------------------------------------------------------------
250 int REMOTE_SCRIPT::Stop()
251 {
252 if (!IsRunning())
253     return 0;
254
255 nonstop = false;
256
257 std::for_each(
258         authorizedUsers.begin(),
259         authorizedUsers.end(),
260         DisconnectUser(*this)
261         );
262
263 FinalizeNet();
264
265 if (isRunning)
266     {
267     //5 seconds to thread stops itself
268     for (int i = 0; i < 25 && isRunning; i++)
269         {
270         struct timespec ts = {0, 200000000};
271         nanosleep(&ts, NULL);
272         }
273     }
274
275 users->DelNotifierUserDel(&onDelUserNotifier);
276 users->DelNotifierUserAdd(&onAddUserNotifier);
277
278 if (isRunning)
279     {
280     logger("Cannot stop thread.");
281     return -1;
282     }
283
284 return 0;
285 }
286 //-----------------------------------------------------------------------------
287 int REMOTE_SCRIPT::Reload(const STG::ModuleSettings & /*ms*/)
288 {
289 NRMapParser nrMapParser;
290
291 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
292     {
293     errorStr = nrMapParser.GetErrorStr();
294     logger("Map file reading error: %s", errorStr.c_str());
295     return -1;
296     }
297
298     {
299     STG_LOCKER lock(&mutex);
300
301     printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
302
303     netRouters = nrMapParser.GetMap();
304     }
305
306 std::for_each(authorizedUsers.begin(),
307               authorizedUsers.end(),
308               UpdateRouter(*this));
309
310 logger("%s reloaded successfully.", rsSettings.GetMapFileName().c_str());
311 printfd(__FILE__, "REMOTE_SCRIPT::Reload() %s reloaded successfully.\n");
312
313 return 0;
314 }
315 //-----------------------------------------------------------------------------
316 bool REMOTE_SCRIPT::PrepareNet()
317 {
318 sock = socket(AF_INET, SOCK_DGRAM, 0);
319
320 if (sock < 0)
321     {
322     errorStr = "Cannot create socket.";
323     logger("Canot create a socket: %s", strerror(errno));
324     printfd(__FILE__, "Cannot create socket\n");
325     return true;
326     }
327
328 return false;
329 }
330 //-----------------------------------------------------------------------------
331 bool REMOTE_SCRIPT::FinalizeNet()
332 {
333 close(sock);
334 return false;
335 }
336 //-----------------------------------------------------------------------------
337 void REMOTE_SCRIPT::PeriodicSend()
338 {
339 STG_LOCKER lock(&mutex);
340
341 std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
342 while (it != authorizedUsers.end())
343     {
344     if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
345         {
346         Send(it->second);
347         }
348     ++it;
349     }
350 }
351 //-----------------------------------------------------------------------------
352 #ifdef NDEBUG
353 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, RS::USER & rsu, bool forceDisconnect) const
354 #else
355 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, RS::USER & rsu, bool forceDisconnect) const
356 #endif
357 {
358 RS::PACKET_HEADER packetHead;
359
360 memset(packetHead.padding, 0, sizeof(packetHead.padding));
361 strcpy((char*)packetHead.magic, RS_ID);
362 packetHead.protoVer[0] = '0';
363 packetHead.protoVer[1] = '2';
364 if (forceDisconnect)
365     {
366     packetHead.packetType = RS_DISCONNECT_PACKET;
367     printfd(__FILE__, "RSCRIPT: force disconnect for '%s'\n", rsu.user->GetLogin().c_str());
368     }
369 else
370     {
371     if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
372         {
373         //SendLong
374         packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
375         if (rsu.user->IsInetable())
376             printfd(__FILE__, "RSCRIPT: connect for '%s'\n", rsu.user->GetLogin().c_str());
377         else
378             printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
379         }
380     else
381         {
382         //SendShort
383         packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
384         if (rsu.user->IsInetable())
385             printfd(__FILE__, "RSCRIPT: alive for '%s'\n", rsu.user->GetLogin().c_str());
386         else
387             printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
388         }
389     }
390 rsu.shortPacketsCount++;
391 rsu.lastSentTime = stgTime;
392
393 packetHead.ip = htonl(rsu.ip);
394 packetHead.id = htonl(rsu.user->GetID());
395 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
396 packetHead.login[RS_LOGIN_LEN - 1] = 0;
397
398 memcpy(buf, &packetHead, sizeof(packetHead));
399
400 if (packetHead.packetType == RS_ALIVE_PACKET)
401     {
402     return false;
403     }
404
405 RS::PACKET_TAIL packetTail;
406
407 memset(packetTail.padding, 0, sizeof(packetTail.padding));
408 strcpy((char*)packetTail.magic, RS_ID);
409 std::vector<std::string>::const_iterator it;
410 std::string params;
411 for(it = rsSettings.GetUserParams().begin();
412     it != rsSettings.GetUserParams().end();
413     ++it)
414     {
415     std::string parameter(rsu.user->GetParamValue(it->c_str()));
416     if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
417     {
418         logger("Script params string length %d exceeds the limit of %d symbols.", params.length() + parameter.length(), RS_PARAMS_LEN);
419         break;
420     }
421     params += parameter + " ";
422     }
423 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
424 packetTail.params[RS_PARAMS_LEN - 1] = 0;
425
426 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
427
428 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
429
430 return false;
431 }
432 //-----------------------------------------------------------------------------
433 bool REMOTE_SCRIPT::Send(RS::USER & rsu, bool forceDisconnect) const
434 {
435 char buffer[RS_MAX_PACKET_LEN];
436
437 memset(buffer, 0, sizeof(buffer));
438
439 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
440     {
441     printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
442     return true;
443     }
444
445 std::for_each(
446         rsu.routers.begin(),
447         rsu.routers.end(),
448         PacketSender(sock, buffer, sizeof(buffer), static_cast<uint16_t>(htons(rsSettings.GetPort())))
449         );
450
451 return false;
452 }
453 //-----------------------------------------------------------------------------
454 bool REMOTE_SCRIPT::SendDirect(RS::USER & rsu, uint32_t routerIP, bool forceDisconnect) const
455 {
456 char buffer[RS_MAX_PACKET_LEN];
457
458 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
459     {
460     printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
461     return true;
462     }
463
464 struct sockaddr_in sendAddr;
465
466 sendAddr.sin_family = AF_INET;
467 sendAddr.sin_port = static_cast<uint16_t>(htons(rsSettings.GetPort()));
468 sendAddr.sin_addr.s_addr = routerIP;
469
470 ssize_t res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
471
472 if (res < 0)
473     logger("sendto error: %s", strerror(errno));
474
475 return (res != sizeof(buffer));
476 }
477 //-----------------------------------------------------------------------------
478 bool REMOTE_SCRIPT::GetUsers()
479 {
480 UserPtr u;
481
482 int h = users->OpenSearch();
483 assert(h && "USERS::OpenSearch is always correct");
484
485 while (!users->SearchNext(h, &u))
486     {
487     SetUserNotifiers(u);
488     }
489
490 users->CloseSearch(h);
491 return false;
492 }
493 //-----------------------------------------------------------------------------
494 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
495 {
496 STG_LOCKER lock(&mutex);
497 for (size_t i = 0; i < netRouters.size(); ++i)
498     {
499     if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
500         {
501         return netRouters[i].routers;
502         }
503     }
504 return std::vector<uint32_t>();
505 }
506 //-----------------------------------------------------------------------------
507 void REMOTE_SCRIPT::SetUserNotifiers(UserPtr u)
508 {
509 ipNotifierList.push_front(RS::IP_NOTIFIER(*this, u));
510 connNotifierList.push_front(RS::CONNECTED_NOTIFIER(*this, u));
511 }
512 //-----------------------------------------------------------------------------
513 void REMOTE_SCRIPT::UnSetUserNotifiers(UserPtr u)
514 {
515 ipNotifierList.erase(std::remove_if(ipNotifierList.begin(),
516                                     ipNotifierList.end(),
517                                     USER_IS<IP_NOTIFIER>(u)),
518                      ipNotifierList.end());
519 connNotifierList.erase(std::remove_if(connNotifierList.begin(),
520                                       connNotifierList.end(),
521                                       USER_IS<CONNECTED_NOTIFIER>(u)),
522                        connNotifierList.end());
523
524 }
525 //-----------------------------------------------------------------------------
526 void REMOTE_SCRIPT::AddRSU(UserPtr user)
527 {
528 RS::USER rsu(IP2Routers(user->GetCurrIP()), user);
529 Send(rsu);
530
531 STG_LOCKER lock(&mutex);
532 authorizedUsers.insert(std::make_pair(user->GetCurrIP(), rsu));
533 }
534 //-----------------------------------------------------------------------------
535 void REMOTE_SCRIPT::DelRSU(UserPtr user)
536 {
537 STG_LOCKER lock(&mutex);
538 std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
539 while (it != authorizedUsers.end())
540     {
541     if (it->second.user == user)
542         {
543         Send(it->second, true);
544         authorizedUsers.erase(it);
545         return;
546         }
547     ++it;
548     }
549 /*const std::map<uint32_t, RS::USER>::iterator it(
550         authorizedUsers.find(user->GetCurrIP())
551         );
552 if (it != authorizedUsers.end())
553     {
554     Send(it->second, true);
555     authorizedUsers.erase(it);
556     }*/
557 }
558 //-----------------------------------------------------------------------------
559 void RS::IP_NOTIFIER::Notify(const uint32_t & /*oldValue*/, const uint32_t & newValue)
560 {
561 if (newValue)
562     rs.AddRSU(user);
563 else
564     rs.DelRSU(user);
565 }
566 //-----------------------------------------------------------------------------
567 void RS::CONNECTED_NOTIFIER::Notify(const bool & /*oldValue*/, const bool & newValue)
568 {
569 if (newValue)
570     rs.AddRSU(user);
571 else
572     rs.DelRSU(user);
573 }
574 //-----------------------------------------------------------------------------
575 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) const
576 {
577 unsigned char keyL[PASSWD_LEN];  // Пароль для шифровки
578 memset(keyL, 0, PASSWD_LEN);
579 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
580 Blowfish_Init(ctx, keyL, PASSWD_LEN);
581 }
582 //-----------------------------------------------------------------------------
583 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8) const
584 {
585 if (dst != src)
586     memcpy(dst, src, len8 * 8);
587 for (size_t i = 0; i < len8; ++i)
588     Blowfish_Encrypt(ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
589 }
590 //-----------------------------------------------------------------------------