2 #include <sys/socket.h>
13 #include "stg/common.h"
14 #include "stg/ia_packets.h"
15 #include "stg/locker.h"
19 class HasIP : public std::unary_function<std::pair<uint32_t, USER>, bool> {
21 explicit HasIP(uint32_t i) : ip(i) {}
22 bool operator()(const std::pair<uint32_t, USER> & value) { return value.first == ip; }
27 PROTO::PROTO(const std::string & server,
35 uint32_t ip = inet_addr(server.c_str());
36 if (ip == INADDR_NONE)
38 struct hostent * hePtr = gethostbyname(server.c_str());
41 ip = *((uint32_t *)hePtr->h_addr_list[0]);
45 errorStr = "Unknown host: '";
48 printfd(__FILE__, "PROTO::PROTO() - %s\n", errorStr.c_str());
49 throw std::runtime_error(errorStr);
53 localAddr.sin_family = AF_INET;
54 localAddr.sin_port = htons(localPort);
55 localAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
57 serverAddr.sin_family = AF_INET;
58 serverAddr.sin_port = htons(port);
59 serverAddr.sin_addr.s_addr = ip;
61 unsigned char key[IA_PASSWD_LEN];
62 memset(key, 0, IA_PASSWD_LEN);
63 strncpy(reinterpret_cast<char *>(key), "pr7Hhen", 8);
64 Blowfish_Init(&ctx, key, IA_PASSWD_LEN);
66 processors["CONN_SYN_ACK"] = &PROTO::CONN_SYN_ACK_Proc;
67 processors["ALIVE_SYN"] = &PROTO::ALIVE_SYN_Proc;
68 processors["DISCONN_SYN_ACK"] = &PROTO::DISCONN_SYN_ACK_Proc;
69 processors["FIN"] = &PROTO::FIN_Proc;
70 processors["INFO"] = &PROTO::INFO_Proc;
71 // ERR_Proc will be handled explicitly
73 pthread_mutex_init(&mutex, NULL);
78 pthread_mutex_destroy(&mutex);
81 void * PROTO::Runner(void * data)
84 sigfillset(&signalSet);
85 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
87 PROTO * protoPtr = static_cast<PROTO *>(data);
96 if (pthread_create(&tid, NULL, &Runner, this))
98 errorStr = "Failed to create listening thread: '";
99 errorStr += strerror(errno);
101 printfd(__FILE__, "PROTO::Start() - %s\n", errorStr.c_str());
111 while (!stopped && time < timeout)
113 struct timespec ts = {1, 0};
114 nanosleep(&ts, NULL);
119 errorStr = "Failed to stop listening thread - timed out";
120 printfd(__FILE__, "PROTO::Stop() - %s\n", errorStr.c_str());
123 if (pthread_join(tid, NULL))
125 errorStr = "Failed to join listening thread after stop: '";
126 errorStr += strerror(errno);
128 printfd(__FILE__, "PROTO::Stop() - %s\n", errorStr.c_str());
134 void PROTO::AddUser(const USER & user, bool connect)
136 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
137 users.push_back(std::make_pair(user.GetIP(), user));
138 users.back().second.InitNetwork();
141 pfd.fd = users.back().second.GetSocket();
144 pollFds.push_back(pfd);
148 RealConnect(&users.back().second);
152 bool PROTO::Connect(uint32_t ip)
154 std::list<std::pair<uint32_t, USER> >::iterator it;
155 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
156 it = std::find_if(users.begin(), users.end(), HasIP(ip));
157 if (it == users.end())
162 return RealConnect(&it->second);
165 bool PROTO::Disconnect(uint32_t ip)
167 std::list<std::pair<uint32_t, USER> >::iterator it;
168 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
169 it = std::find_if(users.begin(), users.end(), HasIP(ip));
170 if (it == users.end())
175 return RealDisconnect(&it->second);
184 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
185 res = poll(&pollFds.front(), pollFds.size(), timeout);
193 printfd(__FILE__, "PROTO::Run() - events: %d\n", res);
205 void PROTO::CheckTimeouts()
207 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
208 std::list<std::pair<uint32_t, USER> >::iterator it;
209 for (it = users.begin(); it != users.end(); ++it)
211 int delta = difftime(time(NULL), it->second.GetPhaseChangeTime());
212 if ((it->second.GetPhase() == 3) &&
213 (delta > it->second.GetUserTimeout()))
215 printfd(__FILE__, "PROTO::CheckTimeouts() - user alive timeout (ip: %s, login: '%s', delta: %d > %d)\n", inet_ntostring(it->second.GetIP()).c_str(), it->second.GetLogin().c_str(), delta, it->second.GetUserTimeout());
216 it->second.SetPhase(1);
218 if ((it->second.GetPhase() == 2) &&
219 (delta > it->second.GetAliveTimeout()))
221 printfd(__FILE__, "PROTO::CheckTimeouts() - user connect timeout (ip: %s, login: '%s', delta: %d > %d)\n", inet_ntostring(it->second.GetIP()).c_str(), it->second.GetLogin().c_str(), delta, it->second.GetAliveTimeout());
222 it->second.SetPhase(1);
227 bool PROTO::RecvPacket()
230 std::vector<struct pollfd>::iterator it;
231 std::list<std::pair<uint32_t, USER> >::iterator userIt;
232 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
233 for (it = pollFds.begin(), userIt = users.begin(); it != pollFds.end() && userIt != users.end(); ++it, ++userIt)
238 assert(it->fd == userIt->second.GetSocket() && "File descriptors from poll fds and users must be syncked");
239 struct sockaddr_in addr;
240 socklen_t fromLen = sizeof(addr);
242 int res = recvfrom(userIt->second.GetSocket(), buffer, sizeof(buffer), 0, (struct sockaddr *)&addr, &fromLen);
250 result = result && HandlePacket(buffer, res, &(userIt->second));
257 bool PROTO::HandlePacket(const char * buffer, size_t length, USER * user)
259 if (!strncmp(buffer + 4 + sizeof(HDR_8), "ERR", 3))
261 return ERR_Proc(buffer, user);
264 for (size_t i = 0; i < length / 8; i++)
265 Blowfish_Decrypt(user->GetCtx(),
266 (uint32_t *)(buffer + i * 8),
267 (uint32_t *)(buffer + i * 8 + 4));
269 std::string packetName(buffer + 12);
271 std::map<std::string, PacketProcessor>::const_iterator it;
272 it = processors.find(packetName);
273 if (it != processors.end())
274 return (this->*it->second)(buffer, user);
276 printfd(__FILE__, "PROTO::HandlePacket() - invalid packet signature: '%s'\n", packetName.c_str());
281 bool PROTO::CONN_SYN_ACK_Proc(const void * buffer, USER * user)
283 const CONN_SYN_ACK_8 * packet = static_cast<const CONN_SYN_ACK_8 *>(buffer);
285 uint32_t rnd = packet->rnd;
286 uint32_t userTimeout = packet->userTimeOut;
287 uint32_t aliveTimeout = packet->aliveDelay;
291 SwapBytes(userTimeout);
292 SwapBytes(aliveDelay);
295 if (user->GetPhase() != 2)
297 errorStr = "Unexpected CONN_SYN_ACK";
298 printfd(__FILE__, "PROTO::CONN_SYN_ACK_Proc() - wrong phase: %d\n", user->GetPhase());
303 user->SetAliveTimeout(aliveTimeout);
304 user->SetUserTimeout(userTimeout);
309 printfd(__FILE__, "PROTO::CONN_SYN_ACK_Proc() - user '%s' successfully logged in from IP %s\n", user->GetLogin().c_str(), inet_ntostring(user->GetIP()).c_str());
314 bool PROTO::ALIVE_SYN_Proc(const void * buffer, USER * user)
316 const ALIVE_SYN_8 * packet = static_cast<const ALIVE_SYN_8 *>(buffer);
318 uint32_t rnd = packet->rnd;
324 if (user->GetPhase() != 3)
326 errorStr = "Unexpected ALIVE_SYN";
327 printfd(__FILE__, "PROTO::ALIVE_SYN_Proc() - wrong phase: %d\n", user->GetPhase());
332 user->SetRnd(rnd); // Set new rnd value for ALIVE_ACK
334 Send_ALIVE_ACK(user);
339 bool PROTO::DISCONN_SYN_ACK_Proc(const void * buffer, USER * user)
341 const DISCONN_SYN_ACK_8 * packet = static_cast<const DISCONN_SYN_ACK_8 *>(buffer);
343 uint32_t rnd = packet->rnd;
349 if (user->GetPhase() != 4)
351 errorStr = "Unexpected DISCONN_SYN_ACK";
352 printfd(__FILE__, "PROTO::DISCONN_SYN_ACK_Proc() - wrong phase: %d\n", user->GetPhase());
356 if (user->GetRnd() + 1 != rnd)
358 errorStr = "Wrong control value at DISCONN_SYN_ACK";
359 printfd(__FILE__, "PROTO::DISCONN_SYN_ACK_Proc() - wrong control value: %d, expected: %d\n", rnd, user->GetRnd() + 1);
365 Send_DISCONN_ACK(user);
370 bool PROTO::FIN_Proc(const void * buffer, USER * user)
372 if (user->GetPhase() != 5)
374 errorStr = "Unexpected FIN";
375 printfd(__FILE__, "PROTO::FIN_Proc() - wrong phase: %d\n", user->GetPhase());
384 bool PROTO::INFO_Proc(const void * buffer, USER * user)
386 //const INFO_8 * packet = static_cast<const INFO_8 *>(buffer);
391 bool PROTO::ERR_Proc(const void * buffer, USER * user)
393 const ERR_8 * packet = static_cast<const ERR_8 *>(buffer);
394 const char * ptr = static_cast<const char *>(buffer);
396 //uint32_t len = packet->len;
402 user->SetPhase(1); //TODO: Check
403 /*KOIToWin((const char*)err.text, &messageText);
404 if (pErrorCb != NULL)
405 pErrorCb(messageText, IA_SERVER_ERROR, errorCbData);
406 phaseTime = GetTickCount();
407 codeError = IA_SERVER_ERROR;*/
412 bool PROTO::Send_CONN_SYN(USER * user)
416 packet.len = sizeof(packet);
419 SwapBytes(packet.len);
422 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
423 strncpy((char *)packet.type, "CONN_SYN", sizeof(packet.type));
424 strncpy((char *)packet.login, user->GetLogin().c_str(), sizeof(packet.login));
425 packet.dirs = 0xFFffFFff;
427 return SendPacket(&packet, sizeof(packet), user);
430 bool PROTO::Send_CONN_ACK(USER * user)
434 packet.len = sizeof(packet);
435 packet.rnd = user->IncRnd();
438 SwapBytes(packet.len);
439 SwapBytes(packet.rnd);
442 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
443 strncpy((char *)packet.type, "CONN_ACK", sizeof(packet.type));
445 return SendPacket(&packet, sizeof(packet), user);
448 bool PROTO::Send_ALIVE_ACK(USER * user)
452 packet.len = sizeof(packet);
453 packet.rnd = user->IncRnd();
456 SwapBytes(packet.len);
457 SwapBytes(packet.rnd);
460 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
461 strncpy((char *)packet.type, "ALIVE_ACK", sizeof(packet.type));
463 return SendPacket(&packet, sizeof(packet), user);
466 bool PROTO::Send_DISCONN_SYN(USER * user)
468 DISCONN_SYN_8 packet;
470 packet.len = sizeof(packet);
473 SwapBytes(packet.len);
476 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
477 strncpy((char *)packet.type, "DISCONN_SYN", sizeof(packet.type));
478 strncpy((char *)packet.login, user->GetLogin().c_str(), sizeof(packet.login));
480 return SendPacket(&packet, sizeof(packet), user);
483 bool PROTO::Send_DISCONN_ACK(USER * user)
485 DISCONN_ACK_8 packet;
487 packet.len = sizeof(packet);
488 packet.rnd = user->IncRnd();
491 SwapBytes(packet.len);
492 SwapBytes(packet.rnd);
495 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
496 strncpy((char *)packet.type, "DISCONN_ACK", sizeof(packet.type));
498 return SendPacket(&packet, sizeof(packet), user);
501 bool PROTO::SendPacket(const void * packet, size_t length, USER * user)
505 assert(length < 2048 && "Packet length must not exceed 2048 bytes");
507 strncpy((char *)hdr.magic, IA_ID, sizeof(hdr.magic));
509 hdr.protoVer[1] = 8; // IA_PROTO_VER
511 unsigned char buffer[2048];
512 memset(buffer, 0, sizeof(buffer));
513 memcpy(buffer, packet, length);
514 memcpy(buffer, &hdr, sizeof(hdr));
516 size_t offset = sizeof(HDR_8);
517 for (size_t i = 0; i < IA_LOGIN_LEN / 8; i++)
519 Blowfish_Encrypt(&ctx,
520 (uint32_t *)(buffer + offset + i * 8),
521 (uint32_t *)(buffer + offset + i * 8 + 4));
524 offset += IA_LOGIN_LEN;
525 size_t encLen = (length - IA_LOGIN_LEN) / 8;
526 for (size_t i = 0; i < encLen; i++)
528 Blowfish_Encrypt(user->GetCtx(),
529 (uint32_t*)(buffer + offset + i * 8),
530 (uint32_t*)(buffer + offset + i * 8 + 4));
533 int res = sendto(user->GetSocket(), buffer, length, 0, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
537 errorStr = "Failed to send packet: '";
538 errorStr += strerror(errno);
540 printfd(__FILE__, "PROTO::SendPacket() - %s, fd: %d\n", errorStr.c_str(), user->GetSocket());
546 errorStr = "Packet sent partially";
547 printfd(__FILE__, "PROTO::SendPacket() - %s\n", errorStr.c_str());
554 bool PROTO::RealConnect(USER * user)
556 if (user->GetPhase() != 1 &&
557 user->GetPhase() != 5)
559 errorStr = "Unexpected connect";
560 printfd(__FILE__, "PROTO::RealConnect() - wrong phase: %d\n", user->GetPhase());
564 return Send_CONN_SYN(user);
567 bool PROTO::RealDisconnect(USER * user)
569 if (user->GetPhase() != 3)
571 errorStr = "Unexpected disconnect";
572 printfd(__FILE__, "PROTO::RealDisconnect() - wrong phase: %d\n", user->GetPhase());
576 return Send_DISCONN_SYN(user);