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

Revision 78, 17.8 kB (checked in by yumileroy, 17 years ago)

[svn] * fixed help for subcommands - source mangos
* Renamed accounts column tbc to expansion and it only took a little over 4 hours o.O

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