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 $
34 #include "stg/common.h"
35 #include "stg/locker.h"
36 #include "stg/user_property.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 //-----------------------------------------------------------------------------
46 //-----------------------------------------------------------------------------
47 //-----------------------------------------------------------------------------
55 : rs(new REMOTE_SCRIPT())
63 REMOTE_SCRIPT * GetPlugin()
68 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
72 //-----------------------------------------------------------------------------
73 //-----------------------------------------------------------------------------
74 //-----------------------------------------------------------------------------
77 return rsc.GetPlugin();
79 //-----------------------------------------------------------------------------
80 //-----------------------------------------------------------------------------
81 //-----------------------------------------------------------------------------
88 //-----------------------------------------------------------------------------
89 RS_USER::RS_USER(const std::vector<uint32_t> & r, USER_PTR it)
96 //-----------------------------------------------------------------------------
97 RS_SETTINGS::RS_SETTINGS()
102 //-----------------------------------------------------------------------------
103 int RS_SETTINGS::ParseIntInRange(const string & str, int min, int max, int * val)
105 if (str2x(str.c_str(), *val))
107 errorStr = "Incorrect value \'" + str + "\'.";
110 if (*val < min || *val > max)
112 errorStr = "Value \'" + str + "\' out of range.";
117 //-----------------------------------------------------------------------------
118 int RS_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
122 vector<PARAM_VALUE>::const_iterator pvi;
124 ///////////////////////////
126 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
127 if (pvi == s.moduleParams.end())
129 errorStr = "Parameter \'Port\' not found.";
130 printfd(__FILE__, "Parameter 'Port' not found\n");
133 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
135 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
136 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
140 ///////////////////////////
141 pv.param = "SendPeriod";
142 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
143 if (pvi == s.moduleParams.end())
145 errorStr = "Parameter \'SendPeriod\' not found.";
146 printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
150 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod))
152 errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
153 printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
156 ///////////////////////////
157 pv.param = "UserParams";
158 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
159 if (pvi == s.moduleParams.end())
161 errorStr = "Parameter \'UserParams\' not found.";
162 printfd(__FILE__, "Parameter 'UserParams' not found\n");
165 userParams = pvi->value;
166 ///////////////////////////
167 pv.param = "Password";
168 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
169 if (pvi == s.moduleParams.end())
171 errorStr = "Parameter \'Password\' not found.";
172 printfd(__FILE__, "Parameter 'Password' not found\n");
175 password = pvi->value[0];
176 ///////////////////////////
177 pv.param = "SubnetFile";
178 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
179 if (pvi == s.moduleParams.end())
181 errorStr = "Parameter \'SubnetFile\' not found.";
182 printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
185 subnetFile = pvi->value[0];
187 NRMapParser nrMapParser;
189 if (nrMapParser.ReadFile(subnetFile))
191 errorStr = nrMapParser.GetErrorStr();
195 netRouters = nrMapParser.GetMap();
197 if (netRouters.empty())
199 errorStr = "Parameter(s) \'Subnet*\' not found.";
200 printfd(__FILE__, "Parameter(s) 'Subnet*' not found\n");
206 //-----------------------------------------------------------------------------
207 //-----------------------------------------------------------------------------
208 //-----------------------------------------------------------------------------
209 REMOTE_SCRIPT::REMOTE_SCRIPT()
216 onAddUserNotifier(*this),
217 onDelUserNotifier(*this)
219 pthread_mutex_init(&mutex, NULL);
221 //-----------------------------------------------------------------------------
222 REMOTE_SCRIPT::~REMOTE_SCRIPT()
224 pthread_mutex_destroy(&mutex);
226 //-----------------------------------------------------------------------------
227 void * REMOTE_SCRIPT::Run(void * d)
229 REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
231 rs->isRunning = true;
239 rs->isRunning = false;
242 //-----------------------------------------------------------------------------
243 int REMOTE_SCRIPT::ParseSettings()
245 int ret = rsSettings.ParseSettings(settings);
247 errorStr = rsSettings.GetStrError();
249 sendPeriod = rsSettings.GetSendPeriod();
250 halfPeriod = sendPeriod / 2;
254 //-----------------------------------------------------------------------------
255 int REMOTE_SCRIPT::Start()
257 netRouters = rsSettings.GetSubnetsMap();
259 InitEncrypt(&ctx, rsSettings.GetPassword());
261 //onAddUserNotifier.SetRemoteScript(this);
262 //onDelUserNotifier.SetRemoteScript(this);
264 users->AddNotifierUserAdd(&onAddUserNotifier);
265 users->AddNotifierUserDel(&onDelUserNotifier);
281 if (pthread_create(&thread, NULL, Run, this))
283 errorStr = "Cannot create thread.";
284 printfd(__FILE__, "Cannot create thread\n");
292 //-----------------------------------------------------------------------------
293 int REMOTE_SCRIPT::Stop()
301 authorizedUsers.begin(),
302 authorizedUsers.end(),
303 DisconnectUser(*this)
310 //5 seconds to thread stops itself
311 for (int i = 0; i < 25 && isRunning; i++)
316 //after 5 seconds waiting thread still running. now killing it
319 if (pthread_kill(thread, SIGINT))
321 errorStr = "Cannot kill thread.";
322 printfd(__FILE__, "Cannot kill thread\n");
325 printfd(__FILE__, "REMOTE_SCRIPT killed Run\n");
329 users->DelNotifierUserDel(&onDelUserNotifier);
330 users->DelNotifierUserAdd(&onAddUserNotifier);
334 //-----------------------------------------------------------------------------
335 int REMOTE_SCRIPT::Reload()
337 NRMapParser nrMapParser;
339 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
341 errorStr = nrMapParser.GetErrorStr();
346 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
348 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
350 netRouters = nrMapParser.GetMap();
353 std::for_each(authorizedUsers.begin(),
354 authorizedUsers.end(),
355 UpdateRouter(*this));
359 //-----------------------------------------------------------------------------
360 bool REMOTE_SCRIPT::PrepareNet()
362 sock = socket(AF_INET, SOCK_DGRAM, 0);
366 errorStr = "Cannot create socket.";
367 printfd(__FILE__, "Cannot create socket\n");
373 //-----------------------------------------------------------------------------
374 bool REMOTE_SCRIPT::FinalizeNet()
379 //-----------------------------------------------------------------------------
380 void REMOTE_SCRIPT::PeriodicSend()
382 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
384 map<uint32_t, RS_USER>::iterator it(authorizedUsers.begin());
385 while (it != authorizedUsers.end())
387 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
388 //if (stgTime - it->second.lastSentTime > sendPeriod)
390 Send(it->first, it->second);
395 //-----------------------------------------------------------------------------
396 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
398 RS_PACKET_HEADER packetHead;
400 memset(packetHead.padding, 0, sizeof(packetHead.padding));
401 strcpy((char*)packetHead.magic, RS_ID);
402 packetHead.protoVer[0] = '0';
403 packetHead.protoVer[1] = '2';
406 packetHead.packetType = RS_DISCONNECT_PACKET;
410 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
413 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
418 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
421 rsu.shortPacketsCount++;
422 rsu.lastSentTime = stgTime;
424 packetHead.ip = htonl(ip);
425 packetHead.id = htonl(rsu.user->GetID());
426 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
427 packetHead.login[RS_LOGIN_LEN - 1] = 0;
429 memcpy(buf, &packetHead, sizeof(packetHead));
431 if (packetHead.packetType == RS_ALIVE_PACKET)
436 RS_PACKET_TAIL packetTail;
438 memset(packetTail.padding, 0, sizeof(packetTail.padding));
439 strcpy((char*)packetTail.magic, RS_ID);
440 vector<string>::const_iterator it;
442 for(it = rsSettings.GetUserParams().begin();
443 it != rsSettings.GetUserParams().end();
446 std::string parameter(GetUserParam(rsu.user, *it));
447 if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
449 params += parameter + " ";
451 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
452 packetTail.params[RS_PARAMS_LEN - 1] = 0;
454 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
456 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
460 //-----------------------------------------------------------------------------
461 bool REMOTE_SCRIPT::Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
463 char buffer[RS_MAX_PACKET_LEN];
465 memset(buffer, 0, sizeof(buffer));
467 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
469 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
476 PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
481 //-----------------------------------------------------------------------------
482 bool REMOTE_SCRIPT::SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect) const
484 char buffer[RS_MAX_PACKET_LEN];
486 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
488 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
492 struct sockaddr_in sendAddr;
494 sendAddr.sin_family = AF_INET;
495 sendAddr.sin_port = htons(rsSettings.GetPort());
496 sendAddr.sin_addr.s_addr = routerIP;
498 int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
500 return (res != sizeof(buffer));
502 //-----------------------------------------------------------------------------
503 bool REMOTE_SCRIPT::GetUsers()
507 int h = users->OpenSearch();
510 errorStr = "users->OpenSearch() error.";
511 printfd(__FILE__, "OpenSearch() error\n");
515 while (!users->SearchNext(h, &u))
520 users->CloseSearch(h);
523 //-----------------------------------------------------------------------------
524 void REMOTE_SCRIPT::ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP)
527 * When ip changes process looks like:
533 RS_USER rsu(IP2Routers(newIP), u);
536 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
537 authorizedUsers[newIP] = rsu;
541 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
542 const map<uint32_t, RS_USER>::iterator it(
543 authorizedUsers.find(oldIP)
545 if (it != authorizedUsers.end())
547 Send(oldIP, it->second, true);
548 authorizedUsers.erase(it);
552 //-----------------------------------------------------------------------------
553 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
555 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
556 for (size_t i = 0; i < netRouters.size(); ++i)
558 if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
560 return netRouters[i].routers;
563 return std::vector<uint32_t>();
565 //-----------------------------------------------------------------------------
566 string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const string & paramName) const
569 if (strcasecmp(paramName.c_str(), "cash") == 0)
570 strprintf(&value, "%f", u->GetProperty().cash.Get());
572 if (strcasecmp(paramName.c_str(), "freeMb") == 0)
573 strprintf(&value, "%f", u->GetProperty().freeMb.Get());
575 if (strcasecmp(paramName.c_str(), "passive") == 0)
576 strprintf(&value, "%d", u->GetProperty().passive.Get());
578 if (strcasecmp(paramName.c_str(), "disabled") == 0)
579 strprintf(&value, "%d", u->GetProperty().disabled.Get());
581 if (strcasecmp(paramName.c_str(), "alwaysOnline") == 0)
582 strprintf(&value, "%d", u->GetProperty().alwaysOnline.Get());
584 if (strcasecmp(paramName.c_str(), "tariffName") == 0 ||
585 strcasecmp(paramName.c_str(), "tariff") == 0)
586 value = "\"" + u->GetProperty().tariffName.Get() + "\"";
588 if (strcasecmp(paramName.c_str(), "nextTariff") == 0)
589 value = "\"" + u->GetProperty().nextTariff.Get() + "\"";
591 if (strcasecmp(paramName.c_str(), "address") == 0)
592 value = "\"" + u->GetProperty().address.Get() + "\"";
594 if (strcasecmp(paramName.c_str(), "note") == 0)
595 value = "\"" + u->GetProperty().note.Get() + "\"";
597 if (strcasecmp(paramName.c_str(), "group") == 0)
598 value = "\"" + u->GetProperty().group.Get() + "\"";
600 if (strcasecmp(paramName.c_str(), "email") == 0)
601 value = "\"" + u->GetProperty().email.Get() + "\"";
603 if (strcasecmp(paramName.c_str(), "realName") == 0)
604 value = "\"" + u->GetProperty().realName.Get() + "\"";
606 if (strcasecmp(paramName.c_str(), "credit") == 0)
607 strprintf(&value, "%f", u->GetProperty().credit.Get());
609 if (strcasecmp(paramName.c_str(), "userdata0") == 0)
610 value = "\"" + u->GetProperty().userdata0.Get() + "\"";
612 if (strcasecmp(paramName.c_str(), "userdata1") == 0)
613 value = "\"" + u->GetProperty().userdata1.Get() + "\"";
615 if (strcasecmp(paramName.c_str(), "userdata2") == 0)
616 value = "\"" + u->GetProperty().userdata2.Get() + "\"";
618 if (strcasecmp(paramName.c_str(), "userdata3") == 0)
619 value = "\"" + u->GetProperty().userdata3.Get() + "\"";
621 if (strcasecmp(paramName.c_str(), "userdata4") == 0)
622 value = "\"" + u->GetProperty().userdata4.Get() + "\"";
624 if (strcasecmp(paramName.c_str(), "userdata5") == 0)
625 value = "\"" + u->GetProperty().userdata5.Get() + "\"";
627 if (strcasecmp(paramName.c_str(), "userdata6") == 0)
628 value = "\"" + u->GetProperty().userdata6.Get() + "\"";
630 if (strcasecmp(paramName.c_str(), "userdata7") == 0)
631 value = "\"" + u->GetProperty().userdata7.Get() + "\"";
633 if (strcasecmp(paramName.c_str(), "userdata8") == 0)
634 value = "\"" + u->GetProperty().userdata8.Get() + "\"";
636 if (strcasecmp(paramName.c_str(), "userdata9") == 0)
637 value = "\"" + u->GetProperty().userdata9.Get() + "\"";
639 if (strcasecmp(paramName.c_str(), "enabledDirs") == 0)
640 value = u->GetEnabledDirs();
642 printfd(__FILE__, "Unknown value name: %s\n", paramName.c_str());
645 //-----------------------------------------------------------------------------
646 void REMOTE_SCRIPT::SetUserNotifier(USER_PTR u)
648 RS_CHG_AFTER_NOTIFIER<uint32_t> afterChgIPNotifier(*this, u);
650 afterChgIPNotifierList.push_front(afterChgIPNotifier);
652 u->AddCurrIPAfterNotifier(&(*afterChgIPNotifierList.begin()));
654 //-----------------------------------------------------------------------------
655 void REMOTE_SCRIPT::UnSetUserNotifier(USER_PTR u)
657 list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator ipAIter;
658 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator> toErase;
660 for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter)
662 if (ipAIter->GetUser() == u)
664 u->DelCurrIPAfterNotifier(&(*ipAIter));
665 toErase.push_back(ipAIter);
669 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator>::iterator eIter;
671 for (eIter = toErase.begin(); eIter != toErase.end(); ++eIter)
673 afterChgIPNotifierList.erase(*eIter);
676 //-----------------------------------------------------------------------------
677 template <typename varParamType>
678 void RS_CHG_AFTER_NOTIFIER<varParamType>::Notify(const varParamType & oldValue, const varParamType & newValue)
680 rs.ChangedIP(user, oldValue, newValue);
682 //-----------------------------------------------------------------------------
683 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
685 unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
686 memset(keyL, 0, PASSWD_LEN);
687 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
688 Blowfish_Init(ctx, keyL, PASSWD_LEN);
690 //-----------------------------------------------------------------------------
691 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
694 memcpy(dst, src, len8 * 8);
695 for (size_t i = 0; i < len8; ++i)
696 Blowfish_Encrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
698 //-----------------------------------------------------------------------------