[7146] Trailing whitespace code cleanup
[getmangos.git] / src / game / WorldSession.cpp
blob9671041f9dc86c3110b9628a05ddd506386c04af
1 /*
2 * Copyright (C) 2005-2009 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_inQueue(false), 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 ///- Retrieve packets from the receive queue and call the appropriate handlers
157 /// not proccess packets if socket already closed
158 while (!_recvQueue.empty() && m_Socket && !m_Socket->IsClosed ())
160 WorldPacket *packet = _recvQueue.next();
162 /*#if 1
163 sLog.outError( "MOEP: %s (0x%.4X)",
164 LookupOpcodeName(packet->GetOpcode()),
165 packet->GetOpcode());
166 #endif*/
168 if(packet->GetOpcode() >= NUM_MSG_TYPES)
170 sLog.outError( "SESSION: received non-existed opcode %s (0x%.4X)",
171 LookupOpcodeName(packet->GetOpcode()),
172 packet->GetOpcode());
174 else
176 OpcodeHandler& opHandle = opcodeTable[packet->GetOpcode()];
177 switch (opHandle.status)
179 case STATUS_LOGGEDIN:
180 if(!_player)
182 // skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
183 if(!m_playerRecentlyLogout)
184 logUnexpectedOpcode(packet, "the player has not logged in yet");
186 else if(_player->IsInWorld())
187 (this->*opHandle.handler)(*packet);
188 // lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
189 break;
190 case STATUS_TRANSFER_PENDING:
191 if(!_player)
192 logUnexpectedOpcode(packet, "the player has not logged in yet");
193 else if(_player->IsInWorld())
194 logUnexpectedOpcode(packet, "the player is still in world");
195 else
196 (this->*opHandle.handler)(*packet);
197 break;
198 case STATUS_AUTHED:
199 // prevent cheating with skip queue wait
200 if(m_inQueue)
202 logUnexpectedOpcode(packet, "the player not pass queue yet");
203 break;
206 m_playerRecentlyLogout = false;
207 (this->*opHandle.handler)(*packet);
208 break;
209 case STATUS_NEVER:
210 sLog.outError( "SESSION: received not allowed opcode %s (0x%.4X)",
211 LookupOpcodeName(packet->GetOpcode()),
212 packet->GetOpcode());
213 break;
217 delete packet;
220 ///- Cleanup socket pointer if need
221 if (m_Socket && m_Socket->IsClosed ())
223 m_Socket->RemoveReference ();
224 m_Socket = NULL;
227 ///- If necessary, log the player out
228 time_t currTime = time(NULL);
229 if (!m_Socket || (ShouldLogOut(currTime) && !m_playerLoading))
230 LogoutPlayer(true);
232 if (!m_Socket)
233 return false; //Will remove this session from the world session map
235 return true;
238 /// %Log the player out
239 void WorldSession::LogoutPlayer(bool Save)
241 // finish pending transfers before starting the logout
242 while(_player && _player->IsBeingTeleported())
243 HandleMoveWorldportAckOpcode();
245 m_playerLogout = true;
247 if (_player)
249 if (uint64 lguid = GetPlayer()->GetLootGUID())
250 DoLootRelease(lguid);
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())
256 _player->getHostilRefManager().deleteReferences();
257 _player->BuildPlayerRepop();
258 _player->RepopAtGraveyard();
260 else if (!_player->getAttackers().empty())
262 _player->CombatStop();
263 _player->getHostilRefManager().setOnlineOfflineState(false);
264 _player->RemoveAllAurasOnDeath();
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)
270 Unit* owner = (*itr)->GetOwner(); // including player controlled case
271 if(owner)
273 if(owner->GetTypeId()==TYPEID_PLAYER)
274 aset.insert((Player*)owner);
276 else
277 if((*itr)->GetTypeId()==TYPEID_PLAYER)
278 aset.insert((Player*)(*itr));
281 _player->SetPvPDeath(!aset.empty());
282 _player->KillPlayer();
283 _player->BuildPlayerRepop();
284 _player->RepopAtGraveyard();
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());
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());
296 else if(_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
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();
306 ///- Remove player from battleground (teleport to entrance)
307 if(_player->InBattleGround())
308 _player->LeaveBattleground();
310 ///- Teleport to home if the player is in an invalid instance
311 if(!_player->m_InstanceValid && !_player->isGameMaster())
312 _player->TeleportTo(_player->m_homebindMapId, _player->m_homebindX, _player->m_homebindY, _player->m_homebindZ, _player->GetOrientation());
314 for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; i++)
316 if(int32 bgTypeId = _player->GetBattleGroundQueueId(i))
318 _player->RemoveBattleGroundQueueId(bgTypeId);
319 sBattleGroundMgr.m_BattleGroundQueues[ bgTypeId ].RemovePlayer(_player->GetGUID(), true);
323 ///- Reset the online field in the account table
324 // 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
325 //No SQL injection as AccountID is uint32
326 loginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = '%u'", GetAccountId());
328 ///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
329 Guild *guild = objmgr.GetGuildById(_player->GetGuildId());
330 if(guild)
332 guild->LoadPlayerStatsByGuid(_player->GetGUID());
333 guild->UpdateLogoutTime(_player->GetGUID());
335 WorldPacket data(SMSG_GUILD_EVENT, (1+1+12+8)); // name limited to 12 in character table.
336 data<<(uint8)GE_SIGNED_OFF;
337 data<<(uint8)1;
338 data<<_player->GetName();
339 data<<_player->GetGUID();
340 guild->BroadcastPacket(&data);
343 ///- Remove pet
344 _player->RemovePet(NULL,PET_SAVE_AS_CURRENT, true);
346 ///- empty buyback items and save the player in the database
347 // some save parts only correctly work in case player present in map/player_lists (pets, etc)
348 if(Save)
350 uint32 eslot;
351 for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
353 eslot = j - BUYBACK_SLOT_START;
354 _player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+eslot*2,0);
355 _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+eslot,0);
356 _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+eslot,0);
358 _player->SaveToDB();
361 ///- Leave all channels before player delete...
362 _player->CleanupChannels();
364 ///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
365 _player->UninviteFromGroup();
367 // remove player from the group if he is:
368 // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
369 if(_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
370 _player->RemoveFromGroup();
372 ///- Remove the player from the world
373 // the player may not be in the world when logging out
374 // e.g if he got disconnected during a transfer to another map
375 // calls to GetMap in this case may cause crashes
376 if(_player->IsInWorld()) _player->GetMap()->Remove(_player, false);
377 // RemoveFromWorld does cleanup that requires the player to be in the accessor
378 ObjectAccessor::Instance().RemoveObject(_player);
380 ///- Send update to group
381 if(_player->GetGroup())
382 _player->GetGroup()->SendUpdate();
384 ///- Broadcast a logout message to the player's friends
385 sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUIDLow(), true);
387 ///- Delete the player object
388 _player->CleanupsBeforeDelete(); // do some cleanup before deleting to prevent crash at crossreferences to already deleted data
390 sSocialMgr.RemovePlayerSocial (_player->GetGUIDLow ());
391 delete _player;
392 _player = NULL;
394 ///- Send the 'logout complete' packet to the client
395 WorldPacket data( SMSG_LOGOUT_COMPLETE, 0 );
396 SendPacket( &data );
398 ///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
399 //No SQL injection as AccountId is uint32
400 CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'",
401 GetAccountId());
402 sLog.outDebug( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
405 m_playerLogout = false;
406 m_playerRecentlyLogout = true;
407 LogoutRequest(0);
410 /// Kick a player out of the World
411 void WorldSession::KickPlayer()
413 if (m_Socket)
414 m_Socket->CloseSocket ();
417 /// Cancel channeling handler
419 void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
421 va_list ap;
422 char szStr [1024];
423 szStr[0] = '\0';
425 va_start(ap, Text);
426 vsnprintf( szStr, 1024, Text, ap );
427 va_end(ap);
429 uint32 length = strlen(szStr)+1;
430 WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4+length);
431 data << length;
432 data << szStr;
433 SendPacket(&data);
436 void WorldSession::SendNotification(const char *format,...)
438 if(format)
440 va_list ap;
441 char szStr [1024];
442 szStr[0] = '\0';
443 va_start(ap, format);
444 vsnprintf( szStr, 1024, format, ap );
445 va_end(ap);
447 WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
448 data << szStr;
449 SendPacket(&data);
453 void WorldSession::SendNotification(int32 string_id,...)
455 char const* format = GetMangosString(string_id);
456 if(format)
458 va_list ap;
459 char szStr [1024];
460 szStr[0] = '\0';
461 va_start(ap, string_id);
462 vsnprintf( szStr, 1024, format, ap );
463 va_end(ap);
465 WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
466 data << szStr;
467 SendPacket(&data);
471 const char * WorldSession::GetMangosString( int32 entry ) const
473 return objmgr.GetMangosString(entry,GetSessionDbLocaleIndex());
476 void WorldSession::Handle_NULL( WorldPacket& recvPacket )
478 sLog.outError( "SESSION: received unhandled opcode %s (0x%.4X)",
479 LookupOpcodeName(recvPacket.GetOpcode()),
480 recvPacket.GetOpcode());
483 void WorldSession::Handle_EarlyProccess( WorldPacket& recvPacket )
485 sLog.outError( "SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead",
486 LookupOpcodeName(recvPacket.GetOpcode()),
487 recvPacket.GetOpcode());
490 void WorldSession::Handle_ServerSide( WorldPacket& recvPacket )
492 sLog.outError( "SESSION: received server-side opcode %s (0x%.4X)",
493 LookupOpcodeName(recvPacket.GetOpcode()),
494 recvPacket.GetOpcode());
497 void WorldSession::Handle_Deprecated( WorldPacket& recvPacket )
499 sLog.outError( "SESSION: received deprecated opcode %s (0x%.4X)",
500 LookupOpcodeName(recvPacket.GetOpcode()),
501 recvPacket.GetOpcode());
504 void WorldSession::SendAuthWaitQue(uint32 position)
506 if(position == 0)
508 WorldPacket packet( SMSG_AUTH_RESPONSE, 1 );
509 packet << uint8( AUTH_OK );
510 SendPacket(&packet);
512 else
514 WorldPacket packet( SMSG_AUTH_RESPONSE, 5 );
515 packet << uint8( AUTH_WAIT_QUEUE );
516 packet << uint32 (position);
517 SendPacket(&packet);
521 void WorldSession::LoadAccountData()
523 for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
525 AccountData data;
526 m_accountData[i] = data;
529 QueryResult *result = CharacterDatabase.PQuery("SELECT type, time, data FROM account_data WHERE account='%u'", GetAccountId());
531 if(!result)
532 return;
536 Field *fields = result->Fetch();
538 uint32 type = fields[0].GetUInt32();
539 if(type < NUM_ACCOUNT_DATA_TYPES)
541 m_accountData[type].Time = fields[1].GetUInt32();
542 m_accountData[type].Data = fields[2].GetCppString();
544 } while (result->NextRow());
546 delete result;
549 void WorldSession::SetAccountData(uint32 type, time_t time_, std::string data)
551 m_accountData[type].Time = time_;
552 m_accountData[type].Data = data;
554 uint32 acc = GetAccountId();
556 CharacterDatabase.BeginTransaction ();
557 CharacterDatabase.PExecute("DELETE FROM account_data WHERE account='%u' AND type='%u'", acc, type);
558 CharacterDatabase.escape_string(data);
559 CharacterDatabase.PExecute("INSERT INTO account_data VALUES ('%u','%u','%u','%s')", acc, type, (uint32)time_, data.c_str());
560 CharacterDatabase.CommitTransaction ();
563 void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo *mi)
565 CHECK_PACKET_SIZE(data, data.rpos()+4+2+4+4+4+4+4);
566 data >> mi->flags;
567 data >> mi->unk1;
568 data >> mi->time;
569 data >> mi->x;
570 data >> mi->y;
571 data >> mi->z;
572 data >> mi->o;
574 if(mi->flags & MOVEMENTFLAG_ONTRANSPORT)
576 CHECK_PACKET_SIZE(data, data.rpos()+8+4+4+4+4+4+1);
577 data >> mi->t_guid;
578 data >> mi->t_x;
579 data >> mi->t_y;
580 data >> mi->t_z;
581 data >> mi->t_o;
582 data >> mi->t_time;
583 data >> mi->t_seat;
586 if((mi->flags & (MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING2)) || (mi->unk1 & 0x20))
588 CHECK_PACKET_SIZE(data, data.rpos()+4);
589 data >> mi->s_pitch;
592 CHECK_PACKET_SIZE(data, data.rpos()+4);
593 data >> mi->fallTime;
595 if(mi->flags & MOVEMENTFLAG_JUMPING)
597 CHECK_PACKET_SIZE(data, data.rpos()+4+4+4+4);
598 data >> mi->j_unk;
599 data >> mi->j_sinAngle;
600 data >> mi->j_cosAngle;
601 data >> mi->j_xyspeed;
604 if(mi->flags & MOVEMENTFLAG_SPLINE)
606 CHECK_PACKET_SIZE(data, data.rpos()+4);
607 data >> mi->u_unk1;