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 //-----------------------------------------------------------------------------
361 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
363 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
366 RS_PACKET_HEADER packetHead;
368 memset(packetHead.padding, 0, sizeof(packetHead.padding));
369 strcpy((char*)packetHead.magic, RS_ID);
370 packetHead.protoVer[0] = '0';
371 packetHead.protoVer[1] = '2';
374 packetHead.packetType = RS_DISCONNECT_PACKET;
378 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
381 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
386 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
389 rsu.shortPacketsCount++;
390 rsu.lastSentTime = stgTime;
392 packetHead.ip = htonl(ip);
393 packetHead.id = htonl(rsu.user->GetID());
394 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
395 packetHead.login[RS_LOGIN_LEN - 1] = 0;
397 memcpy(buf, &packetHead, sizeof(packetHead));
399 if (packetHead.packetType == RS_ALIVE_PACKET)
404 RS_PACKET_TAIL packetTail;
406 memset(packetTail.padding, 0, sizeof(packetTail.padding));
407 strcpy((char*)packetTail.magic, RS_ID);
408 vector<string>::const_iterator it;
410 for(it = rsSettings.GetUserParams().begin();
411 it != rsSettings.GetUserParams().end();
414 std::string parameter(GetUserParam(rsu.user, *it));
415 if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
417 params += parameter + " ";
419 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
420 packetTail.params[RS_PARAMS_LEN - 1] = 0;
422 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
424 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
428 //-----------------------------------------------------------------------------
429 bool REMOTE_SCRIPT::Send(uint32_t ip, RS_USER & rsu, bool forceDisconnect) const
431 char buffer[RS_MAX_PACKET_LEN];
433 memset(buffer, 0, sizeof(buffer));
435 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
437 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
444 PacketSender(sock, buffer, sizeof(buffer), htons(rsSettings.GetPort()))
449 //-----------------------------------------------------------------------------
450 bool REMOTE_SCRIPT::SendDirect(uint32_t ip, RS_USER & rsu, uint32_t routerIP, bool forceDisconnect) const
452 char buffer[RS_MAX_PACKET_LEN];
454 if (PreparePacket(buffer, sizeof(buffer), ip, rsu, forceDisconnect))
456 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
460 struct sockaddr_in sendAddr;
462 sendAddr.sin_family = AF_INET;
463 sendAddr.sin_port = htons(rsSettings.GetPort());
464 sendAddr.sin_addr.s_addr = routerIP;
466 int res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
468 return (res != sizeof(buffer));
470 //-----------------------------------------------------------------------------
471 bool REMOTE_SCRIPT::GetUsers()
475 int h = users->OpenSearch();
478 errorStr = "users->OpenSearch() error.";
479 printfd(__FILE__, "OpenSearch() error\n");
483 while (!users->SearchNext(h, &u))
488 users->CloseSearch(h);
491 //-----------------------------------------------------------------------------
492 void REMOTE_SCRIPT::ChangedIP(USER_PTR u, uint32_t oldIP, uint32_t newIP)
495 * When ip changes process looks like:
501 RS_USER rsu(IP2Routers(newIP), u);
504 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
505 authorizedUsers[newIP] = rsu;
509 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
510 const map<uint32_t, RS_USER>::iterator it(
511 authorizedUsers.find(oldIP)
513 if (it != authorizedUsers.end())
515 Send(oldIP, it->second, true);
516 authorizedUsers.erase(it);
520 //-----------------------------------------------------------------------------
521 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
523 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
524 for (size_t i = 0; i < netRouters.size(); ++i)
526 if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
528 return netRouters[i].routers;
531 return std::vector<uint32_t>();
533 //-----------------------------------------------------------------------------
534 string REMOTE_SCRIPT::GetUserParam(USER_PTR u, const string & paramName) const
537 if (strcasecmp(paramName.c_str(), "cash") == 0)
538 strprintf(&value, "%f", u->GetProperty().cash.Get());
540 if (strcasecmp(paramName.c_str(), "freeMb") == 0)
541 strprintf(&value, "%f", u->GetProperty().freeMb.Get());
543 if (strcasecmp(paramName.c_str(), "passive") == 0)
544 strprintf(&value, "%d", u->GetProperty().passive.Get());
546 if (strcasecmp(paramName.c_str(), "disabled") == 0)
547 strprintf(&value, "%d", u->GetProperty().disabled.Get());
549 if (strcasecmp(paramName.c_str(), "alwaysOnline") == 0)
550 strprintf(&value, "%d", u->GetProperty().alwaysOnline.Get());
552 if (strcasecmp(paramName.c_str(), "tariffName") == 0 ||
553 strcasecmp(paramName.c_str(), "tariff") == 0)
554 value = "\"" + u->GetProperty().tariffName.Get() + "\"";
556 if (strcasecmp(paramName.c_str(), "nextTariff") == 0)
557 value = "\"" + u->GetProperty().nextTariff.Get() + "\"";
559 if (strcasecmp(paramName.c_str(), "address") == 0)
560 value = "\"" + u->GetProperty().address.Get() + "\"";
562 if (strcasecmp(paramName.c_str(), "note") == 0)
563 value = "\"" + u->GetProperty().note.Get() + "\"";
565 if (strcasecmp(paramName.c_str(), "group") == 0)
566 value = "\"" + u->GetProperty().group.Get() + "\"";
568 if (strcasecmp(paramName.c_str(), "email") == 0)
569 value = "\"" + u->GetProperty().email.Get() + "\"";
571 if (strcasecmp(paramName.c_str(), "realName") == 0)
572 value = "\"" + u->GetProperty().realName.Get() + "\"";
574 if (strcasecmp(paramName.c_str(), "credit") == 0)
575 strprintf(&value, "%f", u->GetProperty().credit.Get());
577 if (strcasecmp(paramName.c_str(), "userdata0") == 0)
578 value = "\"" + u->GetProperty().userdata0.Get() + "\"";
580 if (strcasecmp(paramName.c_str(), "userdata1") == 0)
581 value = "\"" + u->GetProperty().userdata1.Get() + "\"";
583 if (strcasecmp(paramName.c_str(), "userdata2") == 0)
584 value = "\"" + u->GetProperty().userdata2.Get() + "\"";
586 if (strcasecmp(paramName.c_str(), "userdata3") == 0)
587 value = "\"" + u->GetProperty().userdata3.Get() + "\"";
589 if (strcasecmp(paramName.c_str(), "userdata4") == 0)
590 value = "\"" + u->GetProperty().userdata4.Get() + "\"";
592 if (strcasecmp(paramName.c_str(), "userdata5") == 0)
593 value = "\"" + u->GetProperty().userdata5.Get() + "\"";
595 if (strcasecmp(paramName.c_str(), "userdata6") == 0)
596 value = "\"" + u->GetProperty().userdata6.Get() + "\"";
598 if (strcasecmp(paramName.c_str(), "userdata7") == 0)
599 value = "\"" + u->GetProperty().userdata7.Get() + "\"";
601 if (strcasecmp(paramName.c_str(), "userdata8") == 0)
602 value = "\"" + u->GetProperty().userdata8.Get() + "\"";
604 if (strcasecmp(paramName.c_str(), "userdata9") == 0)
605 value = "\"" + u->GetProperty().userdata9.Get() + "\"";
607 if (strcasecmp(paramName.c_str(), "enabledDirs") == 0)
608 value = u->GetEnabledDirs();
610 printfd(__FILE__, "Unknown value name: %s\n", paramName.c_str());
613 //-----------------------------------------------------------------------------
614 void REMOTE_SCRIPT::SetUserNotifier(USER_PTR u)
616 RS_CHG_AFTER_NOTIFIER<uint32_t> afterChgIPNotifier(*this, u);
618 afterChgIPNotifierList.push_front(afterChgIPNotifier);
620 u->AddCurrIPAfterNotifier(&(*afterChgIPNotifierList.begin()));
622 //-----------------------------------------------------------------------------
623 void REMOTE_SCRIPT::UnSetUserNotifier(USER_PTR u)
625 list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator ipAIter;
626 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator> toErase;
628 for (ipAIter = afterChgIPNotifierList.begin(); ipAIter != afterChgIPNotifierList.end(); ++ipAIter)
630 if (ipAIter->GetUser() == u)
632 u->DelCurrIPAfterNotifier(&(*ipAIter));
633 toErase.push_back(ipAIter);
637 std::list<list<RS_CHG_AFTER_NOTIFIER<uint32_t> >::iterator>::iterator eIter;
639 for (eIter = toErase.begin(); eIter != toErase.end(); ++eIter)
641 afterChgIPNotifierList.erase(*eIter);
644 //-----------------------------------------------------------------------------
645 template <typename varParamType>
646 void RS_CHG_AFTER_NOTIFIER<varParamType>::Notify(const varParamType & oldValue, const varParamType & newValue)
648 rs.ChangedIP(user, oldValue, newValue);
650 //-----------------------------------------------------------------------------
651 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const string & password) const
653 unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
654 memset(keyL, 0, PASSWD_LEN);
655 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
656 Blowfish_Init(ctx, keyL, PASSWD_LEN);
658 //-----------------------------------------------------------------------------
659 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, size_t len8) const
662 memcpy(dst, src, len8 * 8);
663 for (size_t i = 0; i < len8; ++i)
664 Blowfish_Encrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
666 //-----------------------------------------------------------------------------