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"
40 #include "ur_functor.h"
41 #include "send_functor.h"
43 extern volatile const time_t stgTime;
45 #define RS_MAX_ROUTERS (100)
47 //-----------------------------------------------------------------------------
48 //-----------------------------------------------------------------------------
49 //-----------------------------------------------------------------------------
50 PLUGIN_CREATOR<REMOTE_SCRIPT> rsc;
51 //-----------------------------------------------------------------------------
52 //-----------------------------------------------------------------------------
53 //-----------------------------------------------------------------------------
56 return rsc.GetPlugin();
58 //-----------------------------------------------------------------------------
59 //-----------------------------------------------------------------------------
60 //-----------------------------------------------------------------------------
61 RS_USER & RS_USER::operator=(const RS_USER & rvalue)
63 lastSentTime = rvalue.lastSentTime;
65 routers = rvalue.routers;
66 shortPacketsCount = rvalue.shortPacketsCount;
69 //-----------------------------------------------------------------------------
70 RS_SETTINGS::RS_SETTINGS()
80 //-----------------------------------------------------------------------------
81 int RS_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
85 vector<PARAM_VALUE>::const_iterator pvi;
87 ///////////////////////////
89 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
90 if (pvi == s.moduleParams.end())
92 errorStr = "Parameter \'Port\' not found.";
93 printfd(__FILE__, "Parameter 'Port' not found\n");
96 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
98 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
99 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
103 ///////////////////////////
104 pv.param = "SendPeriod";
105 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
106 if (pvi == s.moduleParams.end())
108 errorStr = "Parameter \'SendPeriod\' not found.";
109 printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
113 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod))
115 errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
116 printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
119 ///////////////////////////
120 pv.param = "UserParams";
121 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
122 if (pvi == s.moduleParams.end())
124 errorStr = "Parameter \'UserParams\' not found.";
125 printfd(__FILE__, "Parameter 'UserParams' not found\n");
128 userParams = pvi->value;
129 ///////////////////////////
130 pv.param = "Password";
131 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
132 if (pvi == s.moduleParams.end())
134 errorStr = "Parameter \'Password\' not found.";
135 printfd(__FILE__, "Parameter 'Password' not found\n");
138 password = pvi->value[0];
139 ///////////////////////////
140 pv.param = "SubnetFile";
141 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
142 if (pvi == s.moduleParams.end())
144 errorStr = "Parameter \'SubnetFile\' not found.";
145 printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
148 subnetFile = pvi->value[0];
150 NRMapParser nrMapParser;
152 if (nrMapParser.ReadFile(subnetFile))
154 errorStr = nrMapParser.GetErrorStr();
158 netRouters = nrMapParser.GetMap();
160 if (netRouters.empty())
162 errorStr = "Parameter(s) \'Subnet*\' not found.";
163 printfd(__FILE__, "Parameter(s) 'Subnet*' not found\n");
169 //-----------------------------------------------------------------------------
170 //-----------------------------------------------------------------------------
171 //-----------------------------------------------------------------------------
172 REMOTE_SCRIPT::REMOTE_SCRIPT()
174 afterChgIPNotifierList(),
188 onAddUserNotifier(*this),
189 onDelUserNotifier(*this)
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 //onAddUserNotifier.SetRemoteScript(this);
238 //onDelUserNotifier.SetRemoteScript(this);
240 users->AddNotifierUserAdd(&onAddUserNotifier);
241 users->AddNotifierUserDel(&onDelUserNotifier);
257 if (pthread_create(&thread, NULL, Run, this))
259 errorStr = "Cannot create thread.";
260 printfd(__FILE__, "Cannot create thread\n");
268 //-----------------------------------------------------------------------------
269 int REMOTE_SCRIPT::Stop()
277 authorizedUsers.begin(),
278 authorizedUsers.end(),
279 DisconnectUser(*this)
286 //5 seconds to thread stops itself
287 for (int i = 0; i < 25 && isRunning; i++)
289 struct timespec ts = {0, 200000000};
290 nanosleep(&ts, NULL);
293 //after 5 seconds waiting thread still running. now killing it
296 if (pthread_kill(thread, SIGINT))
298 errorStr = "Cannot kill thread.";
299 printfd(__FILE__, "Cannot kill thread\n");
302 printfd(__FILE__, "REMOTE_SCRIPT killed Run\n");
306 users->DelNotifierUserDel(&onDelUserNotifier);
307 users->DelNotifierUserAdd(&onAddUserNotifier);
311 //-----------------------------------------------------------------------------
312 int REMOTE_SCRIPT::Reload()
314 NRMapParser nrMapParser;
316 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
318 errorStr = nrMapParser.GetErrorStr();
323 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
325 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
327 netRouters = nrMapParser.GetMap();
330 std::for_each(authorizedUsers.begin(),
331 authorizedUsers.end(),
332 UpdateRouter(*this));
336 //-----------------------------------------------------------------------------
337 bool REMOTE_SCRIPT::PrepareNet()
339 sock = socket(AF_INET, SOCK_DGRAM, 0);
343 errorStr = "Cannot create socket.";
344 printfd(__FILE__, "Cannot create socket\n");
350 //-----------------------------------------------------------------------------
351 bool REMOTE_SCRIPT::FinalizeNet()
356 //-----------------------------------------------------------------------------
357 void REMOTE_SCRIPT::PeriodicSend()
359 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
361 map<uint32_t, RS_USER>::iterator it(authorizedUsers.begin());
362 while (it != authorizedUsers.end())
364 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
365 //if (stgTime - it->second.lastSentTime > sendPeriod)
367 Send(it->first, it->second);
372 //-----------------------------------------------------------------------------
374 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
376 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
379 RS_PACKET_HEADER packetHead;
381 memset(packetHead.padding, 0, sizeof(packetHead.padding));
382 strcpy((char*)packetHead.magic, RS_ID);
383 packetHead.protoVer[0] = '0';
384 packetHead.protoVer[1] = '2';
387 packetHead.packetType = RS_DISCONNECT_PACKET;
391 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
394 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
399 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
402 rsu.shortPacketsCount++;
403 rsu.lastSentTime = stgTime;
405 packetHead.ip = htonl(ip);
406 packetHead.id = htonl(rsu.user->GetID());
407 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
408 packetHead.login[RS_LOGIN_LEN - 1] = 0;
410 memcpy(buf, &packetHead, sizeof(packetHead));
412 if (packetHead.packetType == RS_ALIVE_PACKET)
417 RS_PACKET_TAIL packetTail;
419 memset(packetTail.padding, 0, sizeof(packetTail.padding));
420 strcpy((char*)packetTail.magic, RS_ID);
421 vector<string>::const_iterator it;
423 for(it = rsSettings.GetUserParams().begin();
424 it != rsSettings.GetUserParams().end();
427 std::string parameter(GetUserParam(rsu.user, *it));
428 if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
430 params += parameter + " ";
432 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
433 packetTail.params[RS_PARAMS_LEN - 1] = 0;
435 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
437 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
441 //-----------------------------------------------------------------------------
442 bool REMOTE_SCRIPT::Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
444 char buffer[RS_MAX_PACKET_LEN];
446 memset(buffer, 0, sizeof(buffer));
448 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
450 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
457 PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
462 //-----------------------------------------------------------------------------
463 bool REMOTE_SCRIPT::SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect) const
465 char buffer[RS_MAX_PACKET_LEN];
467 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
469 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
473 struct sockaddr_in sendAddr;
475 sendAddr.sin_family = AF_INET;
476 sendAddr.sin_port = htons(rsSettings.GetPort());
477 sendAddr.sin_addr.s_addr = routerIP;
479 int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
481 return (res != sizeof(buffer));
483 //-----------------------------------------------------------------------------
484 bool REMOTE_SCRIPT::GetUsers()
488 int h = users->OpenSearch();
491 errorStr = "users->OpenSearch() error.";
492 printfd(__FILE__, "OpenSearch() error\n");
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[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(oldIP, 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::SetUserNotifier(USER_PTR u)
629 RS_CHG_AFTER_NOTIFIER<uint32_t> afterChgIPNotifier(*this, u);
631 afterChgIPNotifierList.push_front(afterChgIPNotifier);
633 u->AddCurrIPAfterNotifier(&(*afterChgIPNotifierList.begin()));
635 //-----------------------------------------------------------------------------
636 void REMOTE_SCRIPT::UnSetUserNotifier(USER_PTR u)
638 list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator ipAIter;
639 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator> toErase;
641 for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter)
643 if (ipAIter->GetUser() == u)
645 u->DelCurrIPAfterNotifier(&(*ipAIter));
646 toErase.push_back(ipAIter);
650 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator>::iterator eIter;
652 for (eIter = toErase.begin(); eIter != toErase.end(); ++eIter)
654 afterChgIPNotifierList.erase(*eIter);
657 //-----------------------------------------------------------------------------
658 template <typename varParamType>
659 void RS_CHG_AFTER_NOTIFIER<varParamType>::Notify(const varParamType & oldValue, const varParamType & newValue)
661 rs.ChangedIP(user, oldValue, newValue);
663 //-----------------------------------------------------------------------------
664 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
666 unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
667 memset(keyL, 0, PASSWD_LEN);
668 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
669 Blowfish_Init(ctx, keyL, PASSWD_LEN);
671 //-----------------------------------------------------------------------------
672 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
675 memcpy(dst, src, len8 * 8);
676 for (size_t i = 0; i < len8; ++i)
677 Blowfish_Encrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
679 //-----------------------------------------------------------------------------