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>
31 #include "stg/common.h"
32 #include "stg/locker.h"
33 #include "stg/users.h"
34 #include "stg/user_property.h"
35 #include "stg/plugin_creator.h"
36 #include "stg/logger.h"
38 #include "ur_functor.h"
39 #include "send_functor.h"
41 extern volatile const time_t stgTime;
43 #define RS_MAX_ROUTERS (100)
45 using RS::REMOTE_SCRIPT;
52 USER_IS(USER_PTR u) : user(u) {}
53 bool operator()(const T & notifier) { return notifier.GetUser() == user; }
58 } // namespace anonymous
60 //-----------------------------------------------------------------------------
61 //-----------------------------------------------------------------------------
62 //-----------------------------------------------------------------------------
63 PLUGIN_CREATOR<REMOTE_SCRIPT> rsc;
64 //-----------------------------------------------------------------------------
65 //-----------------------------------------------------------------------------
66 //-----------------------------------------------------------------------------
69 return rsc.GetPlugin();
71 //-----------------------------------------------------------------------------
72 //-----------------------------------------------------------------------------
73 //-----------------------------------------------------------------------------
74 RS::SETTINGS::SETTINGS()
84 //-----------------------------------------------------------------------------
85 int RS::SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
89 vector<PARAM_VALUE>::const_iterator pvi;
91 ///////////////////////////
93 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
94 if (pvi == s.moduleParams.end())
96 errorStr = "Parameter \'Port\' not found.";
97 printfd(__FILE__, "Parameter 'Port' not found\n");
100 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
102 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
103 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
107 ///////////////////////////
108 pv.param = "SendPeriod";
109 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
110 if (pvi == s.moduleParams.end())
112 errorStr = "Parameter \'SendPeriod\' not found.";
113 printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
117 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod))
119 errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
120 printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
123 ///////////////////////////
124 pv.param = "UserParams";
125 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
126 if (pvi == s.moduleParams.end())
128 errorStr = "Parameter \'UserParams\' not found.";
129 printfd(__FILE__, "Parameter 'UserParams' not found\n");
132 userParams = pvi->value;
133 ///////////////////////////
134 pv.param = "Password";
135 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
136 if (pvi == s.moduleParams.end())
138 errorStr = "Parameter \'Password\' not found.";
139 printfd(__FILE__, "Parameter 'Password' not found\n");
142 password = pvi->value[0];
143 ///////////////////////////
144 pv.param = "SubnetFile";
145 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
146 if (pvi == s.moduleParams.end())
148 errorStr = "Parameter \'SubnetFile\' not found.";
149 printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
152 subnetFile = pvi->value[0];
154 NRMapParser nrMapParser;
156 if (!nrMapParser.ReadFile(subnetFile))
158 netRouters = nrMapParser.GetMap();
162 GetStgLogger()("mod_rscript: error opening subnets file '%s'", subnetFile.c_str());
167 //-----------------------------------------------------------------------------
168 //-----------------------------------------------------------------------------
169 //-----------------------------------------------------------------------------
170 REMOTE_SCRIPT::REMOTE_SCRIPT()
187 onAddUserNotifier(*this),
188 onDelUserNotifier(*this),
189 logger(GetPluginLogger(GetStgLogger(), "rscript"))
191 pthread_mutex_init(&mutex, NULL);
193 //-----------------------------------------------------------------------------
194 REMOTE_SCRIPT::~REMOTE_SCRIPT()
196 pthread_mutex_destroy(&mutex);
198 //-----------------------------------------------------------------------------
199 void * REMOTE_SCRIPT::Run(void * d)
202 sigfillset(&signalSet);
203 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
205 REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
207 rs->isRunning = true;
215 rs->isRunning = false;
218 //-----------------------------------------------------------------------------
219 int REMOTE_SCRIPT::ParseSettings()
221 int ret = rsSettings.ParseSettings(settings);
223 errorStr = rsSettings.GetStrError();
225 sendPeriod = rsSettings.GetSendPeriod();
226 halfPeriod = sendPeriod / 2;
230 //-----------------------------------------------------------------------------
231 int REMOTE_SCRIPT::Start()
233 netRouters = rsSettings.GetSubnetsMap();
235 InitEncrypt(&ctx, rsSettings.GetPassword());
237 users->AddNotifierUserAdd(&onAddUserNotifier);
238 users->AddNotifierUserDel(&onDelUserNotifier);
254 if (pthread_create(&thread, NULL, Run, this))
256 errorStr = "Cannot create thread.";
257 logger("Cannot create thread.");
258 printfd(__FILE__, "Cannot create thread\n");
266 //-----------------------------------------------------------------------------
267 int REMOTE_SCRIPT::Stop()
275 authorizedUsers.begin(),
276 authorizedUsers.end(),
277 DisconnectUser(*this)
284 //5 seconds to thread stops itself
285 for (int i = 0; i < 25 && isRunning; i++)
287 struct timespec ts = {0, 200000000};
288 nanosleep(&ts, NULL);
292 users->DelNotifierUserDel(&onDelUserNotifier);
293 users->DelNotifierUserAdd(&onAddUserNotifier);
297 logger("Cannot stop thread.");
303 //-----------------------------------------------------------------------------
304 int REMOTE_SCRIPT::Reload()
306 NRMapParser nrMapParser;
308 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
310 errorStr = nrMapParser.GetErrorStr();
311 logger("Map file reading error: %s", errorStr.c_str());
316 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
318 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
320 netRouters = nrMapParser.GetMap();
323 std::for_each(authorizedUsers.begin(),
324 authorizedUsers.end(),
325 UpdateRouter(*this));
329 //-----------------------------------------------------------------------------
330 bool REMOTE_SCRIPT::PrepareNet()
332 sock = socket(AF_INET, SOCK_DGRAM, 0);
336 errorStr = "Cannot create socket.";
337 logger("Canot create a socket: %s", strerror(errno));
338 printfd(__FILE__, "Cannot create socket\n");
344 //-----------------------------------------------------------------------------
345 bool REMOTE_SCRIPT::FinalizeNet()
350 //-----------------------------------------------------------------------------
351 void REMOTE_SCRIPT::PeriodicSend()
353 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
355 map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
356 while (it != authorizedUsers.end())
358 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
365 //-----------------------------------------------------------------------------
367 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, RS::USER & rsu, bool forceDisconnect) const
369 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, RS::USER & rsu, bool forceDisconnect) const
372 RS::PACKET_HEADER packetHead;
374 memset(packetHead.padding, 0, sizeof(packetHead.padding));
375 strcpy((char*)packetHead.magic, RS_ID);
376 packetHead.protoVer[0] = '0';
377 packetHead.protoVer[1] = '2';
380 packetHead.packetType = RS_DISCONNECT_PACKET;
381 printfd(__FILE__, "RSCRIPT: force disconnect for '%s'\n", rsu.user->GetLogin().c_str());
385 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
388 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
389 if (rsu.user->IsInetable())
390 printfd(__FILE__, "RSCRIPT: connect for '%s'\n", rsu.user->GetLogin().c_str());
392 printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
397 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
398 if (rsu.user->IsInetable())
399 printfd(__FILE__, "RSCRIPT: alive for '%s'\n", rsu.user->GetLogin().c_str());
401 printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
404 rsu.shortPacketsCount++;
405 rsu.lastSentTime = stgTime;
407 packetHead.ip = htonl(rsu.ip);
408 packetHead.id = htonl(rsu.user->GetID());
409 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
410 packetHead.login[RS_LOGIN_LEN - 1] = 0;
412 memcpy(buf, &packetHead, sizeof(packetHead));
414 if (packetHead.packetType == RS_ALIVE_PACKET)
419 RS::PACKET_TAIL packetTail;
421 memset(packetTail.padding, 0, sizeof(packetTail.padding));
422 strcpy((char*)packetTail.magic, RS_ID);
423 vector<string>::const_iterator it;
425 for(it = rsSettings.GetUserParams().begin();
426 it != rsSettings.GetUserParams().end();
429 std::string parameter(GetUserParam(rsu.user, *it));
430 if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
432 params += parameter + " ";
434 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
435 packetTail.params[RS_PARAMS_LEN - 1] = 0;
437 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
439 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
443 //-----------------------------------------------------------------------------
444 bool REMOTE_SCRIPT::Send(RS::USER & rsu, bool forceDisconnect) const
446 char buffer[RS_MAX_PACKET_LEN];
448 memset(buffer, 0, sizeof(buffer));
450 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
452 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
459 PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
464 //-----------------------------------------------------------------------------
465 bool REMOTE_SCRIPT::SendDirect(RS::USER & rsu, uint32_t routerIP, bool forceDisconnect) const
467 char buffer[RS_MAX_PACKET_LEN];
469 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
471 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
475 struct sockaddr_in sendAddr;
477 sendAddr.sin_family = AF_INET;
478 sendAddr.sin_port = htons(rsSettings.GetPort());
479 sendAddr.sin_addr.s_addr = routerIP;
481 int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
484 logger("sendto error: %s", strerror(errno));
486 return (res != sizeof(buffer));
488 //-----------------------------------------------------------------------------
489 bool REMOTE_SCRIPT::GetUsers()
493 int h = users->OpenSearch();
494 assert(h && "USERS::OpenSearch is always correct");
496 while (!users->SearchNext(h, &u))
501 users->CloseSearch(h);
504 //-----------------------------------------------------------------------------
505 void REMOTE_SCRIPT::ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP)
508 * When ip changes process looks like:
514 RS::USER rsu(IP2Routers(newIP), u);
517 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
518 authorizedUsers.insert(std::make_pair(newIP, rsu));
522 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
523 const map<uint32_t, RS::USER>::iterator it(
524 authorizedUsers.find(oldIP)
526 if (it != authorizedUsers.end())
528 Send(it->second, true);
529 authorizedUsers.erase(it);
533 //-----------------------------------------------------------------------------
534 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
536 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
537 for (size_t i = 0; i < netRouters.size(); ++i)
539 if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
541 return netRouters[i].routers;
544 return std::vector<uint32_t>();
546 //-----------------------------------------------------------------------------
547 string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const string & paramName) const
550 if (strcasecmp(paramName.c_str(), "cash") == 0)
551 strprintf(&value, "%f", u->GetProperty().cash.Get());
553 if (strcasecmp(paramName.c_str(), "freeMb") == 0)
554 strprintf(&value, "%f", u->GetProperty().freeMb.Get());
556 if (strcasecmp(paramName.c_str(), "passive") == 0)
557 strprintf(&value, "%d", u->GetProperty().passive.Get());
559 if (strcasecmp(paramName.c_str(), "disabled") == 0)
560 strprintf(&value, "%d", u->GetProperty().disabled.Get());
562 if (strcasecmp(paramName.c_str(), "alwaysOnline") == 0)
563 strprintf(&value, "%d", u->GetProperty().alwaysOnline.Get());
565 if (strcasecmp(paramName.c_str(), "tariffName") == 0 ||
566 strcasecmp(paramName.c_str(), "tariff") == 0)
567 value = "\"" + u->GetProperty().tariffName.Get() + "\"";
569 if (strcasecmp(paramName.c_str(), "nextTariff") == 0)
570 value = "\"" + u->GetProperty().nextTariff.Get() + "\"";
572 if (strcasecmp(paramName.c_str(), "address") == 0)
573 value = "\"" + u->GetProperty().address.Get() + "\"";
575 if (strcasecmp(paramName.c_str(), "note") == 0)
576 value = "\"" + u->GetProperty().note.Get() + "\"";
578 if (strcasecmp(paramName.c_str(), "group") == 0)
579 value = "\"" + u->GetProperty().group.Get() + "\"";
581 if (strcasecmp(paramName.c_str(), "email") == 0)
582 value = "\"" + u->GetProperty().email.Get() + "\"";
584 if (strcasecmp(paramName.c_str(), "realName") == 0)
585 value = "\"" + u->GetProperty().realName.Get() + "\"";
587 if (strcasecmp(paramName.c_str(), "credit") == 0)
588 strprintf(&value, "%f", u->GetProperty().credit.Get());
590 if (strcasecmp(paramName.c_str(), "userdata0") == 0)
591 value = "\"" + u->GetProperty().userdata0.Get() + "\"";
593 if (strcasecmp(paramName.c_str(), "userdata1") == 0)
594 value = "\"" + u->GetProperty().userdata1.Get() + "\"";
596 if (strcasecmp(paramName.c_str(), "userdata2") == 0)
597 value = "\"" + u->GetProperty().userdata2.Get() + "\"";
599 if (strcasecmp(paramName.c_str(), "userdata3") == 0)
600 value = "\"" + u->GetProperty().userdata3.Get() + "\"";
602 if (strcasecmp(paramName.c_str(), "userdata4") == 0)
603 value = "\"" + u->GetProperty().userdata4.Get() + "\"";
605 if (strcasecmp(paramName.c_str(), "userdata5") == 0)
606 value = "\"" + u->GetProperty().userdata5.Get() + "\"";
608 if (strcasecmp(paramName.c_str(), "userdata6") == 0)
609 value = "\"" + u->GetProperty().userdata6.Get() + "\"";
611 if (strcasecmp(paramName.c_str(), "userdata7") == 0)
612 value = "\"" + u->GetProperty().userdata7.Get() + "\"";
614 if (strcasecmp(paramName.c_str(), "userdata8") == 0)
615 value = "\"" + u->GetProperty().userdata8.Get() + "\"";
617 if (strcasecmp(paramName.c_str(), "userdata9") == 0)
618 value = "\"" + u->GetProperty().userdata9.Get() + "\"";
620 if (strcasecmp(paramName.c_str(), "enabledDirs") == 0)
621 value = u->GetEnabledDirs();
623 printfd(__FILE__, "Unknown value name: %s\n", paramName.c_str());
626 //-----------------------------------------------------------------------------
627 void REMOTE_SCRIPT::SetUserNotifiers(USER_PTR u)
629 ipNotifierList.push_front(RS::IP_NOTIFIER(*this, u));
630 connNotifierList.push_front(RS::CONNECTED_NOTIFIER(*this, u));
632 //-----------------------------------------------------------------------------
633 void REMOTE_SCRIPT::UnSetUserNotifiers(USER_PTR u)
635 ipNotifierList.erase(std::remove_if(ipNotifierList.begin(),
636 ipNotifierList.end(),
637 USER_IS<IP_NOTIFIER>(u)),
638 ipNotifierList.end());
639 connNotifierList.erase(std::remove_if(connNotifierList.begin(),
640 connNotifierList.end(),
641 USER_IS<CONNECTED_NOTIFIER>(u)),
642 connNotifierList.end());
645 //-----------------------------------------------------------------------------
646 void REMOTE_SCRIPT::AddRSU(USER_PTR user)
648 RS::USER rsu(IP2Routers(user->GetCurrIP()), user);
651 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
652 authorizedUsers.insert(std::make_pair(user->GetCurrIP(), rsu));
654 //-----------------------------------------------------------------------------
655 void REMOTE_SCRIPT::DelRSU(USER_PTR user)
657 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
658 const map<uint32_t, RS::USER>::iterator it(
659 authorizedUsers.find(user->GetCurrIP())
661 if (it != authorizedUsers.end())
663 Send(it->second, true);
664 authorizedUsers.erase(it);
667 //-----------------------------------------------------------------------------
668 void RS::IP_NOTIFIER::Notify(const uint32_t & /*oldValue*/, const uint32_t & newValue)
670 //rs.ChangedIP(user, oldValue, newValue);
676 //-----------------------------------------------------------------------------
677 void RS::CONNECTED_NOTIFIER::Notify(const bool & /*oldValue*/, const bool & newValue)
684 //-----------------------------------------------------------------------------
685 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
687 unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
688 memset(keyL, 0, PASSWD_LEN);
689 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
690 Blowfish_Init(ctx, keyL, PASSWD_LEN);
692 //-----------------------------------------------------------------------------
693 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
696 memcpy(dst, src, len8 * 8);
697 for (size_t i = 0; i < len8; ++i)
698 Blowfish_Encrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
700 //-----------------------------------------------------------------------------