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 #include "ur_functor.h"
25 #include "send_functor.h"
27 #include "stg/common.h"
28 #include "stg/locker.h"
29 #include "stg/users.h"
30 #include "stg/user_property.h"
31 #include "stg/plugin_creator.h"
32 #include "stg/logger.h"
43 #include <netinet/ip.h>
45 extern volatile time_t stgTime;
47 using RS::REMOTE_SCRIPT;
54 explicit USER_IS(USER_PTR u) : user(u) {}
55 bool operator()(const T & notifier) { return notifier.GetUser() == user; }
60 PLUGIN_CREATOR<REMOTE_SCRIPT> rsc;
62 } // namespace anonymous
64 extern "C" PLUGIN * GetPlugin();
65 //-----------------------------------------------------------------------------
66 //-----------------------------------------------------------------------------
67 //-----------------------------------------------------------------------------
68 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
73 return rsc.GetPlugin();
75 //-----------------------------------------------------------------------------
76 //-----------------------------------------------------------------------------
77 //-----------------------------------------------------------------------------
78 RS::SETTINGS::SETTINGS()
83 //-----------------------------------------------------------------------------
84 int RS::SETTINGS::ParseSettings(const MODULE_SETTINGS & s)
88 std::vector<PARAM_VALUE>::const_iterator pvi;
90 ///////////////////////////
92 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
93 if (pvi == s.moduleParams.end() || pvi->value.empty())
95 errorStr = "Parameter \'Port\' not found.";
96 printfd(__FILE__, "Parameter 'Port' not found\n");
99 if (ParseIntInRange(pvi->value[0], 2, 65535, &p))
101 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
102 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
105 port = static_cast<uint16_t>(p);
106 ///////////////////////////
107 pv.param = "SendPeriod";
108 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
109 if (pvi == s.moduleParams.end() || pvi->value.empty())
111 errorStr = "Parameter \'SendPeriod\' not found.";
112 printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
116 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod))
118 errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
119 printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
122 ///////////////////////////
123 pv.param = "UserParams";
124 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
125 if (pvi == s.moduleParams.end() || pvi->value.empty())
127 errorStr = "Parameter \'UserParams\' not found.";
128 printfd(__FILE__, "Parameter 'UserParams' not found\n");
131 userParams = pvi->value;
132 ///////////////////////////
133 pv.param = "Password";
134 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
135 if (pvi == s.moduleParams.end() || pvi->value.empty())
137 errorStr = "Parameter \'Password\' not found.";
138 printfd(__FILE__, "Parameter 'Password' not found\n");
141 password = pvi->value[0];
142 ///////////////////////////
143 pv.param = "SubnetFile";
144 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
145 if (pvi == s.moduleParams.end() || pvi->value.empty())
147 errorStr = "Parameter \'SubnetFile\' not found.";
148 printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
151 subnetFile = pvi->value[0];
153 NRMapParser nrMapParser;
155 if (!nrMapParser.ReadFile(subnetFile))
157 netRouters = nrMapParser.GetMap();
161 GetStgLogger()("mod_rscript: error opening subnets file '%s'", subnetFile.c_str());
166 //-----------------------------------------------------------------------------
167 //-----------------------------------------------------------------------------
168 //-----------------------------------------------------------------------------
169 REMOTE_SCRIPT::REMOTE_SCRIPT()
186 onAddUserNotifier(*this),
187 onDelUserNotifier(*this),
188 logger(GetPluginLogger(GetStgLogger(), "rscript"))
190 pthread_mutex_init(&mutex, NULL);
192 //-----------------------------------------------------------------------------
193 REMOTE_SCRIPT::~REMOTE_SCRIPT()
195 pthread_mutex_destroy(&mutex);
197 //-----------------------------------------------------------------------------
198 void * REMOTE_SCRIPT::Run(void * d)
201 sigfillset(&signalSet);
202 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
204 REMOTE_SCRIPT * rs = static_cast<REMOTE_SCRIPT *>(d);
206 rs->isRunning = true;
214 rs->isRunning = false;
217 //-----------------------------------------------------------------------------
218 int REMOTE_SCRIPT::ParseSettings()
220 int ret = rsSettings.ParseSettings(settings);
222 errorStr = rsSettings.GetStrError();
224 sendPeriod = rsSettings.GetSendPeriod();
225 halfPeriod = sendPeriod / 2;
229 //-----------------------------------------------------------------------------
230 int REMOTE_SCRIPT::Start()
232 netRouters = rsSettings.GetSubnetsMap();
234 InitEncrypt(&ctx, rsSettings.GetPassword());
236 users->AddNotifierUserAdd(&onAddUserNotifier);
237 users->AddNotifierUserDel(&onDelUserNotifier);
253 if (pthread_create(&thread, NULL, Run, this))
255 errorStr = "Cannot create thread.";
256 logger("Cannot create thread.");
257 printfd(__FILE__, "Cannot create thread\n");
265 //-----------------------------------------------------------------------------
266 int REMOTE_SCRIPT::Stop()
274 authorizedUsers.begin(),
275 authorizedUsers.end(),
276 DisconnectUser(*this)
283 //5 seconds to thread stops itself
284 for (int i = 0; i < 25 && isRunning; i++)
286 struct timespec ts = {0, 200000000};
287 nanosleep(&ts, NULL);
291 users->DelNotifierUserDel(&onDelUserNotifier);
292 users->DelNotifierUserAdd(&onAddUserNotifier);
296 logger("Cannot stop thread.");
302 //-----------------------------------------------------------------------------
303 int REMOTE_SCRIPT::Reload(const MODULE_SETTINGS & /*ms*/)
305 NRMapParser nrMapParser;
307 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
309 errorStr = nrMapParser.GetErrorStr();
310 logger("Map file reading error: %s", errorStr.c_str());
315 STG_LOCKER lock(&mutex);
317 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
319 netRouters = nrMapParser.GetMap();
322 std::for_each(authorizedUsers.begin(),
323 authorizedUsers.end(),
324 UpdateRouter(*this));
326 logger("%s reloaded successfully.", rsSettings.GetMapFileName().c_str());
327 printfd(__FILE__, "REMOTE_SCRIPT::Reload() %s reloaded successfully.\n");
331 //-----------------------------------------------------------------------------
332 bool REMOTE_SCRIPT::PrepareNet()
334 sock = socket(AF_INET, SOCK_DGRAM, 0);
338 errorStr = "Cannot create socket.";
339 logger("Canot create a socket: %s", strerror(errno));
340 printfd(__FILE__, "Cannot create socket\n");
346 //-----------------------------------------------------------------------------
347 bool REMOTE_SCRIPT::FinalizeNet()
352 //-----------------------------------------------------------------------------
353 void REMOTE_SCRIPT::PeriodicSend()
355 STG_LOCKER lock(&mutex);
357 std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
358 while (it != authorizedUsers.end())
360 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
367 //-----------------------------------------------------------------------------
369 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, RS::USER & rsu, bool forceDisconnect) const
371 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, RS::USER & rsu, bool forceDisconnect) const
374 RS::PACKET_HEADER packetHead;
376 memset(packetHead.padding, 0, sizeof(packetHead.padding));
377 strcpy((char*)packetHead.magic, RS_ID);
378 packetHead.protoVer[0] = '0';
379 packetHead.protoVer[1] = '2';
382 packetHead.packetType = RS_DISCONNECT_PACKET;
383 printfd(__FILE__, "RSCRIPT: force disconnect for '%s'\n", rsu.user->GetLogin().c_str());
387 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
390 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
391 if (rsu.user->IsInetable())
392 printfd(__FILE__, "RSCRIPT: connect for '%s'\n", rsu.user->GetLogin().c_str());
394 printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
399 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
400 if (rsu.user->IsInetable())
401 printfd(__FILE__, "RSCRIPT: alive for '%s'\n", rsu.user->GetLogin().c_str());
403 printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
406 rsu.shortPacketsCount++;
407 rsu.lastSentTime = stgTime;
409 packetHead.ip = htonl(rsu.ip);
410 packetHead.id = htonl(rsu.user->GetID());
411 strncpy((char*)packetHead.login, rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
412 packetHead.login[RS_LOGIN_LEN - 1] = 0;
414 memcpy(buf, &packetHead, sizeof(packetHead));
416 if (packetHead.packetType == RS_ALIVE_PACKET)
421 RS::PACKET_TAIL packetTail;
423 memset(packetTail.padding, 0, sizeof(packetTail.padding));
424 strcpy((char*)packetTail.magic, RS_ID);
425 std::vector<std::string>::const_iterator it;
427 for(it = rsSettings.GetUserParams().begin();
428 it != rsSettings.GetUserParams().end();
431 std::string parameter(rsu.user->GetParamValue(it->c_str()));
432 if (params.length() + parameter.length() > RS_PARAMS_LEN - 1)
434 logger("Script params string length %d exceeds the limit of %d symbols.", params.length() + parameter.length(), RS_PARAMS_LEN);
437 params += parameter + " ";
439 strncpy((char *)packetTail.params, params.c_str(), RS_PARAMS_LEN);
440 packetTail.params[RS_PARAMS_LEN - 1] = 0;
442 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
444 Encrypt(&ctx, buf + sizeof(packetHead), (char *)&packetTail, sizeof(packetTail) / 8);
448 //-----------------------------------------------------------------------------
449 bool REMOTE_SCRIPT::Send(RS::USER & rsu, bool forceDisconnect) const
451 char buffer[RS_MAX_PACKET_LEN];
453 memset(buffer, 0, sizeof(buffer));
455 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
457 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
464 PacketSender(sock, buffer, sizeof(buffer), static_cast<uint16_t>(htons(rsSettings.GetPort())))
469 //-----------------------------------------------------------------------------
470 bool REMOTE_SCRIPT::SendDirect(RS::USER & rsu, uint32_t routerIP, bool forceDisconnect) const
472 char buffer[RS_MAX_PACKET_LEN];
474 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
476 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
480 struct sockaddr_in sendAddr;
482 sendAddr.sin_family = AF_INET;
483 sendAddr.sin_port = static_cast<uint16_t>(htons(rsSettings.GetPort()));
484 sendAddr.sin_addr.s_addr = routerIP;
486 ssize_t res = sendto(sock, buffer, sizeof(buffer), 0, (struct sockaddr *)&sendAddr, sizeof(sendAddr));
489 logger("sendto error: %s", strerror(errno));
491 return (res != sizeof(buffer));
493 //-----------------------------------------------------------------------------
494 bool REMOTE_SCRIPT::GetUsers()
498 int h = users->OpenSearch();
499 assert(h && "USERS::OpenSearch is always correct");
501 while (!users->SearchNext(h, &u))
506 users->CloseSearch(h);
509 //-----------------------------------------------------------------------------
510 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
512 STG_LOCKER lock(&mutex);
513 for (size_t i = 0; i < netRouters.size(); ++i)
515 if ((ip & netRouters[i].subnetMask) == (netRouters[i].subnetIP & netRouters[i].subnetMask))
517 return netRouters[i].routers;
520 return std::vector<uint32_t>();
522 //-----------------------------------------------------------------------------
523 void REMOTE_SCRIPT::SetUserNotifiers(USER_PTR u)
525 ipNotifierList.push_front(RS::IP_NOTIFIER(*this, u));
526 connNotifierList.push_front(RS::CONNECTED_NOTIFIER(*this, u));
528 //-----------------------------------------------------------------------------
529 void REMOTE_SCRIPT::UnSetUserNotifiers(USER_PTR u)
531 ipNotifierList.erase(std::remove_if(ipNotifierList.begin(),
532 ipNotifierList.end(),
533 USER_IS<IP_NOTIFIER>(u)),
534 ipNotifierList.end());
535 connNotifierList.erase(std::remove_if(connNotifierList.begin(),
536 connNotifierList.end(),
537 USER_IS<CONNECTED_NOTIFIER>(u)),
538 connNotifierList.end());
541 //-----------------------------------------------------------------------------
542 void REMOTE_SCRIPT::AddRSU(USER_PTR user)
544 RS::USER rsu(IP2Routers(user->GetCurrIP()), user);
547 STG_LOCKER lock(&mutex);
548 authorizedUsers.insert(std::make_pair(user->GetCurrIP(), rsu));
550 //-----------------------------------------------------------------------------
551 void REMOTE_SCRIPT::DelRSU(USER_PTR user)
553 STG_LOCKER lock(&mutex);
554 std::map<uint32_t, RS::USER>::iterator it(authorizedUsers.begin());
555 while (it != authorizedUsers.end())
557 if (it->second.user == user)
559 Send(it->second, true);
560 authorizedUsers.erase(it);
565 /*const std::map<uint32_t, RS::USER>::iterator it(
566 authorizedUsers.find(user->GetCurrIP())
568 if (it != authorizedUsers.end())
570 Send(it->second, true);
571 authorizedUsers.erase(it);
574 //-----------------------------------------------------------------------------
575 void RS::IP_NOTIFIER::Notify(const uint32_t & /*oldValue*/, const uint32_t & newValue)
582 //-----------------------------------------------------------------------------
583 void RS::CONNECTED_NOTIFIER::Notify(const bool & /*oldValue*/, const bool & newValue)
590 //-----------------------------------------------------------------------------
591 void REMOTE_SCRIPT::InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password) const
593 unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
594 memset(keyL, 0, PASSWD_LEN);
595 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
596 Blowfish_Init(ctx, keyL, PASSWD_LEN);
598 //-----------------------------------------------------------------------------
599 void REMOTE_SCRIPT::Encrypt(BLOWFISH_CTX * ctx, void * dst, const void * src, size_t len8) const
602 memcpy(dst, src, len8 * 8);
603 for (size_t i = 0; i < len8; ++i)
604 Blowfish_Encrypt(ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
606 //-----------------------------------------------------------------------------