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.
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.
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
18 * Author : Boris Mikhailenko <stg34@stargazer.dp.ua>
19 * Author : Maxim Mamontov <faust@stargazer.dp.ua>
24 $Date: 2010/04/16 12:30:37 $
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"
41 #include "ur_functor.h"
42 #include "send_functor.h"
44 extern volatile const time_t stgTime;
46 #define RS_MAX_ROUTERS (100)
48 //-----------------------------------------------------------------------------
49 //-----------------------------------------------------------------------------
50 //-----------------------------------------------------------------------------
51 PLUGIN_CREATOR<REMOTE_SCRIPT> rsc;
52 //-----------------------------------------------------------------------------
53 //-----------------------------------------------------------------------------
54 //-----------------------------------------------------------------------------
57 return rsc.GetPlugin();
59 //-----------------------------------------------------------------------------
60 //-----------------------------------------------------------------------------
61 //-----------------------------------------------------------------------------
62 RS_USER & RS_USER::operator=(const RS_USER & rvalue)
64 lastSentTime = rvalue.lastSentTime;
66 routers = rvalue.routers;
67 shortPacketsCount = rvalue.shortPacketsCount;
70 //-----------------------------------------------------------------------------
71 RS_SETTINGS::RS_SETTINGS()
81 //-----------------------------------------------------------------------------
82 int RS_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
86 vector<PARAM_VALUE>::const_iterator pvi;
88 ///////////////////////////
90 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
91 if (pvi == s.moduleParams.end())
93 errorStr = "Parameter \'Port\' not found.";
94 printfd(__FILE__, "Parameter 'Port' not found\n");
97 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
99 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
100 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
104 ///////////////////////////
105 pv.param = "SendPeriod";
106 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
107 if (pvi == s.moduleParams.end())
109 errorStr = "Parameter \'SendPeriod\' not found.";
110 printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
114 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod))
116 errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
117 printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
120 ///////////////////////////
121 pv.param = "UserParams";
122 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
123 if (pvi == s.moduleParams.end())
125 errorStr = "Parameter \'UserParams\' not found.";
126 printfd(__FILE__, "Parameter 'UserParams' not found\n");
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())
135 errorStr = "Parameter \'Password\' not found.";
136 printfd(__FILE__, "Parameter 'Password' not found\n");
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())
145 errorStr = "Parameter \'SubnetFile\' not found.";
146 printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
149 subnetFile = pvi->value[0];
151 NRMapParser nrMapParser;
153 if (!nrMapParser.ReadFile(subnetFile))
155 netRouters = nrMapParser.GetMap();
159 GetStgLogger()("mod_rscript: error opening subnets file '%s'", subnetFile.c_str());
164 //-----------------------------------------------------------------------------
165 //-----------------------------------------------------------------------------
166 //-----------------------------------------------------------------------------
167 REMOTE_SCRIPT::REMOTE_SCRIPT()
169 afterChgIPNotifierList(),
183 onAddUserNotifier(*this),
184 onDelUserNotifier(*this)
186 pthread_mutex_init(&mutex, NULL);
188 //-----------------------------------------------------------------------------
189 REMOTE_SCRIPT::~REMOTE_SCRIPT()
191 pthread_mutex_destroy(&mutex);
193 //-----------------------------------------------------------------------------
194 void * REMOTE_SCRIPT::Run(void * d)
197 sigfillset(&signalSet);
198 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
200 REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
202 rs->isRunning = true;
210 rs->isRunning = false;
213 //-----------------------------------------------------------------------------
214 int REMOTE_SCRIPT::ParseSettings()
216 int ret = rsSettings.ParseSettings(settings);
218 errorStr = rsSettings.GetStrError();
220 sendPeriod = rsSettings.GetSendPeriod();
221 halfPeriod = sendPeriod / 2;
225 //-----------------------------------------------------------------------------
226 int REMOTE_SCRIPT::Start()
228 netRouters = rsSettings.GetSubnetsMap();
230 InitEncrypt(&ctx, rsSettings.GetPassword());
232 //onAddUserNotifier.SetRemoteScript(this);
233 //onDelUserNotifier.SetRemoteScript(this);
235 users->AddNotifierUserAdd(&onAddUserNotifier);
236 users->AddNotifierUserDel(&onDelUserNotifier);
252 if (pthread_create(&thread, NULL, Run, this))
254 errorStr = "Cannot create thread.";
255 printfd(__FILE__, "Cannot create thread\n");
263 //-----------------------------------------------------------------------------
264 int REMOTE_SCRIPT::Stop()
272 authorizedUsers.begin(),
273 authorizedUsers.end(),
274 DisconnectUser(*this)
281 //5 seconds to thread stops itself
282 for (int i = 0; i < 25 && isRunning; i++)
284 struct timespec ts = {0, 200000000};
285 nanosleep(&ts, NULL);
289 users->DelNotifierUserDel(&onDelUserNotifier);
290 users->DelNotifierUserAdd(&onAddUserNotifier);
297 //-----------------------------------------------------------------------------
298 int REMOTE_SCRIPT::Reload()
300 NRMapParser nrMapParser;
302 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
304 errorStr = nrMapParser.GetErrorStr();
309 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
311 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
313 netRouters = nrMapParser.GetMap();
316 std::for_each(authorizedUsers.begin(),
317 authorizedUsers.end(),
318 UpdateRouter(*this));
322 //-----------------------------------------------------------------------------
323 bool REMOTE_SCRIPT::PrepareNet()
325 sock = socket(AF_INET, SOCK_DGRAM, 0);
329 errorStr = "Cannot create socket.";
330 printfd(__FILE__, "Cannot create socket\n");
336 //-----------------------------------------------------------------------------
337 bool REMOTE_SCRIPT::FinalizeNet()
342 //-----------------------------------------------------------------------------
343 void REMOTE_SCRIPT::PeriodicSend()
345 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
347 map<uint32_t, RS_USER>::iterator it(authorizedUsers.begin());
348 while (it != authorizedUsers.end())
350 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
351 //if (stgTime - it->second.lastSentTime > sendPeriod)
353 Send(it->first, it->second);
358 //-----------------------------------------------------------------------------
360 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
362 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
365 RS_PACKET_HEADER packetHead;
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';
373 packetHead.packetType = RS_DISCONNECT_PACKET;
377 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
380 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
385 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
388 rsu.shortPacketsCount++;
389 rsu.lastSentTime = stgTime;
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;
396 memcpy(buf, &packetHead, sizeof(packetHead));
398 if (packetHead.packetType == RS_ALIVE_PACKET)
403 RS_PACKET_TAIL packetTail;
405 memset(packetTail.padding, 0, sizeof(packetTail.padding));
406 strcpy((char*)packetTail.magic, RS_ID);
407 vector<string>::const_iterator it;
409 for(it = rsSettings.GetUserParams().begin();
410 it != rsSettings.GetUserParams().end();
413 std::string parameter(GetUserParam(rsu.user, *it));
414 if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
416 params += parameter + " ";
418 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
419 packetTail.params[RS_PARAMS_LEN - 1] = 0;
421 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
423 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
427 //-----------------------------------------------------------------------------
428 bool REMOTE_SCRIPT::Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
430 char buffer[RS_MAX_PACKET_LEN];
432 memset(buffer, 0, sizeof(buffer));
434 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
436 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
443 PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
448 //-----------------------------------------------------------------------------
449 bool REMOTE_SCRIPT::SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect) const
451 char buffer[RS_MAX_PACKET_LEN];
453 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
455 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
459 struct sockaddr_in sendAddr;
461 sendAddr.sin_family = AF_INET;
462 sendAddr.sin_port = htons(rsSettings.GetPort());
463 sendAddr.sin_addr.s_addr = routerIP;
465 int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
467 return (res != sizeof(buffer));
469 //-----------------------------------------------------------------------------
470 bool REMOTE_SCRIPT::GetUsers()
474 int h = users->OpenSearch();
477 errorStr = "users->OpenSearch() error.";
478 printfd(__FILE__, "OpenSearch() error\n");
482 while (!users->SearchNext(h, &u))
487 users->CloseSearch(h);
490 //-----------------------------------------------------------------------------
491 void REMOTE_SCRIPT::ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP)
494 * When ip changes process looks like:
500 RS_USER rsu(IP2Routers(newIP), u);
503 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
504 authorizedUsers[newIP] = rsu;
508 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
509 const map<uint32_t, RS_USER>::iterator it(
510 authorizedUsers.find(oldIP)
512 if (it != authorizedUsers.end())
514 Send(oldIP, it->second, true);
515 authorizedUsers.erase(it);
519 //-----------------------------------------------------------------------------
520 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
522 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
523 for (size_t i = 0; i < netRouters.size(); ++i)
525 if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
527 return netRouters[i].routers;
530 return std::vector<uint32_t>();
532 //-----------------------------------------------------------------------------
533 string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const string & paramName) const
536 if (strcasecmp(paramName.c_str(), "cash") == 0)
537 strprintf(&value, "%f", u->GetProperty().cash.Get());
539 if (strcasecmp(paramName.c_str(), "freeMb") == 0)
540 strprintf(&value, "%f", u->GetProperty().freeMb.Get());
542 if (strcasecmp(paramName.c_str(), "passive") == 0)
543 strprintf(&value, "%d", u->GetProperty().passive.Get());
545 if (strcasecmp(paramName.c_str(), "disabled") == 0)
546 strprintf(&value, "%d", u->GetProperty().disabled.Get());
548 if (strcasecmp(paramName.c_str(), "alwaysOnline") == 0)
549 strprintf(&value, "%d", u->GetProperty().alwaysOnline.Get());
551 if (strcasecmp(paramName.c_str(), "tariffName") == 0 ||
552 strcasecmp(paramName.c_str(), "tariff") == 0)
553 value = "\"" + u->GetProperty().tariffName.Get() + "\"";
555 if (strcasecmp(paramName.c_str(), "nextTariff") == 0)
556 value = "\"" + u->GetProperty().nextTariff.Get() + "\"";
558 if (strcasecmp(paramName.c_str(), "address") == 0)
559 value = "\"" + u->GetProperty().address.Get() + "\"";
561 if (strcasecmp(paramName.c_str(), "note") == 0)
562 value = "\"" + u->GetProperty().note.Get() + "\"";
564 if (strcasecmp(paramName.c_str(), "group") == 0)
565 value = "\"" + u->GetProperty().group.Get() + "\"";
567 if (strcasecmp(paramName.c_str(), "email") == 0)
568 value = "\"" + u->GetProperty().email.Get() + "\"";
570 if (strcasecmp(paramName.c_str(), "realName") == 0)
571 value = "\"" + u->GetProperty().realName.Get() + "\"";
573 if (strcasecmp(paramName.c_str(), "credit") == 0)
574 strprintf(&value, "%f", u->GetProperty().credit.Get());
576 if (strcasecmp(paramName.c_str(), "userdata0") == 0)
577 value = "\"" + u->GetProperty().userdata0.Get() + "\"";
579 if (strcasecmp(paramName.c_str(), "userdata1") == 0)
580 value = "\"" + u->GetProperty().userdata1.Get() + "\"";
582 if (strcasecmp(paramName.c_str(), "userdata2") == 0)
583 value = "\"" + u->GetProperty().userdata2.Get() + "\"";
585 if (strcasecmp(paramName.c_str(), "userdata3") == 0)
586 value = "\"" + u->GetProperty().userdata3.Get() + "\"";
588 if (strcasecmp(paramName.c_str(), "userdata4") == 0)
589 value = "\"" + u->GetProperty().userdata4.Get() + "\"";
591 if (strcasecmp(paramName.c_str(), "userdata5") == 0)
592 value = "\"" + u->GetProperty().userdata5.Get() + "\"";
594 if (strcasecmp(paramName.c_str(), "userdata6") == 0)
595 value = "\"" + u->GetProperty().userdata6.Get() + "\"";
597 if (strcasecmp(paramName.c_str(), "userdata7") == 0)
598 value = "\"" + u->GetProperty().userdata7.Get() + "\"";
600 if (strcasecmp(paramName.c_str(), "userdata8") == 0)
601 value = "\"" + u->GetProperty().userdata8.Get() + "\"";
603 if (strcasecmp(paramName.c_str(), "userdata9") == 0)
604 value = "\"" + u->GetProperty().userdata9.Get() + "\"";
606 if (strcasecmp(paramName.c_str(), "enabledDirs") == 0)
607 value = u->GetEnabledDirs();
609 printfd(__FILE__, "Unknown value name: %s\n", paramName.c_str());
612 //-----------------------------------------------------------------------------
613 void REMOTE_SCRIPT::SetUserNotifier(USER_PTR u)
615 RS_CHG_AFTER_NOTIFIER<uint32_t> afterChgIPNotifier(*this, u);
617 afterChgIPNotifierList.push_front(afterChgIPNotifier);
619 u->AddCurrIPAfterNotifier(&(*afterChgIPNotifierList.begin()));
621 //-----------------------------------------------------------------------------
622 void REMOTE_SCRIPT::UnSetUserNotifier(USER_PTR u)
624 list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator ipAIter;
625 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator> toErase;
627 for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter)
629 if (ipAIter->GetUser() == u)
631 u->DelCurrIPAfterNotifier(&(*ipAIter));
632 toErase.push_back(ipAIter);
636 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator>::iterator eIter;
638 for (eIter = toErase.begin(); eIter != toErase.end(); ++eIter)
640 afterChgIPNotifierList.erase(*eIter);
643 //-----------------------------------------------------------------------------
644 template <typename varParamType>
645 void RS_CHG_AFTER_NOTIFIER<varParamType>::Notify(const varParamType & oldValue, const varParamType & newValue)
647 rs.ChangedIP(user, oldValue, newValue);
649 //-----------------------------------------------------------------------------
650 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
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);
657 //-----------------------------------------------------------------------------
658 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
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));
665 //-----------------------------------------------------------------------------