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>
22 #include <arpa/inet.h>
23 #include <sys/uio.h> // readv
24 #include <sys/types.h> // for historical versions of BSD
25 #include <sys/socket.h>
26 #include <netinet/in.h>
36 #include "stg/scriptexecuter.h"
37 #include "stg/locker.h"
38 #include "stg/common.h"
41 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password);
42 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8);
44 //-----------------------------------------------------------------------------
46 : WriteServLog(GetStgLogger()),
49 receiverStopped(true),
50 processorStopped(true),
54 version = "rscriptd listener v.1.2";
56 pthread_mutex_init(&mutex, NULL);
58 //-----------------------------------------------------------------------------
59 void LISTENER::SetPassword(const std::string & p)
62 printfd(__FILE__, "Encryption initiated with password \'%s\'\n", password.c_str());
63 InitEncrypt(&ctxS, password);
65 //-----------------------------------------------------------------------------
66 bool LISTENER::Start()
68 printfd(__FILE__, "LISTENER::Start()\n");
78 if (pthread_create(&receiverThread, NULL, Run, this))
80 errorStr = "Cannot create thread.";
87 if (pthread_create(&processorThread, NULL, RunProcessor, this))
89 errorStr = "Cannot create thread.";
98 //-----------------------------------------------------------------------------
103 printfd(__FILE__, "LISTENER::Stop()\n");
105 struct timespec ts = {0, 500000000};
106 nanosleep(&ts, NULL);
108 if (!processorStopped)
110 //5 seconds to thread stops itself
111 for (int i = 0; i < 25 && !processorStopped; i++)
113 struct timespec ts = {0, 200000000};
114 nanosleep(&ts, NULL);
117 //after 5 seconds waiting thread still running. now killing it
118 if (!processorStopped)
120 //TODO pthread_cancel()
121 if (pthread_kill(processorThread, SIGINT))
123 errorStr = "Cannot kill thread.";
126 printfd(__FILE__, "LISTENER killed Timeouter\n");
130 if (!receiverStopped)
132 //5 seconds to thread stops itself
133 for (int i = 0; i < 25 && !receiverStopped; i++)
135 struct timespec ts = {0, 200000000};
136 nanosleep(&ts, NULL);
139 //after 5 seconds waiting thread still running. now killing it
140 if (!receiverStopped)
142 //TODO pthread_cancel()
143 if (pthread_kill(receiverThread, SIGINT))
145 errorStr = "Cannot kill thread.";
148 printfd(__FILE__, "LISTENER killed Run\n");
152 pthread_join(receiverThread, NULL);
153 pthread_join(processorThread, NULL);
155 pthread_mutex_destroy(&mutex);
159 std::for_each(users.begin(), users.end(), DisconnectUser(*this));
161 printfd(__FILE__, "LISTENER::Stoped successfully.\n");
165 //-----------------------------------------------------------------------------
166 void * LISTENER::Run(void * d)
169 sigfillset(&signalSet);
170 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
172 LISTENER * listener = static_cast<LISTENER *>(d);
178 //-----------------------------------------------------------------------------
179 void LISTENER::Runner()
181 receiverStopped = false;
188 receiverStopped = true;
190 //-----------------------------------------------------------------------------
191 void * LISTENER::RunProcessor(void * d)
194 sigfillset(&signalSet);
195 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
197 LISTENER * listener = static_cast<LISTENER *>(d);
199 listener->ProcessorRunner();
203 //-----------------------------------------------------------------------------
204 void LISTENER::ProcessorRunner()
206 processorStopped = false;
210 struct timespec ts = {0, 500000000};
211 nanosleep(&ts, NULL);
212 if (!pending.empty())
217 processorStopped = true;
219 //-----------------------------------------------------------------------------
220 bool LISTENER::PrepareNet()
222 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
224 if (listenSocket < 0)
226 errorStr = "Cannot create socket.";
230 struct sockaddr_in listenAddr;
231 listenAddr.sin_family = AF_INET;
232 listenAddr.sin_port = htons(port);
233 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
235 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
237 errorStr = "LISTENER: Bind failed.";
241 printfd(__FILE__, "LISTENER::PrepareNet() >>>> Start successfull.\n");
245 //-----------------------------------------------------------------------------
246 bool LISTENER::FinalizeNet()
252 //-----------------------------------------------------------------------------
253 bool LISTENER::RecvPacket()
257 char buffer[RS_MAX_PACKET_LEN];
258 RS_PACKET_HEADER packetHead;
260 iov[0].iov_base = reinterpret_cast<char *>(&packetHead);
261 iov[0].iov_len = sizeof(packetHead);
262 iov[1].iov_base = buffer;
263 iov[1].iov_len = sizeof(buffer) - sizeof(packetHead);
266 while (dataLen < sizeof(buffer))
268 if (!WaitPackets(listenSocket))
274 int portion = readv(listenSocket, iov, 2);
282 if (CheckHeader(packetHead))
284 printfd(__FILE__, "Invalid packet or incorrect protocol version!\n");
288 std::string userLogin((char *)packetHead.login);
290 data.login = userLogin;
291 data.ip = ntohl(packetHead.ip);
292 data.id = ntohl(packetHead.id);
294 if (packetHead.packetType == RS_ALIVE_PACKET)
296 data.type = PendingData::ALIVE;
298 else if (packetHead.packetType == RS_CONNECT_PACKET)
300 data.type = PendingData::CONNECT;
301 if (GetParams(buffer, data))
306 else if (packetHead.packetType == RS_DISCONNECT_PACKET)
308 data.type = PendingData::DISCONNECT;
309 if (GetParams(buffer, data))
315 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
316 pending.push_back(data);
320 //-----------------------------------------------------------------------------
321 bool LISTENER::GetParams(char * buffer, UserData & data)
323 RS_PACKET_TAIL packetTail;
325 Decrypt(&ctxS, (char *)&packetTail, buffer, sizeof(packetTail) / 8);
327 if (strncmp((char *)packetTail.magic, RS_ID, RS_MAGIC_LEN))
329 printfd(__FILE__, "Invalid crypto magic\n");
333 std::stringstream params;
334 params << "\"" << data.login << "\" "
335 << inet_ntostring(data.ip) << " "
337 << (char *)packetTail.params;
339 data.params = params.str();
343 //-----------------------------------------------------------------------------
344 void LISTENER::ProcessPending()
346 std::list<PendingData>::iterator it(pending.begin());
348 printfd(__FILE__, "Pending: %d\n", pending.size());
349 while (it != pending.end() && count < 256)
351 std::vector<AliveData>::iterator uit(
357 if (it->type == PendingData::CONNECT)
359 if (uit == users.end() || uit->login != it->login)
363 users.insert(uit, AliveData(static_cast<UserData>(*it)));
365 else if (uit->login == it->login)
367 // Update already existing user
368 time(&uit->lastAlive);
369 uit->params = it->params;
372 else if (it->type == PendingData::ALIVE)
374 if (uit != users.end() && uit->login == it->login)
376 // Update existing user
377 time(&uit->lastAlive);
380 else if (it->type == PendingData::DISCONNECT)
382 if (uit != users.end() && uit->login == it->login.c_str())
384 // Disconnect existing user
392 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
393 pending.erase(pending.begin(), it);
395 //-----------------------------------------------------------------------------
396 void LISTENER::ProcessTimeouts()
398 const std::vector<AliveData>::iterator it(
399 std::stable_partition(
402 IsNotTimedOut(userTimeout)
406 if (it != users.end())
408 printfd(__FILE__, "Total users: %d, users to disconnect: %d\n", users.size(), std::distance(it, users.end()));
413 DisconnectUser(*this)
416 users.erase(it, users.end());
419 //-----------------------------------------------------------------------------
420 bool LISTENER::Connect(const UserData & data) const
422 printfd(__FILE__, "Connect %s\n", data.login.c_str());
423 if (access(scriptOnConnect.c_str(), X_OK) == 0)
425 if (ScriptExec((scriptOnConnect + " " + data.params).c_str()))
427 WriteServLog("Script %s cannot be executed for an unknown reason.", scriptOnConnect.c_str());
433 WriteServLog("Script %s cannot be executed. File not found.", scriptOnConnect.c_str());
438 //-----------------------------------------------------------------------------
439 bool LISTENER::Disconnect(const UserData & data) const
441 printfd(__FILE__, "Disconnect %s\n", data.login.c_str());
442 if (access(scriptOnDisconnect.c_str(), X_OK) == 0)
444 if (ScriptExec((scriptOnDisconnect + " " + data.params).c_str()))
446 WriteServLog("Script %s cannot be executed for an unknown reson.", scriptOnDisconnect.c_str());
452 WriteServLog("Script %s cannot be executed. File not found.", scriptOnDisconnect.c_str());
457 //-----------------------------------------------------------------------------
458 bool LISTENER::CheckHeader(const RS_PACKET_HEADER & header) const
460 if (strncmp((char *)header.magic, RS_ID, RS_MAGIC_LEN))
464 if (strncmp((char *)header.protoVer, "02", RS_PROTO_VER_LEN))
470 //-----------------------------------------------------------------------------
472 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
474 unsigned char keyL[PASSWD_LEN];
475 memset(keyL, 0, PASSWD_LEN);
476 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
477 Blowfish_Init(ctx, keyL, PASSWD_LEN);
479 //-----------------------------------------------------------------------------
481 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
484 memcpy(dst, src, len8 * 8);
486 for (int i = 0; i < len8; i++)
487 Blowfish_Decrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
489 //-----------------------------------------------------------------------------