11 #include "stg/common.h"
12 #include "stg/ia_packets.h"
13 #include "stg/locker.h"
17 class HasIP : public std::unary_function<std::pair<uint32_t, USER>, bool> {
19 explicit HasIP(uint32_t i) : ip(i) {}
20 bool operator()(const std::pair<uint32_t, USER> & value) { return value.first == ip; }
25 PROTO::PROTO(const std::string & server,
33 uint32_t ip = inet_addr(server.c_str());
34 if (ip == INADDR_NONE)
36 struct hostent * hePtr = gethostbyname(server.c_str());
39 ip = *((uint32_t *)hePtr->h_addr_list[0]);
43 errorStr = "Unknown host: '";
46 printfd(__FILE__, "PROTO::PROTO() - %s\n", errorStr.c_str());
47 throw std::runtime_error(errorStr);
51 localAddr.sin_family = AF_INET;
52 localAddr.sin_port = htons(localPort);
53 localAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
55 serverAddr.sin_family = AF_INET;
56 serverAddr.sin_port = htons(port);
57 serverAddr.sin_addr.s_addr = ip;
59 unsigned char key[IA_PASSWD_LEN];
60 memset(key, 0, IA_PASSWD_LEN);
61 strncpy(reinterpret_cast<char *>(key), "pr7Hhen", 8);
62 Blowfish_Init(&ctx, key, IA_PASSWD_LEN);
64 processors["CONN_SYN_ACK"] = &PROTO::CONN_SYN_ACK_Proc;
65 processors["ALIVE_SYN"] = &PROTO::ALIVE_SYN_Proc;
66 processors["DISCONN_SYN_ACK"] = &PROTO::DISCONN_SYN_ACK_Proc;
67 processors["FIN"] = &PROTO::FIN_Proc;
68 processors["INFO"] = &PROTO::INFO_Proc;
69 // ERR_Proc will be handled explicitly
71 pthread_mutex_init(&mutex, NULL);
76 pthread_mutex_destroy(&mutex);
79 void * PROTO::Runner(void * data)
82 sigfillset(&signalSet);
83 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
85 PROTO * protoPtr = static_cast<PROTO *>(data);
94 if (pthread_create(&tid, NULL, &Runner, this))
96 errorStr = "Failed to create listening thread: '";
97 errorStr += strerror(errno);
99 printfd(__FILE__, "PROTO::Start() - %s\n", errorStr.c_str());
109 while (!stopped && time < timeout)
111 struct timespec ts = {1, 0};
112 nanosleep(&ts, NULL);
117 errorStr = "Failed to stop listening thread - timed out";
118 printfd(__FILE__, "PROTO::Stop() - %s\n", errorStr.c_str());
121 if (pthread_join(tid, NULL))
123 errorStr = "Failed to join listening thread after stop: '";
124 errorStr += strerror(errno);
126 printfd(__FILE__, "PROTO::Stop() - %s\n", errorStr.c_str());
132 void PROTO::AddUser(const USER & user, bool connect)
134 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
135 users.push_back(std::make_pair(user.GetIP(), user));
136 users.back().second.InitNetwork();
139 pfd.fd = users.back().second.GetSocket();
142 pollFds.push_back(pfd);
146 RealConnect(&users.back().second);
150 bool PROTO::Connect(uint32_t ip)
152 std::list<std::pair<uint32_t, USER> >::iterator it;
153 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
154 it = std::find_if(users.begin(), users.end(), HasIP(ip));
155 if (it == users.end())
160 return RealConnect(&it->second);
163 bool PROTO::Disconnect(uint32_t ip)
165 std::list<std::pair<uint32_t, USER> >::iterator it;
166 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
167 it = std::find_if(users.begin(), users.end(), HasIP(ip));
168 if (it == users.end())
173 return RealDisconnect(&it->second);
182 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
183 res = poll(&pollFds.front(), pollFds.size(), timeout);
191 printfd(__FILE__, "PROTO::Run() - events: %d\n", res);
203 void PROTO::CheckTimeouts()
205 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
206 std::list<std::pair<uint32_t, USER> >::iterator it;
207 for (it = users.begin(); it != users.end(); ++it)
209 int delta = difftime(time(NULL), it->second.GetPhaseChangeTime());
210 if ((it->second.GetPhase() == 3) &&
211 (delta > it->second.GetUserTimeout()))
213 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());
214 it->second.SetPhase(1);
216 if ((it->second.GetPhase() == 2) &&
217 (delta > it->second.GetAliveTimeout()))
219 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());
220 it->second.SetPhase(1);
225 bool PROTO::RecvPacket()
228 std::vector<struct pollfd>::iterator it;
229 std::list<std::pair<uint32_t, USER> >::iterator userIt;
230 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
231 for (it = pollFds.begin(), userIt = users.begin(); it != pollFds.end() && userIt != users.end(); ++it, ++userIt)
236 assert(it->fd == userIt->second.GetSocket() && "File descriptors from poll fds and users must be syncked");
237 struct sockaddr_in addr;
238 socklen_t fromLen = sizeof(addr);
240 int res = recvfrom(userIt->second.GetSocket(), buffer, sizeof(buffer), 0, (struct sockaddr *)&addr, &fromLen);
248 result = result && HandlePacket(buffer, res, &(userIt->second));
255 bool PROTO::HandlePacket(const char * buffer, size_t length, USER * user)
257 if (!strncmp(buffer + 4 + sizeof(HDR_8), "ERR", 3))
259 return ERR_Proc(buffer, user);
262 for (size_t i = 0; i < length / 8; i++)
263 Blowfish_Decrypt(user->GetCtx(),
264 (uint32_t *)(buffer + i * 8),
265 (uint32_t *)(buffer + i * 8 + 4));
267 std::string packetName(buffer + 12);
269 std::map<std::string, PacketProcessor>::const_iterator it;
270 it = processors.find(packetName);
271 if (it != processors.end())
272 return (this->*it->second)(buffer, user);
274 printfd(__FILE__, "PROTO::HandlePacket() - invalid packet signature: '%s'\n", packetName.c_str());
279 bool PROTO::CONN_SYN_ACK_Proc(const void * buffer, USER * user)
281 const CONN_SYN_ACK_8 * packet = static_cast<const CONN_SYN_ACK_8 *>(buffer);
283 uint32_t rnd = packet->rnd;
284 uint32_t userTimeout = packet->userTimeOut;
285 uint32_t aliveTimeout = packet->aliveDelay;
289 SwapBytes(userTimeout);
290 SwapBytes(aliveDelay);
293 if (user->GetPhase() != 2)
295 errorStr = "Unexpected CONN_SYN_ACK";
296 printfd(__FILE__, "PROTO::CONN_SYN_ACK_Proc() - wrong phase: %d\n", user->GetPhase());
301 user->SetAliveTimeout(aliveTimeout);
302 user->SetUserTimeout(userTimeout);
307 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());
312 bool PROTO::ALIVE_SYN_Proc(const void * buffer, USER * user)
314 const ALIVE_SYN_8 * packet = static_cast<const ALIVE_SYN_8 *>(buffer);
316 uint32_t rnd = packet->rnd;
322 if (user->GetPhase() != 3)
324 errorStr = "Unexpected ALIVE_SYN";
325 printfd(__FILE__, "PROTO::ALIVE_SYN_Proc() - wrong phase: %d\n", user->GetPhase());
330 user->SetRnd(rnd); // Set new rnd value for ALIVE_ACK
332 Send_ALIVE_ACK(user);
337 bool PROTO::DISCONN_SYN_ACK_Proc(const void * buffer, USER * user)
339 const DISCONN_SYN_ACK_8 * packet = static_cast<const DISCONN_SYN_ACK_8 *>(buffer);
341 uint32_t rnd = packet->rnd;
347 if (user->GetPhase() != 4)
349 errorStr = "Unexpected DISCONN_SYN_ACK";
350 printfd(__FILE__, "PROTO::DISCONN_SYN_ACK_Proc() - wrong phase: %d\n", user->GetPhase());
354 if (user->GetRnd() + 1 != rnd)
356 errorStr = "Wrong control value at DISCONN_SYN_ACK";
357 printfd(__FILE__, "PROTO::DISCONN_SYN_ACK_Proc() - wrong control value: %d, expected: %d\n", rnd, user->GetRnd() + 1);
363 Send_DISCONN_ACK(user);
368 bool PROTO::FIN_Proc(const void * buffer, USER * user)
370 if (user->GetPhase() != 5)
372 errorStr = "Unexpected FIN";
373 printfd(__FILE__, "PROTO::FIN_Proc() - wrong phase: %d\n", user->GetPhase());
382 bool PROTO::INFO_Proc(const void * buffer, USER * user)
384 //const INFO_8 * packet = static_cast<const INFO_8 *>(buffer);
389 bool PROTO::ERR_Proc(const void * buffer, USER * user)
391 const ERR_8 * packet = static_cast<const ERR_8 *>(buffer);
392 const char * ptr = static_cast<const char *>(buffer);
394 //uint32_t len = packet->len;
400 user->SetPhase(1); //TODO: Check
401 /*KOIToWin((const char*)err.text, &messageText);
402 if (pErrorCb != NULL)
403 pErrorCb(messageText, IA_SERVER_ERROR, errorCbData);
404 phaseTime = GetTickCount();
405 codeError = IA_SERVER_ERROR;*/
410 bool PROTO::Send_CONN_SYN(USER * user)
414 packet.len = sizeof(packet);
417 SwapBytes(packet.len);
420 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
421 strncpy((char *)packet.type, "CONN_SYN", sizeof(packet.type));
422 strncpy((char *)packet.login, user->GetLogin().c_str(), sizeof(packet.login));
423 packet.dirs = 0xFFffFFff;
425 return SendPacket(&packet, sizeof(packet), user);
428 bool PROTO::Send_CONN_ACK(USER * user)
432 packet.len = sizeof(packet);
433 packet.rnd = user->IncRnd();
436 SwapBytes(packet.len);
437 SwapBytes(packet.rnd);
440 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
441 strncpy((char *)packet.type, "CONN_ACK", sizeof(packet.type));
443 return SendPacket(&packet, sizeof(packet), user);
446 bool PROTO::Send_ALIVE_ACK(USER * user)
450 packet.len = sizeof(packet);
451 packet.rnd = user->IncRnd();
454 SwapBytes(packet.len);
455 SwapBytes(packet.rnd);
458 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
459 strncpy((char *)packet.type, "ALIVE_ACK", sizeof(packet.type));
461 return SendPacket(&packet, sizeof(packet), user);
464 bool PROTO::Send_DISCONN_SYN(USER * user)
466 DISCONN_SYN_8 packet;
468 packet.len = sizeof(packet);
471 SwapBytes(packet.len);
474 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
475 strncpy((char *)packet.type, "DISCONN_SYN", sizeof(packet.type));
476 strncpy((char *)packet.login, user->GetLogin().c_str(), sizeof(packet.login));
478 return SendPacket(&packet, sizeof(packet), user);
481 bool PROTO::Send_DISCONN_ACK(USER * user)
483 DISCONN_ACK_8 packet;
485 packet.len = sizeof(packet);
486 packet.rnd = user->IncRnd();
489 SwapBytes(packet.len);
490 SwapBytes(packet.rnd);
493 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
494 strncpy((char *)packet.type, "DISCONN_ACK", sizeof(packet.type));
496 return SendPacket(&packet, sizeof(packet), user);
499 bool PROTO::SendPacket(const void * packet, size_t length, USER * user)
503 assert(length < 2048 && "Packet length must not exceed 2048 bytes");
505 strncpy((char *)hdr.magic, IA_ID, sizeof(hdr.magic));
507 hdr.protoVer[1] = 8; // IA_PROTO_VER
509 unsigned char buffer[2048];
510 memset(buffer, 0, sizeof(buffer));
511 memcpy(buffer, packet, length);
512 memcpy(buffer, &hdr, sizeof(hdr));
514 size_t offset = sizeof(HDR_8);
515 for (size_t i = 0; i < IA_LOGIN_LEN / 8; i++)
517 Blowfish_Encrypt(&ctx,
518 (uint32_t *)(buffer + offset + i * 8),
519 (uint32_t *)(buffer + offset + i * 8 + 4));
522 offset += IA_LOGIN_LEN;
523 size_t encLen = (length - IA_LOGIN_LEN) / 8;
524 for (size_t i = 0; i < encLen; i++)
526 Blowfish_Encrypt(user->GetCtx(),
527 (uint32_t*)(buffer + offset + i * 8),
528 (uint32_t*)(buffer + offset + i * 8 + 4));
531 int res = sendto(user->GetSocket(), buffer, length, 0, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
535 errorStr = "Failed to send packet: '";
536 errorStr += strerror(errno);
538 printfd(__FILE__, "PROTO::SendPacket() - %s, fd: %d\n", errorStr.c_str(), user->GetSocket());
544 errorStr = "Packet sent partially";
545 printfd(__FILE__, "PROTO::SendPacket() - %s\n", errorStr.c_str());
552 bool PROTO::RealConnect(USER * user)
554 if (user->GetPhase() != 1 &&
555 user->GetPhase() != 5)
557 errorStr = "Unexpected connect";
558 printfd(__FILE__, "PROTO::RealConnect() - wrong phase: %d\n", user->GetPhase());
562 return Send_CONN_SYN(user);
565 bool PROTO::RealDisconnect(USER * user)
567 if (user->GetPhase() != 3)
569 errorStr = "Unexpected disconnect";
570 printfd(__FILE__, "PROTO::RealDisconnect() - wrong phase: %d\n", user->GetPhase());
574 return Send_DISCONN_SYN(user);