Prevent crash at access to deleted social data for player.
[getmangos.git] / src / game / WorldSession.cpp
blob261d613bfb757b789beed560da119159046cf95b
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
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.
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.
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
19 /** \file
20 \ingroup u2w
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"
43 /// WorldSession constructor
44 WorldSession::WorldSession(uint32 id, WorldSocket *sock, uint32 sec, uint8 expansion, time_t mute_time, LocaleConstant locale) :
45 LookingForGroup_auto_join(false), LookingForGroup_auto_add(false), m_muteTime(mute_time),
46 _player(NULL), m_Socket(sock),_security(sec), _accountId(id), m_expansion(expansion),
47 m_sessionDbcLocale(sWorld.GetAvailableDbcLocale(locale)), m_sessionDbLocaleIndex(objmgr.GetIndexForLocale(locale)),
48 _logoutTime(0), m_playerLoading(false), m_playerLogout(false), m_playerRecentlyLogout(false), m_latency(0)
50 if (sock)
52 m_Address = sock->GetRemoteAddress ();
53 sock->AddReference ();
57 /// WorldSession destructor
58 WorldSession::~WorldSession()
60 ///- unload player if not unloaded
61 if(_player)
62 LogoutPlayer(true);
64 /// - If have unclosed socket, close it
65 if (m_Socket)
67 m_Socket->CloseSocket ();
68 m_Socket->RemoveReference ();
69 m_Socket = NULL;
72 ///- empty incoming packet queue
73 while(!_recvQueue.empty())
75 WorldPacket *packet = _recvQueue.next();
76 delete packet;
79 sWorld.RemoveQueuedPlayer(this);
82 void WorldSession::SizeError(WorldPacket const& packet, uint32 size) const
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);
88 /// Get the player name
89 char const* WorldSession::GetPlayerName() const
91 return GetPlayer() ? GetPlayer()->GetName() : "<none>";
94 /// Send a packet to the client
95 void WorldSession::SendPacket(WorldPacket const* packet)
97 if (!m_Socket)
98 return;
100 #ifdef MANGOS_DEBUG
102 // Code for network use statistic
103 static uint64 sendPacketCount = 0;
104 static uint64 sendPacketBytes = 0;
106 static time_t firstTime = time(NULL);
107 static time_t lastTime = firstTime; // next 60 secs start time
109 static uint64 sendLastPacketCount = 0;
110 static uint64 sendLastPacketBytes = 0;
112 time_t cur_time = time(NULL);
114 if((cur_time - lastTime) < 60)
116 sendPacketCount+=1;
117 sendPacketBytes+=packet->size();
119 sendLastPacketCount+=1;
120 sendLastPacketBytes+=packet->size();
122 else
124 uint64 minTime = uint64(cur_time - lastTime);
125 uint64 fullTime = uint64(lastTime - firstTime);
126 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));
127 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 lastTime = cur_time;
130 sendLastPacketCount = 1;
131 sendLastPacketBytes = packet->wpos(); // wpos is real written size
134 #endif // !MANGOS_DEBUG
136 if (m_Socket->SendPacket (*packet) == -1)
137 m_Socket->CloseSocket ();
140 /// Add an incoming packet to the queue
141 void WorldSession::QueuePacket(WorldPacket* new_packet)
143 _recvQueue.add(new_packet);
146 /// Logging helper for unexpected opcodes
147 void WorldSession::logUnexpectedOpcode(WorldPacket* packet, const char *reason)
149 sLog.outError( "SESSION: received unexpected opcode %s (0x%.4X) %s",
150 LookupOpcodeName(packet->GetOpcode()),
151 packet->GetOpcode(),
152 reason);
155 /// Update the WorldSession (triggered by World update)
156 bool WorldSession::Update(uint32 /*diff*/)
158 if (m_Socket && m_Socket->IsClosed ())
160 m_Socket->RemoveReference ();
161 m_Socket = NULL;
164 WorldPacket *packet;
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())
171 packet = _recvQueue.next();
173 /*#if 1
174 sLog.outError( "MOEP: %s (0x%.4X)",
175 LookupOpcodeName(packet->GetOpcode()),
176 packet->GetOpcode());
177 #endif*/
179 if(packet->GetOpcode() >= NUM_MSG_TYPES)
181 sLog.outError( "SESSION: received non-existed opcode %s (0x%.4X)",
182 LookupOpcodeName(packet->GetOpcode()),
183 packet->GetOpcode());
185 else
187 OpcodeHandler& opHandle = opcodeTable[packet->GetOpcode()];
188 switch (opHandle.status)
190 case STATUS_LOGGEDIN:
191 if(!_player)
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");
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;
221 delete packet;
224 ///- If necessary, log the player out
225 time_t currTime = time(NULL);
226 if (!m_Socket || (ShouldLogOut(currTime) && !m_playerLoading))
227 LogoutPlayer(true);
229 if (!m_Socket)
230 return false; //Will remove this session from the world session map
232 return true;
235 /// %Log the player out
236 void WorldSession::LogoutPlayer(bool Save)
238 // finish pending transfers before starting the logout
239 while(_player && _player->IsBeingTeleported())
240 HandleMoveWorldportAckOpcode();
242 m_playerLogout = true;
244 if (_player)
246 if (uint64 lguid = GetPlayer()->GetLootGUID())
247 DoLootRelease(lguid);
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())
253 _player->getHostilRefManager().deleteReferences();
254 _player->BuildPlayerRepop();
255 _player->RepopAtGraveyard();
257 else if (!_player->getAttackers().empty())
259 _player->CombatStop();
260 _player->getHostilRefManager().setOnlineOfflineState(false);
261 _player->RemoveAllAurasOnDeath();
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)
267 Unit* owner = (*itr)->GetOwner(); // including player controlled case
268 if(owner)
270 if(owner->GetTypeId()==TYPEID_PLAYER)
271 aset.insert((Player*)owner);
273 else
274 if((*itr)->GetTypeId()==TYPEID_PLAYER)
275 aset.insert((Player*)(*itr));
278 _player->SetPvPDeath(!aset.empty());
279 _player->KillPlayer();
280 _player->BuildPlayerRepop();
281 _player->RepopAtGraveyard();
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());
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());
293 else if(_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
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();
303 ///- Remove player from battleground (teleport to entrance)
304 if(_player->InBattleGround())
305 _player->LeaveBattleground();
307 for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; i++)
309 if(int32 bgTypeId = _player->GetBattleGroundQueueId(i))
311 _player->RemoveBattleGroundQueueId(bgTypeId);
312 sBattleGroundMgr.m_BattleGroundQueues[ bgTypeId ].RemovePlayer(_player->GetGUID(), true);
316 ///- Reset the online field in the account table
317 // 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
318 //No SQL injection as AccountID is uint32
319 loginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = '%u'", GetAccountId());
321 ///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
322 Guild *guild = objmgr.GetGuildById(_player->GetGuildId());
323 if(guild)
325 guild->LoadPlayerStatsByGuid(_player->GetGUID());
326 guild->UpdateLogoutTime(_player->GetGUID());
328 WorldPacket data(SMSG_GUILD_EVENT, (1+1+12+8)); // name limited to 12 in character table.
329 data<<(uint8)GE_SIGNED_OFF;
330 data<<(uint8)1;
331 data<<_player->GetName();
332 data<<_player->GetGUID();
333 guild->BroadcastPacket(&data);
336 ///- Remove pet
337 _player->RemovePet(NULL,PET_SAVE_AS_CURRENT, true);
339 ///- empty buyback items and save the player in the database
340 // some save parts only correctly work in case player present in map/player_lists (pets, etc)
341 if(Save)
343 uint32 eslot;
344 for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
346 eslot = j - BUYBACK_SLOT_START;
347 _player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+eslot*2,0);
348 _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+eslot,0);
349 _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+eslot,0);
351 _player->SaveToDB();
354 ///- Leave all channels before player delete...
355 _player->CleanupChannels();
357 ///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
358 _player->UninviteFromGroup();
360 // remove player from the group if he is:
361 // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
362 if(_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
363 _player->RemoveFromGroup();
365 ///- Remove the player from the world
366 // the player may not be in the world when logging out
367 // e.g if he got disconnected during a transfer to another map
368 // calls to GetMap in this case may cause crashes
369 if(_player->IsInWorld()) MapManager::Instance().GetMap(_player->GetMapId(), _player)->Remove(_player, false);
370 // RemoveFromWorld does cleanup that requires the player to be in the accessor
371 ObjectAccessor::Instance().RemoveObject(_player);
373 ///- Send update to group
374 if(_player->GetGroup())
375 _player->GetGroup()->SendUpdate();
377 ///- Broadcast a logout message to the player's friends
378 sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUIDLow(), "", true);
380 ///- Delete the player object
381 _player->CleanupsBeforeDelete(); // do some cleanup before deleting to prevent crash at crossreferences to already deleted data
383 sSocialMgr.RemovePlayerSocial (_player->GetGUIDLow ());
384 delete _player;
385 _player = NULL;
387 ///- Send the 'logout complete' packet to the client
388 WorldPacket data( SMSG_LOGOUT_COMPLETE, 0 );
389 SendPacket( &data );
391 ///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
392 //No SQL injection as AccountId is uint32
393 CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'",
394 GetAccountId());
395 sLog.outDebug( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
398 m_playerLogout = false;
399 m_playerRecentlyLogout = true;
400 LogoutRequest(0);
403 /// Kick a player out of the World
404 void WorldSession::KickPlayer()
406 if (m_Socket)
407 m_Socket->CloseSocket ();
410 /// Cancel channeling handler
412 void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
414 va_list ap;
415 char szStr [1024];
416 szStr[0] = '\0';
418 va_start(ap, Text);
419 vsnprintf( szStr, 1024, Text, ap );
420 va_end(ap);
422 uint32 length = strlen(szStr)+1;
423 WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4+length);
424 data << length;
425 data << szStr;
426 SendPacket(&data);
429 void WorldSession::SendNotification(const char *format,...)
431 if(format)
433 va_list ap;
434 char szStr [1024];
435 szStr[0] = '\0';
436 va_start(ap, format);
437 vsnprintf( szStr, 1024, format, ap );
438 va_end(ap);
440 WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
441 data << szStr;
442 SendPacket(&data);
446 void WorldSession::SendNotification(int32 string_id,...)
448 char const* format = GetMangosString(string_id);
449 if(format)
451 va_list ap;
452 char szStr [1024];
453 szStr[0] = '\0';
454 va_start(ap, string_id);
455 vsnprintf( szStr, 1024, format, ap );
456 va_end(ap);
458 WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
459 data << szStr;
460 SendPacket(&data);
464 const char * WorldSession::GetMangosString( int32 entry ) const
466 return objmgr.GetMangosString(entry,GetSessionDbLocaleIndex());
469 void WorldSession::Handle_NULL( WorldPacket& recvPacket )
471 sLog.outError( "SESSION: received unhandled opcode %s (0x%.4X)",
472 LookupOpcodeName(recvPacket.GetOpcode()),
473 recvPacket.GetOpcode());
476 void WorldSession::Handle_EarlyProccess( WorldPacket& recvPacket )
478 sLog.outError( "SESSION: received opcode %s (0x%.4X) that must be proccessed in WorldSocket::OnRead",
479 LookupOpcodeName(recvPacket.GetOpcode()),
480 recvPacket.GetOpcode());
483 void WorldSession::Handle_ServerSide( WorldPacket& recvPacket )
485 sLog.outError( "SESSION: received sever-side opcode %s (0x%.4X)",
486 LookupOpcodeName(recvPacket.GetOpcode()),
487 recvPacket.GetOpcode());
490 void WorldSession::Handle_Depricated( WorldPacket& recvPacket )
492 sLog.outError( "SESSION: received depricated opcode %s (0x%.4X)",
493 LookupOpcodeName(recvPacket.GetOpcode()),
494 recvPacket.GetOpcode());
497 void WorldSession::SendAuthWaitQue(uint32 position)
499 if(position == 0)
501 WorldPacket packet( SMSG_AUTH_RESPONSE, 1 );
502 packet << uint8( AUTH_OK );
503 SendPacket(&packet);
505 else
507 WorldPacket packet( SMSG_AUTH_RESPONSE, 5 );
508 packet << uint8( AUTH_WAIT_QUEUE );
509 packet << uint32 (position);
510 SendPacket(&packet);