PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/src/game/WorldSession.cpp

https://bitbucket.org/oneb1t/crocoduckcore/
C++ | 578 lines | 408 code | 81 blank | 89 comment | 70 complexity | 94f411a2428c5acd3db7c81b5ac5983c MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. /*
  2. * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
  3. *
  4. * Copyright (C) 2008-2009 Trinity <http://www.trinitycore.org/>
  5. *
  6. * Copyright (C) 2010 Oregon <http://www.oregoncore.com/>
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, write to the Free Software
  20. * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  21. */
  22. #include "WorldSocket.h" // must be first to make ACE happy with ACE includes in it
  23. #include "Common.h"
  24. #include "Database/DatabaseEnv.h"
  25. #include "Log.h"
  26. #include "Opcodes.h"
  27. #include "WorldPacket.h"
  28. #include "WorldSession.h"
  29. #include "Player.h"
  30. #include "ObjectMgr.h"
  31. #include "Group.h"
  32. #include "Guild.h"
  33. #include "World.h"
  34. #include "ObjectAccessor.h"
  35. #include "BattleGroundMgr.h"
  36. #include "OutdoorPvPMgr.h"
  37. #include "MapManager.h"
  38. #include "Chat.h"
  39. #include "SocialMgr.h"
  40. #include "ScriptMgr.h"
  41. // WorldSession constructor
  42. WorldSession::WorldSession(uint32 id, WorldSocket *sock, uint32 sec, uint8 expansion, time_t mute_time, LocaleConstant locale) :
  43. LookingForGroup_auto_join(false), LookingForGroup_auto_add(false), m_muteTime(mute_time),
  44. _player(NULL), m_Socket(sock),_security(sec), _accountId(id), m_expansion(expansion),
  45. m_sessionDbcLocale(sWorld.GetAvailableDbcLocale(locale)), m_sessionDbLocaleIndex(objmgr.GetIndexForLocale(locale)),
  46. _logoutTime(0), m_inQueue(false), m_playerLoading(false), m_playerLogout(false), m_playerRecentlyLogout(false), m_playerSave(false),
  47. m_latency(0), m_timeOutTime(0)
  48. {
  49. if (sock)
  50. {
  51. m_Address = sock->GetRemoteAddress();
  52. sock->AddReference();
  53. ResetTimeOutTime();
  54. LoginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = %u;", GetAccountId());
  55. }
  56. }
  57. // WorldSession destructor
  58. WorldSession::~WorldSession()
  59. {
  60. // unload player if not unloaded
  61. if (_player)
  62. LogoutPlayer(true);
  63. // If have unclosed socket, close it
  64. if (m_Socket)
  65. {
  66. m_Socket->CloseSocket();
  67. m_Socket->RemoveReference();
  68. m_Socket = NULL;
  69. }
  70. // empty incoming packet queue
  71. WorldPacket* packet;
  72. while (_recvQueue.next(packet))
  73. delete packet;
  74. LoginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = %u;", GetAccountId());
  75. CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = %u;", GetAccountId());
  76. }
  77. void WorldSession::SizeError(WorldPacket const& packet, uint32 size) const
  78. {
  79. sLog.outError("Client (account %u) send packet %s (%u) with size " SIZEFMTD " but expected %u (attempt crash server?), skipped",
  80. GetAccountId(), LookupOpcodeName(packet.GetOpcode()), packet.GetOpcode(), packet.size(), size);
  81. }
  82. // Get the player name
  83. char const* WorldSession::GetPlayerName() const
  84. {
  85. return GetPlayer() ? GetPlayer()->GetName() : "<none>";
  86. }
  87. // Send a packet to the client
  88. void WorldSession::SendPacket(WorldPacket const* packet)
  89. {
  90. if (!m_Socket)
  91. return;
  92. #ifdef OREGON_DEBUG
  93. // Code for network use statistic
  94. static uint64 sendPacketCount = 0;
  95. static uint64 sendPacketBytes = 0;
  96. static time_t firstTime = time(NULL);
  97. static time_t lastTime = firstTime; // next 60 secs start time
  98. static uint64 sendLastPacketCount = 0;
  99. static uint64 sendLastPacketBytes = 0;
  100. time_t cur_time = time(NULL);
  101. if ((cur_time - lastTime) < 60)
  102. {
  103. sendPacketCount+=1;
  104. sendPacketBytes+=packet->size();
  105. sendLastPacketCount+=1;
  106. sendLastPacketBytes+=packet->size();
  107. }
  108. else
  109. {
  110. uint64 minTime = uint64(cur_time - lastTime);
  111. uint64 fullTime = uint64(lastTime - firstTime);
  112. sLog.outDetail("Send all time packets count: " UI64FMTD " bytes: " UI64FMTD " avr.count/sec: %f avr.bytes/sec: %f time: %u",sendPacketCount,sendPacketBytes,float(sendPacketCount)/fullTime,float(sendPacketBytes)/fullTime,uint32(fullTime));
  113. sLog.outDetail("Send last min packets count: " UI64FMTD " bytes: " UI64FMTD " avr.count/sec: %f avr.bytes/sec: %f",sendLastPacketCount,sendLastPacketBytes,float(sendLastPacketCount)/minTime,float(sendLastPacketBytes)/minTime);
  114. lastTime = cur_time;
  115. sendLastPacketCount = 1;
  116. sendLastPacketBytes = packet->wpos(); // wpos is real written size
  117. }
  118. #endif // !OREGON_DEBUG
  119. if (m_Socket->SendPacket(*packet) == -1)
  120. m_Socket->CloseSocket();
  121. }
  122. // Add an incoming packet to the queue
  123. void WorldSession::QueuePacket(WorldPacket* new_packet)
  124. {
  125. _recvQueue.add(new_packet);
  126. }
  127. // Logging helper for unexpected opcodes
  128. void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, const char *reason)
  129. {
  130. sLog.outError("SESSION: received unexpected opcode %s (0x%.4X) %s",
  131. LookupOpcodeName(packet->GetOpcode()),
  132. packet->GetOpcode(),
  133. reason);
  134. }
  135. // Logging helper for unexpected opcodes
  136. void WorldSession::LogUnprocessedTail(WorldPacket *packet)
  137. {
  138. sLog.outError("SESSION: opcode %s (0x%.4X) has unprocessed tail data (read stop at %u from %u)",
  139. LookupOpcodeName(packet->GetOpcode()),
  140. packet->GetOpcode(),
  141. packet->rpos(),packet->wpos());
  142. }
  143. // Update the WorldSession (triggered by World update)
  144. bool WorldSession::Update(uint32 diff)
  145. {
  146. /// Update Timeout timer.
  147. UpdateTimeOutTime(diff);
  148. ///- Before we process anything:
  149. /// If necessary, kick the player from the character select screen
  150. if (IsConnectionIdle())
  151. m_Socket->CloseSocket();
  152. // Retrieve packets from the receive queue and call the appropriate handlers
  153. // not proccess packets if socket already closed
  154. WorldPacket* packet;
  155. while (m_Socket && !m_Socket->IsClosed() && _recvQueue.next(packet))
  156. {
  157. /*#if 1
  158. sLog.outError("MOEP: %s (0x%.4X)",
  159. LookupOpcodeName(packet->GetOpcode()),
  160. packet->GetOpcode());
  161. #endif*/
  162. if (packet->GetOpcode() >= NUM_MSG_TYPES)
  163. {
  164. sLog.outError("SESSION: received invalid opcode %s (0x%.4X)",
  165. LookupOpcodeName(packet->GetOpcode()),
  166. packet->GetOpcode());
  167. }
  168. else
  169. {
  170. OpcodeHandler& opHandle = opcodeTable[packet->GetOpcode()];
  171. try
  172. {
  173. switch (opHandle.status)
  174. {
  175. case STATUS_LOGGEDIN:
  176. if (!_player)
  177. {
  178. // skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
  179. if (!m_playerRecentlyLogout)
  180. LogUnexpectedOpcode(packet, "the player has not logged in yet");
  181. }
  182. else if (_player->IsInWorld())
  183. ExecuteOpcode(opHandle, packet);
  184. // lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
  185. break;
  186. case STATUS_TRANSFER_PENDING:
  187. if (!_player)
  188. LogUnexpectedOpcode(packet, "the player has not logged in yet");
  189. else if (_player->IsInWorld())
  190. LogUnexpectedOpcode(packet, "the player is still in world");
  191. else
  192. ExecuteOpcode(opHandle, packet);
  193. break;
  194. case STATUS_AUTHED:
  195. // prevent cheating with skip queue wait
  196. if (m_inQueue)
  197. {
  198. LogUnexpectedOpcode(packet, "the player not pass queue yet");
  199. break;
  200. }
  201. m_playerRecentlyLogout = false;
  202. ExecuteOpcode(opHandle, packet);
  203. break;
  204. case STATUS_NEVER:
  205. sLog.outError("SESSION: received not allowed opcode %s (0x%.4X)",
  206. LookupOpcodeName(packet->GetOpcode()),
  207. packet->GetOpcode());
  208. break;
  209. }
  210. }
  211. catch(ByteBufferException &)
  212. {
  213. sLog.outError("WorldSession::Update ByteBufferException occured while parsing a packet (opcode: %u) from client %s, accountid=%i. Skipped packet.",
  214. packet->GetOpcode(), GetRemoteAddress().c_str(), GetAccountId());
  215. if (sLog.IsOutDebug())
  216. {
  217. sLog.outDebug("Dumping error causing packet:");
  218. packet->hexlike();
  219. }
  220. }
  221. }
  222. delete packet;
  223. }
  224. ///- If necessary, log the player out
  225. time_t currTime = time(NULL);
  226. if (ShouldLogOut(currTime) && !m_playerLoading)
  227. LogoutPlayer(true);
  228. // Cleanup socket pointer if need
  229. if (m_Socket && m_Socket->IsClosed())
  230. {
  231. m_Socket->RemoveReference();
  232. m_Socket = NULL;
  233. }
  234. if (!m_Socket)
  235. return false; //Will remove this session from the world session map
  236. return true;
  237. }
  238. // Log the player out
  239. void WorldSession::LogoutPlayer(bool Save)
  240. {
  241. // finish pending transfers before starting the logout
  242. while (_player && _player->IsBeingTeleportedFar())
  243. HandleMoveWorldportAckOpcode();
  244. m_playerLogout = true;
  245. m_playerSave = Save;
  246. if (_player)
  247. {
  248. if (uint64 lguid = GetPlayer()->GetLootGUID())
  249. DoLootRelease(lguid);
  250. // If the player just died before logging out, make him appear as a ghost
  251. // FIXME: logout must be delayed in case lost connection with client in time of combat
  252. if (_player->GetDeathTimer())
  253. {
  254. _player->getHostileRefManager().deleteReferences();
  255. _player->BuildPlayerRepop();
  256. _player->RepopAtGraveyard();
  257. }
  258. else if (!_player->getAttackers().empty())
  259. {
  260. _player->CombatStop();
  261. _player->getHostileRefManager().setOnlineOfflineState(false);
  262. _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)
  266. {
  267. Unit* owner = (*itr)->GetOwner(); // including player controlled case
  268. if (owner)
  269. {
  270. if (owner->GetTypeId() == TYPEID_PLAYER)
  271. aset.insert(owner->ToPlayer());
  272. }
  273. else
  274. if ((*itr)->GetTypeId() == TYPEID_PLAYER)
  275. aset.insert((*itr)->ToPlayer());
  276. }
  277. _player->SetPvPDeath(!aset.empty());
  278. _player->KillPlayer();
  279. _player->BuildPlayerRepop();
  280. _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());
  284. // give bg rewards and update counters like kill by first from attackers
  285. // this can't be called for all attackers.
  286. if (!aset.empty())
  287. if (BattleGround *bg = _player->GetBattleGround())
  288. bg->HandleKillPlayer(_player,*aset.begin());
  289. }
  290. else if (_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
  291. {
  292. // this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
  293. _player->RemoveSpellsCausingAura(SPELL_AURA_MOD_SHAPESHIFT);
  294. //_player->SetDeathPvP(*); set at SPELL_AURA_SPIRIT_OF_REDEMPTION apply time
  295. _player->KillPlayer();
  296. _player->BuildPlayerRepop();
  297. _player->RepopAtGraveyard();
  298. }
  299. //drop a flag if player is carrying it
  300. if (BattleGround *bg = _player->GetBattleGround())
  301. bg->EventPlayerLoggedOut(_player);
  302. // Teleport to home if the player is in an invalid instance
  303. if (!_player->m_InstanceValid && !_player->isGameMaster())
  304. {
  305. _player->TeleportToHomebind();
  306. //this is a bad place to call for far teleport because we need player to be in world for successful logout
  307. //maybe we should implement delayed far teleport logout?
  308. }
  309. // FG: finish pending transfers after starting the logout
  310. // this should fix players beeing able to logout and login back with full hp at death position
  311. while (_player->IsBeingTeleportedFar())
  312. HandleMoveWorldportAckOpcode();
  313. sOutdoorPvPMgr.HandlePlayerLeaveZone(_player,_player->GetZoneId());
  314. for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
  315. {
  316. if (int32 bgTypeId = _player->GetBattleGroundQueueId(i))
  317. {
  318. _player->RemoveBattleGroundQueueId(bgTypeId);
  319. sBattleGroundMgr.m_BattleGroundQueues[ bgTypeId ].RemovePlayer(_player->GetGUID(), true);
  320. }
  321. }
  322. // If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
  323. if (Guild *guild = objmgr.GetGuildById(_player->GetGuildId()))
  324. {
  325. guild->LoadPlayerStatsByGuid(_player->GetGUID());
  326. guild->UpdateLogoutTime(_player->GetGUID());
  327. guild->BroadcastEvent(GE_SIGNED_OFF, _player->GetGUID(), _player->GetName());
  328. }
  329. // Remove pet
  330. _player->RemovePet(NULL, PET_SAVE_AS_CURRENT, true);
  331. // empty buyback items and save the player in the database
  332. // some save parts only correctly work in case player present in map/player_lists (pets, etc)
  333. if (Save)
  334. {
  335. uint32 eslot;
  336. for (int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; ++j)
  337. {
  338. eslot = j - BUYBACK_SLOT_START;
  339. _player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0);
  340. _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
  341. _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
  342. }
  343. _player->SaveToDB();
  344. }
  345. // Leave all channels before player delete...
  346. _player->CleanupChannels();
  347. // If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
  348. _player->UninviteFromGroup();
  349. // remove player from the group if he is:
  350. // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
  351. if (_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
  352. _player->RemoveFromGroup();
  353. // Send update to group
  354. if (_player->GetGroup())
  355. _player->GetGroup()->SendUpdate();
  356. // Broadcast a logout message to the player's friends
  357. sSocialMgr.SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUIDLow(), true);
  358. sSocialMgr.RemovePlayerSocial (_player->GetGUIDLow ());
  359. // Remove the player from the world
  360. // the player may not be in the world when logging out
  361. // e.g if he got disconnected during a transfer to another map
  362. // calls to GetMap in this case may cause crashes
  363. _player->CleanupsBeforeDelete();
  364. Map* _map = _player->GetMap();
  365. _map->Remove(_player, true);
  366. _player = NULL; // deleted in Remove call
  367. // Send the 'logout complete' packet to the client
  368. WorldPacket data(SMSG_LOGOUT_COMPLETE, 0);
  369. SendPacket(&data);
  370. // Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
  371. //No SQL injection as AccountId is uint32
  372. CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'",
  373. GetAccountId());
  374. sLog.outDebug("SESSION: Sent SMSG_LOGOUT_COMPLETE Message");
  375. }
  376. //Hook for OnLogout Event
  377. sScriptMgr.OnLogout(_player);
  378. m_playerLogout = false;
  379. m_playerSave = false;
  380. m_playerRecentlyLogout = true;
  381. LogoutRequest(0);
  382. }
  383. // Kick a player out of the World
  384. void WorldSession::KickPlayer()
  385. {
  386. if (m_Socket)
  387. m_Socket->CloseSocket();
  388. }
  389. // Cancel channeling handler
  390. void WorldSession::SendAreaTriggerMessage(const char* Text, ...)
  391. {
  392. va_list ap;
  393. char szStr [1024];
  394. szStr[0] = '\0';
  395. va_start(ap, Text);
  396. vsnprintf(szStr, 1024, Text, ap);
  397. va_end(ap);
  398. uint32 length = strlen(szStr)+1;
  399. WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4+length);
  400. data << length;
  401. data << szStr;
  402. SendPacket(&data);
  403. }
  404. void WorldSession::SendNotification(const char *format,...)
  405. {
  406. if (format)
  407. {
  408. va_list ap;
  409. char szStr [1024];
  410. szStr[0] = '\0';
  411. va_start(ap, format);
  412. vsnprintf(szStr, 1024, format, ap);
  413. va_end(ap);
  414. WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
  415. data << szStr;
  416. SendPacket(&data);
  417. }
  418. }
  419. void WorldSession::SendNotification(int32 string_id,...)
  420. {
  421. char const* format = GetOregonString(string_id);
  422. if (format)
  423. {
  424. va_list ap;
  425. char szStr [1024];
  426. szStr[0] = '\0';
  427. va_start(ap, string_id);
  428. vsnprintf(szStr, 1024, format, ap);
  429. va_end(ap);
  430. WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr)+1));
  431. data << szStr;
  432. SendPacket(&data);
  433. }
  434. }
  435. const char * WorldSession::GetOregonString(int32 entry) const
  436. {
  437. return objmgr.GetOregonString(entry,GetSessionDbLocaleIndex());
  438. }
  439. void WorldSession::Handle_NULL(WorldPacket& recvPacket)
  440. {
  441. sLog.outError("SESSION: received unhandled opcode %s (0x%.4X)",
  442. LookupOpcodeName(recvPacket.GetOpcode()),
  443. recvPacket.GetOpcode());
  444. }
  445. void WorldSession::Handle_EarlyProccess(WorldPacket& recvPacket)
  446. {
  447. sLog.outError("SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead",
  448. LookupOpcodeName(recvPacket.GetOpcode()),
  449. recvPacket.GetOpcode());
  450. }
  451. void WorldSession::Handle_ServerSide(WorldPacket& recvPacket)
  452. {
  453. sLog.outError("SESSION: received server-side opcode %s (0x%.4X)",
  454. LookupOpcodeName(recvPacket.GetOpcode()),
  455. recvPacket.GetOpcode());
  456. }
  457. void WorldSession::Handle_Deprecated(WorldPacket& recvPacket)
  458. {
  459. sLog.outError("SESSION: received deprecated opcode %s (0x%.4X)",
  460. LookupOpcodeName(recvPacket.GetOpcode()),
  461. recvPacket.GetOpcode());
  462. }
  463. void WorldSession::SendAuthWaitQue(uint32 position)
  464. {
  465. if (position == 0)
  466. {
  467. WorldPacket packet(SMSG_AUTH_RESPONSE, 1);
  468. packet << uint8(AUTH_OK);
  469. SendPacket(&packet);
  470. }
  471. else
  472. {
  473. WorldPacket packet(SMSG_AUTH_RESPONSE, 5);
  474. packet << uint8(AUTH_WAIT_QUEUE);
  475. packet << uint32(position);
  476. SendPacket(&packet);
  477. }
  478. }
  479. void WorldSession::ExecuteOpcode(OpcodeHandler const& opHandle, WorldPacket* packet)
  480. {
  481. // need prevent do internal far teleports in handlers because some handlers do lot steps
  482. // or call code that can do far teleports in some conditions unexpectedly for generic way work code
  483. if (_player)
  484. _player->SetCanDelayTeleport(true);
  485. (this->*opHandle.handler)(*packet);
  486. if (_player)
  487. {
  488. // can be not set in fact for login opcode, but this not create porblems.
  489. _player->SetCanDelayTeleport(false);
  490. //we should execute delayed teleports only for alive(!) players
  491. //because we don't want player's ghost teleported from graveyard
  492. if (_player->IsHasDelayedTeleport())
  493. _player->TeleportTo(_player->m_teleport_dest, _player->m_teleport_options);
  494. }
  495. if (packet->rpos() < packet->wpos())
  496. LogUnprocessedTail(packet);
  497. }