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>
31 #include "stg/common.h"
32 #include "stg/locker.h"
33 #include "stg/users.h"
34 #include "stg/user_property.h"
35 #include "stg/plugin_creator.h"
36 #include "stg/logger.h"
38 #include "ur_functor.h"
39 #include "send_functor.h"
41 extern volatile time_t stgTime;
43 using RS::REMOTE_SCRIPT;
50 USER_IS(USER_PTR u) : user(u) {}
51 bool operator()(const T & notifier) { return notifier.GetUser() == user; }
56 PLUGIN_CREATOR<REMOTE_SCRIPT> rsc;
58 } // namespace anonymous
60 extern "C" PLUGIN * GetPlugin();
61 //-----------------------------------------------------------------------------
62 //-----------------------------------------------------------------------------
63 //-----------------------------------------------------------------------------
64 //-----------------------------------------------------------------------------
65 //-----------------------------------------------------------------------------
66 //-----------------------------------------------------------------------------
69 return rsc.GetPlugin();
71 //-----------------------------------------------------------------------------
72 //-----------------------------------------------------------------------------
73 //-----------------------------------------------------------------------------
74 RS::SETTINGS::SETTINGS()
79 //-----------------------------------------------------------------------------
80 int RS::SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
84 std::vector<PARAM_VALUE>::const_iterator pvi;
86 ///////////////////////////
88 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
89 if (pvi == s.moduleParams.end() || pvi->value.empty())
91 errorStr = "Parameter \'Port\' not found.";
92 printfd(__FILE__, "Parameter 'Port' not found\n");
95 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
97 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
98 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
101 port = static_cast<uint16_t>(p);
102 ///////////////////////////
103 pv.param = "SendPeriod";
104 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
105 if (pvi == s.moduleParams.end() || pvi->value.empty())
107 errorStr = "Parameter \'SendPeriod\' not found.";
108 printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
112 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod))
114 errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
115 printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
118 ///////////////////////////
119 pv.param = "UserParams";
120 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
121 if (pvi == s.moduleParams.end() || pvi->value.empty())
123 errorStr = "Parameter \'UserParams\' not found.";
124 printfd(__FILE__, "Parameter 'UserParams' not found\n");
127 userParams = pvi->value;
128 ///////////////////////////
129 pv.param = "Password";
130 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
131 if (pvi == s.moduleParams.end() || pvi->value.empty())
133 errorStr = "Parameter \'Password\' not found.";
134 printfd(__FILE__, "Parameter 'Password' not found\n");
137 password = pvi->value[0];
138 ///////////////////////////
139 pv.param = "SubnetFile";
140 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
141 if (pvi == s.moduleParams.end() || pvi->value.empty())
143 errorStr = "Parameter \'SubnetFile\' not found.";
144 printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
147 subnetFile = pvi->value[0];
149 NRMapParser nrMapParser;
151 if (!nrMapParser.ReadFile(subnetFile))
153 netRouters = nrMapParser.GetMap();
157 GetStgLogger()("mod_rscript: error opening subnets file '%s'", subnetFile.c_str());
162 //-----------------------------------------------------------------------------
163 //-----------------------------------------------------------------------------
164 //-----------------------------------------------------------------------------
165 REMOTE_SCRIPT::REMOTE_SCRIPT()
182 onAddUserNotifier(*this),
183 onDelUserNotifier(*this),
184 logger(GetPluginLogger(GetStgLogger(), "rscript"))
186 pthread_mutex_init(&mutex, NULL);
188 //-----------------------------------------------------------------------------
189 REMOTE_SCRIPT::~REMOTE_SCRIPT()
191 pthread_mutex_destroy(&mutex);
193 //-----------------------------------------------------------------------------
194 void * REMOTE_SCRIPT::Run(void * d)
197 sigfillset(&signalSet);
198 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
200 REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
202 rs->isRunning = true;
210 rs->isRunning = false;
213 //-----------------------------------------------------------------------------
214 int REMOTE_SCRIPT::ParseSettings()
216 int ret = rsSettings.ParseSettings(settings);
218 errorStr = rsSettings.GetStrError();
220 sendPeriod = rsSettings.GetSendPeriod();
221 halfPeriod = sendPeriod / 2;
225 //-----------------------------------------------------------------------------
226 int REMOTE_SCRIPT::Start()
228 netRouters = rsSettings.GetSubnetsMap();
230 InitEncrypt(&ctx, rsSettings.GetPassword());
232 users->AddNotifierUserAdd(&onAddUserNotifier);
233 users->AddNotifierUserDel(&onDelUserNotifier);
249 if (pthread_create(&thread, NULL, Run, this))
251 errorStr = "Cannot create thread.";
252 logger("Cannot create thread.");
253 printfd(__FILE__, "Cannot create thread\n");
261 //-----------------------------------------------------------------------------
262 int REMOTE_SCRIPT::Stop()
270 authorizedUsers.begin(),
271 authorizedUsers.end(),
272 DisconnectUser(*this)
279 //5 seconds to thread stops itself
280 for (int i = 0; i < 25 && isRunning; i++)
282 struct timespec ts = {0, 200000000};
283 nanosleep(&ts, NULL);
287 users->DelNotifierUserDel(&onDelUserNotifier);
288 users->DelNotifierUserAdd(&onAddUserNotifier);
292 logger("Cannot stop thread.");
298 //-----------------------------------------------------------------------------
299 int REMOTE_SCRIPT::Reload()
301 NRMapParser nrMapParser;
303 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
305 errorStr = nrMapParser.GetErrorStr();
306 logger("Map file reading error: %s", errorStr.c_str());
311 STG_LOCKER lock(&mutex);
313 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
315 netRouters = nrMapParser.GetMap();
318 std::for_each(authorizedUsers.begin(),
319 authorizedUsers.end(),
320 UpdateRouter(*this));
322 logger("%s reloaded successfully.", rsSettings.GetMapFileName().c_str());
323 printfd(__FILE__, "REMOTE_SCRIPT::Reload() %s reloaded successfully.\n");
327 //-----------------------------------------------------------------------------
328 bool REMOTE_SCRIPT::PrepareNet()
330 sock = socket(AF_INET, SOCK_DGRAM, 0);
334 errorStr = "Cannot create socket.";
335 logger("Canot create a socket: %s", strerror(errno));
336 printfd(__FILE__, "Cannot create socket\n");
342 //-----------------------------------------------------------------------------
343 bool REMOTE_SCRIPT::FinalizeNet()
348 //-----------------------------------------------------------------------------
349 void REMOTE_SCRIPT::PeriodicSend()
351 STG_LOCKER lock(&mutex);
353 std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
354 while (it != authorizedUsers.end())
356 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
363 //-----------------------------------------------------------------------------
365 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, RS::USER & rsu, bool forceDisconnect) const
367 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, RS::USER & rsu, bool forceDisconnect) const
370 RS::PACKET_HEADER packetHead;
372 memset(packetHead.padding, 0, sizeof(packetHead.padding));
373 strcpy((char*)packetHead.magic, RS_ID);
374 packetHead.protoVer[0] = '0';
375 packetHead.protoVer[1] = '2';
378 packetHead.packetType = RS_DISCONNECT_PACKET;
379 printfd(__FILE__, "RSCRIPT: force disconnect for '%s'\n", rsu.user->GetLogin().c_str());
383 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
386 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
387 if (rsu.user->IsInetable())
388 printfd(__FILE__, "RSCRIPT: connect for '%s'\n", rsu.user->GetLogin().c_str());
390 printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
395 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
396 if (rsu.user->IsInetable())
397 printfd(__FILE__, "RSCRIPT: alive for '%s'\n", rsu.user->GetLogin().c_str());
399 printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
402 rsu.shortPacketsCount++;
403 rsu.lastSentTime = stgTime;
405 packetHead.ip = htonl(rsu.ip);
406 packetHead.id = htonl(rsu.user->GetID());
407 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
408 packetHead.login[RS_LOGIN_LEN - 1] = 0;
410 memcpy(buf, &packetHead, sizeof(packetHead));
412 if (packetHead.packetType == RS_ALIVE_PACKET)
417 RS::PACKET_TAIL packetTail;
419 memset(packetTail.padding, 0, sizeof(packetTail.padding));
420 strcpy((char*)packetTail.magic, RS_ID);
421 std::vector<std::string>::const_iterator it;
423 for(it = rsSettings.GetUserParams().begin();
424 it != rsSettings.GetUserParams().end();
427 std::string parameter(rsu.user->GetParamValue(it->c_str()));
428 if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
430 logger("Script params string length %d exceeds the limit of %d symbols.", params.length() + parameter.length(), RS_PARAMS_LEN);
433 params += parameter + " ";
435 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
436 packetTail.params[RS_PARAMS_LEN - 1] = 0;
438 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
440 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
444 //-----------------------------------------------------------------------------
445 bool REMOTE_SCRIPT::Send(RS::USER & rsu, bool forceDisconnect) const
447 char buffer[RS_MAX_PACKET_LEN];
449 memset(buffer, 0, sizeof(buffer));
451 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
453 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
460 PacketSender(sock, buffer, sizeof(buffer), static_cast<uint16_t>(htons(rsSettings.GetPort())))
465 //-----------------------------------------------------------------------------
466 bool REMOTE_SCRIPT::SendDirect(RS::USER & rsu, uint32_t routerIP, bool forceDisconnect) const
468 char buffer[RS_MAX_PACKET_LEN];
470 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
472 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
476 struct sockaddr_in sendAddr;
478 sendAddr.sin_family = AF_INET;
479 sendAddr.sin_port = static_cast<uint16_t>(htons(rsSettings.GetPort()));
480 sendAddr.sin_addr.s_addr = routerIP;
482 ssize_t res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
485 logger("sendto error: %s", strerror(errno));
487 return (res != sizeof(buffer));
489 //-----------------------------------------------------------------------------
490 bool REMOTE_SCRIPT::GetUsers()
494 int h = users->OpenSearch();
495 assert(h && "USERS::OpenSearch is always correct");
497 while (!users->SearchNext(h, &u))
502 users->CloseSearch(h);
505 //-----------------------------------------------------------------------------
506 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
508 STG_LOCKER lock(&mutex);
509 for (size_t i = 0; i < netRouters.size(); ++i)
511 if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
513 return netRouters[i].routers;
516 return std::vector<uint32_t>();
518 //-----------------------------------------------------------------------------
519 void REMOTE_SCRIPT::SetUserNotifiers(USER_PTR u)
521 ipNotifierList.push_front(RS::IP_NOTIFIER(*this, u));
522 connNotifierList.push_front(RS::CONNECTED_NOTIFIER(*this, u));
524 //-----------------------------------------------------------------------------
525 void REMOTE_SCRIPT::UnSetUserNotifiers(USER_PTR u)
527 ipNotifierList.erase(std::remove_if(ipNotifierList.begin(),
528 ipNotifierList.end(),
529 USER_IS<IP_NOTIFIER>(u)),
530 ipNotifierList.end());
531 connNotifierList.erase(std::remove_if(connNotifierList.begin(),
532 connNotifierList.end(),
533 USER_IS<CONNECTED_NOTIFIER>(u)),
534 connNotifierList.end());
537 //-----------------------------------------------------------------------------
538 void REMOTE_SCRIPT::AddRSU(USER_PTR user)
540 RS::USER rsu(IP2Routers(user->GetCurrIP()), user);
543 STG_LOCKER lock(&mutex);
544 authorizedUsers.insert(std::make_pair(user->GetCurrIP(), rsu));
546 //-----------------------------------------------------------------------------
547 void REMOTE_SCRIPT::DelRSU(USER_PTR user)
549 STG_LOCKER lock(&mutex);
550 std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
551 while (it != authorizedUsers.end())
553 if (it->second.user == user)
555 Send(it->second, true);
556 authorizedUsers.erase(it);
561 /*const std::map<uint32_t, RS::USER>::iterator it(
562 authorizedUsers.find(user->GetCurrIP())
564 if (it != authorizedUsers.end())
566 Send(it->second, true);
567 authorizedUsers.erase(it);
570 //-----------------------------------------------------------------------------
571 void RS::IP_NOTIFIER::Notify(const uint32_t & /*oldValue*/, const uint32_t & newValue)
578 //-----------------------------------------------------------------------------
579 void RS::CONNECTED_NOTIFIER::Notify(const bool & /*oldValue*/, const bool & newValue)
586 //-----------------------------------------------------------------------------
587 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) const
589 unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
590 memset(keyL, 0, PASSWD_LEN);
591 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
592 Blowfish_Init(ctx, keyL, PASSWD_LEN);
594 //-----------------------------------------------------------------------------
595 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8) const
598 memcpy(dst, src, len8 * 8);
599 for (size_t i = 0; i < len8; ++i)
600 Blowfish_Encrypt(ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
602 //-----------------------------------------------------------------------------