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 namespace RS = STG::RS;
49 using RS::REMOTE_SCRIPT;
51 extern "C" STG::Plugin* GetPlugin()
53 static REMOTE_SCRIPT plugin;
56 //-----------------------------------------------------------------------------
57 //-----------------------------------------------------------------------------
58 //-----------------------------------------------------------------------------
59 RS::SETTINGS::SETTINGS()
64 //-----------------------------------------------------------------------------
65 int RS::SETTINGS::ParseSettings(const ModuleSettings & s)
70 ///////////////////////////
72 auto pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
73 if (pvi == s.moduleParams.end() || pvi->value.empty())
75 errorStr = "Parameter \'Port\' not found.";
76 printfd(__FILE__, "Parameter 'Port' not found\n");
79 if (ParseIntInRange(pvi->value[0], 2, 65535, &p) != 0)
81 errorStr = "Cannot parse parameter \'Port\': " + errorStr;
82 printfd(__FILE__, "Cannot parse parameter 'Port'\n");
85 port = static_cast<uint16_t>(p);
86 ///////////////////////////
87 pv.param = "SendPeriod";
88 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
89 if (pvi == s.moduleParams.end() || pvi->value.empty())
91 errorStr = "Parameter \'SendPeriod\' not found.";
92 printfd(__FILE__, "Parameter 'SendPeriod' not found\n");
96 if (ParseIntInRange(pvi->value[0], 5, 600, &sendPeriod) != 0)
98 errorStr = "Cannot parse parameter \'SendPeriod\': " + errorStr;
99 printfd(__FILE__, "Cannot parse parameter 'SendPeriod'\n");
102 ///////////////////////////
103 pv.param = "UserParams";
104 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
105 if (pvi == s.moduleParams.end() || pvi->value.empty())
107 errorStr = "Parameter \'UserParams\' not found.";
108 printfd(__FILE__, "Parameter 'UserParams' not found\n");
111 userParams = pvi->value;
112 ///////////////////////////
113 pv.param = "Password";
114 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
115 if (pvi == s.moduleParams.end() || pvi->value.empty())
117 errorStr = "Parameter \'Password\' not found.";
118 printfd(__FILE__, "Parameter 'Password' not found\n");
121 password = pvi->value[0];
122 ///////////////////////////
123 pv.param = "SubnetFile";
124 pvi = find(s.moduleParams.begin(), s.moduleParams.end(), pv);
125 if (pvi == s.moduleParams.end() || pvi->value.empty())
127 errorStr = "Parameter \'SubnetFile\' not found.";
128 printfd(__FILE__, "Parameter 'SubnetFile' not found\n");
131 subnetFile = pvi->value[0];
133 NRMapParser nrMapParser;
135 if (!nrMapParser.ReadFile(subnetFile))
136 netRouters = nrMapParser.GetMap();
138 PluginLogger::get("rscript")("mod_rscript: error opening subnets file '%s'", subnetFile.c_str());
142 //-----------------------------------------------------------------------------
143 //-----------------------------------------------------------------------------
144 //-----------------------------------------------------------------------------
145 REMOTE_SCRIPT::REMOTE_SCRIPT()
151 logger(PluginLogger::get("rscript"))
154 //-----------------------------------------------------------------------------
155 void REMOTE_SCRIPT::Run(std::stop_token token)
158 sigfillset(&signalSet);
159 pthread_sigmask(SIG_BLOCK, &signalSet, nullptr);
163 while (!token.stop_requested())
171 //-----------------------------------------------------------------------------
172 int REMOTE_SCRIPT::ParseSettings()
174 auto ret = rsSettings.ParseSettings(settings);
176 errorStr = rsSettings.GetStrError();
178 sendPeriod = rsSettings.GetSendPeriod();
179 halfPeriod = sendPeriod / 2;
183 //-----------------------------------------------------------------------------
184 int REMOTE_SCRIPT::Start()
186 netRouters = rsSettings.GetSubnetsMap();
188 InitEncrypt(rsSettings.GetPassword());
190 m_onAddUserConn = users->onAdd([this](auto user){ AddUser(user); });
191 m_onDelUserConn = users->onDel([this](auto user){ DelUser(user); });
200 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
205 //-----------------------------------------------------------------------------
206 int REMOTE_SCRIPT::Stop()
211 m_thread.request_stop();
214 authorizedUsers.begin(),
215 authorizedUsers.end(),
216 [this](auto& kv){ Send(kv.second, true); }
223 //5 seconds to thread stops itself
224 for (int i = 0; i < 25 && isRunning; i++)
226 struct timespec ts = {0, 200000000};
227 nanosleep(&ts, nullptr);
233 logger("Cannot stop thread.");
241 //-----------------------------------------------------------------------------
242 int REMOTE_SCRIPT::Reload(const ModuleSettings & /*ms*/)
244 NRMapParser nrMapParser;
246 if (nrMapParser.ReadFile(rsSettings.GetMapFileName()))
248 errorStr = nrMapParser.GetErrorStr();
249 logger("Map file reading error: %s", errorStr.c_str());
254 std::lock_guard lock(m_mutex);
256 printfd(__FILE__, "REMOTE_SCRIPT::Reload()\n");
258 netRouters = nrMapParser.GetMap();
261 std::for_each(authorizedUsers.begin(),
262 authorizedUsers.end(),
263 UpdateRouter(*this));
265 logger("%s reloaded successfully.", rsSettings.GetMapFileName().c_str());
266 printfd(__FILE__, "REMOTE_SCRIPT::Reload() %s reloaded successfully.\n");
270 //-----------------------------------------------------------------------------
271 bool REMOTE_SCRIPT::PrepareNet()
273 sock = socket(AF_INET, SOCK_DGRAM, 0);
277 errorStr = "Cannot create socket.";
278 logger("Canot create a socket: %s", strerror(errno));
279 printfd(__FILE__, "Cannot create socket\n");
285 //-----------------------------------------------------------------------------
286 bool REMOTE_SCRIPT::FinalizeNet()
291 //-----------------------------------------------------------------------------
292 void REMOTE_SCRIPT::PeriodicSend()
294 std::lock_guard lock(m_mutex);
296 auto it = authorizedUsers.begin();
297 while (it != authorizedUsers.end())
299 if (difftime(stgTime, it->second.lastSentTime) - (rand() % halfPeriod) > sendPeriod)
306 //-----------------------------------------------------------------------------
308 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t, RS::USER & rsu, bool forceDisconnect) const
310 bool REMOTE_SCRIPT::PreparePacket(char * buf, size_t bufSize, RS::USER & rsu, bool forceDisconnect) const
313 RS::PACKET_HEADER packetHead;
315 memset(packetHead.padding, 0, sizeof(packetHead.padding));
316 memcpy(packetHead.magic, RS_ID, sizeof(RS_ID));
317 packetHead.protoVer[0] = '0';
318 packetHead.protoVer[1] = '2';
321 packetHead.packetType = RS_DISCONNECT_PACKET;
322 printfd(__FILE__, "RSCRIPT: force disconnect for '%s'\n", rsu.user->GetLogin().c_str());
326 if (rsu.shortPacketsCount % MAX_SHORT_PCKT == 0)
329 packetHead.packetType = rsu.user->IsInetable() ? RS_CONNECT_PACKET : RS_DISCONNECT_PACKET;
330 if (rsu.user->IsInetable())
331 printfd(__FILE__, "RSCRIPT: connect for '%s'\n", rsu.user->GetLogin().c_str());
333 printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
338 packetHead.packetType = rsu.user->IsInetable() ? RS_ALIVE_PACKET : RS_DISCONNECT_PACKET;
339 if (rsu.user->IsInetable())
340 printfd(__FILE__, "RSCRIPT: alive for '%s'\n", rsu.user->GetLogin().c_str());
342 printfd(__FILE__, "RSCRIPT: disconnect for '%s'\n", rsu.user->GetLogin().c_str());
345 rsu.shortPacketsCount++;
346 rsu.lastSentTime = stgTime;
348 packetHead.ip = htonl(rsu.ip);
349 packetHead.id = htonl(rsu.user->GetID());
350 strncpy(reinterpret_cast<char*>(packetHead.login), rsu.user->GetLogin().c_str(), RS_LOGIN_LEN);
351 packetHead.login[RS_LOGIN_LEN - 1] = 0;
353 memcpy(buf, &packetHead, sizeof(packetHead));
355 if (packetHead.packetType == RS_ALIVE_PACKET)
360 RS::PACKET_TAIL packetTail;
362 memset(packetTail.padding, 0, sizeof(packetTail.padding));
363 memcpy(packetTail.magic, RS_ID, sizeof(RS_ID));
365 for (const auto& param : rsSettings.GetUserParams())
367 auto value = rsu.user->GetParamValue(param);
368 if (params.length() + value.length() > RS_PARAMS_LEN - 1)
370 logger("Script params string length %d exceeds the limit of %d symbols.", params.length() + value.length(), RS_PARAMS_LEN);
373 params += value + " ";
375 strncpy(reinterpret_cast<char*>(packetTail.params), params.c_str(), RS_PARAMS_LEN);
376 packetTail.params[RS_PARAMS_LEN - 1] = 0;
378 assert(sizeof(packetHead) + sizeof(packetTail) <= bufSize && "Insufficient buffer space");
380 Encrypt(buf + sizeof(packetHead), reinterpret_cast<char *>(&packetTail), sizeof(packetTail) / 8);
384 //-----------------------------------------------------------------------------
385 bool REMOTE_SCRIPT::Send(RS::USER & rsu, bool forceDisconnect) const
387 char buffer[RS_MAX_PACKET_LEN];
389 memset(buffer, 0, sizeof(buffer));
391 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
393 printfd(__FILE__, "REMOTE_SCRIPT::Send() - Invalid packet length!\n");
397 for (const auto& ip : rsu.routers)
399 struct sockaddr_in sendAddr;
401 sendAddr.sin_family = AF_INET;
402 sendAddr.sin_port = htons(rsSettings.GetPort());
403 sendAddr.sin_addr.s_addr = ip;
405 return sendto(sock, buffer, sizeof(buffer), 0, reinterpret_cast<struct sockaddr*>(&sendAddr), sizeof(sendAddr)) > 0;
410 //-----------------------------------------------------------------------------
411 bool REMOTE_SCRIPT::SendDirect(RS::USER & rsu, uint32_t routerIP, bool forceDisconnect) const
413 char buffer[RS_MAX_PACKET_LEN];
415 if (PreparePacket(buffer, sizeof(buffer), rsu, forceDisconnect))
417 printfd(__FILE__, "REMOTE_SCRIPT::SendDirect() - Invalid packet length!\n");
421 struct sockaddr_in sendAddr;
423 sendAddr.sin_family = AF_INET;
424 sendAddr.sin_port = htons(rsSettings.GetPort());
425 sendAddr.sin_addr.s_addr = routerIP;
427 ssize_t res = sendto(sock, buffer, sizeof(buffer), 0, reinterpret_cast<struct sockaddr *>(&sendAddr), sizeof(sendAddr));
430 logger("sendto error: %s", strerror(errno));
432 return (res != sizeof(buffer));
434 //-----------------------------------------------------------------------------
435 bool REMOTE_SCRIPT::GetUsers()
439 int h = users->OpenSearch();
440 assert(h && "USERS::OpenSearch is always correct");
442 while (users->SearchNext(h, &u) != 0)
445 users->CloseSearch(h);
448 //-----------------------------------------------------------------------------
449 std::vector<uint32_t> REMOTE_SCRIPT::IP2Routers(uint32_t ip)
451 std::lock_guard lock(m_mutex);
452 for (auto& nr : netRouters)
453 if ((ip & nr.subnetMask) == (nr.subnetIP & nr.subnetMask))
457 //-----------------------------------------------------------------------------
458 void REMOTE_SCRIPT::SetUserNotifiers(UserPtr u)
460 m_conns.emplace_back(
462 u->afterCurrIPChange([this, u](auto, auto newVal){ addDelUser(u, newVal != 0); }),
463 u->afterConnectedChange([this, u](auto, auto newVal){ addDelUser(u, newVal); })
466 //-----------------------------------------------------------------------------
467 void REMOTE_SCRIPT::UnSetUserNotifiers(UserPtr u)
469 m_conns.erase(std::remove_if(m_conns.begin(), m_conns.end(),
470 [u](const auto& c){ return std::get<0>(c) == u->GetID(); }),
474 //-----------------------------------------------------------------------------
475 void REMOTE_SCRIPT::AddRSU(UserPtr user)
477 RS::USER rsu(IP2Routers(user->GetCurrIP()), user);
480 std::lock_guard lock(m_mutex);
481 authorizedUsers.insert(std::make_pair(user->GetCurrIP(), rsu));
483 //-----------------------------------------------------------------------------
484 void REMOTE_SCRIPT::DelRSU(UserPtr user)
486 std::lock_guard lock(m_mutex);
487 auto it = authorizedUsers.begin();
488 while (it != authorizedUsers.end())
490 if (it->second.user == user)
492 Send(it->second, true);
493 authorizedUsers.erase(it);
498 /*const auto it = authorizedUsers.find(user->GetCurrIP());
499 if (it != authorizedUsers.end())
501 Send(it->second, true);
502 authorizedUsers.erase(it);
505 //-----------------------------------------------------------------------------
506 void REMOTE_SCRIPT::addDelUser(UserPtr user, bool toAdd)
513 //-----------------------------------------------------------------------------
514 void REMOTE_SCRIPT::InitEncrypt(const std::string & password) const
516 unsigned char keyL[PASSWD_LEN]; // Пароль для шифровки
517 memset(keyL, 0, PASSWD_LEN);
518 strncpy(reinterpret_cast<char*>(keyL), password.c_str(), PASSWD_LEN);
519 Blowfish_Init(&ctx, keyL, PASSWD_LEN);
521 //-----------------------------------------------------------------------------
522 void REMOTE_SCRIPT::Encrypt(void * dst, const void * src, size_t len8) const
525 memcpy(dst, src, len8 * 8);
526 for (size_t i = 0; i < len8; ++i)
527 Blowfish_Encrypt(&ctx, static_cast<uint32_t *>(dst) + i * 2, static_cast<uint32_t *>(dst) + i * 2 + 1);
529 //-----------------------------------------------------------------------------