PageRenderTime 60ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/src/server/game/Server/WorldSession.cpp

https://gitlab.com/IlluminatiCore/IlluminatiCore
C++ | 1480 lines | 1151 code | 202 blank | 127 comment | 178 complexity | c6cefbb2ebbcb0801deb78cf51a620f5 MD5 | raw file
Possible License(s): GPL-2.0, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

  1. /*
  2. * Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
  3. * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the
  7. * Free Software Foundation; either version 2 of the License, or (at your
  8. * option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful, but WITHOUT
  11. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  13. * more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. /** \file
  19. \ingroup u2w
  20. */
  21. #include "WorldSocket.h"
  22. #include <zlib.h>
  23. #include "Config.h"
  24. #include "Common.h"
  25. #include "DatabaseEnv.h"
  26. #include "AccountMgr.h"
  27. #include "Log.h"
  28. #include "Opcodes.h"
  29. #include "WorldPacket.h"
  30. #include "WorldSession.h"
  31. #include "Player.h"
  32. #include "Vehicle.h"
  33. #include "ObjectMgr.h"
  34. #include "GuildMgr.h"
  35. #include "Group.h"
  36. #include "Guild.h"
  37. #include "World.h"
  38. #include "ObjectAccessor.h"
  39. #include "BattlegroundMgr.h"
  40. #include "OutdoorPvPMgr.h"
  41. #include "MapManager.h"
  42. #include "SocialMgr.h"
  43. #include "zlib.h"
  44. #include "ScriptMgr.h"
  45. #include "Transport.h"
  46. #include "WardenWin.h"
  47. #include "WardenMac.h"
  48. #include "BattlenetServerManager.h"
  49. namespace {
  50. std::string const DefaultPlayerName = "<none>";
  51. } // namespace
  52. bool MapSessionFilter::Process(WorldPacket* packet)
  53. {
  54. OpcodeHandler const* opHandle = opcodeTable[packet->GetOpcode()];
  55. //let's check if our opcode can be really processed in Map::Update()
  56. if (opHandle->ProcessingPlace == PROCESS_INPLACE)
  57. return true;
  58. //we do not process thread-unsafe packets
  59. if (opHandle->ProcessingPlace == PROCESS_THREADUNSAFE)
  60. return false;
  61. Player* player = m_pSession->GetPlayer();
  62. if (!player)
  63. return false;
  64. //in Map::Update() we do not process packets where player is not in world!
  65. return player->IsInWorld();
  66. }
  67. //we should process ALL packets when player is not in world/logged in
  68. //OR packet handler is not thread-safe!
  69. bool WorldSessionFilter::Process(WorldPacket* packet)
  70. {
  71. OpcodeHandler const* opHandle = opcodeTable[packet->GetOpcode()];
  72. //check if packet handler is supposed to be safe
  73. if (opHandle->ProcessingPlace == PROCESS_INPLACE)
  74. return true;
  75. //thread-unsafe packets should be processed in World::UpdateSessions()
  76. if (opHandle->ProcessingPlace == PROCESS_THREADUNSAFE)
  77. return true;
  78. //no player attached? -> our client! ^^
  79. Player* player = m_pSession->GetPlayer();
  80. if (!player)
  81. return true;
  82. //lets process all packets for non-in-the-world player
  83. return (player->IsInWorld() == false);
  84. }
  85. /// WorldSession constructor
  86. WorldSession::WorldSession(uint32 id, uint32 battlenetAccountId, std::shared_ptr<WorldSocket> sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale, uint32 recruiter, bool isARecruiter):
  87. m_muteTime(mute_time),
  88. m_timeOutTime(0),
  89. AntiDOS(this),
  90. m_GUIDLow(0),
  91. _player(NULL),
  92. m_Socket(sock),
  93. _security(sec),
  94. _accountId(id),
  95. _battlenetAccountId(battlenetAccountId),
  96. m_expansion(expansion),
  97. _warden(NULL),
  98. _logoutTime(0),
  99. m_inQueue(false),
  100. m_playerLoading(false),
  101. m_playerLogout(false),
  102. m_playerRecentlyLogout(false),
  103. m_playerSave(false),
  104. m_sessionDbcLocale(sWorld->GetAvailableDbcLocale(locale)),
  105. m_sessionDbLocaleIndex(locale),
  106. m_latency(0),
  107. m_clientTimeDelay(0),
  108. m_TutorialsChanged(false),
  109. _filterAddonMessages(false),
  110. recruiterId(recruiter),
  111. isRecruiter(isARecruiter),
  112. _RBACData(NULL),
  113. expireTime(60000), // 1 min after socket loss, session is deleted
  114. forceExit(false),
  115. m_currentBankerGUID()
  116. {
  117. memset(m_Tutorials, 0, sizeof(m_Tutorials));
  118. if (sock)
  119. {
  120. m_Address = sock->GetRemoteIpAddress().to_string();
  121. ResetTimeOutTime();
  122. LoginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = %u;", GetAccountId()); // One-time query
  123. }
  124. InitializeQueryCallbackParameters();
  125. _compressionStream = new z_stream();
  126. _compressionStream->zalloc = (alloc_func)NULL;
  127. _compressionStream->zfree = (free_func)NULL;
  128. _compressionStream->opaque = (voidpf)NULL;
  129. _compressionStream->avail_in = 0;
  130. _compressionStream->next_in = NULL;
  131. int32 z_res = deflateInit(_compressionStream, sWorld->getIntConfig(CONFIG_COMPRESSION));
  132. if (z_res != Z_OK)
  133. TC_LOG_ERROR("network", "Can't initialize packet compression (zlib: deflateInit) Error code: %i (%s)", z_res, zError(z_res));
  134. }
  135. /// WorldSession destructor
  136. WorldSession::~WorldSession()
  137. {
  138. ///- unload player if not unloaded
  139. if (_player)
  140. LogoutPlayer (true);
  141. /// - If have unclosed socket, close it
  142. if (m_Socket)
  143. {
  144. m_Socket->CloseSocket();
  145. m_Socket = nullptr;
  146. }
  147. delete _warden;
  148. delete _RBACData;
  149. ///- empty incoming packet queue
  150. WorldPacket* packet = NULL;
  151. while (_recvQueue.next(packet))
  152. delete packet;
  153. LoginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = %u;", GetAccountId()); // One-time query
  154. int32 z_res = deflateEnd(_compressionStream);
  155. if (z_res != Z_OK && z_res != Z_DATA_ERROR) // Z_DATA_ERROR signals that internal state was BUSY
  156. TC_LOG_ERROR("network", "Can't close packet compression stream (zlib: deflateEnd) Error code: %i (%s)", z_res, zError(z_res));
  157. delete _compressionStream;
  158. }
  159. std::string const & WorldSession::GetPlayerName() const
  160. {
  161. return _player != NULL ? _player->GetName() : DefaultPlayerName;
  162. }
  163. std::string WorldSession::GetPlayerInfo() const
  164. {
  165. std::ostringstream ss;
  166. ss << "[Player: " << GetPlayerName() << " (";
  167. if (_player != NULL)
  168. ss << _player->GetGUID().ToString() << ", ";
  169. ss << "Account: " << GetAccountId() << ")]";
  170. return ss.str();
  171. }
  172. /// Get player guid if available. Use for logging purposes only
  173. uint32 WorldSession::GetGuidLow() const
  174. {
  175. return GetPlayer() ? GetPlayer()->GetGUIDLow() : 0;
  176. }
  177. /// Send a packet to the client
  178. void WorldSession::SendPacket(WorldPacket* packet, bool forced /*= false*/)
  179. {
  180. if (!m_Socket)
  181. return;
  182. if (packet->GetOpcode() == NULL_OPCODE)
  183. {
  184. TC_LOG_ERROR("network.opcode", "Prevented sending of NULL_OPCODE to %s", GetPlayerInfo().c_str());
  185. return;
  186. }
  187. else if (packet->GetOpcode() == UNKNOWN_OPCODE)
  188. {
  189. TC_LOG_ERROR("network.opcode", "Prevented sending of UNKNOWN_OPCODE to %s", GetPlayerInfo().c_str());
  190. return;
  191. }
  192. if (!forced)
  193. {
  194. OpcodeHandler const* handler = opcodeTable[packet->GetOpcode()];
  195. if (!handler || handler->Status == STATUS_UNHANDLED)
  196. {
  197. TC_LOG_ERROR("network.opcode", "Prevented sending disabled opcode %s to %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str(), GetPlayerInfo().c_str());
  198. return;
  199. }
  200. }
  201. #ifdef TRINITY_DEBUG
  202. // Code for network use statistic
  203. static uint64 sendPacketCount = 0;
  204. static uint64 sendPacketBytes = 0;
  205. static time_t firstTime = time(NULL);
  206. static time_t lastTime = firstTime; // next 60 secs start time
  207. static uint64 sendLastPacketCount = 0;
  208. static uint64 sendLastPacketBytes = 0;
  209. time_t cur_time = time(NULL);
  210. if ((cur_time - lastTime) < 60)
  211. {
  212. sendPacketCount+=1;
  213. sendPacketBytes+=packet->size();
  214. sendLastPacketCount+=1;
  215. sendLastPacketBytes+=packet->size();
  216. }
  217. else
  218. {
  219. uint64 minTime = uint64(cur_time - lastTime);
  220. uint64 fullTime = uint64(lastTime - firstTime);
  221. TC_LOG_INFO("misc", "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));
  222. TC_LOG_INFO("misc", "Send last min packets count: " UI64FMTD " bytes: " UI64FMTD " avr.count/sec: %f avr.bytes/sec: %f", sendLastPacketCount, sendLastPacketBytes, float(sendLastPacketCount)/minTime, float(sendLastPacketBytes)/minTime);
  223. lastTime = cur_time;
  224. sendLastPacketCount = 1;
  225. sendLastPacketBytes = packet->wpos(); // wpos is real written size
  226. }
  227. #endif // !TRINITY_DEBUG
  228. sScriptMgr->OnPacketSend(this, *packet);
  229. m_Socket->SendPacket(*packet);
  230. }
  231. /// Add an incoming packet to the queue
  232. void WorldSession::QueuePacket(WorldPacket* new_packet)
  233. {
  234. _recvQueue.add(new_packet);
  235. }
  236. /// Logging helper for unexpected opcodes
  237. void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, const char* status, const char *reason)
  238. {
  239. TC_LOG_ERROR("network.opcode", "Received unexpected opcode %s Status: %s Reason: %s from %s",
  240. GetOpcodeNameForLogging(packet->GetOpcode()).c_str(), status, reason, GetPlayerInfo().c_str());
  241. }
  242. /// Logging helper for unexpected opcodes
  243. void WorldSession::LogUnprocessedTail(WorldPacket* packet)
  244. {
  245. if (!sLog->ShouldLog("network.opcode", LOG_LEVEL_TRACE) || packet->rpos() >= packet->wpos())
  246. return;
  247. TC_LOG_TRACE("network.opcode", "Unprocessed tail data (read stop at %u from %u) Opcode %s from %s",
  248. uint32(packet->rpos()), uint32(packet->wpos()), GetOpcodeNameForLogging(packet->GetOpcode()).c_str(), GetPlayerInfo().c_str());
  249. packet->print_storage();
  250. }
  251. /// Update the WorldSession (triggered by World update)
  252. bool WorldSession::Update(uint32 diff, PacketFilter& updater)
  253. {
  254. /// Update Timeout timer.
  255. UpdateTimeOutTime(diff);
  256. ///- Before we process anything:
  257. /// If necessary, kick the player from the character select screen
  258. if (IsConnectionIdle())
  259. m_Socket->CloseSocket();
  260. ///- Retrieve packets from the receive queue and call the appropriate handlers
  261. /// not process packets if socket already closed
  262. WorldPacket* packet = NULL;
  263. //! Delete packet after processing by default
  264. bool deletePacket = true;
  265. //! To prevent infinite loop
  266. WorldPacket* firstDelayedPacket = NULL;
  267. //! If _recvQueue.peek() == firstDelayedPacket it means that in this Update call, we've processed all
  268. //! *properly timed* packets, and we're now at the part of the queue where we find
  269. //! delayed packets that were re-enqueued due to improper timing. To prevent an infinite
  270. //! loop caused by re-enqueueing the same packets over and over again, we stop updating this session
  271. //! and continue updating others. The re-enqueued packets will be handled in the next Update call for this session.
  272. uint32 processedPackets = 0;
  273. time_t currentTime = time(NULL);
  274. while (m_Socket && !_recvQueue.empty() && _recvQueue.peek(true) != firstDelayedPacket && _recvQueue.next(packet, updater))
  275. {
  276. if (!AntiDOS.EvaluateOpcode(*packet, currentTime))
  277. KickPlayer();
  278. OpcodeHandler const* opHandle = opcodeTable[packet->GetOpcode()];
  279. try
  280. {
  281. switch (opHandle->Status)
  282. {
  283. case STATUS_LOGGEDIN:
  284. if (!_player)
  285. {
  286. // skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
  287. //! If player didn't log out a while ago, it means packets are being sent while the server does not recognize
  288. //! the client to be in world yet. We will re-add the packets to the bottom of the queue and process them later.
  289. if (!m_playerRecentlyLogout)
  290. {
  291. //! Prevent infinite loop
  292. if (!firstDelayedPacket)
  293. firstDelayedPacket = packet;
  294. //! Because checking a bool is faster than reallocating memory
  295. deletePacket = false;
  296. QueuePacket(packet);
  297. //! Log
  298. TC_LOG_DEBUG("network", "Re-enqueueing packet with opcode %s with with status STATUS_LOGGEDIN. "
  299. "Player is currently not in world yet.", GetOpcodeNameForLogging(packet->GetOpcode()).c_str());
  300. }
  301. }
  302. else if (_player->IsInWorld())
  303. {
  304. sScriptMgr->OnPacketReceive(this, *packet);
  305. (this->*opHandle->Handler)(*packet);
  306. LogUnprocessedTail(packet);
  307. }
  308. // lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
  309. break;
  310. case STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT:
  311. if (!_player && !m_playerRecentlyLogout && !m_playerLogout) // There's a short delay between _player = null and m_playerRecentlyLogout = true during logout
  312. LogUnexpectedOpcode(packet, "STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT",
  313. "the player has not logged in yet and not recently logout");
  314. else
  315. {
  316. // not expected _player or must checked in packet hanlder
  317. sScriptMgr->OnPacketReceive(this, *packet);
  318. (this->*opHandle->Handler)(*packet);
  319. LogUnprocessedTail(packet);
  320. }
  321. break;
  322. case STATUS_TRANSFER:
  323. if (!_player)
  324. LogUnexpectedOpcode(packet, "STATUS_TRANSFER", "the player has not logged in yet");
  325. else if (_player->IsInWorld())
  326. LogUnexpectedOpcode(packet, "STATUS_TRANSFER", "the player is still in world");
  327. else
  328. {
  329. sScriptMgr->OnPacketReceive(this, *packet);
  330. (this->*opHandle->Handler)(*packet);
  331. LogUnprocessedTail(packet);
  332. }
  333. break;
  334. case STATUS_AUTHED:
  335. // prevent cheating with skip queue wait
  336. if (m_inQueue)
  337. {
  338. LogUnexpectedOpcode(packet, "STATUS_AUTHED", "the player not pass queue yet");
  339. break;
  340. }
  341. // some auth opcodes can be recieved before STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT opcodes
  342. // however when we recieve CMSG_CHAR_ENUM we are surely no longer during the logout process.
  343. if (packet->GetOpcode() == CMSG_CHAR_ENUM)
  344. m_playerRecentlyLogout = false;
  345. sScriptMgr->OnPacketReceive(this, *packet);
  346. (this->*opHandle->Handler)(*packet);
  347. LogUnprocessedTail(packet);
  348. break;
  349. case STATUS_NEVER:
  350. TC_LOG_ERROR("network.opcode", "Received not allowed opcode %s from %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str()
  351. , GetPlayerInfo().c_str());
  352. break;
  353. case STATUS_UNHANDLED:
  354. TC_LOG_ERROR("network.opcode", "Received not handled opcode %s from %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str()
  355. , GetPlayerInfo().c_str());
  356. break;
  357. }
  358. }
  359. catch (ByteBufferException const&)
  360. {
  361. TC_LOG_ERROR("network", "WorldSession::Update ByteBufferException occured while parsing a packet (opcode: %u) from client %s, accountid=%i. Skipped packet.",
  362. packet->GetOpcode(), GetRemoteAddress().c_str(), GetAccountId());
  363. packet->hexlike();
  364. }
  365. if (deletePacket)
  366. delete packet;
  367. deletePacket = true;
  368. #define MAX_PROCESSED_PACKETS_IN_SAME_WORLDSESSION_UPDATE 100
  369. processedPackets++;
  370. //process only a max amout of packets in 1 Update() call.
  371. //Any leftover will be processed in next update
  372. if (processedPackets > MAX_PROCESSED_PACKETS_IN_SAME_WORLDSESSION_UPDATE)
  373. break;
  374. }
  375. if (m_Socket && m_Socket->IsOpen() && _warden)
  376. _warden->Update();
  377. ProcessQueryCallbacks();
  378. //check if we are safe to proceed with logout
  379. //logout procedure should happen only in World::UpdateSessions() method!!!
  380. if (updater.ProcessLogout())
  381. {
  382. time_t currTime = time(NULL);
  383. ///- If necessary, log the player out
  384. if (ShouldLogOut(currTime) && !m_playerLoading)
  385. LogoutPlayer(true);
  386. if (m_Socket && GetPlayer() && _warden)
  387. _warden->Update();
  388. ///- Cleanup socket pointer if need
  389. if (m_Socket && !m_Socket->IsOpen())
  390. {
  391. expireTime -= expireTime > diff ? diff : expireTime;
  392. if (expireTime < diff || forceExit || !GetPlayer())
  393. {
  394. m_Socket = nullptr;
  395. }
  396. }
  397. if (!m_Socket)
  398. return false; //Will remove this session from the world session map
  399. }
  400. return true;
  401. }
  402. /// %Log the player out
  403. void WorldSession::LogoutPlayer(bool save)
  404. {
  405. // finish pending transfers before starting the logout
  406. while (_player && _player->IsBeingTeleportedFar())
  407. HandleMoveWorldportAckOpcode();
  408. m_playerLogout = true;
  409. m_playerSave = save;
  410. if (_player)
  411. {
  412. if (ObjectGuid lguid = _player->GetLootGUID())
  413. DoLootRelease(lguid);
  414. ///- If the player just died before logging out, make him appear as a ghost
  415. if (_player->GetDeathTimer())
  416. {
  417. _player->getHostileRefManager().deleteReferences();
  418. _player->BuildPlayerRepop();
  419. _player->RepopAtGraveyard();
  420. }
  421. else if (_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
  422. {
  423. // this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
  424. _player->RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT);
  425. _player->KillPlayer();
  426. _player->BuildPlayerRepop();
  427. _player->RepopAtGraveyard();
  428. }
  429. else if (_player->HasPendingBind())
  430. {
  431. _player->RepopAtGraveyard();
  432. _player->SetPendingBind(0, 0);
  433. }
  434. //drop a flag if player is carrying it
  435. if (Battleground* bg = _player->GetBattleground())
  436. bg->EventPlayerLoggedOut(_player);
  437. ///- Teleport to home if the player is in an invalid instance
  438. if (!_player->m_InstanceValid && !_player->IsGameMaster())
  439. _player->TeleportTo(_player->m_homebindMapId, _player->m_homebindX, _player->m_homebindY, _player->m_homebindZ, _player->GetOrientation());
  440. sOutdoorPvPMgr->HandlePlayerLeaveZone(_player, _player->GetZoneId());
  441. for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
  442. {
  443. if (BattlegroundQueueTypeId bgQueueTypeId = _player->GetBattlegroundQueueTypeId(i))
  444. {
  445. _player->RemoveBattlegroundQueueId(bgQueueTypeId);
  446. BattlegroundQueue& queue = sBattlegroundMgr->GetBattlegroundQueue(bgQueueTypeId);
  447. queue.RemovePlayer(_player->GetGUID(), true);
  448. }
  449. }
  450. // Repop at GraveYard or other player far teleport will prevent saving player because of not present map
  451. // Teleport player immediately for correct player save
  452. while (_player->IsBeingTeleportedFar())
  453. HandleMoveWorldportAckOpcode();
  454. ///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
  455. if (Guild* guild = sGuildMgr->GetGuildById(_player->GetGuildId()))
  456. guild->HandleMemberLogout(this);
  457. ///- Remove pet
  458. _player->RemovePet(NULL, PET_SAVE_AS_CURRENT, true);
  459. ///- Clear whisper whitelist
  460. _player->ClearWhisperWhiteList();
  461. ///- empty buyback items and save the player in the database
  462. // some save parts only correctly work in case player present in map/player_lists (pets, etc)
  463. if (save)
  464. {
  465. uint32 eslot;
  466. for (int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; ++j)
  467. {
  468. eslot = j - BUYBACK_SLOT_START;
  469. _player->SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), ObjectGuid::Empty);
  470. _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
  471. _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
  472. }
  473. _player->SaveToDB();
  474. }
  475. ///- Leave all channels before player delete...
  476. _player->CleanupChannels();
  477. ///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
  478. _player->UninviteFromGroup();
  479. // remove player from the group if he is:
  480. // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
  481. if (_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
  482. _player->RemoveFromGroup();
  483. //! Send update to group and reset stored max enchanting level
  484. if (_player->GetGroup())
  485. {
  486. _player->GetGroup()->SendUpdate();
  487. _player->GetGroup()->ResetMaxEnchantingLevel();
  488. }
  489. //! Broadcast a logout message to the player's friends
  490. sSocialMgr->SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUIDLow(), true);
  491. sSocialMgr->RemovePlayerSocial(_player->GetGUIDLow());
  492. //! Call script hook before deletion
  493. sScriptMgr->OnPlayerLogout(_player);
  494. //! Remove the player from the world
  495. // the player may not be in the world when logging out
  496. // e.g if he got disconnected during a transfer to another map
  497. // calls to GetMap in this case may cause crashes
  498. _player->CleanupsBeforeDelete();
  499. TC_LOG_INFO("entities.player.character", "Account: %d (IP: %s) Logout Character:[%s] (GUID: %u) Level: %d",
  500. GetAccountId(), GetRemoteAddress().c_str(), _player->GetName().c_str(), _player->GetGUIDLow(), _player->getLevel());
  501. sBattlenetServer.SendChangeToonOnlineState(GetBattlenetAccountId(), GetAccountId(), _player->GetGUID(), _player->GetName(), false);
  502. if (Map* _map = _player->FindMap())
  503. _map->RemovePlayerFromMap(_player, true);
  504. SetPlayer(NULL); //! Pointer already deleted during RemovePlayerFromMap
  505. //! Send the 'logout complete' packet to the client
  506. //! Client will respond by sending 3x CMSG_CANCEL_TRADE, which we currently dont handle
  507. WorldPacket data(SMSG_LOGOUT_COMPLETE, 0);
  508. SendPacket(&data);
  509. TC_LOG_DEBUG("network", "SESSION: Sent SMSG_LOGOUT_COMPLETE Message");
  510. //! Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
  511. PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ACCOUNT_ONLINE);
  512. stmt->setUInt32(0, GetAccountId());
  513. CharacterDatabase.Execute(stmt);
  514. }
  515. m_playerLogout = false;
  516. m_playerSave = false;
  517. m_playerRecentlyLogout = true;
  518. LogoutRequest(0);
  519. }
  520. /// Kick a player out of the World
  521. void WorldSession::KickPlayer()
  522. {
  523. if (m_Socket)
  524. {
  525. m_Socket->CloseSocket();
  526. forceExit = true;
  527. }
  528. }
  529. void WorldSession::SendNotification(const char *format, ...)
  530. {
  531. if (format)
  532. {
  533. va_list ap;
  534. char szStr[1024];
  535. szStr[0] = '\0';
  536. va_start(ap, format);
  537. vsnprintf(szStr, 1024, format, ap);
  538. va_end(ap);
  539. size_t len = strlen(szStr);
  540. WorldPacket data(SMSG_NOTIFICATION, 2 + len);
  541. data.WriteBits(len, 13);
  542. data.FlushBits();
  543. data.append(szStr, len);
  544. SendPacket(&data);
  545. }
  546. }
  547. void WorldSession::SendNotification(uint32 string_id, ...)
  548. {
  549. char const* format = GetTrinityString(string_id);
  550. if (format)
  551. {
  552. va_list ap;
  553. char szStr[1024];
  554. szStr[0] = '\0';
  555. va_start(ap, string_id);
  556. vsnprintf(szStr, 1024, format, ap);
  557. va_end(ap);
  558. size_t len = strlen(szStr);
  559. WorldPacket data(SMSG_NOTIFICATION, 2 + len);
  560. data.WriteBits(len, 13);
  561. data.FlushBits();
  562. data.append(szStr, len);
  563. SendPacket(&data);
  564. }
  565. }
  566. char const* WorldSession::GetTrinityString(uint32 entry) const
  567. {
  568. return sObjectMgr->GetTrinityString(entry, GetSessionDbLocaleIndex());
  569. }
  570. void WorldSession::Handle_NULL(WorldPacket& recvPacket)
  571. {
  572. TC_LOG_ERROR("network.opcode", "Received unhandled opcode %s from %s"
  573. , GetOpcodeNameForLogging(recvPacket.GetOpcode()).c_str(), GetPlayerInfo().c_str());
  574. }
  575. void WorldSession::Handle_EarlyProccess(WorldPacket& recvPacket)
  576. {
  577. TC_LOG_ERROR("network.opcode", "Received opcode %s that must be processed in WorldSocket::OnRead from %s"
  578. , GetOpcodeNameForLogging(recvPacket.GetOpcode()).c_str(), GetPlayerInfo().c_str());
  579. }
  580. void WorldSession::Handle_ServerSide(WorldPacket& recvPacket)
  581. {
  582. TC_LOG_ERROR("network.opcode", "Received server-side opcode %s from %s"
  583. , GetOpcodeNameForLogging(recvPacket.GetOpcode()).c_str(), GetPlayerInfo().c_str());
  584. }
  585. void WorldSession::Handle_Deprecated(WorldPacket& recvPacket)
  586. {
  587. TC_LOG_ERROR("network.opcode", "Received deprecated opcode %s from %s"
  588. , GetOpcodeNameForLogging(recvPacket.GetOpcode()).c_str(), GetPlayerInfo().c_str());
  589. }
  590. void WorldSession::SendAuthWaitQue(uint32 position)
  591. {
  592. if (position == 0)
  593. {
  594. WorldPacket packet(SMSG_AUTH_RESPONSE, 1);
  595. packet.WriteBit(0); // has queue info
  596. packet.WriteBit(0); // has account info
  597. packet.FlushBits();
  598. packet << uint8(AUTH_OK);
  599. SendPacket(&packet);
  600. }
  601. else
  602. {
  603. WorldPacket packet(SMSG_AUTH_RESPONSE, 6);
  604. packet.WriteBit(1); // has queue info
  605. packet.WriteBit(0); // unk queue bool
  606. packet.WriteBit(0); // has account info
  607. packet.FlushBits();
  608. packet << uint8(AUTH_WAIT_QUEUE);
  609. packet << uint32(position);
  610. SendPacket(&packet);
  611. }
  612. }
  613. void WorldSession::LoadGlobalAccountData()
  614. {
  615. PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ACCOUNT_DATA);
  616. stmt->setUInt32(0, GetAccountId());
  617. LoadAccountData(CharacterDatabase.Query(stmt), GLOBAL_CACHE_MASK);
  618. }
  619. void WorldSession::LoadAccountData(PreparedQueryResult result, uint32 mask)
  620. {
  621. for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
  622. if (mask & (1 << i))
  623. m_accountData[i] = AccountData();
  624. if (!result)
  625. return;
  626. do
  627. {
  628. Field* fields = result->Fetch();
  629. uint32 type = fields[0].GetUInt8();
  630. if (type >= NUM_ACCOUNT_DATA_TYPES)
  631. {
  632. TC_LOG_ERROR("misc", "Table `%s` have invalid account data type (%u), ignore.",
  633. mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
  634. continue;
  635. }
  636. if ((mask & (1 << type)) == 0)
  637. {
  638. TC_LOG_ERROR("misc", "Table `%s` have non appropriate for table account data type (%u), ignore.",
  639. mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
  640. continue;
  641. }
  642. m_accountData[type].Time = time_t(fields[1].GetUInt32());
  643. m_accountData[type].Data = fields[2].GetString();
  644. }
  645. while (result->NextRow());
  646. }
  647. void WorldSession::SetAccountData(AccountDataType type, time_t tm, std::string const& data)
  648. {
  649. uint32 id = 0;
  650. uint32 index = 0;
  651. if ((1 << type) & GLOBAL_CACHE_MASK)
  652. {
  653. id = GetAccountId();
  654. index = CHAR_REP_ACCOUNT_DATA;
  655. }
  656. else
  657. {
  658. // _player can be NULL and packet received after logout but m_GUID still store correct guid
  659. if (!m_GUIDLow)
  660. return;
  661. id = m_GUIDLow;
  662. index = CHAR_REP_PLAYER_ACCOUNT_DATA;
  663. }
  664. PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(index);
  665. stmt->setUInt32(0, id);
  666. stmt->setUInt8 (1, type);
  667. stmt->setUInt32(2, uint32(tm));
  668. stmt->setString(3, data);
  669. CharacterDatabase.Execute(stmt);
  670. m_accountData[type].Time = tm;
  671. m_accountData[type].Data = data;
  672. }
  673. void WorldSession::SendAccountDataTimes(uint32 mask)
  674. {
  675. WorldPacket data(SMSG_ACCOUNT_DATA_TIMES, 4 + 1 + 4 + NUM_ACCOUNT_DATA_TYPES * 4);
  676. data << uint32(time(NULL)); // Server time
  677. data << uint8(1);
  678. data << uint32(mask); // type mask
  679. for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
  680. if (mask & (1 << i))
  681. data << uint32(GetAccountData(AccountDataType(i))->Time);// also unix time
  682. SendPacket(&data);
  683. }
  684. void WorldSession::LoadTutorialsData()
  685. {
  686. memset(m_Tutorials, 0, sizeof(uint32) * MAX_ACCOUNT_TUTORIAL_VALUES);
  687. PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_TUTORIALS);
  688. stmt->setUInt32(0, GetAccountId());
  689. if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
  690. for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
  691. m_Tutorials[i] = (*result)[i].GetUInt32();
  692. m_TutorialsChanged = false;
  693. }
  694. void WorldSession::SendTutorialsData()
  695. {
  696. WorldPacket data(SMSG_TUTORIAL_FLAGS, 4 * MAX_ACCOUNT_TUTORIAL_VALUES);
  697. for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
  698. data << m_Tutorials[i];
  699. SendPacket(&data);
  700. }
  701. void WorldSession::SaveTutorialsData(SQLTransaction &trans)
  702. {
  703. if (!m_TutorialsChanged)
  704. return;
  705. PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_HAS_TUTORIALS);
  706. stmt->setUInt32(0, GetAccountId());
  707. bool hasTutorials = bool(CharacterDatabase.Query(stmt));
  708. // Modify data in DB
  709. stmt = CharacterDatabase.GetPreparedStatement(hasTutorials ? CHAR_UPD_TUTORIALS : CHAR_INS_TUTORIALS);
  710. for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
  711. stmt->setUInt32(i, m_Tutorials[i]);
  712. stmt->setUInt32(MAX_ACCOUNT_TUTORIAL_VALUES, GetAccountId());
  713. trans->Append(stmt);
  714. m_TutorialsChanged = false;
  715. }
  716. void WorldSession::ReadAddonsInfo(WorldPacket &data)
  717. {
  718. if (data.rpos() + 4 > data.size())
  719. return;
  720. uint32 size;
  721. data >> size;
  722. if (!size)
  723. return;
  724. if (size > 0xFFFFF)
  725. {
  726. TC_LOG_ERROR("misc", "WorldSession::ReadAddonsInfo addon info too big, size %u", size);
  727. return;
  728. }
  729. uLongf uSize = size;
  730. uint32 pos = data.rpos();
  731. ByteBuffer addonInfo;
  732. addonInfo.resize(size);
  733. if (uncompress(addonInfo.contents(), &uSize, data.contents() + pos, data.size() - pos) == Z_OK)
  734. {
  735. uint32 addonsCount;
  736. addonInfo >> addonsCount; // addons count
  737. for (uint32 i = 0; i < addonsCount; ++i)
  738. {
  739. std::string addonName;
  740. uint8 enabled;
  741. uint32 crc, unk1;
  742. // check next addon data format correctness
  743. if (addonInfo.rpos() + 1 > addonInfo.size())
  744. return;
  745. addonInfo >> addonName;
  746. addonInfo >> enabled >> crc >> unk1;
  747. TC_LOG_INFO("misc", "ADDON: Name: %s, Enabled: 0x%x, CRC: 0x%x, Unknown2: 0x%x", addonName.c_str(), enabled, crc, unk1);
  748. AddonInfo addon(addonName, enabled, crc, 2, true);
  749. SavedAddon const* savedAddon = AddonMgr::GetAddonInfo(addonName);
  750. if (savedAddon)
  751. {
  752. if (addon.CRC != savedAddon->CRC)
  753. TC_LOG_INFO("misc", "ADDON: %s was known, but didn't match known CRC (0x%x)!", addon.Name.c_str(), savedAddon->CRC);
  754. else
  755. TC_LOG_INFO("misc", "ADDON: %s was known, CRC is correct (0x%x)", addon.Name.c_str(), savedAddon->CRC);
  756. }
  757. else
  758. {
  759. AddonMgr::SaveAddon(addon);
  760. TC_LOG_INFO("misc", "ADDON: %s (0x%x) was not known, saving...", addon.Name.c_str(), addon.CRC);
  761. }
  762. /// @todo Find out when to not use CRC/pubkey, and other possible states.
  763. m_addonsList.push_back(addon);
  764. }
  765. uint32 currentTime;
  766. addonInfo >> currentTime;
  767. TC_LOG_DEBUG("network", "ADDON: CurrentTime: %u", currentTime);
  768. }
  769. else
  770. TC_LOG_ERROR("misc", "Addon packet uncompress error!");
  771. }
  772. void WorldSession::SendAddonsInfo()
  773. {
  774. uint8 addonPublicKey[256] =
  775. {
  776. 0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54,
  777. 0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75,
  778. 0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34,
  779. 0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8,
  780. 0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8,
  781. 0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A,
  782. 0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3,
  783. 0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9,
  784. 0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22,
  785. 0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E,
  786. 0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB,
  787. 0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7,
  788. 0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0,
  789. 0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6,
  790. 0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A,
  791. 0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2
  792. };
  793. WorldPacket data(SMSG_ADDON_INFO, 4);
  794. for (AddonsList::iterator itr = m_addonsList.begin(); itr != m_addonsList.end(); ++itr)
  795. {
  796. data << uint8(itr->State);
  797. uint8 crcpub = itr->UsePublicKeyOrCRC;
  798. data << uint8(crcpub);
  799. if (crcpub)
  800. {
  801. uint8 usepk = (itr->CRC != STANDARD_ADDON_CRC); // If addon is Standard addon CRC
  802. data << uint8(usepk);
  803. if (usepk) // if CRC is wrong, add public key (client need it)
  804. {
  805. TC_LOG_INFO("misc", "ADDON: CRC (0x%x) for addon %s is wrong (does not match expected 0x%x), sending pubkey",
  806. itr->CRC, itr->Name.c_str(), STANDARD_ADDON_CRC);
  807. data.append(addonPublicKey, sizeof(addonPublicKey));
  808. }
  809. data << uint32(0); /// @todo Find out the meaning of this.
  810. }
  811. data << uint8(0); // uses URL
  812. //if (usesURL)
  813. // data << uint8(0); // URL
  814. }
  815. m_addonsList.clear();
  816. AddonMgr::BannedAddonList const* bannedAddons = AddonMgr::GetBannedAddons();
  817. data << uint32(bannedAddons->size());
  818. for (AddonMgr::BannedAddonList::const_iterator itr = bannedAddons->begin(); itr != bannedAddons->end(); ++itr)
  819. {
  820. data << uint32(itr->Id);
  821. data.append(itr->NameMD5, sizeof(itr->NameMD5));
  822. data.append(itr->VersionMD5, sizeof(itr->VersionMD5));
  823. data << uint32(itr->Timestamp);
  824. data << uint32(1); // IsBanned
  825. }
  826. SendPacket(&data);
  827. }
  828. bool WorldSession::IsAddonRegistered(const std::string& prefix) const
  829. {
  830. if (!_filterAddonMessages) // if we have hit the softcap (64) nothing should be filtered
  831. return true;
  832. if (_registeredAddonPrefixes.empty())
  833. return false;
  834. std::vector<std::string>::const_iterator itr = std::find(_registeredAddonPrefixes.begin(), _registeredAddonPrefixes.end(), prefix);
  835. return itr != _registeredAddonPrefixes.end();
  836. }
  837. void WorldSession::HandleUnregisterAddonPrefixesOpcode(WorldPacket& /*recvPacket*/) // empty packet
  838. {
  839. TC_LOG_DEBUG("network", "WORLD: Received CMSG_UNREGISTER_ALL_ADDON_PREFIXES");
  840. _registeredAddonPrefixes.clear();
  841. }
  842. void WorldSession::HandleAddonRegisteredPrefixesOpcode(WorldPacket& recvPacket)
  843. {
  844. TC_LOG_DEBUG("network", "WORLD: Received CMSG_ADDON_REGISTERED_PREFIXES");
  845. // This is always sent after CMSG_UNREGISTER_ALL_ADDON_PREFIXES
  846. uint32 count = recvPacket.ReadBits(25);
  847. if (count > REGISTERED_ADDON_PREFIX_SOFTCAP)
  848. {
  849. // if we have hit the softcap (64) nothing should be filtered
  850. _filterAddonMessages = false;
  851. recvPacket.rfinish();
  852. return;
  853. }
  854. std::vector<uint8> lengths(count);
  855. for (uint32 i = 0; i < count; ++i)
  856. lengths[i] = recvPacket.ReadBits(5);
  857. for (uint32 i = 0; i < count; ++i)
  858. _registeredAddonPrefixes.push_back(recvPacket.ReadString(lengths[i]));
  859. if (_registeredAddonPrefixes.size() > REGISTERED_ADDON_PREFIX_SOFTCAP) // shouldn't happen
  860. {
  861. _filterAddonMessages = false;
  862. return;
  863. }
  864. _filterAddonMessages = true;
  865. }
  866. void WorldSession::SetPlayer(Player* player)
  867. {
  868. _player = player;
  869. // set m_GUID that can be used while player loggined and later until m_playerRecentlyLogout not reset
  870. if (_player)
  871. m_GUIDLow = _player->GetGUIDLow();
  872. }
  873. void WorldSession::InitializeQueryCallbackParameters()
  874. {
  875. // Callback parameters that have pointers in them should be properly
  876. // initialized to NULL here.
  877. _charCreateCallback.SetParam(NULL);
  878. }
  879. void WorldSession::ProcessQueryCallbacks()
  880. {
  881. PreparedQueryResult result;
  882. //! HandleCharEnumOpcode
  883. if (_charEnumCallback.valid() && _charEnumCallback.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
  884. {
  885. result = _charEnumCallback.get();
  886. HandleCharEnum(result);
  887. }
  888. if (_charCreateCallback.IsReady())
  889. {
  890. _charCreateCallback.GetResult(result);
  891. HandleCharCreateCallback(result, _charCreateCallback.GetParam());
  892. }
  893. //! HandlePlayerLoginOpcode
  894. if (_charLoginCallback.valid() && _charLoginCallback.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
  895. {
  896. SQLQueryHolder* param = _charLoginCallback.get();
  897. HandlePlayerLogin((LoginQueryHolder*)param);
  898. }
  899. //! HandleAddFriendOpcode
  900. if (_addFriendCallback.IsReady())
  901. {
  902. std::string param = _addFriendCallback.GetParam();
  903. _addFriendCallback.GetResult(result);
  904. HandleAddFriendOpcodeCallBack(result, param);
  905. _addFriendCallback.FreeResult();
  906. }
  907. //- HandleCharRenameOpcode
  908. if (_charRenameCallback.IsReady())
  909. {
  910. std::string param = _charRenameCallback.GetParam();
  911. _charRenameCallback.GetResult(result);
  912. HandleChangePlayerNameOpcodeCallBack(result, param);
  913. _charRenameCallback.FreeResult();
  914. }
  915. //- HandleCharAddIgnoreOpcode
  916. if (_addIgnoreCallback.valid() && _addIgnoreCallback.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
  917. {
  918. result = _addIgnoreCallback.get();
  919. HandleAddIgnoreOpcodeCallBack(result);
  920. }
  921. //- SendStabledPet
  922. if (_sendStabledPetCallback.IsReady())
  923. {
  924. ObjectGuid param = _sendStabledPetCallback.GetParam();
  925. _sendStabledPetCallback.GetResult(result);
  926. SendStablePetCallback(result, param);
  927. _sendStabledPetCallback.FreeResult();
  928. }
  929. //- HandleStablePet
  930. if (_stablePetCallback.valid() && _stablePetCallback.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
  931. {
  932. result = _stablePetCallback.get();
  933. HandleStablePetCallback(result);
  934. }
  935. //- HandleUnstablePet
  936. if (_unstablePetCallback.IsReady())
  937. {
  938. uint32 param = _unstablePetCallback.GetParam();
  939. _unstablePetCallback.GetResult(result);
  940. HandleUnstablePetCallback(result, param);
  941. _unstablePetCallback.FreeResult();
  942. }
  943. //- HandleStableSwapPet
  944. if (_stableSwapCallback.IsReady())
  945. {
  946. uint32 param = _stableSwapCallback.GetParam();
  947. _stableSwapCallback.GetResult(result);
  948. HandleStableSwapPetCallback(result, param);
  949. _stableSwapCallback.FreeResult();
  950. }
  951. }
  952. void WorldSession::InitWarden(BigNumber* k, std::string const& os)
  953. {
  954. if (os == "Win")
  955. {
  956. _warden = new WardenWin();
  957. _warden->Init(this, k);
  958. }
  959. else if (os == "OSX")
  960. {
  961. // Disabled as it is causing the client to crash
  962. // _warden = new WardenMac();
  963. // _warden->Init(this, k);
  964. }
  965. }
  966. void WorldSession::LoadPermissions()
  967. {
  968. uint32 id = GetAccountId();
  969. std::string name;
  970. AccountMgr::GetName(id, name);
  971. uint8 secLevel = GetSecurity();
  972. _RBACData = new rbac::RBACData(id, name, realmHandle.Index, secLevel);
  973. _RBACData->LoadFromDB();
  974. TC_LOG_DEBUG("rbac", "WorldSession::LoadPermissions [AccountId: %u, Name: %s, realmId: %d, secLevel: %u]",
  975. id, name.c_str(), realmHandle.Index, secLevel);
  976. }
  977. rbac::RBACData* WorldSession::GetRBACData()
  978. {
  979. return _RBACData;
  980. }
  981. bool WorldSession::HasPermission(uint32 permission)
  982. {
  983. if (!_RBACData)
  984. LoadPermissions();
  985. bool hasPermission = _RBACData->HasPermission(permission);
  986. TC_LOG_DEBUG("rbac", "WorldSession::HasPermission [AccountId: %u, Name: %s, realmId: %d]",
  987. _RBACData->GetId(), _RBACData->GetName().c_str(), realmHandle.Index);
  988. return hasPermission;
  989. }
  990. void WorldSession::InvalidateRBACData()
  991. {
  992. TC_LOG_DEBUG("rbac", "WorldSession::Invalidaterbac::RBACData [AccountId: %u, Name: %s, realmId: %d]",
  993. _RBACData->GetId(), _RBACData->GetName().c_str(), realmHandle.Index);
  994. delete _RBACData;
  995. _RBACData = NULL;
  996. }
  997. bool WorldSession::DosProtection::EvaluateOpcode(WorldPacket& p, time_t time) const
  998. {
  999. uint32 maxPacketCounterAllowed = GetMaxPacketCounterAllowed(p.GetOpcode());
  1000. // Return true if there no limit for the opcode
  1001. if (!maxPacketCounterAllowed)
  1002. return true;
  1003. PacketCounter& packetCounter = _PacketThrottlingMap[p.GetOpcode()];
  1004. if (packetCounter.lastReceiveTime != time)
  1005. {
  1006. packetCounter.lastReceiveTime = time;
  1007. packetCounter.amountCounter = 0;
  1008. }
  1009. // Check if player is flooding some packets
  1010. if (++packetCounter.amountCounter <= maxPacketCounterAllowed)
  1011. return true;
  1012. TC_LOG_WARN("network", "AntiDOS: Account %u, IP: %s, Ping: %u, Character: %s, flooding packet (opc: %s (0x%X), count: %u)",
  1013. Session->GetAccountId(), Session->GetRemoteAddress().c_str(), Session->GetLatency(), Session->GetPlayerName().c_str(),
  1014. opcodeTable[p.GetOpcode()]->Name, p.GetOpcode(), packetCounter.amountCounter);
  1015. switch (_policy)
  1016. {
  1017. case POLICY_LOG:
  1018. return true;
  1019. case POLICY_KICK:
  1020. TC_LOG_INFO("network", "AntiDOS: Player kicked!");
  1021. return false;
  1022. case POLICY_BAN:
  1023. {
  1024. BanMode bm = (BanMode)sWorld->getIntConfig(CONFIG_PACKET_SPOOF_BANMODE);
  1025. uint32 duration = sWorld->getIntConfig(CONFIG_PACKET_SPOOF_BANDURATION); // in seconds
  1026. std::string nameOrIp = "";
  1027. switch (bm)
  1028. {
  1029. case BAN_CHARACTER: // not supported, ban account
  1030. case BAN_ACCOUNT: (void)sAccountMgr->GetName(Session->GetAccountId(), nameOrIp); break;
  1031. case BAN_IP: nameOrIp = Session->GetRemoteAddress(); break;
  1032. }
  1033. sWorld->BanAccount(bm, nameOrIp, duration, "DOS (Packet Flooding/Spoofing", "Server: AutoDOS");
  1034. TC_LOG_INFO("network", "AntiDOS: Player automatically banned for %u seconds.", duration);
  1035. return false;
  1036. }
  1037. default: // invalid policy
  1038. return true;
  1039. }
  1040. }
  1041. uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) const
  1042. {
  1043. uint32 maxPacketCounterAllowed;
  1044. switch (opcode)
  1045. {
  1046. // CPU usage sending 2000 packets/second on a 3.70 GHz 4 cores on Win x64
  1047. // [% CPU mysqld] [%CPU worldserver RelWithDebInfo]
  1048. case CMSG_PLAYER_LOGIN: // 0 0.5
  1049. case CMSG_NAME_QUERY: // 0 1
  1050. case CMSG_PET_NAME_QUERY: // 0 1
  1051. case CMSG_NPC_TEXT_QUERY: // 0 1
  1052. case CMSG_ATTACKSTOP: // 0 1
  1053. case CMSG_QUERY_QUESTS_COMPLETED: // 0 1
  1054. case CMSG_QUERY_TIME: // 0 1
  1055. case CMSG_CORPSE_MAP_POSITION_QUERY: // 0 1
  1056. case CMSG_MOVE_TIME_SKIPPED: // 0 1
  1057. case MSG_QUERY_NEXT_MAIL_TIME: // 0 1
  1058. case CMSG_SETSHEATHED: // 0 1
  1059. case MSG_RAID_TARGET_UPDATE: // 0 1
  1060. case CMSG_PLAYER_LOGOUT: // 0 1
  1061. case CMSG_LOGOUT_REQUEST: // 0 1
  1062. case CMSG_PET_RENAME: // 0 1
  1063. case CMSG_QUESTGIVER_REQUEST_REWARD: // 0 1
  1064. case CMSG_COMPLETE_CINEMATIC: // 0 1
  1065. case CMSG_BANKER_ACTIVATE: // 0 1
  1066. case CMSG_BUY_BANK_SLOT: // 0 1
  1067. case CMSG_OPT_OUT_OF_LOOT: // 0 1
  1068. case CMSG_DUEL_ACCEPTED: // 0 1
  1069. case CMSG_DUEL_CANCELLED: // 0 1
  1070. case CMSG_CALENDAR_COMPLAIN: // 0 1
  1071. case CMSG_QUEST_QUERY: // 0 1.5
  1072. case CMSG_GAMEOBJECT_QUERY: // 0 1.5
  1073. case CMSG_CREATURE_QUERY: // 0 1.5
  1074. case CMSG_QUESTGIVER_STATUS_QUERY: // 0 1.5
  1075. case CMSG_GUILD_QUERY: // 0 1.5
  1076. case CMSG_ARENA_TEAM_QUERY: // 0 1.5
  1077. case CMSG_TAXINODE_STATUS_QUERY: // 0 1.5
  1078. case CMSG_TAXIQUERYAVAILABLENODES: // 0 1.5
  1079. case CMSG_QUESTGIVER_QUERY_QUEST: // 0 1.5
  1080. case CMSG_PAGE_TEXT_QUERY: // 0 1.5
  1081. case CMSG_GUILD_BANK_QUERY_TEXT: // 0 1.5
  1082. case MSG_CORPSE_QUERY: // 0 1.5
  1083. case MSG_MOVE_SET_FACING: // 0 1.5
  1084. case CMSG_REQUEST_PARTY_MEMBER_STATS: // 0 1.5
  1085. case CMSG_QUESTGIVER_COMPLETE_QUEST: // 0 1.5
  1086. case CMSG_SET_ACTION_BUTTON: // 0 1.5
  1087. case CMSG_RESET_INSTANCES: // 0 1.5
  1088. case CMSG_HEARTH_AND_RESURRECT: // 0 1.5
  1089. case CMSG_TOGGLE_PVP: // 0 1.5
  1090. case CMSG_PET_ABANDON: // 0 1.5
  1091. case CMSG_ACTIVATETAXIEXPRESS: // 0 1.5
  1092. case CMSG_ACTIVATETAXI: // 0 1.5
  1093. case CMSG_SELF_RES: // 0 1.5
  1094. case CMSG_UNLEARN_SKILL: // 0 1.5
  1095. case CMSG_EQUIPMENT_SET_SAVE: // 0 1.5
  1096. case CMSG_EQUIPMENT_SET_DELETE: // 0 1.5
  1097. case CMSG_DISMISS_CRITTER: // 0 1.5
  1098. case CMSG_REPOP_REQUEST: // 0 1.5
  1099. case CMSG_GROUP_INVITE: // 0 1.5
  1100. case CMSG_GROUP_INVITE_RESPONSE: // 0 1.5
  1101. case CMSG_GROUP_UNINVITE_GUID: // 0 1.5
  1102. case CMSG_GROUP_DISBAND: // 0 1.5
  1103. case CMSG_BATTLEMASTER_JOIN_ARENA: // 0 1.5
  1104. case CMSG_BATTLEFIELD_LEAVE: // 0 1.5
  1105. case CMSG_GUILD_BANK_LOG_QUERY: // 0 2
  1106. case CMSG_LOGOUT_CANCEL: // 0 2
  1107. case CMSG_REALM_SPLIT: // 0 2
  1108. case CMSG_ALTER_APPEARANCE: // 0 2
  1109. case CMSG_QUEST_CONFIRM_ACCEPT: // 0 2
  1110. case CMSG_GUILD_EVENT_LOG_QUERY: // 0 2.5
  1111. case CMSG_READY_FOR_ACCOUNT_DATA_TIMES: // 0 …

Large files files are truncated, but you can click here to view the full file