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
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 ///- 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();
163 sLog.outError( "MOEP: %s (0x%.4X)",
164 LookupOpcodeName(packet->GetOpcode()),
165 packet->GetOpcode());
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());
176 OpcodeHandler
& opHandle
= opcodeTable
[packet
->GetOpcode()];
177 switch (opHandle
.status
)
179 case STATUS_LOGGEDIN
:
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
190 case STATUS_TRANSFER_PENDING
:
192 logUnexpectedOpcode(packet
, "the player has not logged in yet");
193 else if(_player
->IsInWorld())
194 logUnexpectedOpcode(packet
, "the player is still in world");
196 (this->*opHandle
.handler
)(*packet
);
199 // prevent cheating with skip queue wait
202 logUnexpectedOpcode(packet
, "the player not pass queue yet");
206 m_playerRecentlyLogout
= false;
207 (this->*opHandle
.handler
)(*packet
);
210 sLog
.outError( "SESSION: received not allowed opcode %s (0x%.4X)",
211 LookupOpcodeName(packet
->GetOpcode()),
212 packet
->GetOpcode());
220 ///- Cleanup socket pointer if need
221 if (m_Socket
&& m_Socket
->IsClosed ())
223 m_Socket
->RemoveReference ();
227 ///- If necessary, log the player out
228 time_t currTime
= time(NULL
);
229 if (!m_Socket
|| (ShouldLogOut(currTime
) && !m_playerLoading
))
233 return false; //Will remove this session from the world session map
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;
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
273 if(owner
->GetTypeId()==TYPEID_PLAYER
)
274 aset
.insert((Player
*)owner
);
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.
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 ///- Teleport to home if the player is in an invalid instance
307 if(!_player
->m_InstanceValid
&& !_player
->isGameMaster())
308 _player
->TeleportTo(_player
->m_homebindMapId
, _player
->m_homebindX
, _player
->m_homebindY
, _player
->m_homebindZ
, _player
->GetOrientation());
310 for (int i
=0; i
< PLAYER_MAX_BATTLEGROUND_QUEUES
; i
++)
312 if(int32 bgTypeId
= _player
->GetBattleGroundQueueId(i
))
314 _player
->RemoveBattleGroundQueueId(bgTypeId
);
315 sBattleGroundMgr
.m_BattleGroundQueues
[ bgTypeId
].RemovePlayer(_player
->GetGUID(), true);
319 ///- Reset the online field in the account table
320 // 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
321 //No SQL injection as AccountID is uint32
322 loginDatabase
.PExecute("UPDATE account SET online = 0 WHERE id = '%u'", GetAccountId());
324 ///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
325 Guild
*guild
= objmgr
.GetGuildById(_player
->GetGuildId());
328 guild
->LoadPlayerStatsByGuid(_player
->GetGUID());
329 guild
->UpdateLogoutTime(_player
->GetGUID());
331 WorldPacket
data(SMSG_GUILD_EVENT
, (1+1+12+8)); // name limited to 12 in character table.
332 data
<<(uint8
)GE_SIGNED_OFF
;
334 data
<<_player
->GetName();
335 data
<<_player
->GetGUID();
336 guild
->BroadcastPacket(&data
);
340 _player
->RemovePet(NULL
,PET_SAVE_AS_CURRENT
, true);
342 ///- empty buyback items and save the player in the database
343 // some save parts only correctly work in case player present in map/player_lists (pets, etc)
347 for(int j
= BUYBACK_SLOT_START
; j
< BUYBACK_SLOT_END
; j
++)
349 eslot
= j
- BUYBACK_SLOT_START
;
350 _player
->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+eslot
*2,0);
351 _player
->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1
+eslot
,0);
352 _player
->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+eslot
,0);
357 ///- Leave all channels before player delete...
358 _player
->CleanupChannels();
360 ///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
361 _player
->UninviteFromGroup();
363 // remove player from the group if he is:
364 // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
365 if(_player
->GetGroup() && !_player
->GetGroup()->isRaidGroup() && m_Socket
)
366 _player
->RemoveFromGroup();
368 ///- Remove the player from the world
369 // the player may not be in the world when logging out
370 // e.g if he got disconnected during a transfer to another map
371 // calls to GetMap in this case may cause crashes
372 if(_player
->IsInWorld()) _player
->GetMap()->Remove(_player
, false);
373 // RemoveFromWorld does cleanup that requires the player to be in the accessor
374 ObjectAccessor::Instance().RemoveObject(_player
);
376 ///- Send update to group
377 if(_player
->GetGroup())
378 _player
->GetGroup()->SendUpdate();
380 ///- Broadcast a logout message to the player's friends
381 sSocialMgr
.SendFriendStatus(_player
, FRIEND_OFFLINE
, _player
->GetGUIDLow(), true);
383 ///- Delete the player object
384 _player
->CleanupsBeforeDelete(); // do some cleanup before deleting to prevent crash at crossreferences to already deleted data
386 sSocialMgr
.RemovePlayerSocial (_player
->GetGUIDLow ());
390 ///- Send the 'logout complete' packet to the client
391 WorldPacket
data( SMSG_LOGOUT_COMPLETE
, 0 );
394 ///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
395 //No SQL injection as AccountId is uint32
396 CharacterDatabase
.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'",
398 sLog
.outDebug( "SESSION: Sent SMSG_LOGOUT_COMPLETE Message" );
401 m_playerLogout
= false;
402 m_playerRecentlyLogout
= true;
406 /// Kick a player out of the World
407 void WorldSession::KickPlayer()
410 m_Socket
->CloseSocket ();
413 /// Cancel channeling handler
415 void WorldSession::SendAreaTriggerMessage(const char* Text
, ...)
422 vsnprintf( szStr
, 1024, Text
, ap
);
425 uint32 length
= strlen(szStr
)+1;
426 WorldPacket
data(SMSG_AREA_TRIGGER_MESSAGE
, 4+length
);
432 void WorldSession::SendNotification(const char *format
,...)
439 va_start(ap
, format
);
440 vsnprintf( szStr
, 1024, format
, ap
);
443 WorldPacket
data(SMSG_NOTIFICATION
, (strlen(szStr
)+1));
449 void WorldSession::SendNotification(int32 string_id
,...)
451 char const* format
= GetMangosString(string_id
);
457 va_start(ap
, string_id
);
458 vsnprintf( szStr
, 1024, format
, ap
);
461 WorldPacket
data(SMSG_NOTIFICATION
, (strlen(szStr
)+1));
467 const char * WorldSession::GetMangosString( int32 entry
) const
469 return objmgr
.GetMangosString(entry
,GetSessionDbLocaleIndex());
472 void WorldSession::Handle_NULL( WorldPacket
& recvPacket
)
474 sLog
.outError( "SESSION: received unhandled opcode %s (0x%.4X)",
475 LookupOpcodeName(recvPacket
.GetOpcode()),
476 recvPacket
.GetOpcode());
479 void WorldSession::Handle_EarlyProccess( WorldPacket
& recvPacket
)
481 sLog
.outError( "SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead",
482 LookupOpcodeName(recvPacket
.GetOpcode()),
483 recvPacket
.GetOpcode());
486 void WorldSession::Handle_ServerSide( WorldPacket
& recvPacket
)
488 sLog
.outError( "SESSION: received server-side opcode %s (0x%.4X)",
489 LookupOpcodeName(recvPacket
.GetOpcode()),
490 recvPacket
.GetOpcode());
493 void WorldSession::Handle_Deprecated( WorldPacket
& recvPacket
)
495 sLog
.outError( "SESSION: received deprecated opcode %s (0x%.4X)",
496 LookupOpcodeName(recvPacket
.GetOpcode()),
497 recvPacket
.GetOpcode());
500 void WorldSession::SendAuthWaitQue(uint32 position
)
504 WorldPacket
packet( SMSG_AUTH_RESPONSE
, 1 );
505 packet
<< uint8( AUTH_OK
);
510 WorldPacket
packet( SMSG_AUTH_RESPONSE
, 5 );
511 packet
<< uint8( AUTH_WAIT_QUEUE
);
512 packet
<< uint32 (position
);
517 void WorldSession::LoadAccountData()
519 for (uint32 i
= 0; i
< NUM_ACCOUNT_DATA_TYPES
; ++i
)
522 m_accountData
[i
] = data
;
525 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT type, time, data FROM account_data WHERE account='%u'", GetAccountId());
532 Field
*fields
= result
->Fetch();
534 uint32 type
= fields
[0].GetUInt32();
535 if(type
< NUM_ACCOUNT_DATA_TYPES
)
537 m_accountData
[type
].Time
= fields
[1].GetUInt32();
538 m_accountData
[type
].Data
= fields
[2].GetCppString();
540 } while (result
->NextRow());
545 void WorldSession::SetAccountData(uint32 type
, time_t time_
, std::string data
)
547 m_accountData
[type
].Time
= time_
;
548 m_accountData
[type
].Data
= data
;
550 uint32 acc
= GetAccountId();
552 CharacterDatabase
.BeginTransaction ();
553 CharacterDatabase
.PExecute("DELETE FROM account_data WHERE account='%u' AND type='%u'", acc
, type
);
554 CharacterDatabase
.escape_string(data
);
555 CharacterDatabase
.PExecute("INSERT INTO account_data VALUES ('%u','%u','%u','%s')", acc
, type
, (uint32
)time_
, data
.c_str());
556 CharacterDatabase
.CommitTransaction ();
559 void WorldSession::ReadMovementInfo(WorldPacket
&data
, MovementInfo
*mi
)
561 CHECK_PACKET_SIZE(data
, data
.rpos()+4+2+4+4+4+4+4);
570 if(mi
->flags
& MOVEMENTFLAG_ONTRANSPORT
)
572 CHECK_PACKET_SIZE(data
, data
.rpos()+8+4+4+4+4+4+1);
582 if((mi
->flags
& (MOVEMENTFLAG_SWIMMING
| MOVEMENTFLAG_FLYING2
)) || (mi
->unk1
& 0x20))
584 CHECK_PACKET_SIZE(data
, data
.rpos()+4);
588 CHECK_PACKET_SIZE(data
, data
.rpos()+4);
589 data
>> mi
->fallTime
;
591 if(mi
->flags
& MOVEMENTFLAG_JUMPING
)
593 CHECK_PACKET_SIZE(data
, data
.rpos()+4+4+4+4);
595 data
>> mi
->j_sinAngle
;
596 data
>> mi
->j_cosAngle
;
597 data
>> mi
->j_xyspeed
;
600 if(mi
->flags
& MOVEMENTFLAG_SPLINE
)
602 CHECK_PACKET_SIZE(data
, data
.rpos()+4);