]> git.stg.codes - stg.git/blob - projects/stargazer/plugins/other/rscript/rscript.cpp
Allow to start mod_rscript without subnets file
[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 /*
23  $Revision: 1.33 $
24  $Date: 2010/04/16 12:30:37 $
25  $Author: faust $
26 */
27
28 #include <sys/time.h>
29
30 #include <csignal>
31 #include <cassert>
32 #include <cstdlib>
33 #include <algorithm>
34
35 #include "stg/common.h"
36 #include "stg/locker.h"
37 #include "stg/user_property.h"
38 #include "stg/plugin_creator.h"
39 #include "stg/logger.h"
40 #include "rscript.h"
41 #include "ur_functor.h"
42 #include "send_functor.h"
43
44 extern volatile const time_t stgTime;
45
46 #define RS_MAX_ROUTERS  (100)
47
48 //-----------------------------------------------------------------------------
49 //-----------------------------------------------------------------------------
50 //-----------------------------------------------------------------------------
51 PLUGIN_CREATOR<REMOTE_SCRIPT> rsc;
52 //-----------------------------------------------------------------------------
53 //-----------------------------------------------------------------------------
54 //-----------------------------------------------------------------------------
55 PLUGIN * GetPlugin()
56 {
57 return rsc.GetPlugin();
58 }
59 //-----------------------------------------------------------------------------
60 //-----------------------------------------------------------------------------
61 //-----------------------------------------------------------------------------
62 RS_USER & RS_USER::operator=(const RS_USER & rvalue)
63 {
64 lastSentTime = rvalue.lastSentTime;
65 user = rvalue.user;
66 routers = rvalue.routers;
67 shortPacketsCount = rvalue.shortPacketsCount;
68 return *this;
69 }
70 //-----------------------------------------------------------------------------
71 RS_SETTINGS::RS_SETTINGS()
72     : sendPeriod(0),
73       port(0),
74       errorStr(),
75       netRouters(),
76       userParams(),
77       password(),
78       subnetFile()
79 {
80 }
81 //-----------------------------------------------------------------------------
82 int RS_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
83 {
84 int p;
85 PARAM_VALUE pv;
86 vector<PARAM_VALUE>::const_iterator pvi;
87 netRouters.clear();
88 ///////////////////////////
89 pv.param = "Port";
90 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
91 if (pvi == s.moduleParams.end())
92     {
93     errorStr = "Parameter \'Port\' not found.";
94     printfd(__FILE__, "Parameter 'Port' not found\n");
95     return -1;
96     }
97 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
98     {
99     errorStr = "Cannot parse parameter \'Port\': " + errorStr;
100     printfd(__FILE__, "Cannot parse parameter 'Port'\n");
101     return -1;
102     }
103 port = p;
104 ///////////////////////////
105 pv.param = "SendPeriod";
106 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
107 if (pvi == s.moduleParams.end())
108     {
109     errorStr = "Parameter \'SendPeriod\' not found.";
110     printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
111     return -1;
112     }
113
114 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod))
115     {
116     errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
117     printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
118     return -1;
119     }
120 ///////////////////////////
121 pv.param = "UserParams";
122 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
123 if (pvi == s.moduleParams.end())
124     {
125     errorStr = "Parameter \'UserParams\' not found.";
126     printfd(__FILE__, "Parameter 'UserParams' not found\n");
127     return -1;
128     }
129 userParams = pvi->value;
130 ///////////////////////////
131 pv.param = "Password";
132 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
133 if (pvi == s.moduleParams.end())
134     {
135     errorStr = "Parameter \'Password\' not found.";
136     printfd(__FILE__, "Parameter 'Password' not found\n");
137     return -1;
138     }
139 password = pvi->value[0];
140 ///////////////////////////
141 pv.param = "SubnetFile";
142 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
143 if (pvi == s.moduleParams.end())
144     {
145     errorStr = "Parameter \'SubnetFile\' not found.";
146     printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
147     return -1;
148     }
149 subnetFile = pvi->value[0];
150
151 NRMapParser nrMapParser;
152
153 if (!nrMapParser.ReadFile(subnetFile))
154     {
155     netRouters = nrMapParser.GetMap();
156     }
157 else
158     {
159     GetStgLogger()("mod_rscript: error opening subnets file '%s'", subnetFile.c_str());
160     }
161
162 return 0;
163 }
164 //-----------------------------------------------------------------------------
165 //-----------------------------------------------------------------------------
166 //-----------------------------------------------------------------------------
167 REMOTE_SCRIPT::REMOTE_SCRIPT()
168     : ctx(),
169       afterChgIPNotifierList(),
170       authorizedUsers(),
171       errorStr(),
172       rsSettings(),
173       settings(),
174       sendPeriod(15),
175       halfPeriod(8),
176       nonstop(false),
177       isRunning(false),
178       users(NULL),
179       netRouters(),
180       thread(),
181       mutex(),
182       sock(0),
183       onAddUserNotifier(*this),
184       onDelUserNotifier(*this)
185 {
186 pthread_mutex_init(&mutex, NULL);
187 }
188 //-----------------------------------------------------------------------------
189 REMOTE_SCRIPT::~REMOTE_SCRIPT()
190 {
191 pthread_mutex_destroy(&mutex);
192 }
193 //-----------------------------------------------------------------------------
194 void * REMOTE_SCRIPT::Run(void * d)
195 {
196 sigset_t signalSet;
197 sigfillset(&signalSet);
198 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
199
200 REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
201
202 rs->isRunning = true;
203
204 while (rs->nonstop)
205     {
206     rs->PeriodicSend();
207     sleep(2);
208     }
209
210 rs->isRunning = false;
211 return NULL;
212 }
213 //-----------------------------------------------------------------------------
214 int REMOTE_SCRIPT::ParseSettings()
215 {
216 int ret = rsSettings.ParseSettings(settings);
217 if (ret)
218     errorStr = rsSettings.GetStrError();
219
220 sendPeriod = rsSettings.GetSendPeriod();
221 halfPeriod = sendPeriod / 2;
222
223 return ret;
224 }
225 //-----------------------------------------------------------------------------
226 int REMOTE_SCRIPT::Start()
227 {
228 netRouters = rsSettings.GetSubnetsMap();
229
230 InitEncrypt(&ctx, rsSettings.GetPassword());
231
232 //onAddUserNotifier.SetRemoteScript(this);
233 //onDelUserNotifier.SetRemoteScript(this);
234
235 users->AddNotifierUserAdd(&onAddUserNotifier);
236 users->AddNotifierUserDel(&onDelUserNotifier);
237
238 nonstop = true;
239
240 if (GetUsers())
241     {
242     return -1;
243     }
244
245 if (PrepareNet())
246     {
247     return -1;
248     }
249
250 if (!isRunning)
251     {
252     if (pthread_create(&thread, NULL, Run, this))
253         {
254         errorStr = "Cannot create thread.";
255         printfd(__FILE__, "Cannot create thread\n");
256         return -1;
257         }
258     }
259
260 errorStr = "";
261 return 0;
262 }
263 //-----------------------------------------------------------------------------
264 int REMOTE_SCRIPT::Stop()
265 {
266 if (!IsRunning())
267     return 0;
268
269 nonstop = false;
270
271 std::for_each(
272         authorizedUsers.begin(),
273         authorizedUsers.end(),
274         DisconnectUser(*this)
275         );
276
277 FinalizeNet();
278
279 if (isRunning)
280     {
281     //5 seconds to thread stops itself
282     for (int i = 0; i < 25 && isRunning; i++)
283         {
284         struct timespec ts = {0, 200000000};
285         nanosleep(&ts, NULL);
286         }
287     }
288
289 users->DelNotifierUserDel(&onDelUserNotifier);
290 users->DelNotifierUserAdd(&onAddUserNotifier);
291
292 if (isRunning)
293     return -1;
294
295 return 0;
296 }
297 //-----------------------------------------------------------------------------
298 int REMOTE_SCRIPT::Reload()
299 {
300 NRMapParser nrMapParser;
301
302 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
303     {
304     errorStr = nrMapParser.GetErrorStr();
305     return -1;
306     }
307
308     {
309     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
310
311     printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
312
313     netRouters = nrMapParser.GetMap();
314     }
315
316 std::for_each(authorizedUsers.begin(),
317               authorizedUsers.end(),
318               UpdateRouter(*this));
319
320 return 0;
321 }
322 //-----------------------------------------------------------------------------
323 bool REMOTE_SCRIPT::PrepareNet()
324 {
325 sock = socket(AF_INET, SOCK_DGRAM, 0);
326
327 if (sock < 0)
328     {
329     errorStr = "Cannot create socket.";
330     printfd(__FILE__, "Cannot create socket\n");
331     return true;
332     }
333
334 return false;
335 }
336 //-----------------------------------------------------------------------------
337 bool REMOTE_SCRIPT::FinalizeNet()
338 {
339 close(sock);
340 return false;
341 }
342 //-----------------------------------------------------------------------------
343 void REMOTE_SCRIPT::PeriodicSend()
344 {
345 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
346
347 map<uint32_t, RS_USER>::iterator it(authorizedUsers.begin());
348 while (it != authorizedUsers.end())
349     {
350     if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
351     //if (stgTime - it->second.lastSentTime > sendPeriod)
352         {
353         Send(it->first, it->second);
354         }
355     ++it;
356     }
357 }
358 //-----------------------------------------------------------------------------
359 #ifdef NDEBUG
360 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
361 #else
362 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
363 #endif
364 {
365 RS_PACKET_HEADER packetHead;
366
367 memset(packetHead.padding, 0, sizeof(packetHead.padding));
368 strcpy((char*)packetHead.magic, RS_ID);
369 packetHead.protoVer[0] = '0';
370 packetHead.protoVer[1] = '2';
371 if (forceDisconnect)
372     {
373     packetHead.packetType = RS_DISCONNECT_PACKET;
374     }
375 else
376     {
377     if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
378         {
379         //SendLong
380         packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
381         }
382     else
383         {
384         //SendShort
385         packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
386         }
387     }
388 rsu.shortPacketsCount++;
389 rsu.lastSentTime = stgTime;
390
391 packetHead.ip = htonl(ip);
392 packetHead.id = htonl(rsu.user->GetID());
393 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
394 packetHead.login[RS_LOGIN_LEN - 1] = 0;
395
396 memcpy(buf, &packetHead, sizeof(packetHead));
397
398 if (packetHead.packetType == RS_ALIVE_PACKET)
399     {
400     return false;
401     }
402
403 RS_PACKET_TAIL packetTail;
404
405 memset(packetTail.padding, 0, sizeof(packetTail.padding));
406 strcpy((char*)packetTail.magic, RS_ID);
407 vector<string>::const_iterator it;
408 std::string params;
409 for(it = rsSettings.GetUserParams().begin();
410     it != rsSettings.GetUserParams().end();
411     ++it)
412     {
413     std::string parameter(GetUserParam(rsu.user, *it));
414     if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
415         break;
416     params += parameter + " ";
417     }
418 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
419 packetTail.params[RS_PARAMS_LEN - 1] = 0;
420
421 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
422
423 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
424
425 return false;
426 }
427 //-----------------------------------------------------------------------------
428 bool REMOTE_SCRIPT::Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
429 {
430 char buffer[RS_MAX_PACKET_LEN];
431
432 memset(buffer, 0, sizeof(buffer));
433
434 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
435     {
436     printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
437     return true;
438     }
439
440 std::for_each(
441         rsu.routers.begin(),
442         rsu.routers.end(),
443         PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
444         );
445
446 return false;
447 }
448 //-----------------------------------------------------------------------------
449 bool REMOTE_SCRIPT::SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect) const
450 {
451 char buffer[RS_MAX_PACKET_LEN];
452
453 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
454     {
455     printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
456     return true;
457     }
458
459 struct sockaddr_in sendAddr;
460
461 sendAddr.sin_family = AF_INET;
462 sendAddr.sin_port = htons(rsSettings.GetPort());
463 sendAddr.sin_addr.s_addr = routerIP;
464
465 int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
466
467 return (res != sizeof(buffer));
468 }
469 //-----------------------------------------------------------------------------
470 bool REMOTE_SCRIPT::GetUsers()
471 {
472 USER_PTR u;
473
474 int h = users->OpenSearch();
475 if (!h)
476     {
477     errorStr = "users->OpenSearch() error.";
478     printfd(__FILE__, "OpenSearch() error\n");
479     return true;
480     }
481
482 while (!users->SearchNext(h, &u))
483     {
484     SetUserNotifier(u);
485     }
486
487 users->CloseSearch(h);
488 return false;
489 }
490 //-----------------------------------------------------------------------------
491 void REMOTE_SCRIPT::ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP)
492 {
493 /*
494  * When ip changes process looks like:
495  * old => 0, 0 => new
496  *
497  */
498 if (newIP)
499     {
500     RS_USER rsu(IP2Routers(newIP), u);
501     Send(newIP, rsu);
502
503     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
504     authorizedUsers[newIP] = rsu;
505     }
506 else
507     {
508     STG_LOCKER lock(&mutex, __FILE__, __LINE__);
509     const map<uint32_t, RS_USER>::iterator it(
510             authorizedUsers.find(oldIP)
511             );
512     if (it != authorizedUsers.end())
513         {
514         Send(oldIP, it->second, true);
515         authorizedUsers.erase(it);
516         }
517     }
518 }
519 //-----------------------------------------------------------------------------
520 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
521 {
522 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
523 for (size_t i = 0; i < netRouters.size(); ++i)
524     {
525     if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
526         {
527         return netRouters[i].routers;
528         }
529     }
530 return std::vector<uint32_t>();
531 }
532 //-----------------------------------------------------------------------------
533 string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const string & paramName) const
534 {
535 string value = "";
536 if (strcasecmp(paramName.c_str(), "cash") == 0)
537     strprintf(&value, "%f", u->GetProperty().cash.Get());
538 else
539 if (strcasecmp(paramName.c_str(), "freeMb") == 0)
540     strprintf(&value, "%f", u->GetProperty().freeMb.Get());
541 else
542 if (strcasecmp(paramName.c_str(), "passive") == 0)
543     strprintf(&value, "%d", u->GetProperty().passive.Get());
544 else
545 if (strcasecmp(paramName.c_str(), "disabled") == 0)
546     strprintf(&value, "%d", u->GetProperty().disabled.Get());
547 else
548 if (strcasecmp(paramName.c_str(), "alwaysOnline") == 0)
549     strprintf(&value, "%d", u->GetProperty().alwaysOnline.Get());
550 else
551 if (strcasecmp(paramName.c_str(), "tariffName") == 0 ||
552     strcasecmp(paramName.c_str(), "tariff") == 0)
553     value = "\"" + u->GetProperty().tariffName.Get() + "\"";
554 else
555 if (strcasecmp(paramName.c_str(), "nextTariff") == 0)
556     value = "\"" + u->GetProperty().nextTariff.Get() + "\"";
557 else
558 if (strcasecmp(paramName.c_str(), "address") == 0)
559     value = "\"" + u->GetProperty().address.Get() + "\"";
560 else
561 if (strcasecmp(paramName.c_str(), "note") == 0)
562     value = "\"" + u->GetProperty().note.Get() + "\"";
563 else
564 if (strcasecmp(paramName.c_str(), "group") == 0)
565     value = "\"" + u->GetProperty().group.Get() + "\"";
566 else
567 if (strcasecmp(paramName.c_str(), "email") == 0)
568     value = "\"" + u->GetProperty().email.Get() + "\"";
569 else
570 if (strcasecmp(paramName.c_str(), "realName") == 0)
571     value = "\"" + u->GetProperty().realName.Get() + "\"";
572 else
573 if (strcasecmp(paramName.c_str(), "credit") == 0)
574     strprintf(&value, "%f", u->GetProperty().credit.Get());
575 else
576 if (strcasecmp(paramName.c_str(), "userdata0") == 0)
577     value = "\"" + u->GetProperty().userdata0.Get() + "\"";
578 else
579 if (strcasecmp(paramName.c_str(), "userdata1") == 0)
580     value = "\"" + u->GetProperty().userdata1.Get() + "\"";
581 else
582 if (strcasecmp(paramName.c_str(), "userdata2") == 0)
583     value = "\"" + u->GetProperty().userdata2.Get() + "\"";
584 else
585 if (strcasecmp(paramName.c_str(), "userdata3") == 0)
586     value = "\"" + u->GetProperty().userdata3.Get() + "\"";
587 else
588 if (strcasecmp(paramName.c_str(), "userdata4") == 0)
589     value = "\"" + u->GetProperty().userdata4.Get() + "\"";
590 else
591 if (strcasecmp(paramName.c_str(), "userdata5") == 0)
592     value = "\"" + u->GetProperty().userdata5.Get() + "\"";
593 else
594 if (strcasecmp(paramName.c_str(), "userdata6") == 0)
595     value = "\"" + u->GetProperty().userdata6.Get() + "\"";
596 else
597 if (strcasecmp(paramName.c_str(), "userdata7") == 0)
598     value = "\"" + u->GetProperty().userdata7.Get() + "\"";
599 else
600 if (strcasecmp(paramName.c_str(), "userdata8") == 0)
601     value = "\"" + u->GetProperty().userdata8.Get() + "\"";
602 else
603 if (strcasecmp(paramName.c_str(), "userdata9") == 0)
604     value = "\"" + u->GetProperty().userdata9.Get() + "\"";
605 else
606 if (strcasecmp(paramName.c_str(), "enabledDirs") == 0)
607     value = u->GetEnabledDirs();
608 else
609     printfd(__FILE__, "Unknown value name: %s\n", paramName.c_str());
610 return value;
611 }
612 //-----------------------------------------------------------------------------
613 void REMOTE_SCRIPT::SetUserNotifier(USER_PTR u)
614 {
615 RS_CHG_AFTER_NOTIFIER<uint32_t> afterChgIPNotifier(*this, u);
616
617 afterChgIPNotifierList.push_front(afterChgIPNotifier);
618
619 u->AddCurrIPAfterNotifier(&(*afterChgIPNotifierList.begin()));
620 }
621 //-----------------------------------------------------------------------------
622 void REMOTE_SCRIPT::UnSetUserNotifier(USER_PTR u)
623 {
624 list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator  ipAIter;
625 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator> toErase;
626
627 for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter)
628     {
629     if (ipAIter->GetUser() == u)
630         {
631         u->DelCurrIPAfterNotifier(&(*ipAIter));
632         toErase.push_back(ipAIter);
633         }
634     }
635
636 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator>::iterator eIter;
637
638 for (eIter = toErase.begin(); eIter != toErase.end(); ++eIter)
639     {
640     afterChgIPNotifierList.erase(*eIter);
641     }
642 }
643 //-----------------------------------------------------------------------------
644 template <typename varParamType>
645 void RS_CHG_AFTER_NOTIFIER<varParamType>::Notify(const varParamType & oldValue, const varParamType & newValue)
646 {
647 rs.ChangedIP(user, oldValue, newValue);
648 }
649 //-----------------------------------------------------------------------------
650 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
651 {
652 unsigned char keyL[PASSWD_LEN];  // Пароль для шифровки
653 memset(keyL, 0, PASSWD_LEN);
654 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
655 Blowfish_Init(ctx, keyL, PASSWD_LEN);
656 }
657 //-----------------------------------------------------------------------------
658 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
659 {
660 if (dst != src)
661     memcpy(dst, src, len8 * 8);
662 for (size_t i = 0; i < len8; ++i)
663     Blowfish_Encrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
664 }
665 //-----------------------------------------------------------------------------