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
23 #include "WorldSocket.h"
25 #include "Database/DatabaseEnv.h"
28 #include "WorldSocket.h"
29 #include "WorldPacket.h"
30 #include "WorldSession.h"
32 #include "ObjectMgr.h"
36 #include "MapManager.h"
37 #include "ObjectAccessor.h"
38 #include "BattleGroundMgr.h"
39 #include "Language.h" // for CMSG_CANCEL_MOUNT_AURA handler
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)
52 m_Address
= sock
->GetRemoteAddress ();
53 sock
->AddReference ();
57 /// WorldSession destructor
58 WorldSession::~WorldSession()
60 ///- unload player if not unloaded
64 /// - If have unclosed socket, close it
67 m_Socket
->CloseSocket ();
68 m_Socket
->RemoveReference ();
72 ///- empty incoming packet queue
73 while(!_recvQueue
.empty())
75 WorldPacket
*packet
= _recvQueue
.next ();
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
)
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)
115 sendPacketBytes
+=packet
->size();
117 sendLastPacketCount
+=1;
118 sendLastPacketBytes
+=packet
->size();
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
);
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()),
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 ();
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();
172 sLog.outError( "MOEP: %s (0x%.4X)",
173 LookupOpcodeName(packet->GetOpcode()),
174 packet->GetOpcode());
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());
185 OpcodeHandler
& opHandle
= opcodeTable
[packet
->GetOpcode()];
186 switch (opHandle
.status
)
188 case STATUS_LOGGEDIN
:
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
199 case STATUS_TRANSFER_PENDING
:
201 logUnexpectedOpcode(packet
, "the player has not logged in yet");
202 else if(_player
->IsInWorld())
203 logUnexpectedOpcode(packet
, "the player is still in world");
205 (this->*opHandle
.handler
)(*packet
);
208 // prevent cheating with skip queue wait
211 logUnexpectedOpcode(packet
, "the player not pass queue yet");
215 m_playerRecentlyLogout
= false;
216 (this->*opHandle
.handler
)(*packet
);
219 sLog
.outError( "SESSION: received not allowed opcode %s (0x%.4X)",
220 LookupOpcodeName(packet
->GetOpcode()),
221 packet
->GetOpcode());
229 ///- If necessary, log the player out
230 time_t currTime
= time(NULL
);
231 if (!m_Socket
|| (ShouldLogOut(currTime
) && !m_playerLoading
))
235 return false; //Will remove this session from the world session map
240 /// %Log the player out
241 void WorldSession::LogoutPlayer(bool Save
)
243 // finish pending transfers before starting the logout
244 while(_player
&& _player
->IsBeingTeleported())
245 HandleMoveWorldportAckOpcode();
247 m_playerLogout
= true;
251 if (uint64 lguid
= GetPlayer()->GetLootGUID())
252 DoLootRelease(lguid
);
254 ///- If the player just died before logging out, make him appear as a ghost
255 //FIXME: logout must be delayed in case lost connection with client in time of combat
256 if (_player
->GetDeathTimer())
258 _player
->getHostilRefManager().deleteReferences();
259 _player
->BuildPlayerRepop();
260 _player
->RepopAtGraveyard();
262 else if (!_player
->getAttackers().empty())
264 _player
->CombatStop();
265 _player
->getHostilRefManager().setOnlineOfflineState(false);
266 _player
->RemoveAllAurasOnDeath();
268 // build set of player who attack _player or who have pet attacking of _player
269 std::set
<Player
*> aset
;
270 for(Unit::AttackerSet::const_iterator itr
= _player
->getAttackers().begin(); itr
!= _player
->getAttackers().end(); ++itr
)
272 Unit
* owner
= (*itr
)->GetOwner(); // including player controlled case
275 if(owner
->GetTypeId()==TYPEID_PLAYER
)
276 aset
.insert((Player
*)owner
);
279 if((*itr
)->GetTypeId()==TYPEID_PLAYER
)
280 aset
.insert((Player
*)(*itr
));
283 _player
->SetPvPDeath(!aset
.empty());
284 _player
->KillPlayer();
285 _player
->BuildPlayerRepop();
286 _player
->RepopAtGraveyard();
288 // give honor to all attackers from set like group case
289 for(std::set
<Player
*>::const_iterator itr
= aset
.begin(); itr
!= aset
.end(); ++itr
)
290 (*itr
)->RewardHonor(_player
,aset
.size());
292 // give bg rewards and update counters like kill by first from attackers
293 // this can't be called for all attackers.
295 if(BattleGround
*bg
= _player
->GetBattleGround())
296 bg
->HandleKillPlayer(_player
,*aset
.begin());
298 else if(_player
->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION
))
300 // this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
301 _player
->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT
);
302 //_player->SetDeathPvP(*); set at SPELL_AURA_SPIRIT_OF_REDEMPTION apply time
303 _player
->KillPlayer();
304 _player
->BuildPlayerRepop();
305 _player
->RepopAtGraveyard();
308 ///- Remove player from battleground (teleport to entrance)
309 if(_player
->InBattleGround())
310 _player
->LeaveBattleground();
312 for (int i
=0; i
< PLAYER_MAX_BATTLEGROUND_QUEUES
; i
++)
314 if(int32 bgTypeId
= _player
->GetBattleGroundQueueId(i
))
316 _player
->RemoveBattleGroundQueueId(bgTypeId
);
317 sBattleGroundMgr
.m_BattleGroundQueues
[ bgTypeId
].RemovePlayer(_player
->GetGUID(), true);
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());
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());
330 guild
->LoadPlayerStatsByGuid(_player
->GetGUID());
331 guild
->UpdateLogoutTime(_player
->GetGUID());
333 WorldPacket
data(SMSG_GUILD_EVENT
, (1+1+12+8)); // name limited to 12 in character table.
334 data
<<(uint8
)GE_SIGNED_OFF
;
336 data
<<_player
->GetName();
337 data
<<_player
->GetGUID();
338 guild
->BroadcastPacket(&data
);
342 _player
->RemovePet(NULL
,PET_SAVE_AS_CURRENT
, true);
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)
349 for(int j
= BUYBACK_SLOT_START
; j
< BUYBACK_SLOT_END
; j
++)
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);
359 ///- Leave all channels before player delete...
360 _player
->CleanupChannels();
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();
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();
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()) _player
->GetMap()->Remove(_player
, false);
375 // RemoveFromWorld does cleanup that requires the player to be in the accessor
376 ObjectAccessor::Instance().RemoveObject(_player
);
378 ///- Send update to group
379 if(_player
->GetGroup())
380 _player
->GetGroup()->SendUpdate();
382 ///- Broadcast a logout message to the player's friends
383 sSocialMgr
.SendFriendStatus(_player
, FRIEND_OFFLINE
, _player
->GetGUIDLow(), true);
385 ///- Delete the player object
386 _player
->CleanupsBeforeDelete(); // do some cleanup before deleting to prevent crash at crossreferences to already deleted data
388 sSocialMgr
.RemovePlayerSocial (_player
->GetGUIDLow ());
392 ///- Send the 'logout complete' packet to the client
393 WorldPacket
data( SMSG_LOGOUT_COMPLETE
, 0 );
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'",
400 sLog
.outDebug( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
403 m_playerLogout
= false;
404 m_playerRecentlyLogout
= true;
408 /// Kick a player out of the World
409 void WorldSession::KickPlayer()
412 m_Socket
->CloseSocket ();
415 /// Cancel channeling handler
417 void WorldSession::SendAreaTriggerMessage(const char* Text
, ...)
424 vsnprintf( szStr
, 1024, Text
, ap
);
427 uint32 length
= strlen(szStr
)+1;
428 WorldPacket
data(SMSG_AREA_TRIGGER_MESSAGE
, 4+length
);
434 void WorldSession::SendNotification(const char *format
,...)
441 va_start(ap
, format
);
442 vsnprintf( szStr
, 1024, format
, ap
);
445 WorldPacket
data(SMSG_NOTIFICATION
, (strlen(szStr
)+1));
451 void WorldSession::SendNotification(int32 string_id
,...)
453 char const* format
= GetMangosString(string_id
);
459 va_start(ap
, string_id
);
460 vsnprintf( szStr
, 1024, format
, ap
);
463 WorldPacket
data(SMSG_NOTIFICATION
, (strlen(szStr
)+1));
469 const char * WorldSession::GetMangosString( int32 entry
) const
471 return objmgr
.GetMangosString(entry
,GetSessionDbLocaleIndex());
474 void WorldSession::Handle_NULL( WorldPacket
& recvPacket
)
476 sLog
.outError( "SESSION: received unhandled opcode %s (0x%.4X)",
477 LookupOpcodeName(recvPacket
.GetOpcode()),
478 recvPacket
.GetOpcode());
481 void WorldSession::Handle_EarlyProccess( WorldPacket
& recvPacket
)
483 sLog
.outError( "SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead",
484 LookupOpcodeName(recvPacket
.GetOpcode()),
485 recvPacket
.GetOpcode());
488 void WorldSession::Handle_ServerSide( WorldPacket
& recvPacket
)
490 sLog
.outError( "SESSION: received server-side opcode %s (0x%.4X)",
491 LookupOpcodeName(recvPacket
.GetOpcode()),
492 recvPacket
.GetOpcode());
495 void WorldSession::Handle_Deprecated( WorldPacket
& recvPacket
)
497 sLog
.outError( "SESSION: received deprecated opcode %s (0x%.4X)",
498 LookupOpcodeName(recvPacket
.GetOpcode()),
499 recvPacket
.GetOpcode());
502 void WorldSession::SendAuthWaitQue(uint32 position
)
506 WorldPacket
packet( SMSG_AUTH_RESPONSE
, 1 );
507 packet
<< uint8( AUTH_OK
);
512 WorldPacket
packet( SMSG_AUTH_RESPONSE
, 5 );
513 packet
<< uint8( AUTH_WAIT_QUEUE
);
514 packet
<< uint32 (position
);