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 //-----------------------------------------------------------------------------
67 //-----------------------------------------------------------------------------
68 RS_USER::RS_USER(const std::vector<uint32_t> & r, USER_PTR it)
75 //-----------------------------------------------------------------------------
76 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 errorStr = nrMapParser.GetErrorStr();
159 netRouters = nrMapParser.GetMap();
161 if (netRouters.empty())
163 errorStr = "Parameter(s) \'Subnet*\' not found.";
164 printfd(__FILE__, "Parameter(s) 'Subnet*' not found\n");
170 //-----------------------------------------------------------------------------
171 //-----------------------------------------------------------------------------
172 //-----------------------------------------------------------------------------
173 REMOTE_SCRIPT::REMOTE_SCRIPT()
180 onAddUserNotifier(*this),
181 onDelUserNotifier(*this)
183 pthread_mutex_init(&mutex, NULL);
185 //-----------------------------------------------------------------------------
186 REMOTE_SCRIPT::~REMOTE_SCRIPT()
188 pthread_mutex_destroy(&mutex);
190 //-----------------------------------------------------------------------------
191 void * REMOTE_SCRIPT::Run(void * d)
193 REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
195 rs->isRunning = true;
203 rs->isRunning = false;
206 //-----------------------------------------------------------------------------
207 int REMOTE_SCRIPT::ParseSettings()
209 int ret = rsSettings.ParseSettings(settings);
211 errorStr = rsSettings.GetStrError();
213 sendPeriod = rsSettings.GetSendPeriod();
214 halfPeriod = sendPeriod / 2;
218 //-----------------------------------------------------------------------------
219 int REMOTE_SCRIPT::Start()
221 netRouters = rsSettings.GetSubnetsMap();
223 InitEncrypt(&ctx, rsSettings.GetPassword());
225 //onAddUserNotifier.SetRemoteScript(this);
226 //onDelUserNotifier.SetRemoteScript(this);
228 users->AddNotifierUserAdd(&onAddUserNotifier);
229 users->AddNotifierUserDel(&onDelUserNotifier);
245 if (pthread_create(&thread, NULL, Run, this))
247 errorStr = "Cannot create thread.";
248 printfd(__FILE__, "Cannot create thread\n");
256 //-----------------------------------------------------------------------------
257 int REMOTE_SCRIPT::Stop()
265 authorizedUsers.begin(),
266 authorizedUsers.end(),
267 DisconnectUser(*this)
274 //5 seconds to thread stops itself
275 for (int i = 0; i < 25 && isRunning; i++)
280 //after 5 seconds waiting thread still running. now killing it
283 if (pthread_kill(thread, SIGINT))
285 errorStr = "Cannot kill thread.";
286 printfd(__FILE__, "Cannot kill thread\n");
289 printfd(__FILE__, "REMOTE_SCRIPT killed Run\n");
293 users->DelNotifierUserDel(&onDelUserNotifier);
294 users->DelNotifierUserAdd(&onAddUserNotifier);
298 //-----------------------------------------------------------------------------
299 int REMOTE_SCRIPT::Reload()
301 NRMapParser nrMapParser;
303 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
305 errorStr = nrMapParser.GetErrorStr();
310 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
312 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
314 netRouters = nrMapParser.GetMap();
317 std::for_each(authorizedUsers.begin(),
318 authorizedUsers.end(),
319 UpdateRouter(*this));
323 //-----------------------------------------------------------------------------
324 bool REMOTE_SCRIPT::PrepareNet()
326 sock = socket(AF_INET, SOCK_DGRAM, 0);
330 errorStr = "Cannot create socket.";
331 printfd(__FILE__, "Cannot create socket\n");
337 //-----------------------------------------------------------------------------
338 bool REMOTE_SCRIPT::FinalizeNet()
343 //-----------------------------------------------------------------------------
344 void REMOTE_SCRIPT::PeriodicSend()
346 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
348 map<uint32_t, RS_USER>::iterator it(authorizedUsers.begin());
349 while (it != authorizedUsers.end())
351 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
352 //if (stgTime - it->second.lastSentTime > sendPeriod)
354 Send(it->first, it->second);
359 //-----------------------------------------------------------------------------
360 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
362 RS_PACKET_HEADER packetHead;
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';
370 packetHead.packetType = RS_DISCONNECT_PACKET;
374 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
377 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
382 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
385 rsu.shortPacketsCount++;
386 rsu.lastSentTime = stgTime;
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;
393 memcpy(buf, &packetHead, sizeof(packetHead));
395 if (packetHead.packetType == RS_ALIVE_PACKET)
400 RS_PACKET_TAIL packetTail;
402 memset(packetTail.padding, 0, sizeof(packetTail.padding));
403 strcpy((char*)packetTail.magic, RS_ID);
404 vector<string>::const_iterator it;
406 for(it = rsSettings.GetUserParams().begin();
407 it != rsSettings.GetUserParams().end();
410 std::string parameter(GetUserParam(rsu.user, *it));
411 if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
413 params += parameter + " ";
415 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
416 packetTail.params[RS_PARAMS_LEN - 1] = 0;
418 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
420 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
424 //-----------------------------------------------------------------------------
425 bool REMOTE_SCRIPT::Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
427 char buffer[RS_MAX_PACKET_LEN];
429 memset(buffer, 0, sizeof(buffer));
431 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
433 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
440 PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
445 //-----------------------------------------------------------------------------
446 bool REMOTE_SCRIPT::SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect) const
448 char buffer[RS_MAX_PACKET_LEN];
450 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
452 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
456 struct sockaddr_in sendAddr;
458 sendAddr.sin_family = AF_INET;
459 sendAddr.sin_port = htons(rsSettings.GetPort());
460 sendAddr.sin_addr.s_addr = routerIP;
462 int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
464 return (res != sizeof(buffer));
466 //-----------------------------------------------------------------------------
467 bool REMOTE_SCRIPT::GetUsers()
471 int h = users->OpenSearch();
474 errorStr = "users->OpenSearch() error.";
475 printfd(__FILE__, "OpenSearch() error\n");
479 while (!users->SearchNext(h, &u))
484 users->CloseSearch(h);
487 //-----------------------------------------------------------------------------
488 void REMOTE_SCRIPT::ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP)
491 * When ip changes process looks like:
497 RS_USER rsu(IP2Routers(newIP), u);
500 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
501 authorizedUsers[newIP] = rsu;
505 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
506 const map<uint32_t, RS_USER>::iterator it(
507 authorizedUsers.find(oldIP)
509 if (it != authorizedUsers.end())
511 Send(oldIP, it->second, true);
512 authorizedUsers.erase(it);
516 //-----------------------------------------------------------------------------
517 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
519 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
520 for (size_t i = 0; i < netRouters.size(); ++i)
522 if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
524 return netRouters[i].routers;
527 return std::vector<uint32_t>();
529 //-----------------------------------------------------------------------------
530 string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const string & paramName) const
533 if (strcasecmp(paramName.c_str(), "cash") == 0)
534 strprintf(&value, "%f", u->GetProperty().cash.Get());
536 if (strcasecmp(paramName.c_str(), "freeMb") == 0)
537 strprintf(&value, "%f", u->GetProperty().freeMb.Get());
539 if (strcasecmp(paramName.c_str(), "passive") == 0)
540 strprintf(&value, "%d", u->GetProperty().passive.Get());
542 if (strcasecmp(paramName.c_str(), "disabled") == 0)
543 strprintf(&value, "%d", u->GetProperty().disabled.Get());
545 if (strcasecmp(paramName.c_str(), "alwaysOnline") == 0)
546 strprintf(&value, "%d", u->GetProperty().alwaysOnline.Get());
548 if (strcasecmp(paramName.c_str(), "tariffName") == 0 ||
549 strcasecmp(paramName.c_str(), "tariff") == 0)
550 value = "\"" + u->GetProperty().tariffName.Get() + "\"";
552 if (strcasecmp(paramName.c_str(), "nextTariff") == 0)
553 value = "\"" + u->GetProperty().nextTariff.Get() + "\"";
555 if (strcasecmp(paramName.c_str(), "address") == 0)
556 value = "\"" + u->GetProperty().address.Get() + "\"";
558 if (strcasecmp(paramName.c_str(), "note") == 0)
559 value = "\"" + u->GetProperty().note.Get() + "\"";
561 if (strcasecmp(paramName.c_str(), "group") == 0)
562 value = "\"" + u->GetProperty().group.Get() + "\"";
564 if (strcasecmp(paramName.c_str(), "email") == 0)
565 value = "\"" + u->GetProperty().email.Get() + "\"";
567 if (strcasecmp(paramName.c_str(), "realName") == 0)
568 value = "\"" + u->GetProperty().realName.Get() + "\"";
570 if (strcasecmp(paramName.c_str(), "credit") == 0)
571 strprintf(&value, "%f", u->GetProperty().credit.Get());
573 if (strcasecmp(paramName.c_str(), "userdata0") == 0)
574 value = "\"" + u->GetProperty().userdata0.Get() + "\"";
576 if (strcasecmp(paramName.c_str(), "userdata1") == 0)
577 value = "\"" + u->GetProperty().userdata1.Get() + "\"";
579 if (strcasecmp(paramName.c_str(), "userdata2") == 0)
580 value = "\"" + u->GetProperty().userdata2.Get() + "\"";
582 if (strcasecmp(paramName.c_str(), "userdata3") == 0)
583 value = "\"" + u->GetProperty().userdata3.Get() + "\"";
585 if (strcasecmp(paramName.c_str(), "userdata4") == 0)
586 value = "\"" + u->GetProperty().userdata4.Get() + "\"";
588 if (strcasecmp(paramName.c_str(), "userdata5") == 0)
589 value = "\"" + u->GetProperty().userdata5.Get() + "\"";
591 if (strcasecmp(paramName.c_str(), "userdata6") == 0)
592 value = "\"" + u->GetProperty().userdata6.Get() + "\"";
594 if (strcasecmp(paramName.c_str(), "userdata7") == 0)
595 value = "\"" + u->GetProperty().userdata7.Get() + "\"";
597 if (strcasecmp(paramName.c_str(), "userdata8") == 0)
598 value = "\"" + u->GetProperty().userdata8.Get() + "\"";
600 if (strcasecmp(paramName.c_str(), "userdata9") == 0)
601 value = "\"" + u->GetProperty().userdata9.Get() + "\"";
603 if (strcasecmp(paramName.c_str(), "enabledDirs") == 0)
604 value = u->GetEnabledDirs();
606 printfd(__FILE__, "Unknown value name: %s\n", paramName.c_str());
609 //-----------------------------------------------------------------------------
610 void REMOTE_SCRIPT::SetUserNotifier(USER_PTR u)
612 RS_CHG_AFTER_NOTIFIER<uint32_t> afterChgIPNotifier(*this, u);
614 afterChgIPNotifierList.push_front(afterChgIPNotifier);
616 u->AddCurrIPAfterNotifier(&(*afterChgIPNotifierList.begin()));
618 //-----------------------------------------------------------------------------
619 void REMOTE_SCRIPT::UnSetUserNotifier(USER_PTR u)
621 list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator ipAIter;
622 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator> toErase;
624 for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter)
626 if (ipAIter->GetUser() == u)
628 u->DelCurrIPAfterNotifier(&(*ipAIter));
629 toErase.push_back(ipAIter);
633 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator>::iterator eIter;
635 for (eIter = toErase.begin(); eIter != toErase.end(); ++eIter)
637 afterChgIPNotifierList.erase(*eIter);
640 //-----------------------------------------------------------------------------
641 template <typename varParamType>
642 void RS_CHG_AFTER_NOTIFIER<varParamType>::Notify(const varParamType & oldValue, const varParamType & newValue)
644 rs.ChangedIP(user, oldValue, newValue);
646 //-----------------------------------------------------------------------------
647 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
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);
654 //-----------------------------------------------------------------------------
655 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
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));
662 //-----------------------------------------------------------------------------