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 "script_executer.h"
37 #include "stg_locker.h"
40 //-----------------------------------------------------------------------------
42 : WriteServLog(GetStgLogger()),
45 receiverStopped(true),
46 processorStopped(true),
50 version = "rscriptd listener v.1.2";
52 pthread_mutex_init(&mutex, NULL);
54 //-----------------------------------------------------------------------------
55 void LISTENER::SetPassword(const string & p)
58 printfd(__FILE__, "Encryption initiated with password \'%s\'\n", password.c_str());
59 InitEncrypt(&ctxS, password);
61 //-----------------------------------------------------------------------------
62 bool LISTENER::Start()
64 printfd(__FILE__, "LISTENER::Start()\n");
74 if (pthread_create(&receiverThread, NULL, Run, this))
76 errorStr = "Cannot create thread.";
83 if (pthread_create(&processorThread, NULL, RunProcessor, this))
85 errorStr = "Cannot create thread.";
94 //-----------------------------------------------------------------------------
99 printfd(__FILE__, "LISTENER::Stop()\n");
103 if (!processorStopped)
105 //5 seconds to thread stops itself
106 for (int i = 0; i < 25 && !processorStopped; i++)
111 //after 5 seconds waiting thread still running. now killing it
112 if (!processorStopped)
114 //TODO pthread_cancel()
115 if (pthread_kill(processorThread, SIGINT))
117 errorStr = "Cannot kill thread.";
120 printfd(__FILE__, "LISTENER killed Timeouter\n");
124 if (!receiverStopped)
126 //5 seconds to thread stops itself
127 for (int i = 0; i < 25 && !receiverStopped; i++)
132 //after 5 seconds waiting thread still running. now killing it
133 if (!receiverStopped)
135 //TODO pthread_cancel()
136 if (pthread_kill(receiverThread, SIGINT))
138 errorStr = "Cannot kill thread.";
141 printfd(__FILE__, "LISTENER killed Run\n");
145 pthread_join(receiverThread, NULL);
146 pthread_join(processorThread, NULL);
148 pthread_mutex_destroy(&mutex);
152 std::for_each(users.begin(), users.end(), DisconnectUser(*this));
154 printfd(__FILE__, "LISTENER::Stoped successfully.\n");
158 //-----------------------------------------------------------------------------
159 void * LISTENER::Run(void * d)
161 LISTENER * ia = static_cast<LISTENER *>(d);
167 //-----------------------------------------------------------------------------
168 void LISTENER::Runner()
170 receiverStopped = false;
177 receiverStopped = true;
179 //-----------------------------------------------------------------------------
180 void * LISTENER::RunProcessor(void * d)
182 LISTENER * ia = static_cast<LISTENER *>(d);
184 ia->ProcessorRunner();
188 //-----------------------------------------------------------------------------
189 void LISTENER::ProcessorRunner()
191 processorStopped = false;
196 if (!pending.empty())
201 processorStopped = true;
203 //-----------------------------------------------------------------------------
204 bool LISTENER::PrepareNet()
206 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
208 if (listenSocket < 0)
210 errorStr = "Cannot create socket.";
214 printfd(__FILE__, "Port: %d\n", port);
216 struct sockaddr_in listenAddr;
217 listenAddr.sin_family = AF_INET;
218 listenAddr.sin_port = htons(port);
219 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
221 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
223 errorStr = "LISTENER: Bind failed.";
227 printfd(__FILE__, "LISTENER::PrepareNet() >>>> Start successfull.\n");
231 //-----------------------------------------------------------------------------
232 bool LISTENER::FinalizeNet()
238 //-----------------------------------------------------------------------------
239 bool LISTENER::RecvPacket()
243 char buffer[RS_MAX_PACKET_LEN];
244 RS_PACKET_HEADER packetHead;
246 iov[0].iov_base = reinterpret_cast<char *>(&packetHead);
247 iov[0].iov_len = sizeof(packetHead);
248 iov[1].iov_base = buffer;
249 iov[1].iov_len = sizeof(buffer);
252 while (dataLen < sizeof(buffer))
254 if (!WaitPackets(listenSocket))
260 int portion = readv(listenSocket, iov, 2);
268 if (CheckHeader(packetHead))
270 printfd(__FILE__, "Invalid packet or incorrect protocol version!\n");
274 std::string userLogin((char *)packetHead.login);
276 data.login = userLogin;
277 data.ip = ntohl(packetHead.ip);
278 data.id = ntohl(packetHead.id);
280 if (packetHead.packetType == RS_ALIVE_PACKET)
282 data.type = PendingData::ALIVE;
284 else if (packetHead.packetType == RS_CONNECT_PACKET)
286 data.type = PendingData::CONNECT;
287 if (GetParams(buffer, data))
292 else if (packetHead.packetType == RS_DISCONNECT_PACKET)
294 data.type = PendingData::DISCONNECT;
295 if (GetParams(buffer, data))
301 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
302 pending.push_back(data);
306 //-----------------------------------------------------------------------------
307 bool LISTENER::GetParams(char * buffer, UserData & data)
309 RS_PACKET_TAIL packetTail;
311 Decrypt(&ctxS, (char *)&packetTail, buffer, sizeof(packetTail) / 8);
313 if (strncmp((char *)packetTail.magic, RS_ID, RS_MAGIC_LEN))
315 printfd(__FILE__, "Invalid crypto magic\n");
319 std::stringstream params;
320 params << data.login << " "
321 << inet_ntostring(data.ip) << " "
322 << ntohl(data.id) << " "
323 << (char *)packetTail.params;
325 data.params = params.str();
329 //-----------------------------------------------------------------------------
330 void LISTENER::ProcessPending()
332 printfd(__FILE__, "Pending data size: %d\n", pending.size());
333 std::list<PendingData>::iterator it(pending.begin());
334 while (it != pending.end())
336 std::vector<AliveData>::iterator uit(
342 if (it->type == PendingData::CONNECT)
344 if (uit == users.end() || uit->login != it->login)
348 users.insert(uit, AliveData(static_cast<UserData>(*it)));
350 else if (uit->login == it->login)
352 // Update already existing user
353 time(&uit->lastAlive);
354 uit->params = it->params;
357 else if (it->type == PendingData::ALIVE)
359 if (uit != users.end() && uit->login == it->login)
361 // Update existing user
362 time(&uit->lastAlive);
365 else if (it->type == PendingData::DISCONNECT)
367 if (uit != users.end() && uit->login == it->login.c_str())
369 // Disconnect existing user
375 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
379 //-----------------------------------------------------------------------------
380 void LISTENER::ProcessTimeouts()
382 const std::vector<AliveData>::iterator it(
383 std::stable_partition(
386 IsNotTimedOut(userTimeout)
390 if (it != users.end())
392 printfd(__FILE__, "Total users: %d, users to disconnect: %d\n", users.size(), std::distance(it, users.end()));
397 DisconnectUser(*this)
400 users.erase(it, users.end());
403 //-----------------------------------------------------------------------------
404 bool LISTENER::Connect(const UserData & data) const
406 printfd(__FILE__, "Connect %s\n", data.login.c_str());
407 if (access(scriptOnConnect.c_str(), X_OK) == 0)
409 if (ScriptExec(scriptOnConnect + " " + data.params))
411 WriteServLog("Script %s cannot be executed for an unknown reason.", scriptOnConnect.c_str());
417 WriteServLog("Script %s cannot be executed. File not found.", scriptOnConnect.c_str());
422 //-----------------------------------------------------------------------------
423 bool LISTENER::Disconnect(const UserData & data) const
425 printfd(__FILE__, "Disconnect %s\n", data.login.c_str());
426 if (access(scriptOnDisconnect.c_str(), X_OK) == 0)
428 if (ScriptExec(scriptOnDisconnect + " " + data.params))
430 WriteServLog("Script %s cannot be executed for an unknown reson.", scriptOnDisconnect.c_str());
436 WriteServLog("Script %s cannot be executed. File not found.", scriptOnDisconnect.c_str());
441 //-----------------------------------------------------------------------------
442 void LISTENER::InitEncrypt(BLOWFISH_CTX * ctx, const string & password)
444 unsigned char keyL[PASSWD_LEN];
445 memset(keyL, 0, PASSWD_LEN);
446 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
447 Blowfish_Init(ctx, keyL, PASSWD_LEN);
449 //-----------------------------------------------------------------------------
450 void LISTENER::Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
453 memcpy(dst, src, len8 * 8);
455 for (int i = 0; i < len8; i++)
456 Blowfish_Decrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
458 //-----------------------------------------------------------------------------
459 bool LISTENER::CheckHeader(const RS_PACKET_HEADER & header) const
461 if (strncmp((char *)header.magic, RS_ID, RS_MAGIC_LEN))
465 if (strncmp((char *)header.protoVer, "02", RS_PROTO_VER_LEN))
471 //-----------------------------------------------------------------------------
472 bool LISTENER::WaitPackets(int sd) const
482 int res = select(sd + 1, &rfds, NULL, NULL, &tv);
483 if (res == -1) // Error
487 printfd(__FILE__, "Error on select: '%s'\n", strerror(errno));
492 if (res == 0) // Timeout
499 //-----------------------------------------------------------------------------