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/script_executer.h"
37 #include "stg/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");
107 if (!processorStopped)
109 //5 seconds to thread stops itself
110 for (int i = 0; i < 25 && !processorStopped; i++)
115 //after 5 seconds waiting thread still running. now killing it
116 if (!processorStopped)
118 //TODO pthread_cancel()
119 if (pthread_kill(processorThread, SIGINT))
121 errorStr = "Cannot kill thread.";
124 printfd(__FILE__, "LISTENER killed Timeouter\n");
128 if (!receiverStopped)
130 //5 seconds to thread stops itself
131 for (int i = 0; i < 25 && !receiverStopped; i++)
136 //after 5 seconds waiting thread still running. now killing it
137 if (!receiverStopped)
139 //TODO pthread_cancel()
140 if (pthread_kill(receiverThread, SIGINT))
142 errorStr = "Cannot kill thread.";
145 printfd(__FILE__, "LISTENER killed Run\n");
149 pthread_join(receiverThread, NULL);
150 pthread_join(processorThread, NULL);
152 pthread_mutex_destroy(&mutex);
156 std::for_each(users.begin(), users.end(), DisconnectUser(*this));
158 printfd(__FILE__, "LISTENER::Stoped successfully.\n");
162 //-----------------------------------------------------------------------------
163 void * LISTENER::Run(void * d)
165 LISTENER * listener = static_cast<LISTENER *>(d);
171 //-----------------------------------------------------------------------------
172 void LISTENER::Runner()
174 receiverStopped = false;
181 receiverStopped = true;
183 //-----------------------------------------------------------------------------
184 void * LISTENER::RunProcessor(void * d)
186 LISTENER * listener = static_cast<LISTENER *>(d);
188 listener->ProcessorRunner();
192 //-----------------------------------------------------------------------------
193 void LISTENER::ProcessorRunner()
195 processorStopped = false;
200 if (!pending.empty())
205 processorStopped = true;
207 //-----------------------------------------------------------------------------
208 bool LISTENER::PrepareNet()
210 listenSocket = socket(AF_INET, SOCK_DGRAM, 0);
212 if (listenSocket < 0)
214 errorStr = "Cannot create socket.";
218 struct sockaddr_in listenAddr;
219 listenAddr.sin_family = AF_INET;
220 listenAddr.sin_port = htons(port);
221 listenAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
223 if (bind(listenSocket, (struct sockaddr*)&listenAddr, sizeof(listenAddr)) < 0)
225 errorStr = "LISTENER: Bind failed.";
229 printfd(__FILE__, "LISTENER::PrepareNet() >>>> Start successfull.\n");
233 //-----------------------------------------------------------------------------
234 bool LISTENER::FinalizeNet()
240 //-----------------------------------------------------------------------------
241 bool LISTENER::RecvPacket()
245 char buffer[RS_MAX_PACKET_LEN];
246 RS_PACKET_HEADER packetHead;
248 iov[0].iov_base = reinterpret_cast<char *>(&packetHead);
249 iov[0].iov_len = sizeof(packetHead);
250 iov[1].iov_base = buffer;
251 iov[1].iov_len = sizeof(buffer) - sizeof(packetHead);
254 while (dataLen < sizeof(buffer))
256 if (!WaitPackets(listenSocket))
262 int portion = readv(listenSocket, iov, 2);
270 if (CheckHeader(packetHead))
272 printfd(__FILE__, "Invalid packet or incorrect protocol version!\n");
276 std::string userLogin((char *)packetHead.login);
278 data.login = userLogin;
279 data.ip = ntohl(packetHead.ip);
280 data.id = ntohl(packetHead.id);
282 if (packetHead.packetType == RS_ALIVE_PACKET)
284 data.type = PendingData::ALIVE;
286 else if (packetHead.packetType == RS_CONNECT_PACKET)
288 data.type = PendingData::CONNECT;
289 if (GetParams(buffer, data))
294 else if (packetHead.packetType == RS_DISCONNECT_PACKET)
296 data.type = PendingData::DISCONNECT;
297 if (GetParams(buffer, data))
303 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
304 pending.push_back(data);
308 //-----------------------------------------------------------------------------
309 bool LISTENER::GetParams(char * buffer, UserData & data)
311 RS_PACKET_TAIL packetTail;
313 Decrypt(&ctxS, (char *)&packetTail, buffer, sizeof(packetTail) / 8);
315 if (strncmp((char *)packetTail.magic, RS_ID, RS_MAGIC_LEN))
317 printfd(__FILE__, "Invalid crypto magic\n");
321 std::stringstream params;
322 params << "\"" << data.login << "\" "
323 << inet_ntostring(data.ip) << " "
325 << (char *)packetTail.params;
327 data.params = params.str();
331 //-----------------------------------------------------------------------------
332 void LISTENER::ProcessPending()
334 std::list<PendingData>::iterator it(pending.begin());
336 printfd(__FILE__, "Pending: %d\n", pending.size());
337 while (it != pending.end() && count < 256)
339 std::vector<AliveData>::iterator uit(
345 if (it->type == PendingData::CONNECT)
347 if (uit == users.end() || uit->login != it->login)
351 users.insert(uit, AliveData(static_cast<UserData>(*it)));
353 else if (uit->login == it->login)
355 // Update already existing user
356 time(&uit->lastAlive);
357 uit->params = it->params;
360 else if (it->type == PendingData::ALIVE)
362 if (uit != users.end() && uit->login == it->login)
364 // Update existing user
365 time(&uit->lastAlive);
368 else if (it->type == PendingData::DISCONNECT)
370 if (uit != users.end() && uit->login == it->login.c_str())
372 // Disconnect existing user
380 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
381 pending.erase(pending.begin(), it);
383 //-----------------------------------------------------------------------------
384 void LISTENER::ProcessTimeouts()
386 const std::vector<AliveData>::iterator it(
387 std::stable_partition(
390 IsNotTimedOut(userTimeout)
394 if (it != users.end())
396 printfd(__FILE__, "Total users: %d, users to disconnect: %d\n", users.size(), std::distance(it, users.end()));
401 DisconnectUser(*this)
404 users.erase(it, users.end());
407 //-----------------------------------------------------------------------------
408 bool LISTENER::Connect(const UserData & data) const
410 printfd(__FILE__, "Connect %s\n", data.login.c_str());
411 if (access(scriptOnConnect.c_str(), X_OK) == 0)
413 if (ScriptExec(scriptOnConnect + " " + data.params))
415 WriteServLog("Script %s cannot be executed for an unknown reason.", scriptOnConnect.c_str());
421 WriteServLog("Script %s cannot be executed. File not found.", scriptOnConnect.c_str());
426 //-----------------------------------------------------------------------------
427 bool LISTENER::Disconnect(const UserData & data) const
429 printfd(__FILE__, "Disconnect %s\n", data.login.c_str());
430 if (access(scriptOnDisconnect.c_str(), X_OK) == 0)
432 if (ScriptExec(scriptOnDisconnect + " " + data.params))
434 WriteServLog("Script %s cannot be executed for an unknown reson.", scriptOnDisconnect.c_str());
440 WriteServLog("Script %s cannot be executed. File not found.", scriptOnDisconnect.c_str());
445 //-----------------------------------------------------------------------------
446 bool LISTENER::CheckHeader(const RS_PACKET_HEADER & header) const
448 if (strncmp((char *)header.magic, RS_ID, RS_MAGIC_LEN))
452 if (strncmp((char *)header.protoVer, "02", RS_PROTO_VER_LEN))
458 //-----------------------------------------------------------------------------
459 bool LISTENER::WaitPackets(int sd) const
469 int res = select(sd + 1, &rfds, NULL, NULL, &tv);
470 if (res == -1) // Error
474 printfd(__FILE__, "Error on select: '%s'\n", strerror(errno));
479 if (res == 0) // Timeout
486 //-----------------------------------------------------------------------------
488 void InitEncrypt(BLOWFISH_CTX * ctx, const std::string & password)
490 unsigned char keyL[PASSWD_LEN];
491 memset(keyL, 0, PASSWD_LEN);
492 strncpy((char *)keyL, password.c_str(), PASSWD_LEN);
493 Blowfish_Init(ctx, keyL, PASSWD_LEN);
495 //-----------------------------------------------------------------------------
497 void Decrypt(BLOWFISH_CTX * ctx, char * dst, const char * src, int len8)
500 memcpy(dst, src, len8 * 8);
502 for (int i = 0; i < len8; i++)
503 Blowfish_Decrypt(ctx, (uint32_t *)(dst + i * 8), (uint32_t *)(dst + i * 8 + 4));
505 //-----------------------------------------------------------------------------