]> git.stg.codes - stg.git/blob - projects/sgauthstress/proto.cpp
Locks added, rnd logic for ALIVE changed, CONN_ACK bug fixed
[stg.git] / projects / sgauthstress / proto.cpp
1 #include <netdb.h>
2 #include <arpa/inet.h>
3
4 #include <cerrno>
5 #include <cstring>
6 #include <cassert>
7 #include <stdexcept>
8 #include <algorithm>
9
10 #include "stg/common.h"
11 #include "stg/ia_packets.h"
12 #include "stg/locker.h"
13
14 #include "proto.h"
15
16 class HasIP : public std::unary_function<std::pair<uint32_t, USER>, bool> {
17     public:
18         explicit HasIP(uint32_t i) : ip(i) {}
19         bool operator()(const std::pair<uint32_t, USER> & value) { return value.first == ip; }
20     private:
21         uint32_t ip;
22 };
23
24 PROTO::PROTO(const std::string & server,
25              uint16_t port,
26              uint16_t localPort,
27              int to)
28     : timeout(to),
29       running(false),
30       stopped(true)
31 {
32 uint32_t ip = inet_addr(server.c_str());
33 if (ip == INADDR_NONE)
34     {
35     struct hostent * hePtr = gethostbyname(server.c_str());
36     if (hePtr)
37         {
38         ip = *((uint32_t *)hePtr->h_addr_list[0]);
39         }
40     else
41         {
42         errorStr = "Unknown host: '";
43         errorStr += server;
44         errorStr += "'";
45         printfd(__FILE__, "PROTO::PROTO() - %s\n", errorStr.c_str());
46         throw std::runtime_error(errorStr);
47         }
48     }
49
50 localAddr.sin_family = AF_INET;
51 localAddr.sin_port = htons(localPort);
52 localAddr.sin_addr.s_addr = inet_addr("0.0.0.0");
53
54 serverAddr.sin_family = AF_INET;
55 serverAddr.sin_port = htons(port);
56 serverAddr.sin_addr.s_addr = ip;
57
58 unsigned char key[IA_PASSWD_LEN];
59 memset(key, 0, IA_PASSWD_LEN);
60 strncpy(reinterpret_cast<char *>(key), "pr7Hhen", 8);
61 Blowfish_Init(&ctx, key, IA_PASSWD_LEN);
62
63 processors["CONN_SYN_ACK"] = &PROTO::CONN_SYN_ACK_Proc;
64 processors["ALIVE_SYN"] = &PROTO::ALIVE_SYN_Proc;
65 processors["DISCONN_SYN_ACK"] = &PROTO::DISCONN_SYN_ACK_Proc;
66 processors["FIN"] = &PROTO::FIN_Proc;
67 processors["INFO"] = &PROTO::INFO_Proc;
68 // ERR_Proc will be handled explicitly
69
70 pthread_mutex_init(&mutex, NULL);
71 }
72
73 PROTO::~PROTO()
74 {
75 pthread_mutex_destroy(&mutex);
76 }
77
78 void * PROTO::Runner(void * data)
79 {
80 PROTO * protoPtr = static_cast<PROTO *>(data);
81 protoPtr->Run();
82 return NULL;
83 }
84
85 bool PROTO::Start()
86 {
87 stopped = false;
88 running = true;
89 if (pthread_create(&tid, NULL, &Runner, this))
90     {
91     errorStr = "Failed to create listening thread: '";
92     errorStr += strerror(errno);
93     errorStr += "'";
94     printfd(__FILE__, "PROTO::Start() - %s\n", errorStr.c_str());
95     return false;
96     }
97 return true;
98 }
99
100 bool PROTO::Stop()
101 {
102 running = false;
103 int time = 0;
104 while (!stopped && time < timeout)
105     {
106     struct timespec ts = {1, 0};
107     nanosleep(&ts, NULL);
108     ++time;
109     }
110 if (!stopped)
111     {
112     errorStr = "Failed to stop listening thread - timed out";
113     printfd(__FILE__, "PROTO::Stop() - %s\n", errorStr.c_str());
114     return false;
115     }
116 if (pthread_join(tid, NULL))
117     {
118     errorStr = "Failed to join listening thread after stop: '";
119     errorStr += strerror(errno);
120     errorStr += "'";
121     printfd(__FILE__, "PROTO::Stop() - %s\n", errorStr.c_str());
122     return false;
123     }
124 return true;
125 }
126
127 void PROTO::AddUser(const USER & user, bool connect)
128 {
129 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
130 users.push_back(std::make_pair(user.GetIP(), user));
131 users.back().second.InitNetwork();
132
133 struct pollfd pfd;
134 pfd.fd = users.back().second.GetSocket();
135 pfd.events = POLLIN;
136 pfd.revents = 0;
137 pollFds.push_back(pfd);
138
139 if (connect)
140     {
141     RealConnect(&users.back().second);
142     }
143 }
144
145 bool PROTO::Connect(uint32_t ip)
146 {
147 std::list<std::pair<uint32_t, USER> >::iterator it;
148 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
149 it = std::find_if(users.begin(), users.end(), HasIP(ip));
150 if (it == users.end())
151     return false;
152
153 // Do something
154
155 return RealConnect(&it->second);
156 }
157
158 bool PROTO::Disconnect(uint32_t ip)
159 {
160 std::list<std::pair<uint32_t, USER> >::iterator it;
161 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
162 it = std::find_if(users.begin(), users.end(), HasIP(ip));
163 if (it == users.end())
164     return false;
165
166 // Do something
167
168 return RealDisconnect(&it->second);
169 }
170
171 void PROTO::Run()
172 {
173 while (running)
174     {
175     int res = poll(&pollFds.front(), pollFds.size(), timeout);
176     if (res < 0)
177         break;
178     if (!running)
179         break;
180     if (res)
181         {
182         printfd(__FILE__, "PROTO::Run() - events: %d\n", res);
183         RecvPacket();
184         }
185     }
186
187 stopped = true;
188 }
189
190 bool PROTO::RecvPacket()
191 {
192 bool result = true;
193 std::vector<struct pollfd>::iterator it;
194 std::list<std::pair<uint32_t, USER> >::iterator userIt;
195 STG_LOCKER lock(&mutex, __FILE__, __LINE__);
196 for (it = pollFds.begin(), userIt = users.begin(); it != pollFds.end() && userIt != users.end(); ++it, ++userIt)
197     {
198     if (it->revents)
199         {
200         it->revents = 0;
201         printfd(__FILE__, "PROTO::RecvPacket() - pollfd: %d, socket: %d\n", it->fd, userIt->second.GetSocket());
202         assert(it->fd == userIt->second.GetSocket() && "File descriptors from poll fds and users must be syncked");
203         struct sockaddr_in addr;
204         socklen_t fromLen = sizeof(addr);
205         char buffer[2048];
206         int res = recvfrom(userIt->second.GetSocket(), buffer, sizeof(buffer), 0, (struct sockaddr *)&addr, &fromLen);
207
208         if (res == -1)
209             {
210             result = false;
211             continue;
212             }
213
214         result = result && HandlePacket(buffer, res, &(userIt->second));
215         }
216     }
217
218 return result;
219 }
220
221 bool PROTO::HandlePacket(const char * buffer, size_t length, USER * user)
222 {
223 if (!strncmp(buffer + 4 + sizeof(HDR_8), "ERR", 3))
224     {
225     return ERR_Proc(buffer, user);
226     }
227
228 for (size_t i = 0; i < length / 8; i++)
229     Blowfish_Decrypt(user->GetCtx(),
230                      (uint32_t *)(buffer + i * 8),
231                      (uint32_t *)(buffer + i * 8 + 4));
232
233 std::string packetName(buffer + 12);
234
235 std::map<std::string, PacketProcessor>::const_iterator it;
236 it = processors.find(packetName);
237 if (it != processors.end())
238     return (this->*it->second)(buffer, user);
239
240 printfd(__FILE__, "PROTO::HandlePacket() - invalid packet signature: '%s'\n", packetName.c_str());
241
242 return false;
243 }
244
245 bool PROTO::CONN_SYN_ACK_Proc(const void * buffer, USER * user)
246 {
247 const CONN_SYN_ACK_8 * packet = static_cast<const CONN_SYN_ACK_8 *>(buffer);
248
249 uint32_t rnd = packet->rnd;
250 uint32_t userTimeout = packet->userTimeOut;
251 uint32_t aliveTimeout = packet->aliveDelay;
252
253 #ifdef ARCH_BE
254 SwapBytes(rnd);
255 SwapBytes(userTimeout);
256 SwapBytes(aliveDelay);
257 #endif
258
259 if (user->GetPhase() != 2)
260     {
261     errorStr = "Unexpected CONN_SYN_ACK";
262     printfd(__FILE__, "PROTO::CONN_SYN_ACK_Proc() - wrong phase: %d\n", user->GetPhase());
263     }
264
265 user->SetPhase(3);
266 user->SetAliveTimeout(aliveTimeout);
267 user->SetUserTimeout(userTimeout);
268 user->SetRnd(rnd);
269
270 Send_CONN_ACK(user);
271
272 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());
273
274 return true;
275 }
276
277 bool PROTO::ALIVE_SYN_Proc(const void * buffer, USER * user)
278 {
279 const ALIVE_SYN_8 * packet = static_cast<const ALIVE_SYN_8 *>(buffer);
280
281 uint32_t rnd = packet->rnd;
282
283 #ifdef ARCH_BE
284 SwapBytes(rnd);
285 #endif
286
287 if (user->GetPhase() != 3)
288     {
289     errorStr = "Unexpected ALIVE_SYN";
290     printfd(__FILE__, "PROTO::ALIVE_SYN_Proc() - wrong phase: %d\n", user->GetPhase());
291     }
292
293 user->SetPhase(3);
294 user->SetRnd(rnd); // Set new rnd value for ALIVE_ACK
295
296 Send_ALIVE_ACK(user);
297
298 return true;
299 }
300
301 bool PROTO::DISCONN_SYN_ACK_Proc(const void * buffer, USER * user)
302 {
303 const DISCONN_SYN_ACK_8 * packet = static_cast<const DISCONN_SYN_ACK_8 *>(buffer);
304
305 uint32_t rnd = packet->rnd;
306
307 #ifdef ARCH_BE
308 SwapBytes(rnd);
309 #endif
310
311 if (user->GetPhase() != 4)
312     {
313     errorStr = "Unexpected DISCONN_SYN_ACK";
314     printfd(__FILE__, "PROTO::DISCONN_SYN_ACK_Proc() - wrong phase: %d\n", user->GetPhase());
315     }
316
317 if (user->GetRnd() + 1 != rnd)
318     {
319     errorStr = "Wrong control value at DISCONN_SYN_ACK";
320     printfd(__FILE__, "PROTO::DISCONN_SYN_ACK_Proc() - wrong control value: %d, expected: %d\n", rnd, user->GetRnd() + 1);
321     }
322
323 user->SetPhase(5);
324 user->SetRnd(rnd);
325
326 Send_DISCONN_ACK(user);
327
328 return true;
329 }
330
331 bool PROTO::FIN_Proc(const void * buffer, USER * user)
332 {
333 if (user->GetPhase() != 5)
334     {
335     errorStr = "Unexpected FIN";
336     printfd(__FILE__, "PROTO::FIN_Proc() - wrong phase: %d\n", user->GetPhase());
337     }
338
339 user->SetPhase(1);
340
341 return true;
342 }
343
344 bool PROTO::INFO_Proc(const void * buffer, USER * user)
345 {
346 //const INFO_8 * packet = static_cast<const INFO_8 *>(buffer);
347
348 return true;
349 }
350
351 bool PROTO::ERR_Proc(const void * buffer, USER * user)
352 {
353 const ERR_8 * packet = static_cast<const ERR_8 *>(buffer);
354 const char * ptr = static_cast<const char *>(buffer);
355
356 //uint32_t len = packet->len;
357
358 #ifdef ARCH_BE
359 //SwapBytes(len);
360 #endif
361
362 user->SetPhase(1); //TODO: Check
363 /*KOIToWin((const char*)err.text, &messageText);
364 if (pErrorCb != NULL)
365     pErrorCb(messageText, IA_SERVER_ERROR, errorCbData);
366 phaseTime = GetTickCount();
367 codeError = IA_SERVER_ERROR;*/
368
369 return true;
370 }
371
372 bool PROTO::Send_CONN_SYN(USER * user)
373 {
374 CONN_SYN_8 packet;
375
376 packet.len = sizeof(packet);
377
378 #ifdef ARCH_BE
379 SwapBytes(packet.len);
380 #endif
381
382 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
383 strncpy((char *)packet.type, "CONN_SYN", sizeof(packet.type));
384 strncpy((char *)packet.login, user->GetLogin().c_str(), sizeof(packet.login));
385 packet.dirs = 0xFFffFFff;
386
387 return SendPacket(&packet, sizeof(packet), user);
388 }
389
390 bool PROTO::Send_CONN_ACK(USER * user)
391 {
392 CONN_ACK_8 packet;
393
394 packet.len = sizeof(packet);
395 packet.rnd = user->IncRnd();
396
397 #ifdef ARCH_BE
398 SwapBytes(packet.len);
399 SwapBytes(packet.rnd);
400 #endif
401
402 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
403 strncpy((char *)packet.type, "CONN_ACK", sizeof(packet.type));
404
405 return SendPacket(&packet, sizeof(packet), user);
406 }
407
408 bool PROTO::Send_ALIVE_ACK(USER * user)
409 {
410 ALIVE_ACK_8 packet;
411
412 packet.len = sizeof(packet);
413 packet.rnd = user->IncRnd();
414
415 #ifdef ARCH_BE
416 SwapBytes(packet.len);
417 SwapBytes(packet.rnd);
418 #endif
419
420 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
421 strncpy((char *)packet.type, "ALIVE_ACK", sizeof(packet.type));
422
423 return SendPacket(&packet, sizeof(packet), user);
424 }
425
426 bool PROTO::Send_DISCONN_SYN(USER * user)
427 {
428 DISCONN_SYN_8 packet;
429
430 packet.len = sizeof(packet);
431
432 #ifdef ARCH_BE
433 SwapBytes(packet.len);
434 #endif
435
436 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
437 strncpy((char *)packet.type, "DISCONN_SYN", sizeof(packet.type));
438 strncpy((char *)packet.login, user->GetLogin().c_str(), sizeof(packet.login));
439
440 return SendPacket(&packet, sizeof(packet), user);
441 }
442
443 bool PROTO::Send_DISCONN_ACK(USER * user)
444 {
445 DISCONN_ACK_8 packet;
446
447 packet.len = sizeof(packet);
448 packet.rnd = user->IncRnd();
449
450 #ifdef ARCH_BE
451 SwapBytes(packet.len);
452 SwapBytes(packet.rnd);
453 #endif
454
455 strncpy((char *)packet.loginS, user->GetLogin().c_str(), sizeof(packet.loginS));
456 strncpy((char *)packet.type, "DISCONN_ACK", sizeof(packet.type));
457
458 return SendPacket(&packet, sizeof(packet), user);
459 }
460
461 bool PROTO::SendPacket(const void * packet, size_t length, USER * user)
462 {
463 HDR_8 hdr;
464
465 assert(length < 2048 && "Packet length must not exceed 2048 bytes");
466
467 strncpy((char *)hdr.magic, IA_ID, sizeof(hdr.magic));
468 hdr.protoVer[0] = 0;
469 hdr.protoVer[1] = 8; // IA_PROTO_VER
470
471 unsigned char buffer[2048];
472 memset(buffer, 0, sizeof(buffer));
473 memcpy(buffer, packet, length);
474 memcpy(buffer, &hdr, sizeof(hdr));
475
476 size_t offset = sizeof(HDR_8);
477 for (size_t i = 0; i < IA_LOGIN_LEN / 8; i++)
478     {
479     Blowfish_Encrypt(&ctx,
480                      (uint32_t *)(buffer + offset + i * 8),
481                      (uint32_t *)(buffer + offset + i * 8 + 4));
482     }
483
484 offset += IA_LOGIN_LEN;
485 size_t encLen = (length - IA_LOGIN_LEN) / 8;
486 for (size_t i = 0; i < encLen; i++)
487     {
488     Blowfish_Encrypt(user->GetCtx(),
489                      (uint32_t*)(buffer + offset + i * 8),
490                      (uint32_t*)(buffer + offset + i * 8 + 4));
491     }
492
493 int res = sendto(user->GetSocket(), buffer, length, 0, (struct sockaddr *)&serverAddr, sizeof(serverAddr));
494
495 if (res < 0)
496     {
497     errorStr = "Failed to send packet: '";
498     errorStr += strerror(errno);
499     errorStr += "'";
500     printfd(__FILE__, "PROTO::SendPacket() - %s, fd: %d\n", errorStr.c_str(), user->GetSocket());
501     return false;
502     }
503
504 if (res < length)
505     {
506     errorStr = "Packet sent partially";
507     printfd(__FILE__, "PROTO::SendPacket() - %s\n", errorStr.c_str());
508     return false;
509     }
510
511 return true;
512 }
513
514 bool PROTO::RealConnect(USER * user)
515 {
516 if (user->GetPhase() != 1 &&
517     user->GetPhase() != 5)
518     {
519     errorStr = "Unexpected connect";
520     printfd(__FILE__, "PROTO::RealConnect() - wrong phase: %d\n", user->GetPhase());
521     }
522 user->SetPhase(2);
523
524 return Send_CONN_SYN(user);
525 }
526
527 bool PROTO::RealDisconnect(USER * user)
528 {
529 if (user->GetPhase() != 3)
530     {
531     errorStr = "Unexpected disconnect";
532     printfd(__FILE__, "PROTO::RealDisconnect() - wrong phase: %d\n", user->GetPhase());
533     }
534 user->SetPhase(4);
535
536 return Send_DISCONN_SYN(user);
537 }