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

Revision 2, 16.6 kB (checked in by yumileroy, 17 years ago)

[svn] * Proper SVN structure

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