root/trunk/src/game/WorldSession.cpp @ 34

Revision 34, 18.1 kB (checked in by yumileroy, 17 years ago)

[svn] * Removing useless data accidentally committed.
* Applying ImpConfig? patch.
* Note: QUEUE_FOR_GM currently disabled as it's not compatible with the ACE patch. Anyone care to rewrite it?
* Note2: This is untested - I may have done some mistakes here and there. Will try to compile now.

Original author: XTZGZoReX
Date: 2008-10-10 13:37:21-05:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17 */
18
19/** \file
20    \ingroup u2w
21*/
22
23#include "WorldSocket.h"
24#include "Common.h"
25#include "Database/DatabaseEnv.h"
26#include "Log.h"
27#include "Opcodes.h"
28#include "WorldSocket.h"
29#include "WorldPacket.h"
30#include "WorldSession.h"
31#include "Player.h"
32#include "ObjectMgr.h"
33#include "Group.h"
34#include "Guild.h"
35#include "World.h"
36#include "MapManager.h"
37#include "ObjectAccessor.h"
38#include "BattleGroundMgr.h"
39#include "Language.h"                                       // for CMSG_CANCEL_MOUNT_AURA handler
40#include "Chat.h"
41#include "SocialMgr.h"
42
43/// WorldSession constructor
44WorldSession::WorldSession(uint32 id, WorldSocket *sock, uint32 sec, bool tbc, time_t mute_time, LocaleConstant locale) :
45LookingForGroup_auto_join(false), LookingForGroup_auto_add(false), m_muteTime(mute_time),
46_player(NULL), m_Socket(sock),_security(sec), _accountId(id), m_isTBC(tbc),
47m_sessionDbcLocale(sWorld.GetAvailableDbcLocale(locale)), m_sessionDbLocaleIndex(objmgr.GetIndexForLocale(locale)),
48_logoutTime(0), m_playerLoading(false), m_playerLogout(false), m_playerRecentlyLogout(false), m_latency(0)
49{
50   if (sock)
51     {
52       m_Address = sock->GetRemoteAddress ();
53       sock->AddReference ();
54     }
55}
56
57/// WorldSession destructor
58WorldSession::~WorldSession()
59{
60    ///- unload player if not unloaded
61    if(_player)
62        LogoutPlayer(true);
63
64    /// - If have unclosed socket, close it
65  if (m_Socket)
66    {
67      m_Socket->CloseSocket ();   
68      m_Socket->RemoveReference ();
69      m_Socket = NULL;
70    }
71
72    ///- empty incoming packet queue
73    while(!_recvQueue.empty())
74    {
75        WorldPacket *packet = _recvQueue.next();
76        delete packet;
77    }
78   
79    sWorld.RemoveQueuedPlayer(this);
80}
81
82void WorldSession::SizeError(WorldPacket const& packet, uint32 size) const
83{
84    sLog.outError("Client (account %u) send packet %s (%u) with size %u but expected %u (attempt crash server?), skipped",
85        GetAccountId(),LookupOpcodeName(packet.GetOpcode()),packet.GetOpcode(),packet.size(),size);
86}
87
88/// Get the player name
89char const* WorldSession::GetPlayerName() const
90{
91    return GetPlayer() ? GetPlayer()->GetName() : "<none>";
92}
93
94/// Send a packet to the client
95void WorldSession::SendPacket(WorldPacket const* packet)
96{
97    if (!m_Socket)
98        return;
99    #ifdef MANGOS_DEBUG
100    // Code for network use statistic
101    static uint64 sendPacketCount = 0;
102    static uint64 sendPacketBytes = 0;
103
104    static time_t firstTime = time(NULL);
105    static time_t lastTime = firstTime;                     // next 60 secs start time
106
107    static uint64 sendLastPacketCount = 0;
108    static uint64 sendLastPacketBytes = 0;
109
110    time_t cur_time = time(NULL);
111
112    if((cur_time - lastTime) < 60)
113    {
114        sendPacketCount+=1;
115        sendPacketBytes+=packet->size();
116
117        sendLastPacketCount+=1;
118        sendLastPacketBytes+=packet->size();
119    }
120    else
121    {
122        uint64 minTime = uint64(cur_time - lastTime);
123        uint64 fullTime = uint64(lastTime - firstTime);
124        sLog.outDetail("Send all time packets count: " I64FMTD " bytes: " I64FMTD " avr.count/sec: %f avr.bytes/sec: %f time: %u",sendPacketCount,sendPacketBytes,float(sendPacketCount)/fullTime,float(sendPacketBytes)/fullTime,uint32(fullTime));
125        sLog.outDetail("Send last min packets count: " I64FMTD " bytes: " I64FMTD " avr.count/sec: %f avr.bytes/sec: %f",sendLastPacketCount,sendLastPacketBytes,float(sendLastPacketCount)/minTime,float(sendLastPacketBytes)/minTime);
126
127        lastTime = cur_time;
128        sendLastPacketCount = 1;
129        sendLastPacketBytes = packet->wpos();               // wpos is real written size
130    }
131#endif                                                  // !MANGOS_DEBUG
132
133  if (m_Socket->SendPacket (*packet) == -1)
134    {
135      m_Socket->CloseSocket ();
136    }
137}
138
139/// Add an incoming packet to the queue
140void WorldSession::QueuePacket(WorldPacket* new_packet)
141{
142    _recvQueue.add(new_packet);
143}
144
145/// Logging helper for unexpected opcodes
146void WorldSession::logUnexpectedOpcode(WorldPacket* packet, const char *reason)
147{
148    sLog.outError( "SESSION: received unexpected opcode %s (0x%.4X) %s",
149        LookupOpcodeName(packet->GetOpcode()),
150        packet->GetOpcode(),
151        reason);
152}
153
154/// Update the WorldSession (triggered by World update)
155bool WorldSession::Update(uint32 /*diff*/)
156{
157  if (m_Socket)
158    if (m_Socket->IsClosed ())
159      { 
160        m_Socket->RemoveReference ();
161        m_Socket = NULL;
162      }
163 
164    WorldPacket *packet;
165
166    ///- Retrieve packets from the receive queue and call the appropriate handlers
167    /// \todo Is there a way to consolidate the OpcondeHandlerTable and the g_worldOpcodeNames to only maintain 1 list?
168    /// answer : there is a way, but this is better, because it would use redundant RAM
169    while (!_recvQueue.empty())
170    {
171        packet = _recvQueue.next();
172
173        /*#if 1
174        sLog.outError( "MOEP: %s (0x%.4X)",
175                        LookupOpcodeName(packet->GetOpcode()),
176                        packet->GetOpcode());
177        #endif*/
178
179        if(packet->GetOpcode() >= NUM_MSG_TYPES)
180        {
181            sLog.outError( "SESSION: received non-existed opcode %s (0x%.4X)",
182                LookupOpcodeName(packet->GetOpcode()),
183                packet->GetOpcode());
184        }
185        else
186        {
187            OpcodeHandler& opHandle = opcodeTable[packet->GetOpcode()];
188            switch (opHandle.status)
189            {
190                case STATUS_LOGGEDIN:
191                    if(!_player)
192                    {
193                        // skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
194                        if(!m_playerRecentlyLogout)
195                            logUnexpectedOpcode(packet, "the player has not logged in yet");
196                    }
197                    else if(_player->IsInWorld())
198                        (this->*opHandle.handler)(*packet);
199                    // lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
200                    break;
201                case STATUS_TRANSFER_PENDING:
202                    if(!_player)
203                        logUnexpectedOpcode(packet, "the player has not logged in yet");
204                    else if(_player->IsInWorld())
205                        logUnexpectedOpcode(packet, "the player is still in world");
206                    else
207                        (this->*opHandle.handler)(*packet);
208                    break;
209                case STATUS_AUTHED:
210                    m_playerRecentlyLogout = false;
211                    (this->*opHandle.handler)(*packet);
212                    break;
213                case STATUS_NEVER:
214                    sLog.outError( "SESSION: received not allowed opcode %s (0x%.4X)",
215                        LookupOpcodeName(packet->GetOpcode()),
216                        packet->GetOpcode());
217                    break;
218            }
219        }
220
221        delete packet;
222    }
223
224    ///- If necessary, log the player out
225    time_t currTime = time(NULL);
226    if (!m_Socket || (ShouldLogOut(currTime) && !m_playerLoading))
227        LogoutPlayer(true);
228
229    if (!m_Socket)
230        return false;                                       //Will remove this session from the world session map
231
232    return true;
233}
234
235/// %Log the player out
236void WorldSession::LogoutPlayer(bool Save)
237{
238    // finish pending transfers before starting the logout
239    while(_player && _player->IsBeingTeleported())
240        HandleMoveWorldportAckOpcode();
241
242    m_playerLogout = true;
243
244    if (_player)
245    {
246        ///- If the player just died before logging out, make him appear as a ghost
247        //FIXME: logout must be delayed in case lost connection with client in time of combat
248        if (_player->GetDeathTimer())
249        {
250            _player->getHostilRefManager().deleteReferences();
251            _player->BuildPlayerRepop();
252            _player->RepopAtGraveyard();
253        }
254        else if (!_player->getAttackers().empty())
255        {
256            _player->CombatStop();
257            _player->getHostilRefManager().setOnlineOfflineState(false);
258            _player->RemoveAllAurasOnDeath();
259
260            // build set of player who attack _player or who have pet attacking of _player
261            std::set<Player*> aset;
262            for(Unit::AttackerSet::const_iterator itr = _player->getAttackers().begin(); itr != _player->getAttackers().end(); ++itr)
263            {
264                Unit* owner = (*itr)->GetOwner();           // including player controlled case
265                if(owner)
266                {
267                    if(owner->GetTypeId()==TYPEID_PLAYER)
268                        aset.insert((Player*)owner);
269                }
270                else
271                if((*itr)->GetTypeId()==TYPEID_PLAYER)
272                    aset.insert((Player*)(*itr));
273            }
274
275            _player->SetPvPDeath(!aset.empty());
276            _player->KillPlayer();
277            _player->BuildPlayerRepop();
278            _player->RepopAtGraveyard();
279
280            // give honor to all attackers from set like group case
281            for(std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr)
282                (*itr)->RewardHonor(_player, aset.size(), -1, true);
283
284            // give bg rewards and update counters like kill by first from attackers
285            // this can't be called for all attackers.
286            if(!aset.empty())
287                if(BattleGround *bg = _player->GetBattleGround())
288                    bg->HandleKillPlayer(_player,*aset.begin());
289        }
290        else if(_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
291        {
292            // this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
293            _player->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
294            //_player->SetDeathPvP(*); set at SPELL_AURA_SPIRIT_OF_REDEMPTION apply time
295            _player->KillPlayer();
296            _player->BuildPlayerRepop();
297            _player->RepopAtGraveyard();
298        }
299
300        ///- Remove player from battleground (teleport to entrance)
301        if(_player->InBattleGround())
302            _player->LeaveBattleground();
303
304        for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; i++)
305        {
306            if(int32 bgTypeId = _player->GetBattleGroundQueueId(i))
307            {
308                _player->RemoveBattleGroundQueueId(bgTypeId);
309                sBattleGroundMgr.m_BattleGroundQueues[ bgTypeId ].RemovePlayer(_player->GetGUID(), true);
310            }
311        }
312
313        ///- Reset the online field in the account table
314        // no point resetting online in character table here as Player::SaveToDB() will set it to 1 since player has not been removed from world at this stage
315        //No SQL injection as AccountID is uint32
316        loginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = '%u'", GetAccountId());
317
318        ///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
319        Guild *guild = objmgr.GetGuildById(_player->GetGuildId());
320        if(guild)
321        {
322            guild->LoadPlayerStatsByGuid(_player->GetGUID());
323            guild->UpdateLogoutTime(_player->GetGUID());
324
325            WorldPacket data(SMSG_GUILD_EVENT, (1+1+12+8)); // name limited to 12 in character table.
326            data<<(uint8)GE_SIGNED_OFF;
327            data<<(uint8)1;
328            data<<_player->GetName();
329            data<<_player->GetGUID();
330            guild->BroadcastPacket(&data);
331        }
332
333        ///- Remove pet
334        _player->RemovePet(NULL,PET_SAVE_AS_CURRENT, true);
335
336        ///- empty buyback items and save the player in the database
337        // some save parts only correctly work in case player present in map/player_lists (pets, etc)
338        if(Save)
339        {
340            uint32 eslot;
341            for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
342            {
343                eslot = j - BUYBACK_SLOT_START;
344                _player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+eslot*2,0);
345                _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+eslot,0);
346                _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+eslot,0);
347            }
348            _player->SaveToDB();
349        }
350
351        ///- Leave all channels before player delete...
352        _player->CleanupChannels();
353
354        ///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
355        _player->UninviteFromGroup();
356
357        // remove player from the group if he is:
358        // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
359        if(_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
360            _player->RemoveFromGroup();
361
362        ///- Remove the player from the world
363        // the player may not be in the world when logging out
364        // e.g if he got disconnected during a transfer to another map
365        // calls to GetMap in this case may cause crashes
366        if(_player->IsInWorld()) MapManager::Instance().GetMap(_player->GetMapId(), _player)->Remove(_player, false);
367        // RemoveFromWorld does cleanup that requires the player to be in the accessor
368        ObjectAccessor::Instance().RemoveObject(_player);
369
370        ///- Send update to group
371        if(_player->GetGroup())
372            _player->GetGroup()->SendUpdate();
373
374        ///- Broadcast a logout message to the player's friends
375        sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUIDLow(), "", true);
376
377        ///- Delete the player object
378        _player->CleanupsBeforeDelete();                    // do some cleanup before deleting to prevent crash at crossreferences to already deleted data
379
380        delete _player;
381        _player = NULL;
382
383        ///- Send the 'logout complete' packet to the client
384        WorldPacket data( SMSG_LOGOUT_COMPLETE, 0 );
385        SendPacket( &data );
386
387        ///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
388        //No SQL injection as AccountId is uint32
389        CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'", GetAccountId());
390        sLog.outDebug( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
391    }
392
393    m_playerLogout = false;
394    m_playerRecentlyLogout = true;
395    LogoutRequest(0);
396}
397
398/// Kick a player out of the World
399void WorldSession::KickPlayer()
400{
401  if (m_Socket)
402    {
403      m_Socket->CloseSocket ();
404    }
405}
406
407/// Cancel channeling handler
408
409void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
410{
411    va_list ap;
412    char szStr [1024];
413    szStr[0] = '\0';
414
415    va_start(ap, Text);
416    vsnprintf( szStr, 1024, Text, ap );
417    va_end(ap);
418
419    uint32 length = strlen(szStr)+1;
420    WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4+length);
421    data << length;
422    data << szStr;
423    SendPacket(&data);
424}
425
426void WorldSession::SendNotification(const char *format,...)
427{
428    if(format)
429    {
430        va_list ap;
431        char szStr [1024];
432        szStr[0] = '\0';
433        va_start(ap, format);
434        vsnprintf( szStr, 1024, format, ap );
435        va_end(ap);
436
437        WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
438        data << szStr;
439        SendPacket(&data);
440    }
441}
442
443void WorldSession::SendNotification(int32 string_id,...)
444{
445    char const* format = GetMangosString(string_id);
446    if(format)
447    {
448        va_list ap;
449        char szStr [1024];
450        szStr[0] = '\0';
451        va_start(ap, format);
452        vsnprintf( szStr, 1024, format, ap );
453        va_end(ap);
454
455        WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
456        data << szStr;
457        SendPacket(&data);
458    }
459}
460
461const char * WorldSession::GetMangosString( int32 entry )
462{
463    return objmgr.GetMangosString(entry,GetSessionDbLocaleIndex());
464}
465
466void WorldSession::Handle_NULL( WorldPacket& recvPacket )
467{
468    sLog.outError( "SESSION: received unhandled opcode %s (0x%.4X)",
469        LookupOpcodeName(recvPacket.GetOpcode()),
470        recvPacket.GetOpcode());
471}
472
473void WorldSession::Handle_EarlyProccess( WorldPacket& recvPacket )
474{
475    sLog.outError( "SESSION: received opcode %s (0x%.4X) that must be proccessed in WorldSocket::OnRead",
476        LookupOpcodeName(recvPacket.GetOpcode()),
477        recvPacket.GetOpcode());
478}
479
480void WorldSession::Handle_ServerSide( WorldPacket& recvPacket )
481{
482    sLog.outError( "SESSION: received sever-side opcode %s (0x%.4X)",
483        LookupOpcodeName(recvPacket.GetOpcode()),
484        recvPacket.GetOpcode());
485}
486
487void WorldSession::Handle_Depricated( WorldPacket& recvPacket )
488{
489    sLog.outError( "SESSION: received depricated opcode %s (0x%.4X)",
490        LookupOpcodeName(recvPacket.GetOpcode()),
491        recvPacket.GetOpcode());
492}
493
494void WorldSession::SendAuthWaitQue(uint32 position)
495 {
496     if(position == 0)
497     {
498         WorldPacket packet( SMSG_AUTH_RESPONSE, 1 );
499         packet << uint8( AUTH_OK );
500         SendPacket(&packet);
501     }
502     else
503     {
504         WorldPacket packet( SMSG_AUTH_RESPONSE, 5 );
505         packet << uint8( AUTH_WAIT_QUEUE );
506         packet << uint32 (position);
507         SendPacket(&packet);
508     }
509 }
510 
511
Note: See TracBrowser for help on using the browser.