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"
39 #include "ur_functor.h"
40 #include "send_functor.h"
42 extern volatile const time_t stgTime;
44 #define RS_MAX_ROUTERS (100)
46 //-----------------------------------------------------------------------------
47 //-----------------------------------------------------------------------------
48 //-----------------------------------------------------------------------------
56 : rs(new REMOTE_SCRIPT())
64 REMOTE_SCRIPT * GetPlugin()
69 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
71 //-----------------------------------------------------------------------------
73 //-----------------------------------------------------------------------------
74 //-----------------------------------------------------------------------------
75 //-----------------------------------------------------------------------------
78 return rsc.GetPlugin();
80 //-----------------------------------------------------------------------------
81 //-----------------------------------------------------------------------------
82 //-----------------------------------------------------------------------------
89 //-----------------------------------------------------------------------------
90 RS_USER::RS_USER(const std::vector<uint32_t> & r, USER_PTR it)
97 //-----------------------------------------------------------------------------
98 RS_SETTINGS::RS_SETTINGS()
103 //-----------------------------------------------------------------------------
104 int RS_SETTINGS::ParseIntInRange(const string & str, int min, int max, int * val)
106 if (str2x(str.c_str(), *val))
108 errorStr = "Incorrect value \'" + str + "\'.";
111 if (*val < min || *val > max)
113 errorStr = "Value \'" + str + "\' out of range.";
118 //-----------------------------------------------------------------------------
119 int RS_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
123 vector<PARAM_VALUE>::const_iterator pvi;
125 ///////////////////////////
127 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
128 if (pvi == s.moduleParams.end())
130 errorStr = "Parameter \'Port\' not found.";
131 printfd(__FILE__, "Parameter 'Port' not found\n");
134 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
136 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
137 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
141 ///////////////////////////
142 pv.param = "SendPeriod";
143 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
144 if (pvi == s.moduleParams.end())
146 errorStr = "Parameter \'SendPeriod\' not found.";
147 printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
151 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod))
153 errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
154 printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
157 ///////////////////////////
158 pv.param = "UserParams";
159 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
160 if (pvi == s.moduleParams.end())
162 errorStr = "Parameter \'UserParams\' not found.";
163 printfd(__FILE__, "Parameter 'UserParams' not found\n");
166 userParams = pvi->value;
167 ///////////////////////////
168 pv.param = "Password";
169 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
170 if (pvi == s.moduleParams.end())
172 errorStr = "Parameter \'Password\' not found.";
173 printfd(__FILE__, "Parameter 'Password' not found\n");
176 password = pvi->value[0];
177 ///////////////////////////
178 pv.param = "SubnetFile";
179 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
180 if (pvi == s.moduleParams.end())
182 errorStr = "Parameter \'SubnetFile\' not found.";
183 printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
186 subnetFile = pvi->value[0];
188 NRMapParser nrMapParser;
190 if (nrMapParser.ReadFile(subnetFile))
192 errorStr = nrMapParser.GetErrorStr();
196 netRouters = nrMapParser.GetMap();
198 if (netRouters.empty())
200 errorStr = "Parameter(s) \'Subnet*\' not found.";
201 printfd(__FILE__, "Parameter(s) 'Subnet*' not found\n");
207 //-----------------------------------------------------------------------------
208 //-----------------------------------------------------------------------------
209 //-----------------------------------------------------------------------------
210 REMOTE_SCRIPT::REMOTE_SCRIPT()
217 onAddUserNotifier(*this),
218 onDelUserNotifier(*this)
220 pthread_mutex_init(&mutex, NULL);
222 //-----------------------------------------------------------------------------
223 REMOTE_SCRIPT::~REMOTE_SCRIPT()
225 pthread_mutex_destroy(&mutex);
227 //-----------------------------------------------------------------------------
228 void * REMOTE_SCRIPT::Run(void * d)
230 REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
232 rs->isRunning = true;
240 rs->isRunning = false;
243 //-----------------------------------------------------------------------------
244 int REMOTE_SCRIPT::ParseSettings()
246 int ret = rsSettings.ParseSettings(settings);
248 errorStr = rsSettings.GetStrError();
250 sendPeriod = rsSettings.GetSendPeriod();
251 halfPeriod = sendPeriod / 2;
255 //-----------------------------------------------------------------------------
256 int REMOTE_SCRIPT::Start()
258 netRouters = rsSettings.GetSubnetsMap();
260 InitEncrypt(&ctx, rsSettings.GetPassword());
262 //onAddUserNotifier.SetRemoteScript(this);
263 //onDelUserNotifier.SetRemoteScript(this);
265 users->AddNotifierUserAdd(&onAddUserNotifier);
266 users->AddNotifierUserDel(&onDelUserNotifier);
282 if (pthread_create(&thread, NULL, Run, this))
284 errorStr = "Cannot create thread.";
285 printfd(__FILE__, "Cannot create thread\n");
293 //-----------------------------------------------------------------------------
294 int REMOTE_SCRIPT::Stop()
302 authorizedUsers.begin(),
303 authorizedUsers.end(),
304 DisconnectUser(*this)
311 //5 seconds to thread stops itself
312 for (int i = 0; i < 25 && isRunning; i++)
317 //after 5 seconds waiting thread still running. now killing it
320 if (pthread_kill(thread, SIGINT))
322 errorStr = "Cannot kill thread.";
323 printfd(__FILE__, "Cannot kill thread\n");
326 printfd(__FILE__, "REMOTE_SCRIPT killed Run\n");
330 users->DelNotifierUserDel(&onDelUserNotifier);
331 users->DelNotifierUserAdd(&onAddUserNotifier);
335 //-----------------------------------------------------------------------------
336 int REMOTE_SCRIPT::Reload()
338 NRMapParser nrMapParser;
340 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
342 errorStr = nrMapParser.GetErrorStr();
347 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
349 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
351 netRouters = nrMapParser.GetMap();
354 std::for_each(authorizedUsers.begin(),
355 authorizedUsers.end(),
356 UpdateRouter(*this));
360 //-----------------------------------------------------------------------------
361 bool REMOTE_SCRIPT::PrepareNet()
363 sock = socket(AF_INET, SOCK_DGRAM, 0);
367 errorStr = "Cannot create socket.";
368 printfd(__FILE__, "Cannot create socket\n");
374 //-----------------------------------------------------------------------------
375 bool REMOTE_SCRIPT::FinalizeNet()
380 //-----------------------------------------------------------------------------
381 void REMOTE_SCRIPT::PeriodicSend()
383 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
385 map<uint32_t, RS_USER>::iterator it(authorizedUsers.begin());
386 while (it != authorizedUsers.end())
388 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
389 //if (stgTime - it->second.lastSentTime > sendPeriod)
391 Send(it->first, it->second);
396 //-----------------------------------------------------------------------------
397 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
399 RS_PACKET_HEADER packetHead;
401 memset(packetHead.padding, 0, sizeof(packetHead.padding));
402 strcpy((char*)packetHead.magic, RS_ID);
403 packetHead.protoVer[0] = '0';
404 packetHead.protoVer[1] = '2';
407 packetHead.packetType = RS_DISCONNECT_PACKET;
411 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
414 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
419 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
422 rsu.shortPacketsCount++;
423 rsu.lastSentTime = stgTime;
425 packetHead.ip = htonl(ip);
426 packetHead.id = htonl(rsu.user->GetID());
427 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
428 packetHead.login[RS_LOGIN_LEN - 1] = 0;
430 memcpy(buf, &packetHead, sizeof(packetHead));
432 if (packetHead.packetType == RS_ALIVE_PACKET)
437 RS_PACKET_TAIL packetTail;
439 memset(packetTail.padding, 0, sizeof(packetTail.padding));
440 strcpy((char*)packetTail.magic, RS_ID);
441 vector<string>::const_iterator it;
443 for(it = rsSettings.GetUserParams().begin();
444 it != rsSettings.GetUserParams().end();
447 std::string parameter(GetUserParam(rsu.user, *it));
448 if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
450 params += parameter + " ";
452 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
453 packetTail.params[RS_PARAMS_LEN - 1] = 0;
455 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
457 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
461 //-----------------------------------------------------------------------------
462 bool REMOTE_SCRIPT::Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
464 char buffer[RS_MAX_PACKET_LEN];
466 memset(buffer, 0, sizeof(buffer));
468 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
470 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
477 PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
482 //-----------------------------------------------------------------------------
483 bool REMOTE_SCRIPT::SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect) const
485 char buffer[RS_MAX_PACKET_LEN];
487 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
489 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
493 struct sockaddr_in sendAddr;
495 sendAddr.sin_family = AF_INET;
496 sendAddr.sin_port = htons(rsSettings.GetPort());
497 sendAddr.sin_addr.s_addr = routerIP;
499 int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
501 return (res != sizeof(buffer));
503 //-----------------------------------------------------------------------------
504 bool REMOTE_SCRIPT::GetUsers()
508 int h = users->OpenSearch();
511 errorStr = "users->OpenSearch() error.";
512 printfd(__FILE__, "OpenSearch() error\n");
516 while (!users->SearchNext(h, &u))
521 users->CloseSearch(h);
524 //-----------------------------------------------------------------------------
525 void REMOTE_SCRIPT::ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP)
528 * When ip changes process looks like:
534 RS_USER rsu(IP2Routers(newIP), u);
537 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
538 authorizedUsers[newIP] = rsu;
542 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
543 const map<uint32_t, RS_USER>::iterator it(
544 authorizedUsers.find(oldIP)
546 if (it != authorizedUsers.end())
548 Send(oldIP, it->second, true);
549 authorizedUsers.erase(it);
553 //-----------------------------------------------------------------------------
554 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
556 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
557 for (size_t i = 0; i < netRouters.size(); ++i)
559 if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
561 return netRouters[i].routers;
564 return std::vector<uint32_t>();
566 //-----------------------------------------------------------------------------
567 string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const string & paramName) const
570 if (strcasecmp(paramName.c_str(), "cash") == 0)
571 strprintf(&value, "%f", u->GetProperty().cash.Get());
573 if (strcasecmp(paramName.c_str(), "freeMb") == 0)
574 strprintf(&value, "%f", u->GetProperty().freeMb.Get());
576 if (strcasecmp(paramName.c_str(), "passive") == 0)
577 strprintf(&value, "%d", u->GetProperty().passive.Get());
579 if (strcasecmp(paramName.c_str(), "disabled") == 0)
580 strprintf(&value, "%d", u->GetProperty().disabled.Get());
582 if (strcasecmp(paramName.c_str(), "alwaysOnline") == 0)
583 strprintf(&value, "%d", u->GetProperty().alwaysOnline.Get());
585 if (strcasecmp(paramName.c_str(), "tariffName") == 0 ||
586 strcasecmp(paramName.c_str(), "tariff") == 0)
587 value = "\"" + u->GetProperty().tariffName.Get() + "\"";
589 if (strcasecmp(paramName.c_str(), "nextTariff") == 0)
590 value = "\"" + u->GetProperty().nextTariff.Get() + "\"";
592 if (strcasecmp(paramName.c_str(), "address") == 0)
593 value = "\"" + u->GetProperty().address.Get() + "\"";
595 if (strcasecmp(paramName.c_str(), "note") == 0)
596 value = "\"" + u->GetProperty().note.Get() + "\"";
598 if (strcasecmp(paramName.c_str(), "group") == 0)
599 value = "\"" + u->GetProperty().group.Get() + "\"";
601 if (strcasecmp(paramName.c_str(), "email") == 0)
602 value = "\"" + u->GetProperty().email.Get() + "\"";
604 if (strcasecmp(paramName.c_str(), "realName") == 0)
605 value = "\"" + u->GetProperty().realName.Get() + "\"";
607 if (strcasecmp(paramName.c_str(), "credit") == 0)
608 strprintf(&value, "%f", u->GetProperty().credit.Get());
610 if (strcasecmp(paramName.c_str(), "userdata0") == 0)
611 value = "\"" + u->GetProperty().userdata0.Get() + "\"";
613 if (strcasecmp(paramName.c_str(), "userdata1") == 0)
614 value = "\"" + u->GetProperty().userdata1.Get() + "\"";
616 if (strcasecmp(paramName.c_str(), "userdata2") == 0)
617 value = "\"" + u->GetProperty().userdata2.Get() + "\"";
619 if (strcasecmp(paramName.c_str(), "userdata3") == 0)
620 value = "\"" + u->GetProperty().userdata3.Get() + "\"";
622 if (strcasecmp(paramName.c_str(), "userdata4") == 0)
623 value = "\"" + u->GetProperty().userdata4.Get() + "\"";
625 if (strcasecmp(paramName.c_str(), "userdata5") == 0)
626 value = "\"" + u->GetProperty().userdata5.Get() + "\"";
628 if (strcasecmp(paramName.c_str(), "userdata6") == 0)
629 value = "\"" + u->GetProperty().userdata6.Get() + "\"";
631 if (strcasecmp(paramName.c_str(), "userdata7") == 0)
632 value = "\"" + u->GetProperty().userdata7.Get() + "\"";
634 if (strcasecmp(paramName.c_str(), "userdata8") == 0)
635 value = "\"" + u->GetProperty().userdata8.Get() + "\"";
637 if (strcasecmp(paramName.c_str(), "userdata9") == 0)
638 value = "\"" + u->GetProperty().userdata9.Get() + "\"";
640 if (strcasecmp(paramName.c_str(), "enabledDirs") == 0)
641 value = u->GetEnabledDirs();
643 printfd(__FILE__, "Unknown value name: %s\n", paramName.c_str());
646 //-----------------------------------------------------------------------------
647 void REMOTE_SCRIPT::SetUserNotifier(USER_PTR u)
649 RS_CHG_AFTER_NOTIFIER<uint32_t> afterChgIPNotifier(*this, u);
651 afterChgIPNotifierList.push_front(afterChgIPNotifier);
653 u->AddCurrIPAfterNotifier(&(*afterChgIPNotifierList.begin()));
655 //-----------------------------------------------------------------------------
656 void REMOTE_SCRIPT::UnSetUserNotifier(USER_PTR u)
658 list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator ipAIter;
659 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator> toErase;
661 for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter)
663 if (ipAIter->GetUser() == u)
665 u->DelCurrIPAfterNotifier(&(*ipAIter));
666 toErase.push_back(ipAIter);
670 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator>::iterator eIter;
672 for (eIter = toErase.begin(); eIter != toErase.end(); ++eIter)
674 afterChgIPNotifierList.erase(*eIter);
677 //-----------------------------------------------------------------------------
678 template <typename varParamType>
679 void RS_CHG_AFTER_NOTIFIER<varParamType>::Notify(const varParamType & oldValue, const varParamType & newValue)
681 rs.ChangedIP(user, oldValue, newValue);
683 //-----------------------------------------------------------------------------
684 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
686 unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
687 memset(keyL, 0, PASSWD_LEN);
688 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
689 Blowfish_Init(ctx, keyL, PASSWD_LEN);
691 //-----------------------------------------------------------------------------
692 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
695 memcpy(dst, src, len8 * 8);
696 for (size_t i = 0; i < len8; ++i)
697 Blowfish_Encrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
699 //-----------------------------------------------------------------------------