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),
53 version("rscriptd listener v.1.2")
55 pthread_mutex_init(&mutex, NULL);
57 //-----------------------------------------------------------------------------
58 void LISTENER::SetPassword(const std::string & p)
61 printfd(__FILE__, "Encryption initiated with password \'%s\'\n", password.c_str());
62 InitEncrypt(&ctxS, password);
64 //-----------------------------------------------------------------------------
65 bool LISTENER::Start()
67 printfd(__FILE__, "LISTENER::Start()\n");
77 if (pthread_create(&receiverThread, NULL, Run, this))
79 errorStr = "Cannot create thread.";
86 if (pthread_create(&processorThread, NULL, RunProcessor, this))
88 errorStr = "Cannot create thread.";
97 //-----------------------------------------------------------------------------
102 printfd(__FILE__, "LISTENER::Stop()\n");
104 struct timespec ts = {0, 500000000};
105 nanosleep(&ts, NULL);
107 if (!processorStopped)
109 //5 seconds to thread stops itself
110 for (int i = 0; i < 25 && !processorStopped; i++)
112 struct timespec ts = {0, 200000000};
113 nanosleep(&ts, NULL);
116 //after 5 seconds waiting thread still running. now killing it
117 if (!processorStopped)
119 //TODO pthread_cancel()
120 if (pthread_kill(processorThread, SIGINT))
122 errorStr = "Cannot kill thread.";
125 printfd(__FILE__, "LISTENER killed Timeouter\n");
129 if (!receiverStopped)
131 //5 seconds to thread stops itself
132 for (int i = 0; i < 25 && !receiverStopped; i++)
134 struct timespec ts = {0, 200000000};
135 nanosleep(&ts, NULL);
138 //after 5 seconds waiting thread still running. now killing it
139 if (!receiverStopped)
141 //TODO pthread_cancel()
142 if (pthread_kill(receiverThread, SIGINT))
144 errorStr = "Cannot kill thread.";
147 printfd(__FILE__, "LISTENER killed Run\n");
151 pthread_join(receiverThread, NULL);
152 pthread_join(processorThread, NULL);
154 pthread_mutex_destroy(&mutex);
158 std::for_each(users.begin(), users.end(), DisconnectUser(*this));
160 printfd(__FILE__, "LISTENER::Stoped successfully.\n");
164 //-----------------------------------------------------------------------------
165 void * LISTENER::Run(void * d)
168 sigfillset(&signalSet);
169 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
171 LISTENER * listener = static_cast<LISTENER *>(d);
177 //-----------------------------------------------------------------------------
178 void LISTENER::Runner()
180 receiverStopped = false;
187 receiverStopped = true;
189 //-----------------------------------------------------------------------------
190 void * LISTENER::RunProcessor(void * d)
193 sigfillset(&signalSet);
194 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
196 LISTENER * listener = static_cast<LISTENER *>(d);
198 listener->ProcessorRunner();
202 //-----------------------------------------------------------------------------
203 void LISTENER::ProcessorRunner()
205 processorStopped = false;
209 struct timespec ts = {0, 500000000};
210 nanosleep(&ts, NULL);
211 if (!pending.empty())
216 processorStopped = true;
218 //-----------------------------------------------------------------------------
219 bool LISTENER::PrepareNet()
221 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
223 if (listenSocket < 0)
225 errorStr = "Cannot create socket.";
229 struct sockaddr_in listenAddr;
230 listenAddr.sin_family = AF_INET;
231 listenAddr.sin_port = htons(port);
232 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
234 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
236 errorStr = "LISTENER: Bind failed.";
240 printfd(__FILE__, "LISTENER::PrepareNet() >>>> Start successfull.\n");
244 //-----------------------------------------------------------------------------
245 bool LISTENER::FinalizeNet()
251 //-----------------------------------------------------------------------------
252 bool LISTENER::RecvPacket()
256 char buffer[RS_MAX_PACKET_LEN];
257 RS::PACKET_HEADER packetHead;
259 iov[0].iov_base = reinterpret_cast<char *>(&packetHead);
260 iov[0].iov_len = sizeof(packetHead);
261 iov[1].iov_base = buffer;
262 iov[1].iov_len = sizeof(buffer) - sizeof(packetHead);
265 while (dataLen < sizeof(buffer))
267 if (!WaitPackets(listenSocket))
273 int portion = readv(listenSocket, iov, 2);
281 if (CheckHeader(packetHead))
283 printfd(__FILE__, "Invalid packet or incorrect protocol version!\n");
287 std::string userLogin((char *)packetHead.login);
289 data.login = userLogin;
290 data.ip = ntohl(packetHead.ip);
291 data.id = ntohl(packetHead.id);
293 if (packetHead.packetType == RS_ALIVE_PACKET)
295 data.type = PendingData::ALIVE;
297 else if (packetHead.packetType == RS_CONNECT_PACKET)
299 data.type = PendingData::CONNECT;
300 if (GetParams(buffer, data))
305 else if (packetHead.packetType == RS_DISCONNECT_PACKET)
307 data.type = PendingData::DISCONNECT;
308 if (GetParams(buffer, data))
314 STG_LOCKER lock(&mutex);
315 pending.push_back(data);
319 //-----------------------------------------------------------------------------
320 bool LISTENER::GetParams(char * buffer, UserData & data)
322 RS::PACKET_TAIL packetTail;
324 Decrypt(&ctxS, (char *)&packetTail, buffer, sizeof(packetTail) / 8);
326 if (strncmp((char *)packetTail.magic, RS_ID, RS_MAGIC_LEN))
328 printfd(__FILE__, "Invalid crypto magic\n");
332 std::ostringstream params;
333 params << "\"" << data.login << "\" "
334 << inet_ntostring(data.ip) << " "
336 << (char *)packetTail.params;
338 data.params = params.str();
342 //-----------------------------------------------------------------------------
343 void LISTENER::ProcessPending()
345 std::list<PendingData>::iterator it(pending.begin());
347 printfd(__FILE__, "Pending: %d\n", pending.size());
348 while (it != pending.end() && count < 256)
350 std::vector<AliveData>::iterator uit(
356 if (it->type == PendingData::CONNECT)
358 printfd(__FILE__, "Connect packet\n");
359 if (uit == users.end() || uit->login != it->login)
361 printfd(__FILE__, "Connect new user '%s'\n", it->login.c_str());
364 users.insert(uit, AliveData(static_cast<UserData>(*it)));
366 else if (uit->login == it->login)
368 printfd(__FILE__, "Update existing user '%s'\n", it->login.c_str());
369 // Update already existing user
370 time(&uit->lastAlive);
371 uit->params = it->params;
375 printfd(__FILE__, "Hmmm... Strange connect for '%s'\n", it->login.c_str());
378 else if (it->type == PendingData::ALIVE)
380 printfd(__FILE__, "Alive packet\n");
381 if (uit != users.end() && uit->login == it->login)
383 printfd(__FILE__, "Alive user '%s'\n", it->login.c_str());
384 // Update existing user
385 time(&uit->lastAlive);
389 printfd(__FILE__, "Alive user '%s' is not found\n", it->login.c_str());
392 else if (it->type == PendingData::DISCONNECT)
394 printfd(__FILE__, "Disconnect packet\n");
395 if (uit != users.end() && uit->login == it->login.c_str())
397 printfd(__FILE__, "Disconnect user '%s'\n", it->login.c_str());
398 // Disconnect existing user
404 printfd(__FILE__, "Cannot find user '%s' for disconnect\n", it->login.c_str());
409 printfd(__FILE__, "Unknown packet type\n");
414 STG_LOCKER lock(&mutex);
415 pending.erase(pending.begin(), it);
417 //-----------------------------------------------------------------------------
418 void LISTENER::ProcessTimeouts()
420 const std::vector<AliveData>::iterator it(
421 std::stable_partition(
424 IsNotTimedOut(userTimeout)
428 if (it != users.end())
430 printfd(__FILE__, "Total users: %d, users to disconnect: %d\n", users.size(), std::distance(it, users.end()));
435 DisconnectUser(*this)
438 users.erase(it, users.end());
441 //-----------------------------------------------------------------------------
442 bool LISTENER::Connect(const UserData & data) const
444 printfd(__FILE__, "Connect %s\n", data.login.c_str());
445 if (access(scriptOnConnect.c_str(), X_OK) == 0)
447 if (ScriptExec((scriptOnConnect + " " + data.params).c_str()))
449 WriteServLog("Script %s cannot be executed for an unknown reason.", scriptOnConnect.c_str());
455 WriteServLog("Script %s cannot be executed. File not found.", scriptOnConnect.c_str());
460 //-----------------------------------------------------------------------------
461 bool LISTENER::Disconnect(const UserData & data) const
463 printfd(__FILE__, "Disconnect %s\n", data.login.c_str());
464 if (access(scriptOnDisconnect.c_str(), X_OK) == 0)
466 if (ScriptExec((scriptOnDisconnect + " " + data.params).c_str()))
468 WriteServLog("Script %s cannot be executed for an unknown reson.", scriptOnDisconnect.c_str());
474 WriteServLog("Script %s cannot be executed. File not found.", scriptOnDisconnect.c_str());
479 //-----------------------------------------------------------------------------
480 bool LISTENER::CheckHeader(const RS::PACKET_HEADER & header) const
482 if (strncmp((char *)header.magic, RS_ID, RS_MAGIC_LEN))
486 if (strncmp((char *)header.protoVer, "02", RS_PROTO_VER_LEN))
492 //-----------------------------------------------------------------------------
494 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
496 unsigned char keyL[PASSWD_LEN];
497 memset(keyL, 0, PASSWD_LEN);
498 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
499 Blowfish_Init(ctx, keyL, PASSWD_LEN);
501 //-----------------------------------------------------------------------------
503 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
506 memcpy(dst, src, len8 * 8);
508 for (int i = 0; i < len8; i++)
509 Blowfish_Decrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
511 //-----------------------------------------------------------------------------