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 $
36 #include "ur_functor.h"
37 #include "send_functor.h"
39 extern volatile const time_t stgTime;
41 #define RS_MAX_ROUTERS (100)
43 //-----------------------------------------------------------------------------
44 //-----------------------------------------------------------------------------
45 //-----------------------------------------------------------------------------
53 : rs(new REMOTE_SCRIPT())
61 REMOTE_SCRIPT * GetPlugin()
66 //-----------------------------------------------------------------------------
67 //-----------------------------------------------------------------------------
68 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
71 //-----------------------------------------------------------------------------
72 //-----------------------------------------------------------------------------
73 BASE_PLUGIN * GetPlugin()
75 return rsc.GetPlugin();
77 //-----------------------------------------------------------------------------
78 //-----------------------------------------------------------------------------
79 //-----------------------------------------------------------------------------
85 //-----------------------------------------------------------------------------
86 RS_USER::RS_USER(const std::vector<uint32_t> & r, user_iter it)
93 //-----------------------------------------------------------------------------
94 RS_SETTINGS::RS_SETTINGS()
99 //-----------------------------------------------------------------------------
100 int RS_SETTINGS::ParseIntInRange(const string & str, int min, int max, int * val)
102 if (str2x(str.c_str(), *val))
104 errorStr = "Incorrect value \'" + str + "\'.";
107 if (*val < min || *val > max)
109 errorStr = "Value \'" + str + "\' out of range.";
114 //-----------------------------------------------------------------------------
115 int RS_SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
119 vector<PARAM_VALUE>::const_iterator pvi;
121 ///////////////////////////
123 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
124 if (pvi == s.moduleParams.end())
126 errorStr = "Parameter \'Port\' not found.";
127 printfd(__FILE__, "Parameter 'Port' not found\n");
130 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
132 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
133 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
137 ///////////////////////////
138 pv.param = "SendPeriod";
139 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
140 if (pvi == s.moduleParams.end())
142 errorStr = "Parameter \'SendPeriod\' not found.";
143 printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
147 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod))
149 errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
150 printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
153 ///////////////////////////
154 pv.param = "UserParams";
155 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
156 if (pvi == s.moduleParams.end())
158 errorStr = "Parameter \'UserParams\' not found.";
159 printfd(__FILE__, "Parameter 'UserParams' not found\n");
162 userParams = pvi->value;
163 ///////////////////////////
164 pv.param = "Password";
165 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
166 if (pvi == s.moduleParams.end())
168 errorStr = "Parameter \'Password\' not found.";
169 printfd(__FILE__, "Parameter 'Password' not found\n");
172 password = pvi->value[0];
173 ///////////////////////////
174 pv.param = "SubnetFile";
175 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
176 if (pvi == s.moduleParams.end())
178 errorStr = "Parameter \'SubnetFile\' not found.";
179 printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
182 subnetFile = pvi->value[0];
184 NRMapParser nrMapParser;
186 if (nrMapParser.ReadFile(subnetFile))
188 errorStr = nrMapParser.GetErrorStr();
192 netRouters = nrMapParser.GetMap();
194 if (netRouters.empty())
196 errorStr = "Parameter(s) \'Subnet*\' not found.";
197 printfd(__FILE__, "Parameter(s) 'Subnet*' not found\n");
203 //-----------------------------------------------------------------------------
204 //-----------------------------------------------------------------------------
205 //-----------------------------------------------------------------------------
206 REMOTE_SCRIPT::REMOTE_SCRIPT()
213 onAddUserNotifier(*this),
214 onDelUserNotifier(*this)
216 pthread_mutex_init(&mutex, NULL);
218 //-----------------------------------------------------------------------------
219 REMOTE_SCRIPT::~REMOTE_SCRIPT()
221 pthread_mutex_destroy(&mutex);
223 //-----------------------------------------------------------------------------
224 void * REMOTE_SCRIPT::Run(void * d)
226 REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
228 rs->isRunning = true;
236 rs->isRunning = false;
239 //-----------------------------------------------------------------------------
240 int REMOTE_SCRIPT::ParseSettings()
242 int ret = rsSettings.ParseSettings(settings);
244 errorStr = rsSettings.GetStrError();
246 sendPeriod = rsSettings.GetSendPeriod();
247 halfPeriod = sendPeriod / 2;
251 //-----------------------------------------------------------------------------
252 int REMOTE_SCRIPT::Start()
254 netRouters = rsSettings.GetSubnetsMap();
256 InitEncrypt(&ctx, rsSettings.GetPassword());
258 //onAddUserNotifier.SetRemoteScript(this);
259 //onDelUserNotifier.SetRemoteScript(this);
261 users->AddNotifierUserAdd(&onAddUserNotifier);
262 users->AddNotifierUserDel(&onDelUserNotifier);
278 if (pthread_create(&thread, NULL, Run, this))
280 errorStr = "Cannot create thread.";
281 printfd(__FILE__, "Cannot create thread\n");
289 //-----------------------------------------------------------------------------
290 int REMOTE_SCRIPT::Stop()
298 authorizedUsers.begin(),
299 authorizedUsers.end(),
300 DisconnectUser(*this)
307 //5 seconds to thread stops itself
308 for (int i = 0; i < 25 && isRunning; i++)
313 //after 5 seconds waiting thread still running. now killing it
316 if (pthread_kill(thread, SIGINT))
318 errorStr = "Cannot kill thread.";
319 printfd(__FILE__, "Cannot kill thread\n");
322 printfd(__FILE__, "REMOTE_SCRIPT killed Run\n");
326 users->DelNotifierUserDel(&onDelUserNotifier);
327 users->DelNotifierUserAdd(&onAddUserNotifier);
331 //-----------------------------------------------------------------------------
332 int REMOTE_SCRIPT::Reload()
334 NRMapParser nrMapParser;
336 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
338 errorStr = nrMapParser.GetErrorStr();
343 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
345 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
347 netRouters = nrMapParser.GetMap();
350 std::for_each(authorizedUsers.begin(),
351 authorizedUsers.end(),
352 UpdateRouter(*this));
356 //-----------------------------------------------------------------------------
357 bool REMOTE_SCRIPT::PrepareNet()
359 sock = socket(AF_INET, SOCK_DGRAM, 0);
363 errorStr = "Cannot create socket.";
364 printfd(__FILE__, "Cannot create socket\n");
370 //-----------------------------------------------------------------------------
371 bool REMOTE_SCRIPT::FinalizeNet()
376 //-----------------------------------------------------------------------------
377 void REMOTE_SCRIPT::PeriodicSend()
379 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
381 map<uint32_t, RS_USER>::iterator it(authorizedUsers.begin());
382 while (it != authorizedUsers.end())
384 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
385 //if (stgTime - it->second.lastSentTime > sendPeriod)
387 Send(it->first, it->second);
392 //-----------------------------------------------------------------------------
393 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
395 RS_PACKET_HEADER packetHead;
397 memset(packetHead.padding, 0, sizeof(packetHead.padding));
398 strcpy((char*)packetHead.magic, RS_ID);
399 packetHead.protoVer[0] = '0';
400 packetHead.protoVer[1] = '2';
403 packetHead.packetType = RS_DISCONNECT_PACKET;
407 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
410 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
415 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
418 rsu.shortPacketsCount++;
419 rsu.lastSentTime = stgTime;
421 packetHead.ip = htonl(ip);
422 packetHead.id = htonl(rsu.user->GetID());
423 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
424 packetHead.login[RS_LOGIN_LEN - 1] = 0;
426 memcpy(buf, &packetHead, sizeof(packetHead));
428 if (packetHead.packetType == RS_ALIVE_PACKET)
433 RS_PACKET_TAIL packetTail;
435 memset(packetTail.padding, 0, sizeof(packetTail.padding));
436 strcpy((char*)packetTail.magic, RS_ID);
437 vector<string>::const_iterator it;
439 for(it = rsSettings.GetUserParams().begin();
440 it != rsSettings.GetUserParams().end();
443 std::string parameter(GetUserParam(rsu.user, *it));
444 if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
446 params += parameter + " ";
448 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
449 packetTail.params[RS_PARAMS_LEN - 1] = 0;
451 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
453 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
457 //-----------------------------------------------------------------------------
458 bool REMOTE_SCRIPT::Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
460 char buffer[RS_MAX_PACKET_LEN];
462 memset(buffer, 0, sizeof(buffer));
464 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
466 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
473 PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
478 //-----------------------------------------------------------------------------
479 bool REMOTE_SCRIPT::SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect) const
481 char buffer[RS_MAX_PACKET_LEN];
483 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
485 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
489 struct sockaddr_in sendAddr;
491 sendAddr.sin_family = AF_INET;
492 sendAddr.sin_port = htons(rsSettings.GetPort());
493 sendAddr.sin_addr.s_addr = routerIP;
495 int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
497 return (res != sizeof(buffer));
499 //-----------------------------------------------------------------------------
500 bool REMOTE_SCRIPT::GetUsers()
504 int h = users->OpenSearch();
507 errorStr = "users->OpenSearch() error.";
508 printfd(__FILE__, "OpenSearch() error\n");
512 while (!users->SearchNext(h, &u))
517 users->CloseSearch(h);
520 //-----------------------------------------------------------------------------
521 void REMOTE_SCRIPT::ChangedIP(user_iter u, uint32_t oldIP, uint32_t newIP)
524 * When ip changes process looks like:
530 RS_USER rsu(IP2Routers(newIP), u);
533 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
534 authorizedUsers[newIP] = rsu;
538 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
539 const map<uint32_t, RS_USER>::iterator it(
540 authorizedUsers.find(oldIP)
542 if (it != authorizedUsers.end())
544 Send(oldIP, it->second, true);
545 authorizedUsers.erase(it);
549 //-----------------------------------------------------------------------------
550 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
552 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
553 for (size_t i = 0; i < netRouters.size(); ++i)
555 if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
557 return netRouters[i].routers;
560 return std::vector<uint32_t>();
562 //-----------------------------------------------------------------------------
563 string REMOTE_SCRIPT::GetUserParam(user_iter u, const string & paramName) const
566 if (strcasecmp(paramName.c_str(), "cash") == 0)
567 strprintf(&value, "%f", u->property.cash.Get());
569 if (strcasecmp(paramName.c_str(), "freeMb") == 0)
570 strprintf(&value, "%f", u->property.freeMb.Get());
572 if (strcasecmp(paramName.c_str(), "passive") == 0)
573 strprintf(&value, "%d", u->property.passive.Get());
575 if (strcasecmp(paramName.c_str(), "disabled") == 0)
576 strprintf(&value, "%d", u->property.disabled.Get());
578 if (strcasecmp(paramName.c_str(), "alwaysOnline") == 0)
579 strprintf(&value, "%d", u->property.alwaysOnline.Get());
581 if (strcasecmp(paramName.c_str(), "tariffName") == 0 ||
582 strcasecmp(paramName.c_str(), "tariff") == 0)
583 value = "\"" + u->property.tariffName.Get() + "\"";
585 if (strcasecmp(paramName.c_str(), "nextTariff") == 0)
586 value = "\"" + u->property.nextTariff.Get() + "\"";
588 if (strcasecmp(paramName.c_str(), "address") == 0)
589 value = "\"" + u->property.address.Get() + "\"";
591 if (strcasecmp(paramName.c_str(), "note") == 0)
592 value = "\"" + u->property.note.Get() + "\"";
594 if (strcasecmp(paramName.c_str(), "group") == 0)
595 value = "\"" + u->property.group.Get() + "\"";
597 if (strcasecmp(paramName.c_str(), "email") == 0)
598 value = "\"" + u->property.email.Get() + "\"";
600 if (strcasecmp(paramName.c_str(), "realName") == 0)
601 value = "\"" + u->property.realName.Get() + "\"";
603 if (strcasecmp(paramName.c_str(), "credit") == 0)
604 strprintf(&value, "%f", u->property.credit.Get());
606 if (strcasecmp(paramName.c_str(), "userdata0") == 0)
607 value = "\"" + u->property.userdata0.Get() + "\"";
609 if (strcasecmp(paramName.c_str(), "userdata1") == 0)
610 value = "\"" + u->property.userdata1.Get() + "\"";
612 if (strcasecmp(paramName.c_str(), "userdata2") == 0)
613 value = "\"" + u->property.userdata2.Get() + "\"";
615 if (strcasecmp(paramName.c_str(), "userdata3") == 0)
616 value = "\"" + u->property.userdata3.Get() + "\"";
618 if (strcasecmp(paramName.c_str(), "userdata4") == 0)
619 value = "\"" + u->property.userdata4.Get() + "\"";
621 if (strcasecmp(paramName.c_str(), "userdata5") == 0)
622 value = "\"" + u->property.userdata5.Get() + "\"";
624 if (strcasecmp(paramName.c_str(), "userdata6") == 0)
625 value = "\"" + u->property.userdata6.Get() + "\"";
627 if (strcasecmp(paramName.c_str(), "userdata7") == 0)
628 value = "\"" + u->property.userdata7.Get() + "\"";
630 if (strcasecmp(paramName.c_str(), "userdata8") == 0)
631 value = "\"" + u->property.userdata8.Get() + "\"";
633 if (strcasecmp(paramName.c_str(), "userdata9") == 0)
634 value = "\"" + u->property.userdata9.Get() + "\"";
636 if (strcasecmp(paramName.c_str(), "enabledDirs") == 0)
637 value = u->GetEnabledDirs();
639 printfd(__FILE__, "Unknown value name: %s\n", paramName.c_str());
642 //-----------------------------------------------------------------------------
643 void REMOTE_SCRIPT::SetUserNotifier(user_iter u)
645 RS_CHG_AFTER_NOTIFIER<uint32_t> afterChgIPNotifier(*this, u);
647 afterChgIPNotifierList.push_front(afterChgIPNotifier);
649 u->AddCurrIPAfterNotifier(&(*afterChgIPNotifierList.begin()));
651 //-----------------------------------------------------------------------------
652 void REMOTE_SCRIPT::UnSetUserNotifier(user_iter u)
654 list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator ipAIter;
655 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator> toErase;
657 for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter)
659 if (ipAIter->GetUser() == u)
661 u->DelCurrIPAfterNotifier(&(*ipAIter));
662 toErase.push_back(ipAIter);
666 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator>::iterator eIter;
668 for (eIter = toErase.begin(); eIter != toErase.end(); ++eIter)
670 afterChgIPNotifierList.erase(*eIter);
673 //-----------------------------------------------------------------------------
674 template <typename varParamType>
675 void RS_CHG_AFTER_NOTIFIER<varParamType>::Notify(const varParamType & oldValue, const varParamType & newValue)
677 rs.ChangedIP(user, oldValue, newValue);
679 //-----------------------------------------------------------------------------
680 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
682 unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
683 memset(keyL, 0, PASSWD_LEN);
684 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
685 Blowfish_Init(ctx, keyL, PASSWD_LEN);
687 //-----------------------------------------------------------------------------
688 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
691 memcpy(dst, src, len8 * 8);
692 for (size_t i = 0; i < len8; ++i)
693 Blowfish_Encrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
695 //-----------------------------------------------------------------------------