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