Merge branch 'master' into 303
[getmangos.git] / src / game / WorldSession.cpp
blobb79b13dd367cfc1cabe438a64a78c3a0643a639a
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;
80 void WorldSession::SizeError(WorldPacket const& packet, uint32 size) const
82 sLog.outError("Client (account %u) send packet %s (%u) with size %u but expected %u (attempt crash server?), skipped",
83 GetAccountId(),LookupOpcodeName(packet.GetOpcode()),packet.GetOpcode(),packet.size(),size);
86 /// Get the player name
87 char const* WorldSession::GetPlayerName() const
89 return GetPlayer() ? GetPlayer()->GetName() : "<none>";
92 /// Send a packet to the client
93 void WorldSession::SendPacket(WorldPacket const* packet)
95 if (!m_Socket)
96 return;
98 #ifdef MANGOS_DEBUG
100 // Code for network use statistic
101 static uint64 sendPacketCount = 0;
102 static uint64 sendPacketBytes = 0;
104 static time_t firstTime = time(NULL);
105 static time_t lastTime = firstTime; // next 60 secs start time
107 static uint64 sendLastPacketCount = 0;
108 static uint64 sendLastPacketBytes = 0;
110 time_t cur_time = time(NULL);
112 if((cur_time - lastTime) < 60)
114 sendPacketCount+=1;
115 sendPacketBytes+=packet->size();
117 sendLastPacketCount+=1;
118 sendLastPacketBytes+=packet->size();
120 else
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);
127 lastTime = cur_time;
128 sendLastPacketCount = 1;
129 sendLastPacketBytes = packet->wpos(); // wpos is real written size
132 #endif // !MANGOS_DEBUG
134 if (m_Socket->SendPacket (*packet) == -1)
135 m_Socket->CloseSocket ();
138 /// Add an incoming packet to the queue
139 void WorldSession::QueuePacket(WorldPacket* new_packet)
141 _recvQueue.add(new_packet);
144 /// Logging helper for unexpected opcodes
145 void WorldSession::logUnexpectedOpcode(WorldPacket* packet, const char *reason)
147 sLog.outError( "SESSION: received unexpected opcode %s (0x%.4X) %s",
148 LookupOpcodeName(packet->GetOpcode()),
149 packet->GetOpcode(),
150 reason);
153 /// Update the WorldSession (triggered by World update)
154 bool WorldSession::Update(uint32 /*diff*/)
156 if (m_Socket && m_Socket->IsClosed ())
158 m_Socket->RemoveReference ();
159 m_Socket = NULL;
162 WorldPacket *packet;
164 ///- Retrieve packets from the receive queue and call the appropriate handlers
165 /// \todo Is there a way to consolidate the OpcondeHandlerTable and the g_worldOpcodeNames to only maintain 1 list?
166 /// answer : there is a way, but this is better, because it would use redundant RAM
167 while (!_recvQueue.empty())
169 packet = _recvQueue.next();
171 /*#if 1
172 sLog.outError( "MOEP: %s (0x%.4X)",
173 LookupOpcodeName(packet->GetOpcode()),
174 packet->GetOpcode());
175 #endif*/
177 if(packet->GetOpcode() >= NUM_MSG_TYPES)
179 sLog.outError( "SESSION: received non-existed opcode %s (0x%.4X)",
180 LookupOpcodeName(packet->GetOpcode()),
181 packet->GetOpcode());
183 else
185 OpcodeHandler& opHandle = opcodeTable[packet->GetOpcode()];
186 switch (opHandle.status)
188 case STATUS_LOGGEDIN:
189 if(!_player)
191 // skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
192 if(!m_playerRecentlyLogout)
193 logUnexpectedOpcode(packet, "the player has not logged in yet");
195 else if(_player->IsInWorld())
196 (this->*opHandle.handler)(*packet);
197 // lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
198 break;
199 case STATUS_TRANSFER_PENDING:
200 if(!_player)
201 logUnexpectedOpcode(packet, "the player has not logged in yet");
202 else if(_player->IsInWorld())
203 logUnexpectedOpcode(packet, "the player is still in world");
204 else
205 (this->*opHandle.handler)(*packet);
206 break;
207 case STATUS_AUTHED:
208 m_playerRecentlyLogout = false;
209 (this->*opHandle.handler)(*packet);
210 break;
211 case STATUS_NEVER:
212 sLog.outError( "SESSION: received not allowed opcode %s (0x%.4X)",
213 LookupOpcodeName(packet->GetOpcode()),
214 packet->GetOpcode());
215 break;
219 delete packet;
222 ///- If necessary, log the player out
223 time_t currTime = time(NULL);
224 if (!m_Socket || (ShouldLogOut(currTime) && !m_playerLoading))
225 LogoutPlayer(true);
227 if (!m_Socket)
228 return false; //Will remove this session from the world session map
230 return true;
233 /// %Log the player out
234 void WorldSession::LogoutPlayer(bool Save)
236 // finish pending transfers before starting the logout
237 while(_player && _player->IsBeingTeleported())
238 HandleMoveWorldportAckOpcode();
240 m_playerLogout = true;
242 if (_player)
244 if (uint64 lguid = GetPlayer()->GetLootGUID())
245 DoLootRelease(lguid);
247 ///- If the player just died before logging out, make him appear as a ghost
248 //FIXME: logout must be delayed in case lost connection with client in time of combat
249 if (_player->GetDeathTimer())
251 _player->getHostilRefManager().deleteReferences();
252 _player->BuildPlayerRepop();
253 _player->RepopAtGraveyard();
255 else if (!_player->getAttackers().empty())
257 _player->CombatStop();
258 _player->getHostilRefManager().setOnlineOfflineState(false);
259 _player->RemoveAllAurasOnDeath();
261 // build set of player who attack _player or who have pet attacking of _player
262 std::set<Player*> aset;
263 for(Unit::AttackerSet::const_iterator itr = _player->getAttackers().begin(); itr != _player->getAttackers().end(); ++itr)
265 Unit* owner = (*itr)->GetOwner(); // including player controlled case
266 if(owner)
268 if(owner->GetTypeId()==TYPEID_PLAYER)
269 aset.insert((Player*)owner);
271 else
272 if((*itr)->GetTypeId()==TYPEID_PLAYER)
273 aset.insert((Player*)(*itr));
276 _player->SetPvPDeath(!aset.empty());
277 _player->KillPlayer();
278 _player->BuildPlayerRepop();
279 _player->RepopAtGraveyard();
281 // give honor to all attackers from set like group case
282 for(std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr)
283 (*itr)->RewardHonor(_player,aset.size());
285 // give bg rewards and update counters like kill by first from attackers
286 // this can't be called for all attackers.
287 if(!aset.empty())
288 if(BattleGround *bg = _player->GetBattleGround())
289 bg->HandleKillPlayer(_player,*aset.begin());
291 else if(_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
293 // this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
294 _player->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
295 //_player->SetDeathPvP(*); set at SPELL_AURA_SPIRIT_OF_REDEMPTION apply time
296 _player->KillPlayer();
297 _player->BuildPlayerRepop();
298 _player->RepopAtGraveyard();
301 ///- Remove player from battleground (teleport to entrance)
302 if(_player->InBattleGround())
303 _player->LeaveBattleground();
305 for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; i++)
307 if(int32 bgTypeId = _player->GetBattleGroundQueueId(i))
309 _player->RemoveBattleGroundQueueId(bgTypeId);
310 sBattleGroundMgr.m_BattleGroundQueues[ bgTypeId ].RemovePlayer(_player->GetGUID(), true);
314 ///- Reset the online field in the account table
315 // 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
316 //No SQL injection as AccountID is uint32
317 loginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = '%u'", GetAccountId());
319 ///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
320 Guild *guild = objmgr.GetGuildById(_player->GetGuildId());
321 if(guild)
323 guild->LoadPlayerStatsByGuid(_player->GetGUID());
324 guild->UpdateLogoutTime(_player->GetGUID());
326 WorldPacket data(SMSG_GUILD_EVENT, (1+1+12+8)); // name limited to 12 in character table.
327 data<<(uint8)GE_SIGNED_OFF;
328 data<<(uint8)1;
329 data<<_player->GetName();
330 data<<_player->GetGUID();
331 guild->BroadcastPacket(&data);
334 ///- Remove pet
335 _player->RemovePet(NULL,PET_SAVE_AS_CURRENT, true);
337 ///- empty buyback items and save the player in the database
338 // some save parts only correctly work in case player present in map/player_lists (pets, etc)
339 if(Save)
341 uint32 eslot;
342 for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
344 eslot = j - BUYBACK_SLOT_START;
345 _player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+eslot*2,0);
346 _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+eslot,0);
347 _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+eslot,0);
349 _player->SaveToDB();
352 ///- Leave all channels before player delete...
353 _player->CleanupChannels();
355 ///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
356 _player->UninviteFromGroup();
358 // remove player from the group if he is:
359 // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
360 if(_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
361 _player->RemoveFromGroup();
363 ///- Remove the player from the world
364 // the player may not be in the world when logging out
365 // e.g if he got disconnected during a transfer to another map
366 // calls to GetMap in this case may cause crashes
367 if(_player->IsInWorld()) MapManager::Instance().GetMap(_player->GetMapId(), _player)->Remove(_player, false);
368 // RemoveFromWorld does cleanup that requires the player to be in the accessor
369 ObjectAccessor::Instance().RemoveObject(_player);
371 ///- Send update to group
372 if(_player->GetGroup())
373 _player->GetGroup()->SendUpdate();
375 ///- Broadcast a logout message to the player's friends
376 sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUIDLow(), true);
378 ///- Delete the player object
379 _player->CleanupsBeforeDelete(); // do some cleanup before deleting to prevent crash at crossreferences to already deleted data
381 sSocialMgr.RemovePlayerSocial (_player->GetGUIDLow ());
382 delete _player;
383 _player = NULL;
385 ///- Send the 'logout complete' packet to the client
386 WorldPacket data( SMSG_LOGOUT_COMPLETE, 0 );
387 SendPacket( &data );
389 ///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
390 //No SQL injection as AccountId is uint32
391 CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'",
392 GetAccountId());
393 sLog.outDebug( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
396 m_playerLogout = false;
397 m_playerRecentlyLogout = true;
398 LogoutRequest(0);
401 /// Kick a player out of the World
402 void WorldSession::KickPlayer()
404 if (m_Socket)
405 m_Socket->CloseSocket ();
408 /// Cancel channeling handler
410 void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
412 va_list ap;
413 char szStr [1024];
414 szStr[0] = '\0';
416 va_start(ap, Text);
417 vsnprintf( szStr, 1024, Text, ap );
418 va_end(ap);
420 uint32 length = strlen(szStr)+1;
421 WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4+length);
422 data << length;
423 data << szStr;
424 SendPacket(&data);
427 void WorldSession::SendNotification(const char *format,...)
429 if(format)
431 va_list ap;
432 char szStr [1024];
433 szStr[0] = '\0';
434 va_start(ap, format);
435 vsnprintf( szStr, 1024, format, ap );
436 va_end(ap);
438 WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
439 data << szStr;
440 SendPacket(&data);
444 void WorldSession::SendNotification(int32 string_id,...)
446 char const* format = GetMangosString(string_id);
447 if(format)
449 va_list ap;
450 char szStr [1024];
451 szStr[0] = '\0';
452 va_start(ap, string_id);
453 vsnprintf( szStr, 1024, format, ap );
454 va_end(ap);
456 WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
457 data << szStr;
458 SendPacket(&data);
462 const char * WorldSession::GetMangosString( int32 entry ) const
464 return objmgr.GetMangosString(entry,GetSessionDbLocaleIndex());
467 void WorldSession::Handle_NULL( WorldPacket& recvPacket )
469 sLog.outError( "SESSION: received unhandled opcode %s (0x%.4X)",
470 LookupOpcodeName(recvPacket.GetOpcode()),
471 recvPacket.GetOpcode());
474 void WorldSession::Handle_EarlyProccess( WorldPacket& recvPacket )
476 sLog.outError( "SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead",
477 LookupOpcodeName(recvPacket.GetOpcode()),
478 recvPacket.GetOpcode());
481 void WorldSession::Handle_ServerSide( WorldPacket& recvPacket )
483 sLog.outError( "SESSION: received server-side opcode %s (0x%.4X)",
484 LookupOpcodeName(recvPacket.GetOpcode()),
485 recvPacket.GetOpcode());
488 void WorldSession::Handle_Deprecated( WorldPacket& recvPacket )
490 sLog.outError( "SESSION: received deprecated opcode %s (0x%.4X)",
491 LookupOpcodeName(recvPacket.GetOpcode()),
492 recvPacket.GetOpcode());
495 void WorldSession::SendAuthWaitQue(uint32 position)
497 if(position == 0)
499 WorldPacket packet( SMSG_AUTH_RESPONSE, 1 );
500 packet << uint8( AUTH_OK );
501 SendPacket(&packet);
503 else
505 WorldPacket packet( SMSG_AUTH_RESPONSE, 5 );
506 packet << uint8( AUTH_WAIT_QUEUE );
507 packet << uint32 (position);
508 SendPacket(&packet);
512 void WorldSession::LoadAccountData()
514 for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
516 AccountData data;
517 m_accountData[i] = data;
520 QueryResult *result = CharacterDatabase.PQuery("SELECT type, time, data FROM account_data WHERE account='%u'", GetAccountId());
522 if(!result)
523 return;
527 Field *fields = result->Fetch();
529 uint32 type = fields[0].GetUInt32();
530 if(type < NUM_ACCOUNT_DATA_TYPES)
532 m_accountData[type].Time = fields[1].GetUInt32();
533 m_accountData[type].Data = fields[2].GetCppString();
535 } while (result->NextRow());
537 delete result;
540 void WorldSession::SetAccountData(uint32 type, time_t time_, std::string data)
542 m_accountData[type].Time = time_;
543 m_accountData[type].Data = data;
545 uint32 acc = GetAccountId();
546 CharacterDatabase.PExecute("DELETE FROM account_data WHERE account='%u' AND type='%u'", acc, type);
547 CharacterDatabase.PExecute("INSERT INTO account_data VALUES ('%u','%u','%u','%s')", acc, type, (uint32)time_, data.c_str());