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

Revision 149, 17.9 kB (checked in by yumileroy, 17 years ago)

[svn] *Implement new player conditions CONDITION_NO_AURA, CONDITION_ACTIVE_EVENT
* Default behaviour of pets for creatures changed to REACT_DEFENSIVE
* Disallowed sending wrapped items as COD
* Prevent loading and saving single target auras for pet in same way as already implemented for player
* Correctly limit use some flask types to zones.
* Fixed extracting common.MPQ under *nix
* Many small xleanups and fixes.
** mangos merge rev.

TEST REV so be careful of creepy crawly bugs!

Original author: KingPin?
Date: 2008-11-02 16:53:46-06:00

Line 
1/*
2 * Copyright (C) 2005-2008 MaNGOS <http://www.mangosproject.org/>
3 *
4 * Copyright (C) 2008 Trinity <http://www.trinitycore.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
103    #ifdef TRINITY_DEBUG
104
105    // Code for network use statistic
106    static uint64 sendPacketCount = 0;
107    static uint64 sendPacketBytes = 0;
108
109    static time_t firstTime = time(NULL);
110    static time_t lastTime = firstTime;                     // next 60 secs start time
111
112    static uint64 sendLastPacketCount = 0;
113    static uint64 sendLastPacketBytes = 0;
114
115    time_t cur_time = time(NULL);
116
117    if((cur_time - lastTime) < 60)
118    {
119        sendPacketCount+=1;
120        sendPacketBytes+=packet->size();
121
122        sendLastPacketCount+=1;
123        sendLastPacketBytes+=packet->size();
124    }
125    else
126    {
127        uint64 minTime = uint64(cur_time - lastTime);
128        uint64 fullTime = uint64(lastTime - firstTime);
129        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));
130        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);
131
132        lastTime = cur_time;
133        sendLastPacketCount = 1;
134        sendLastPacketBytes = packet->wpos();               // wpos is real written size
135    }
136
137        #endif                                                  // !TRINITY_DEBUG
138
139        if (m_Socket->SendPacket (*packet) == -1)
140                m_Socket->CloseSocket ();
141}
142
143/// Add an incoming packet to the queue
144void WorldSession::QueuePacket(WorldPacket* new_packet)
145{
146    _recvQueue.add(new_packet);
147}
148
149/// Logging helper for unexpected opcodes
150void WorldSession::logUnexpectedOpcode(WorldPacket* packet, const char *reason)
151{
152    sLog.outError( "SESSION: received unexpected opcode %s (0x%.4X) %s",
153        LookupOpcodeName(packet->GetOpcode()),
154        packet->GetOpcode(),
155        reason);
156}
157
158/// Update the WorldSession (triggered by World update)
159bool WorldSession::Update(uint32 /*diff*/)
160{
161  if (m_Socket && 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 (uint64 lguid = GetPlayer()->GetLootGUID())
250            DoLootRelease(lguid);
251           
252        ///- If the player just died before logging out, make him appear as a ghost
253        //FIXME: logout must be delayed in case lost connection with client in time of combat
254        if (_player->GetDeathTimer())
255        {
256            _player->getHostilRefManager().deleteReferences();
257            _player->BuildPlayerRepop();
258            _player->RepopAtGraveyard();
259        }
260        else if (!_player->getAttackers().empty())
261        {
262            _player->CombatStop();
263            _player->getHostilRefManager().setOnlineOfflineState(false);
264            _player->RemoveAllAurasOnDeath();
265
266            // build set of player who attack _player or who have pet attacking of _player
267            std::set<Player*> aset;
268            for(Unit::AttackerSet::const_iterator itr = _player->getAttackers().begin(); itr != _player->getAttackers().end(); ++itr)
269            {
270                Unit* owner = (*itr)->GetOwner();           // including player controlled case
271                if(owner)
272                {
273                    if(owner->GetTypeId()==TYPEID_PLAYER)
274                        aset.insert((Player*)owner);
275                }
276                else
277                if((*itr)->GetTypeId()==TYPEID_PLAYER)
278                    aset.insert((Player*)(*itr));
279            }
280
281            _player->SetPvPDeath(!aset.empty());
282            _player->KillPlayer();
283            _player->BuildPlayerRepop();
284            _player->RepopAtGraveyard();
285
286            // give honor to all attackers from set like group case
287            for(std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr)
288                (*itr)->RewardHonor(_player, aset.size(), -1, true);
289
290            // give bg rewards and update counters like kill by first from attackers
291            // this can't be called for all attackers.
292            if(!aset.empty())
293                if(BattleGround *bg = _player->GetBattleGround())
294                    bg->HandleKillPlayer(_player,*aset.begin());
295        }
296        else if(_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
297        {
298            // this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
299            _player->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
300            //_player->SetDeathPvP(*); set at SPELL_AURA_SPIRIT_OF_REDEMPTION apply time
301            _player->KillPlayer();
302            _player->BuildPlayerRepop();
303            _player->RepopAtGraveyard();
304        }
305
306        ///- Remove player from battleground (teleport to entrance)
307        if(_player->InBattleGround())
308            _player->LeaveBattleground();
309
310        sOutdoorPvPMgr.HandlePlayerLeaveZone(_player,_player->GetZoneId());
311
312        for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; i++)
313        {
314            if(int32 bgTypeId = _player->GetBattleGroundQueueId(i))
315            {
316                _player->RemoveBattleGroundQueueId(bgTypeId);
317                sBattleGroundMgr.m_BattleGroundQueues[ bgTypeId ].RemovePlayer(_player->GetGUID(), true);
318            }
319        }
320
321        ///- Reset the online field in the account table
322        // 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
323        //No SQL injection as AccountID is uint32
324        loginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = '%u'", GetAccountId());
325
326        ///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
327        Guild *guild = objmgr.GetGuildById(_player->GetGuildId());
328        if(guild)
329        {
330            guild->LoadPlayerStatsByGuid(_player->GetGUID());
331            guild->UpdateLogoutTime(_player->GetGUID());
332
333            WorldPacket data(SMSG_GUILD_EVENT, (1+1+12+8)); // name limited to 12 in character table.
334            data<<(uint8)GE_SIGNED_OFF;
335            data<<(uint8)1;
336            data<<_player->GetName();
337            data<<_player->GetGUID();
338            guild->BroadcastPacket(&data);
339        }
340
341        ///- Remove pet
342        _player->RemovePet(NULL,PET_SAVE_AS_CURRENT, true);
343
344        ///- empty buyback items and save the player in the database
345        // some save parts only correctly work in case player present in map/player_lists (pets, etc)
346        if(Save)
347        {
348            uint32 eslot;
349            for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
350            {
351                eslot = j - BUYBACK_SLOT_START;
352                _player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+eslot*2,0);
353                _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+eslot,0);
354                _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+eslot,0);
355            }
356            _player->SaveToDB();
357        }
358
359        ///- Leave all channels before player delete...
360        _player->CleanupChannels();
361
362        ///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
363        _player->UninviteFromGroup();
364
365        // remove player from the group if he is:
366        // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
367        if(_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
368            _player->RemoveFromGroup();
369
370        ///- Remove the player from the world
371        // the player may not be in the world when logging out
372        // e.g if he got disconnected during a transfer to another map
373        // calls to GetMap in this case may cause crashes
374        if(_player->IsInWorld()) MapManager::Instance().GetMap(_player->GetMapId(), _player)->Remove(_player, false);
375        // RemoveFromWorld does cleanup that requires the player to be in the accessor
376        ObjectAccessor::Instance().RemoveObject(_player);
377
378        ///- Send update to group
379        if(_player->GetGroup())
380            _player->GetGroup()->SendUpdate();
381
382        ///- Broadcast a logout message to the player's friends
383        sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUIDLow(), "", true);
384
385        ///- Delete the player object
386        _player->CleanupsBeforeDelete();                    // do some cleanup before deleting to prevent crash at crossreferences to already deleted data
387
388        sSocialMgr.RemovePlayerSocial (_player->GetGUIDLow ());
389        delete _player;
390        _player = NULL;
391
392        ///- Send the 'logout complete' packet to the client
393        WorldPacket data( SMSG_LOGOUT_COMPLETE, 0 );
394        SendPacket( &data );
395
396        ///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
397        //No SQL injection as AccountId is uint32
398        CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'",
399                        GetAccountId());
400        sLog.outDebug( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
401    }
402
403    m_playerLogout = false;
404    m_playerRecentlyLogout = true;
405    LogoutRequest(0);
406}
407
408/// Kick a player out of the World
409void WorldSession::KickPlayer()
410{
411        if (m_Socket)
412                m_Socket->CloseSocket ();
413}
414
415/// Cancel channeling handler
416
417void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
418{
419    va_list ap;
420    char szStr [1024];
421    szStr[0] = '\0';
422
423    va_start(ap, Text);
424    vsnprintf( szStr, 1024, Text, ap );
425    va_end(ap);
426
427    uint32 length = strlen(szStr)+1;
428    WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4+length);
429    data << length;
430    data << szStr;
431    SendPacket(&data);
432}
433
434void WorldSession::SendNotification(const char *format,...)
435{
436    if(format)
437    {
438        va_list ap;
439        char szStr [1024];
440        szStr[0] = '\0';
441        va_start(ap, format);
442        vsnprintf( szStr, 1024, format, ap );
443        va_end(ap);
444
445        WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
446        data << szStr;
447        SendPacket(&data);
448    }
449}
450
451void WorldSession::SendNotification(int32 string_id,...)
452{
453    char const* format = GetTrinityString(string_id);
454    if(format)
455    {
456        va_list ap;
457        char szStr [1024];
458        szStr[0] = '\0';
459        va_start(ap, string_id);
460        vsnprintf( szStr, 1024, format, ap );
461        va_end(ap);
462
463        WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
464        data << szStr;
465        SendPacket(&data);
466    }
467}
468
469const char * WorldSession::GetTrinityString( int32 entry ) const
470{
471    return objmgr.GetTrinityString(entry,GetSessionDbLocaleIndex());
472}
473
474void WorldSession::Handle_NULL( WorldPacket& recvPacket )
475{
476    sLog.outError( "SESSION: received unhandled opcode %s (0x%.4X)",
477        LookupOpcodeName(recvPacket.GetOpcode()),
478        recvPacket.GetOpcode());
479}
480
481void WorldSession::Handle_EarlyProccess( WorldPacket& recvPacket )
482{
483    sLog.outError( "SESSION: received opcode %s (0x%.4X) that must be proccessed in WorldSocket::OnRead",
484        LookupOpcodeName(recvPacket.GetOpcode()),
485        recvPacket.GetOpcode());
486}
487
488void WorldSession::Handle_ServerSide( WorldPacket& recvPacket )
489{
490    sLog.outError( "SESSION: received sever-side opcode %s (0x%.4X)",
491        LookupOpcodeName(recvPacket.GetOpcode()),
492        recvPacket.GetOpcode());
493}
494
495void WorldSession::Handle_Depricated( WorldPacket& recvPacket )
496{
497    sLog.outError( "SESSION: received depricated opcode %s (0x%.4X)",
498        LookupOpcodeName(recvPacket.GetOpcode()),
499        recvPacket.GetOpcode());
500}
501
502void WorldSession::SendAuthWaitQue(uint32 position)
503 {
504     if(position == 0)
505     {
506         WorldPacket packet( SMSG_AUTH_RESPONSE, 1 );
507         packet << uint8( AUTH_OK );
508         SendPacket(&packet);
509     }
510     else
511     {
512         WorldPacket packet( SMSG_AUTH_RESPONSE, 5 );
513         packet << uint8( AUTH_WAIT_QUEUE );
514         packet << uint32 (position);
515         SendPacket(&packet);
516     }
517 }
518 
519
520
521
Note: See TracBrowser for help on using the browser.