root/trunk/src/game/WorldSocket.cpp @ 44

Revision 44, 25.7 kB (checked in by yumileroy, 17 years ago)

[svn] * Merge Temp dev SVN with Assembla.
* Changes include:

  • Implementation of w12x's Outdoor PvP and Game Event Systems.
  • Temporary removal of IRC Chat Bot (until infinite loop when disabled is fixed).
  • All mangos -> trinity (to convert your mangos_string table, please run mangos_string_to_trinity_string.sql).
  • Improved Config cleanup.
  • And many more changes.

Original author: Seline
Date: 2008-10-14 11:57:03-05:00

Line 
1/*
2 * Copyright (C) 2008 Trinity <http://www.trinitycore.org/>
3 *
4 * Thanks to the original authors: MaNGOS <http://www.mangosproject.org/>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21#include "Common.h"
22#include "WorldSocket.h"
23
24#include <ace/Message_Block.h>
25#include <ace/OS_NS_string.h>
26#include <ace/OS_NS_unistd.h>
27#include <ace/os_include/arpa/os_inet.h>
28#include <ace/os_include/netinet/os_tcp.h>
29#include <ace/os_include/sys/os_types.h>
30#include <ace/os_include/sys/os_socket.h>
31#include <ace/OS_NS_string.h>
32#include <ace/Reactor.h>
33#include <ace/Auto_Ptr.h>
34
35#include "Util.h"
36#include "World.h"
37#include "WorldPacket.h"
38#include "SharedDefines.h"
39#include "ByteBuffer.h"
40#include "AddonHandler.h"
41#include "Opcodes.h"
42#include "Database/DatabaseEnv.h"
43#include "Auth/Sha1.h"
44#include "WorldSession.h"
45#include "WorldSocketMgr.h"
46#include "Log.h"
47#include "WorldLog.h"
48
49#if defined( __GNUC__ )
50#pragma pack(1)
51#else
52#pragma pack(push,1)
53#endif
54
55struct ServerPktHeader
56{
57  ACE_UINT16 size;
58  ACE_UINT16 cmd;
59};
60
61struct ClientPktHeader
62{
63  ACE_UINT16 size;
64  ACE_UINT32 cmd;
65};
66
67#if defined( __GNUC__ )
68#pragma pack()
69#else
70#pragma pack(pop)
71#endif
72
73WorldSocket::WorldSocket (void) :
74WorldHandler (),
75m_Session (0),
76m_RecvWPct (0),
77m_RecvPct (),
78m_Header (sizeof (ClientPktHeader)),
79m_OutBuffer (0),
80m_OutBufferSize (65536),
81m_OutActive (false),
82m_Seed (static_cast<uint32> (rand32 ())),
83m_OverSpeedPings (0),
84m_LastPingTime (ACE_Time_Value::zero)
85{
86  this->reference_counting_policy ().value (ACE_Event_Handler::Reference_Counting_Policy::ENABLED);
87}
88
89WorldSocket::~WorldSocket (void)
90{
91  if (m_RecvWPct)
92    delete m_RecvWPct;
93
94  if (m_OutBuffer)
95    m_OutBuffer->release ();
96
97  this->closing_ = true;
98
99  this->peer ().close ();
100
101  WorldPacket* pct;
102  while (m_PacketQueue.dequeue_head (pct) == 0)
103    delete pct;
104}
105
106bool
107WorldSocket::IsClosed (void) const
108{
109  return this->closing_;
110}
111
112void
113WorldSocket::CloseSocket (void)
114{
115  {
116    ACE_GUARD (LockType, Guard, m_OutBufferLock);
117
118    if (this->closing_)
119      return;
120
121    this->closing_ = true;
122
123    this->peer ().close_writer ();
124  }
125
126  {
127    ACE_GUARD (LockType, Guard, m_SessionLock);
128
129    m_Session = NULL;
130  }
131
132}
133
134const std::string&
135WorldSocket::GetRemoteAddress (void) const
136{
137  return m_Address;
138}
139
140int
141WorldSocket::SendPacket (const WorldPacket& pct)
142{
143  ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
144
145  if (this->closing_)
146    return -1;
147
148  // Dump outgoing packet.
149  if (sWorldLog.LogWorld ())
150    {
151      sWorldLog.Log ("SERVER:\nSOCKET: %u\nLENGTH: %u\nOPCODE: %s (0x%.4X)\nDATA:\n",
152                     (uint32) get_handle (),
153                     pct.size (),
154                     LookupOpcodeName (pct.GetOpcode ()),
155                     pct.GetOpcode ());
156
157      uint32 p = 0;
158      while (p < pct.size ())
159        {
160          for (uint32 j = 0; j < 16 && p < pct.size (); j++)
161            sWorldLog.Log ("%.2X ", const_cast<WorldPacket&> (pct)[p++]);
162
163          sWorldLog.Log ("\n");
164        }
165
166      sWorldLog.Log ("\n\n");
167    }
168
169  if (iSendPacket (pct) == -1)
170    {
171      WorldPacket* npct;
172
173      ACE_NEW_RETURN (npct, WorldPacket (pct), -1);
174
175      // NOTE maybe check of the size of the queue can be good ?
176      // to make it bounded instead of unbounded
177      if (m_PacketQueue.enqueue_tail (npct) == -1)
178        {
179          delete npct;
180          sLog.outError ("WorldSocket::SendPacket: m_PacketQueue.enqueue_tail failed");
181          return -1;
182        }
183    }
184
185  return 0;
186}
187
188long
189WorldSocket::AddReference (void)
190{
191  return static_cast<long> (this->add_reference ());
192}
193
194long
195WorldSocket::RemoveReference (void)
196{
197  return static_cast<long> (this->remove_reference ());
198}
199
200int
201WorldSocket::open (void *a)
202{
203  ACE_UNUSED_ARG (a);
204
205  // Prevent double call to this func.
206  if (m_OutBuffer)
207    return -1;
208
209  // This will also prevent the socket from being Updated
210  // while we are initializing it.
211  m_OutActive = true;
212
213  // Hook for the manager.
214  if (sWorldSocketMgr->OnSocketOpen (this) == -1)
215    return -1;
216
217  // Allocate the buffer.
218  ACE_NEW_RETURN (m_OutBuffer, ACE_Message_Block (m_OutBufferSize), -1);
219
220  // Store peer address.
221  ACE_INET_Addr remote_addr;
222
223  if (this->peer ().get_remote_addr (remote_addr) == -1)
224    {
225      sLog.outError ("WorldSocket::open: peer ().get_remote_addr errno = %s", ACE_OS::strerror (errno));
226      return -1;
227    }
228
229  m_Address = remote_addr.get_host_addr ();
230
231  // Send startup packet.
232  WorldPacket packet (SMSG_AUTH_CHALLENGE, 4);
233  packet << m_Seed;
234
235  if (SendPacket (packet) == -1)
236    return -1;
237
238  // Register with ACE Reactor
239  if (this->reactor ()->register_handler
240      (this,
241       ACE_Event_Handler::READ_MASK | ACE_Event_Handler::WRITE_MASK) == -1)
242    {
243      sLog.outError ("WorldSocket::open: unable to register client handler errno = %s", ACE_OS::strerror (errno));
244      return -1;
245    }
246
247  // reactor takes care of the socket from now on
248  this->remove_reference ();
249
250  return 0;
251}
252
253int
254WorldSocket::close (int)
255{
256  this->shutdown ();
257
258  this->closing_ = true;
259
260  this->remove_reference ();
261
262  return 0;
263}
264
265int
266WorldSocket::handle_input (ACE_HANDLE)
267{
268  if (this->closing_)
269    return -1;
270
271  switch (this->handle_input_missing_data ())
272    {
273    case -1 :
274      {
275        if ((errno == EWOULDBLOCK) ||
276            (errno == EAGAIN))
277          {
278            //return 0;
279            return this->Update (); // interesting line ,isnt it ?
280          }
281
282        DEBUG_LOG ("WorldSocket::handle_input: Peer error closing connection errno = %s", ACE_OS::strerror (errno));
283
284        return -1;
285      }
286    case 0:
287      {
288        DEBUG_LOG ("WorldSocket::handle_input: Peer has closed connection\n");
289
290        errno = ECONNRESET;
291
292        return -1;
293      }
294    case 1:
295      return 1;
296    }
297
298  //return 0;
299  return this->Update (); // another interesting line ;)
300}
301
302int
303WorldSocket::handle_output (ACE_HANDLE)
304{
305  ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
306
307  if (this->closing_)
308    return -1;
309
310  const size_t send_len = m_OutBuffer->length ();
311
312  if (send_len == 0)
313    return this->cancel_wakeup_output (Guard);
314
315  // TODO SO_NOSIGPIPE on platforms that support it
316#ifdef MSG_NOSIGNAL
317  ssize_t n = this->peer ().send (m_OutBuffer->rd_ptr (), send_len, MSG_NOSIGNAL);
318#else
319  ssize_t n = this->peer ().send (m_OutBuffer->rd_ptr (), send_len);
320#endif // MSG_NOSIGNAL
321
322  if (n == 0)
323    return -1;
324  else if (n == -1)
325    {
326      if (errno == EWOULDBLOCK || errno == EAGAIN)
327        return this->schedule_wakeup_output (Guard);
328
329      return -1;
330    }
331  else if (n < send_len) //now n > 0
332    {
333      m_OutBuffer->rd_ptr (static_cast<size_t> (n));
334
335      // move the data to the base of the buffer
336      m_OutBuffer->crunch ();
337
338      return this->schedule_wakeup_output (Guard);
339    }
340  else //now n == send_len
341    {
342      m_OutBuffer->reset ();
343
344      if (!iFlushPacketQueue ())
345        return this->cancel_wakeup_output (Guard);
346      else
347        return this->schedule_wakeup_output (Guard);
348    }
349
350  ACE_NOTREACHED (return 0);
351}
352
353int
354WorldSocket::handle_close (ACE_HANDLE h, ACE_Reactor_Mask)
355{
356  // Critical section
357  {
358    ACE_GUARD_RETURN (LockType, Guard, m_OutBufferLock, -1);
359
360    this->closing_ = true;
361
362    if (h == ACE_INVALID_HANDLE)
363      this->peer ().close_writer ();
364  }
365
366  // Critical section
367  {
368    ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
369
370    m_Session = NULL;
371  }
372
373  return 0;
374}
375
376int
377WorldSocket::Update (void)
378{
379  if (this->closing_)
380    return -1;
381
382  if (m_OutActive || m_OutBuffer->length () == 0)
383    return 0;
384
385  return this->handle_output (this->get_handle ());
386}
387
388int
389WorldSocket::handle_input_header (void)
390{
391  ACE_ASSERT (m_RecvWPct == NULL);
392
393  if (m_Header.length () != sizeof (ClientPktHeader))
394    {
395      sLog.outError ("WorldSocket::handle_input_header: internal error: invalid header");
396      errno = EINVAL;
397      return -1;
398    }
399
400  m_Crypt.DecryptRecv ((ACE_UINT8*) m_Header.rd_ptr (), sizeof (ClientPktHeader));
401
402  ClientPktHeader& header = *((ClientPktHeader*) m_Header.rd_ptr ());
403
404  header.size = ACE_NTOHS (header.size);
405
406#if ACE_BYTE_ORDER == ACE_BIG_ENDIAN
407  header.cmd = ACE_SWAP_LONG (header.cmd)
408#endif // ACE_BIG_ENDIAN
409
410  if ((header.size < 4) ||
411      (header.size > 10240) ||
412      (header.cmd <= 0) ||
413      (header.cmd > 10240)
414      )
415    {
416      sLog.outError ("WorldSocket::handle_input_header: client sent mailformed packet size = %d , cmd = %d",
417                     header.size,
418                     header.cmd);
419
420      errno = EINVAL;
421      return -1;
422    }
423
424  header.size -= 4;
425
426  ACE_NEW_RETURN (m_RecvWPct, WorldPacket ((uint16) header.cmd, header.size), -1);
427
428  if (header.size > 0)
429    {
430      m_RecvWPct->resize (header.size);
431      m_RecvPct.base ((char*) m_RecvWPct->contents (), m_RecvWPct->size ());
432    }
433  else
434    {
435      ACE_ASSERT (m_RecvPct.space () == 0);
436    }
437
438
439  return 0;
440}
441
442int
443WorldSocket::handle_input_payload (void)
444{
445  // set errno properly here on error !!!
446  // now have a header and payload
447
448  ACE_ASSERT (m_RecvPct.space () == 0);
449  ACE_ASSERT (m_Header.space () == 0);
450  ACE_ASSERT (m_RecvWPct != NULL);
451
452  const int ret = this->ProcessIncoming (m_RecvWPct);
453
454  m_RecvPct.base (NULL, 0);
455  m_RecvPct.reset ();
456  m_RecvWPct = NULL;
457
458  m_Header.reset ();
459
460  if (ret == -1)
461    errno = EINVAL;
462
463  return ret;
464}
465
466int
467WorldSocket::handle_input_missing_data (void)
468{
469  char buf [1024];
470
471  ACE_Data_Block db (sizeof (buf),
472                     ACE_Message_Block::MB_DATA,
473                     buf,
474                     0,
475                     0,
476                     ACE_Message_Block::DONT_DELETE,
477                     0);
478
479  ACE_Message_Block message_block (&db,
480                                   ACE_Message_Block::DONT_DELETE,
481                                   0);
482
483  const size_t recv_size = message_block.space ();
484
485  const ssize_t n = this->peer ().recv (message_block.wr_ptr (),
486                                        recv_size);
487
488  if (n <= 0)
489    return n;
490
491  message_block.wr_ptr (n);
492
493  while (message_block.length () > 0)
494    {
495      if (m_Header.space () > 0)
496        {
497          //need to recieve the header
498          const size_t to_header = (message_block.length () > m_Header.space () ? m_Header.space () : message_block.length ());
499          m_Header.copy (message_block.rd_ptr (), to_header);
500          message_block.rd_ptr (to_header);
501
502          if (m_Header.space () > 0)
503            {
504              //couldnt recieve the whole header this time
505              ACE_ASSERT (message_block.length () == 0);
506              errno = EWOULDBLOCK;
507              return -1;
508            }
509
510          //we just recieved nice new header
511          if (this->handle_input_header () == -1)
512            {
513              ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
514              return -1;
515            }
516        }
517
518      // Its possible on some error situations that this happens
519      // for example on closing when epoll recieves more chunked data and stuff
520      // hope this is not hack ,as proper m_RecvWPct is asserted around
521      if (!m_RecvWPct)
522        {
523          sLog.outError ("Forsing close on input m_RecvWPct = NULL");
524          errno = EINVAL;
525          return -1;
526        }
527
528      // We have full readed header, now check the data payload
529      if (m_RecvPct.space () > 0)
530        {
531          //need more data in the payload
532          const size_t to_data = (message_block.length () > m_RecvPct.space () ? m_RecvPct.space () : message_block.length ());
533          m_RecvPct.copy (message_block.rd_ptr (), to_data);
534          message_block.rd_ptr (to_data);
535
536          if (m_RecvPct.space () > 0)
537            {
538              //couldnt recieve the whole data this time
539              ACE_ASSERT (message_block.length () == 0);
540              errno = EWOULDBLOCK;
541              return -1;
542            }
543        }
544
545      //just recieved fresh new payload
546      if (this->handle_input_payload () == -1)
547        {
548          ACE_ASSERT ((errno != EWOULDBLOCK) && (errno != EAGAIN));
549          return -1;
550        }
551    }
552
553  return n == recv_size ? 1 : 2;
554}
555
556int
557WorldSocket::cancel_wakeup_output (GuardType& g)
558{
559  if (!m_OutActive)
560    return 0;
561
562  m_OutActive = false;
563
564  g.release ();
565
566  if (this->reactor ()->cancel_wakeup
567      (this, ACE_Event_Handler::WRITE_MASK) == -1)
568    {
569      // would be good to store errno from reactor with errno guard
570      sLog.outError ("WorldSocket::cancel_wakeup_output");
571      return -1;
572    }
573
574  return 0;
575}
576
577int
578WorldSocket::schedule_wakeup_output (GuardType& g)
579{
580  if (m_OutActive)
581    return 0;
582
583  m_OutActive = true;
584
585  g.release ();
586
587  if (this->reactor ()->schedule_wakeup
588      (this, ACE_Event_Handler::WRITE_MASK) == -1)
589    {
590      sLog.outError ("WorldSocket::schedule_wakeup_output");
591      return -1;
592    }
593
594  return 0;
595}
596
597int
598WorldSocket::ProcessIncoming (WorldPacket* new_pct)
599{
600  ACE_ASSERT (new_pct);
601
602  // manage memory ;)
603  ACE_Auto_Ptr<WorldPacket> aptr (new_pct);
604
605  const ACE_UINT16 opcode = new_pct->GetOpcode ();
606
607  if (this->closing_)
608    return -1;
609
610  // dump recieved packet
611  if (sWorldLog.LogWorld ())
612    {
613      sWorldLog.Log ("CLIENT:\nSOCKET: %u\nLENGTH: %u\nOPCODE: %s (0x%.4X)\nDATA:\n",
614                     (uint32) get_handle (),
615                     new_pct->size (),
616                     LookupOpcodeName (new_pct->GetOpcode ()),
617                     new_pct->GetOpcode ());
618
619      uint32 p = 0;
620      while (p < new_pct->size ())
621        {
622          for (uint32 j = 0; j < 16 && p < new_pct->size (); j++)
623            sWorldLog.Log ("%.2X ", (*new_pct)[p++]);
624          sWorldLog.Log ("\n");
625        }
626      sWorldLog.Log ("\n\n");
627    }
628
629  // like one switch ;)
630  if (opcode == CMSG_PING)
631    {
632      return HandlePing (*new_pct);
633    }
634  else if (opcode == CMSG_AUTH_SESSION)
635    {
636      if (m_Session)
637        {
638          sLog.outError ("WorldSocket::ProcessIncoming: Player send CMSG_AUTH_SESSION again");
639          return -1;
640        }
641
642      return HandleAuthSession (*new_pct);
643    }
644  else if (opcode == CMSG_KEEP_ALIVE)
645    {
646      DEBUG_LOG ("CMSG_KEEP_ALIVE ,size: %d", new_pct->size ());
647
648      return 0;
649    }
650  else
651    {
652      ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
653
654      if (m_Session != NULL)
655        {
656          // OK ,give the packet to WorldSession
657          aptr.release ();
658          // WARNINIG here we call it with locks held.
659          // Its possible to cause deadlock if QueuePacket calls back
660          m_Session->QueuePacket (new_pct);
661          return 0;
662        }
663      else
664        {
665          sLog.outError ("WorldSocket::ProcessIncoming: Client not authed opcode = ", opcode);
666          return -1;
667        }
668    }
669
670  ACE_NOTREACHED (return 0);
671}
672
673int
674WorldSocket::HandleAuthSession (WorldPacket& recvPacket)
675{
676  uint8 digest[20];
677  uint32 clientSeed;
678  uint32 unk2;
679  uint32 BuiltNumberClient;
680  uint32 id, security;
681  bool tbc = false;
682  LocaleConstant locale;
683  std::string account;
684  Sha1Hash sha1;
685  BigNumber v, s, g, N, x, I;
686  WorldPacket packet, SendAddonPacked;
687
688  BigNumber K;
689
690  if (recvPacket.size () < (4 + 4 + 1 + 4 + 20))
691    {
692      sLog.outError ("WorldSocket::HandleAuthSession: wrong packet size");
693      return -1;
694    }
695
696  // Read the content of the packet
697  recvPacket >> BuiltNumberClient; // for now no use
698  recvPacket >> unk2;
699  recvPacket >> account;
700
701  if (recvPacket.size () < (4 + 4 + (account.size () + 1) + 4 + 20))
702    {
703      sLog.outError ("WorldSocket::HandleAuthSession: wrong packet size second check");
704      return -1;
705    }
706
707  recvPacket >> clientSeed;
708  recvPacket.read (digest, 20);
709
710  DEBUG_LOG ("WorldSocket::HandleAuthSession: client %u, unk2 %u, account %s, clientseed %u",
711             BuiltNumberClient,
712             unk2,
713             account.c_str (),
714             clientSeed);
715
716  // Get the account information from the realmd database
717  std::string safe_account = account; // Duplicate, else will screw the SHA hash verification below
718  loginDatabase.escape_string (safe_account);
719  // No SQL injection, username escaped.
720
721  QueryResult *result =
722          loginDatabase.PQuery ("SELECT "
723                                "id, " //0
724                                "gmlevel, " //1
725                                "sessionkey, " //2
726                                "last_ip, " //3
727                                "locked, " //4
728                                "sha_pass_hash, " //5
729                                "v, " //6
730                                "s, " //7
731                                "tbc, " //8
732                                "mutetime, " //9
733                                "locale " //10
734                                "FROM account "
735                                "WHERE username = '%s'",
736                                safe_account.c_str ());
737
738  // Stop if the account is not found
739  if (!result)
740    {
741      packet.Initialize (SMSG_AUTH_RESPONSE, 1);
742      packet << uint8 (AUTH_UNKNOWN_ACCOUNT);
743
744      SendPacket (packet);
745
746      sLog.outError ("WorldSocket::HandleAuthSession: Sent Auth Response (unknown account).");
747      return -1;
748    }
749
750  Field* fields = result->Fetch ();
751
752  tbc = fields[8].GetUInt8 () && sWorld.getConfig (CONFIG_EXPANSION) > 0;
753
754  N.SetHexStr ("894B645E89E1535BBDAD5B8B290650530801B18EBFBF5E8FAB3C82872A3E9BB7");
755  g.SetDword (7);
756  I.SetHexStr (fields[5].GetString ());
757
758  //In case of leading zeros in the I hash, restore them
759  uint8 mDigest[SHA_DIGEST_LENGTH];
760  memset (mDigest, 0, SHA_DIGEST_LENGTH);
761
762  if (I.GetNumBytes () <= SHA_DIGEST_LENGTH)
763    memcpy (mDigest, I.AsByteArray (), I.GetNumBytes ());
764
765  std::reverse (mDigest, mDigest + SHA_DIGEST_LENGTH);
766
767  s.SetHexStr (fields[7].GetString ());
768  sha1.UpdateData (s.AsByteArray (), s.GetNumBytes ());
769  sha1.UpdateData (mDigest, SHA_DIGEST_LENGTH);
770  sha1.Finalize ();
771  x.SetBinary (sha1.GetDigest (), sha1.GetLength ());
772  v = g.ModExp (x, N);
773
774  const char* sStr = s.AsHexStr (); //Must be freed by OPENSSL_free()
775  const char* vStr = v.AsHexStr (); //Must be freed by OPENSSL_free()
776  const char* vold = fields[6].GetString ();
777
778  DEBUG_LOG ("WorldSocket::HandleAuthSession: "
779             "(s,v) check s: %s v_old: %s v_new: %s",
780             sStr,
781             vold,
782             vStr);
783
784  loginDatabase.PExecute ("UPDATE account "
785                          "SET "
786                          "v = '0', "
787                          "s = '0' "
788                          "WHERE username = '%s'",
789                          safe_account.c_str ());
790
791  if (!vold || strcmp (vStr, vold))
792    {
793      packet.Initialize (SMSG_AUTH_RESPONSE, 1);
794      packet << uint8 (AUTH_UNKNOWN_ACCOUNT);
795      SendPacket (packet);
796      delete result;
797      OPENSSL_free ((void*) sStr);
798      OPENSSL_free ((void*) vStr);
799
800      sLog.outBasic ("WorldSocket::HandleAuthSession: User not logged.");
801      return -1;
802    }
803
804  OPENSSL_free ((void*) sStr);
805  OPENSSL_free ((void*) vStr);
806
807  ///- Re-check ip locking (same check as in realmd).
808  if (fields[4].GetUInt8 () == 1) // if ip is locked
809    {
810      if (strcmp (fields[3].GetString (), GetRemoteAddress ().c_str ()))
811        {
812          packet.Initialize (SMSG_AUTH_RESPONSE, 1);
813          packet << uint8 (AUTH_FAILED);
814          SendPacket (packet);
815
816          delete result;
817          sLog.outBasic ("WorldSocket::HandleAuthSession: Sent Auth Response (Account IP differs).");
818          return -1;
819        }
820    }
821
822  id = fields[0].GetUInt32 ();
823  security = fields[1].GetUInt16 ();
824  K.SetHexStr (fields[2].GetString ());
825
826  time_t mutetime = time_t (fields[9].GetUInt64 ());
827
828  locale = LocaleConstant (fields[10].GetUInt8 ());
829  if (locale >= MAX_LOCALE)
830    locale = LOCALE_enUS;
831
832  delete result;
833
834  // Re-check account ban (same check as in realmd)
835  QueryResult *banresult =
836          loginDatabase.PQuery ("SELECT "
837                                "bandate, "
838                                "unbandate "
839                                "FROM account_banned "
840                                "WHERE id = '%u' "
841                                "AND active = 1",
842                                id);
843
844  if (banresult) // if account banned
845    {
846      packet.Initialize (SMSG_AUTH_RESPONSE, 1);
847      packet << uint8 (AUTH_BANNED);
848      SendPacket (packet);
849
850      delete banresult;
851
852      sLog.outBasic ("WorldSocket::HandleAuthSession: Sent Auth Response (Account banned).");
853      return -1;
854    }
855
856  // Check locked state for server
857  AccountTypes allowedAccountType = sWorld.GetPlayerSecurityLimit ();
858
859  if (allowedAccountType > SEC_PLAYER && security < allowedAccountType)
860    {
861      WorldPacket Packet (SMSG_AUTH_RESPONSE, 1);
862      Packet << uint8 (AUTH_UNAVAILABLE);
863
864      SendPacket (packet);
865
866      sLog.outBasic ("WorldSocket::HandleAuthSession: User tryes to login but his security level is not enough");
867      return -1;
868    }
869
870  // Check that Key and account name are the same on client and server
871  Sha1Hash sha;
872
873  uint32 t = 0;
874  uint32 seed = m_Seed;
875
876  sha.UpdateData (account);
877  sha.UpdateData ((uint8 *) & t, 4);
878  sha.UpdateData ((uint8 *) & clientSeed, 4);
879  sha.UpdateData ((uint8 *) & seed, 4);
880  sha.UpdateBigNumbers (&K, NULL);
881  sha.Finalize ();
882
883  if (memcmp (sha.GetDigest (), digest, 20))
884    {
885      packet.Initialize (SMSG_AUTH_RESPONSE, 1);
886      packet << uint8 (AUTH_FAILED);
887
888      SendPacket (packet);
889
890      sLog.outBasic ("WorldSocket::HandleAuthSession: Sent Auth Response (authentification failed).");
891      return -1;
892    }
893
894  std::string address = this->GetRemoteAddress ();
895
896  DEBUG_LOG ("WorldSocket::HandleAuthSession: Client '%s' authenticated successfully from %s.",
897             account.c_str (),
898             address.c_str ());
899
900  // Update the last_ip in the database
901  // No SQL injection, username escaped.
902  loginDatabase.escape_string (address);
903
904  loginDatabase.PExecute ("UPDATE account "
905                          "SET last_ip = '%s' "
906                          "WHERE username = '%s'",
907                          address.c_str (),
908                          safe_account.c_str ());
909
910  // TODO protect here probably ?
911  // Althought atm the socket is singlethreaded
912  ACE_NEW_RETURN (m_Session, WorldSession (id, this, security, tbc, mutetime, locale), -1);
913
914  m_Crypt.SetKey (&K);
915  m_Crypt.Init ();
916
917  // In case needed sometime the second arg is in microseconds 1 000 000 = 1 sec
918  ACE_OS::sleep (ACE_Time_Value (0, 10000));
919
920  // TODO error handling
921  sWorld.AddSession (this->m_Session);
922
923  // Create and send the Addon packet
924  if (sAddOnHandler.BuildAddonPacket (&recvPacket, &SendAddonPacked))
925    SendPacket (SendAddonPacked);
926
927  return 0;
928}
929
930int
931WorldSocket::HandlePing (WorldPacket& recvPacket)
932{
933  uint32 ping;
934  uint32 latency;
935
936  if (recvPacket.size () < 8)
937    {
938      sLog.outError ("WorldSocket::_HandlePing wrong packet size");
939      return -1;
940    }
941
942  // Get the ping packet content
943  recvPacket >> ping;
944  recvPacket >> latency;
945
946  if (m_LastPingTime == ACE_Time_Value::zero)
947    m_LastPingTime = ACE_OS::gettimeofday (); // for 1st ping
948  else
949    {
950      ACE_Time_Value cur_time = ACE_OS::gettimeofday ();
951      ACE_Time_Value diff_time (cur_time);
952      diff_time -= m_LastPingTime;
953      m_LastPingTime = cur_time;
954
955      if (diff_time < ACE_Time_Value (27))
956        {
957          ++m_OverSpeedPings;
958
959          uint32 max_count = sWorld.getConfig (CONFIG_MAX_OVERSPEED_PINGS);
960
961          if (max_count && m_OverSpeedPings > max_count)
962            {
963              ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
964
965              if (m_Session && m_Session->GetSecurity () == SEC_PLAYER)
966                {
967                  sLog.outError ("WorldSocket::HandlePing: Player kicked for "
968                                 "overspeeded pings adress = %s",
969                                 GetRemoteAddress ().c_str ());
970
971                  return -1;
972                }
973            }
974        }
975      else
976        m_OverSpeedPings = 0;
977    }
978
979  // critical section
980  {
981    ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
982
983    if (m_Session)
984      m_Session->SetLatency (latency);
985    else
986      {
987        sLog.outError ("WorldSocket::HandlePing: peer sent CMSG_PING, "
988                       "but is not authenticated or got recently kicked,"
989                       " adress = %s",
990                       this->GetRemoteAddress ().c_str ());
991        return -1;
992      }
993  }
994
995  WorldPacket packet (SMSG_PONG, 4);
996  packet << ping;
997  return this->SendPacket (packet);
998}
999
1000int
1001WorldSocket::iSendPacket (const WorldPacket& pct)
1002{
1003  if (m_OutBuffer->space () < pct.size () + sizeof (ServerPktHeader))
1004    {
1005      errno = ENOBUFS;
1006      return -1;
1007    }
1008
1009  ServerPktHeader header;
1010
1011  header.cmd = pct.GetOpcode ();
1012
1013#if ACE_BYTE_ORDER == ACE_BIG_ENDIAN
1014  header.cmd = ACE_SWAP_WORD (header.cmd)
1015#endif
1016
1017          header.size = (uint16) pct.size () + 2;
1018  header.size = ACE_HTONS (header.size);
1019
1020  m_Crypt.EncryptSend ((uint8*) & header, sizeof (header));
1021
1022  if (m_OutBuffer->copy ((char*) & header, sizeof (header)) == -1)
1023    ACE_ASSERT (false);
1024
1025  if (!pct.empty ())
1026    if (m_OutBuffer->copy ((char*) pct.contents (), pct.size ()) == -1)
1027      ACE_ASSERT (false);
1028
1029  return 0;
1030}
1031
1032bool
1033WorldSocket::iFlushPacketQueue ()
1034{
1035  WorldPacket *pct;
1036  bool haveone = false;
1037
1038  while (m_PacketQueue.dequeue_head (pct) == 0)
1039    {
1040      if (iSendPacket (*pct) == -1)
1041        {
1042          if (m_PacketQueue.enqueue_head (pct) == -1)
1043            {
1044              delete pct;
1045              sLog.outError ("WorldSocket::iFlushPacketQueue m_PacketQueue->enqueue_head");
1046              return false;
1047            }
1048
1049          break;
1050        }
1051      else
1052        {
1053          haveone = true;
1054          delete pct;
1055        }
1056    }
1057
1058  return haveone;
1059}
Note: See TracBrowser for help on using the browser.