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"
26 #include "stg/common.h"
27 #include "stg/locker.h"
28 #include "stg/users.h"
29 #include "stg/user_property.h"
30 #include "stg/logger.h"
41 #include <netinet/ip.h>
44 #define MAX_SHORT_PCKT (3)
46 extern volatile time_t stgTime;
48 using RS::REMOTE_SCRIPT;
55 explicit USER_IS(RS::UserPtr u) : user(u) {}
56 bool operator()(const T & notifier) { return notifier.GetUser() == user; }
61 } // namespace anonymous
63 extern "C" STG::Plugin* GetPlugin()
65 static REMOTE_SCRIPT plugin;
68 //-----------------------------------------------------------------------------
69 //-----------------------------------------------------------------------------
70 //-----------------------------------------------------------------------------
71 RS::SETTINGS::SETTINGS()
76 //-----------------------------------------------------------------------------
77 int RS::SETTINGS::ParseSettings(const STG::ModuleSettings & s)
82 ///////////////////////////
84 auto pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
85 if (pvi == s.moduleParams.end() || pvi->value.empty())
87 errorStr = "Parameter \'Port\' not found.";
88 printfd(__FILE__, "Parameter 'Port' not found\n");
91 if (ParseIntInRange(pvi->value[0], 2, 65535, &p) != 0)
93 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
94 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
97 port = static_cast<uint16_t>(p);
98 ///////////////////////////
99 pv.param = "SendPeriod";
100 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
101 if (pvi == s.moduleParams.end() || pvi->value.empty())
103 errorStr = "Parameter \'SendPeriod\' not found.";
104 printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
108 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod) != 0)
110 errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
111 printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
114 ///////////////////////////
115 pv.param = "UserParams";
116 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
117 if (pvi == s.moduleParams.end() || pvi->value.empty())
119 errorStr = "Parameter \'UserParams\' not found.";
120 printfd(__FILE__, "Parameter 'UserParams' not found\n");
123 userParams = pvi->value;
124 ///////////////////////////
125 pv.param = "Password";
126 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
127 if (pvi == s.moduleParams.end() || pvi->value.empty())
129 errorStr = "Parameter \'Password\' not found.";
130 printfd(__FILE__, "Parameter 'Password' not found\n");
133 password = pvi->value[0];
134 ///////////////////////////
135 pv.param = "SubnetFile";
136 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
137 if (pvi == s.moduleParams.end() || pvi->value.empty())
139 errorStr = "Parameter \'SubnetFile\' not found.";
140 printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
143 subnetFile = pvi->value[0];
145 NRMapParser nrMapParser;
147 if (!nrMapParser.ReadFile(subnetFile))
148 netRouters = nrMapParser.GetMap();
150 STG::PluginLogger::get("rscript")("mod_rscript: error opening subnets file '%s'", subnetFile.c_str());
154 //-----------------------------------------------------------------------------
155 //-----------------------------------------------------------------------------
156 //-----------------------------------------------------------------------------
157 REMOTE_SCRIPT::REMOTE_SCRIPT()
163 onAddUserNotifier(*this),
164 onDelUserNotifier(*this),
165 logger(STG::PluginLogger::get("rscript"))
168 //-----------------------------------------------------------------------------
169 void REMOTE_SCRIPT::Run(std::stop_token token)
172 sigfillset(&signalSet);
173 pthread_sigmask(SIG_BLOCK, &signalSet, nullptr);
177 while (!token.stop_requested())
185 //-----------------------------------------------------------------------------
186 int REMOTE_SCRIPT::ParseSettings()
188 auto ret = rsSettings.ParseSettings(settings);
190 errorStr = rsSettings.GetStrError();
192 sendPeriod = rsSettings.GetSendPeriod();
193 halfPeriod = sendPeriod / 2;
197 //-----------------------------------------------------------------------------
198 int REMOTE_SCRIPT::Start()
200 netRouters = rsSettings.GetSubnetsMap();
202 InitEncrypt(rsSettings.GetPassword());
204 users->AddNotifierUserAdd(&onAddUserNotifier);
205 users->AddNotifierUserDel(&onDelUserNotifier);
214 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
219 //-----------------------------------------------------------------------------
220 int REMOTE_SCRIPT::Stop()
225 m_thread.request_stop();
228 authorizedUsers.begin(),
229 authorizedUsers.end(),
230 DisconnectUser(*this)
237 //5 seconds to thread stops itself
238 for (int i = 0; i < 25 && isRunning; i++)
240 struct timespec ts = {0, 200000000};
241 nanosleep(&ts, nullptr);
245 users->DelNotifierUserDel(&onDelUserNotifier);
246 users->DelNotifierUserAdd(&onAddUserNotifier);
250 logger("Cannot stop thread.");
258 //-----------------------------------------------------------------------------
259 int REMOTE_SCRIPT::Reload(const STG::ModuleSettings & /*ms*/)
261 NRMapParser nrMapParser;
263 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
265 errorStr = nrMapParser.GetErrorStr();
266 logger("Map file reading error: %s", errorStr.c_str());
271 std::lock_guard lock(m_mutex);
273 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
275 netRouters = nrMapParser.GetMap();
278 std::for_each(authorizedUsers.begin(),
279 authorizedUsers.end(),
280 UpdateRouter(*this));
282 logger("%s reloaded successfully.", rsSettings.GetMapFileName().c_str());
283 printfd(__FILE__, "REMOTE_SCRIPT::Reload() %s reloaded successfully.\n");
287 //-----------------------------------------------------------------------------
288 bool REMOTE_SCRIPT::PrepareNet()
290 sock = socket(AF_INET, SOCK_DGRAM, 0);
294 errorStr = "Cannot create socket.";
295 logger("Canot create a socket: %s", strerror(errno));
296 printfd(__FILE__, "Cannot create socket\n");
302 //-----------------------------------------------------------------------------
303 bool REMOTE_SCRIPT::FinalizeNet()
308 //-----------------------------------------------------------------------------
309 void REMOTE_SCRIPT::PeriodicSend()
311 std::lock_guard lock(m_mutex);
313 auto it = authorizedUsers.begin();
314 while (it != authorizedUsers.end())
316 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
323 //-----------------------------------------------------------------------------
325 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, RS::USER & rsu, bool forceDisconnect) const
327 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, RS::USER & rsu, bool forceDisconnect) const
330 RS::PACKET_HEADER packetHead;
332 memset(packetHead.padding, 0, sizeof(packetHead.padding));
333 memcpy(packetHead.magic, RS_ID, sizeof(RS_ID));
334 packetHead.protoVer[0] = '0';
335 packetHead.protoVer[1] = '2';
338 packetHead.packetType = RS_DISCONNECT_PACKET;
339 printfd(__FILE__, "RSCRIPT: force disconnect for '%s'\n", rsu.user->GetLogin().c_str());
343 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
346 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
347 if (rsu.user->IsInetable())
348 printfd(__FILE__, "RSCRIPT: connect for '%s'\n", rsu.user->GetLogin().c_str());
350 printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
355 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
356 if (rsu.user->IsInetable())
357 printfd(__FILE__, "RSCRIPT: alive for '%s'\n", rsu.user->GetLogin().c_str());
359 printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
362 rsu.shortPacketsCount++;
363 rsu.lastSentTime = stgTime;
365 packetHead.ip = htonl(rsu.ip);
366 packetHead.id = htonl(rsu.user->GetID());
367 strncpy(reinterpret_cast<char*>(packetHead.login), rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
368 packetHead.login[RS_LOGIN_LEN - 1] = 0;
370 memcpy(buf, &packetHead, sizeof(packetHead));
372 if (packetHead.packetType == RS_ALIVE_PACKET)
377 RS::PACKET_TAIL packetTail;
379 memset(packetTail.padding, 0, sizeof(packetTail.padding));
380 memcpy(packetTail.magic, RS_ID, sizeof(RS_ID));
382 for (const auto& param : rsSettings.GetUserParams())
384 auto value = rsu.user->GetParamValue(param);
385 if (params.length() + value.length() > RS_PARAMS_LEN - 1)
387 logger("Script params string length %d exceeds the limit of %d symbols.", params.length() + value.length(), RS_PARAMS_LEN);
390 params += value + " ";
392 strncpy(reinterpret_cast<char*>(packetTail.params), params.c_str(), RS_PARAMS_LEN);
393 packetTail.params[RS_PARAMS_LEN - 1] = 0;
395 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
397 Encrypt(buf + sizeof(packetHead), reinterpret_cast<char *>(&packetTail), sizeof(packetTail) / 8);
401 //-----------------------------------------------------------------------------
402 bool REMOTE_SCRIPT::Send(RS::USER & rsu, bool forceDisconnect) const
404 char buffer[RS_MAX_PACKET_LEN];
406 memset(buffer, 0, sizeof(buffer));
408 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
410 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
414 for (const auto& ip : rsu.routers)
416 struct sockaddr_in sendAddr;
418 sendAddr.sin_family = AF_INET;
419 sendAddr.sin_port = htons(rsSettings.GetPort());
420 sendAddr.sin_addr.s_addr = ip;
422 return sendto(sock, buffer, sizeof(buffer), 0, reinterpret_cast<struct sockaddr*>(&sendAddr), sizeof(sendAddr)) > 0;
427 //-----------------------------------------------------------------------------
428 bool REMOTE_SCRIPT::SendDirect(RS::USER & rsu, uint32_t routerIP, bool forceDisconnect) const
430 char buffer[RS_MAX_PACKET_LEN];
432 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
434 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
438 struct sockaddr_in sendAddr;
440 sendAddr.sin_family = AF_INET;
441 sendAddr.sin_port = htons(rsSettings.GetPort());
442 sendAddr.sin_addr.s_addr = routerIP;
444 ssize_t res = sendto(sock, buffer, sizeof(buffer), 0, reinterpret_cast<struct sockaddr *>(&sendAddr), sizeof(sendAddr));
447 logger("sendto error: %s", strerror(errno));
449 return (res != sizeof(buffer));
451 //-----------------------------------------------------------------------------
452 bool REMOTE_SCRIPT::GetUsers()
456 int h = users->OpenSearch();
457 assert(h && "USERS::OpenSearch is always correct");
459 while (users->SearchNext(h, &u) != 0)
462 users->CloseSearch(h);
465 //-----------------------------------------------------------------------------
466 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
468 std::lock_guard lock(m_mutex);
469 for (auto& nr : netRouters)
470 if ((ip & nr.subnetMask) == (nr.subnetIP & nr.subnetMask))
474 //-----------------------------------------------------------------------------
475 void REMOTE_SCRIPT::SetUserNotifiers(UserPtr u)
477 ipNotifierList.push_front(RS::IP_NOTIFIER(*this, u));
478 connNotifierList.push_front(RS::CONNECTED_NOTIFIER(*this, u));
480 //-----------------------------------------------------------------------------
481 void REMOTE_SCRIPT::UnSetUserNotifiers(UserPtr u)
483 ipNotifierList.erase(std::remove_if(ipNotifierList.begin(),
484 ipNotifierList.end(),
485 USER_IS<IP_NOTIFIER>(u)),
486 ipNotifierList.end());
487 connNotifierList.erase(std::remove_if(connNotifierList.begin(),
488 connNotifierList.end(),
489 USER_IS<CONNECTED_NOTIFIER>(u)),
490 connNotifierList.end());
493 //-----------------------------------------------------------------------------
494 void REMOTE_SCRIPT::AddRSU(UserPtr user)
496 RS::USER rsu(IP2Routers(user->GetCurrIP()), user);
499 std::lock_guard lock(m_mutex);
500 authorizedUsers.insert(std::make_pair(user->GetCurrIP(), rsu));
502 //-----------------------------------------------------------------------------
503 void REMOTE_SCRIPT::DelRSU(UserPtr user)
505 std::lock_guard lock(m_mutex);
506 auto it = authorizedUsers.begin();
507 while (it != authorizedUsers.end())
509 if (it->second.user == user)
511 Send(it->second, true);
512 authorizedUsers.erase(it);
517 /*const auto it = authorizedUsers.find(user->GetCurrIP());
518 if (it != authorizedUsers.end())
520 Send(it->second, true);
521 authorizedUsers.erase(it);
524 //-----------------------------------------------------------------------------
525 void RS::IP_NOTIFIER::notify(const uint32_t & /*oldValue*/, const uint32_t & newValue)
532 //-----------------------------------------------------------------------------
533 void RS::CONNECTED_NOTIFIER::notify(const bool & /*oldValue*/, const bool & newValue)
540 //-----------------------------------------------------------------------------
541 void REMOTE_SCRIPT::InitEncrypt(const std::string & password) const
543 unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
544 memset(keyL, 0, PASSWD_LEN);
545 strncpy(reinterpret_cast<char*>(keyL), password.c_str(), PASSWD_LEN);
546 Blowfish_Init(&ctx, keyL, PASSWD_LEN);
548 //-----------------------------------------------------------------------------
549 void REMOTE_SCRIPT::Encrypt(void * dst, const void * src, size_t len8) const
552 memcpy(dst, src, len8 * 8);
553 for (size_t i = 0; i < len8; ++i)
554 Blowfish_Encrypt(&ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
556 //-----------------------------------------------------------------------------