PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/chucho/FaceCore
C++ | 1087 lines | 806 code | 165 blank | 116 comment | 172 complexity | ce79065632892d2cada3db498337802c MD5 | raw file
  1. /*
  2. * Copyright (C) 2008-2011 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" // must be first to make ACE happy with ACE includes in it
  22. #include "Common.h"
  23. #include "DatabaseEnv.h"
  24. #include "Log.h"
  25. #include "Opcodes.h"
  26. #include "WorldPacket.h"
  27. #include "WorldSession.h"
  28. #include "Player.h"
  29. #include "Vehicle.h"
  30. #include "ObjectMgr.h"
  31. #include "GuildMgr.h"
  32. #include "Group.h"
  33. #include "Guild.h"
  34. #include "World.h"
  35. #include "ObjectAccessor.h"
  36. #include "BattlegroundMgr.h"
  37. #include "OutdoorPvPMgr.h"
  38. #include "MapManager.h"
  39. #include "SocialMgr.h"
  40. #include "zlib.h"
  41. #include "ScriptMgr.h"
  42. #include "Transport.h"
  43. bool MapSessionFilter::Process(WorldPacket* packet)
  44. {
  45. OpcodeHandler const &opHandle = opcodeTable[packet->GetOpcode()];
  46. //let's check if our opcode can be really processed in Map::Update()
  47. if (opHandle.packetProcessing == PROCESS_INPLACE)
  48. return true;
  49. //we do not process thread-unsafe packets
  50. if (opHandle.packetProcessing == PROCESS_THREADUNSAFE)
  51. return false;
  52. Player* plr = m_pSession->GetPlayer();
  53. if (!plr)
  54. return false;
  55. //in Map::Update() we do not process packets where player is not in world!
  56. return plr->IsInWorld();
  57. }
  58. //we should process ALL packets when player is not in world/logged in
  59. //OR packet handler is not thread-safe!
  60. bool WorldSessionFilter::Process(WorldPacket* packet)
  61. {
  62. OpcodeHandler const &opHandle = opcodeTable[packet->GetOpcode()];
  63. //check if packet handler is supposed to be safe
  64. if (opHandle.packetProcessing == PROCESS_INPLACE)
  65. return true;
  66. //thread-unsafe packets should be processed in World::UpdateSessions()
  67. if (opHandle.packetProcessing == PROCESS_THREADUNSAFE)
  68. return true;
  69. //no player attached? -> our client! ^^
  70. Player* plr = m_pSession->GetPlayer();
  71. if (!plr)
  72. return true;
  73. //lets process all packets for non-in-the-world player
  74. return (plr->IsInWorld() == false);
  75. }
  76. /// WorldSession constructor
  77. WorldSession::WorldSession(uint32 id, WorldSocket* sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale, uint32 recruiter, bool isARecruiter):
  78. m_muteTime(mute_time), m_timeOutTime(0), _player(NULL), m_Socket(sock),
  79. _security(sec), _accountId(id), m_expansion(expansion), _logoutTime(0),
  80. m_inQueue(false), m_playerLoading(false), m_playerLogout(false),
  81. m_playerRecentlyLogout(false), m_playerSave(false),
  82. m_sessionDbcLocale(sWorld->GetAvailableDbcLocale(locale)),
  83. m_sessionDbLocaleIndex(locale),
  84. m_latency(0), m_TutorialsChanged(false), recruiterId(recruiter),
  85. isRecruiter(isARecruiter)
  86. {
  87. if (sock)
  88. {
  89. m_Address = sock->GetRemoteAddress();
  90. sock->AddReference();
  91. ResetTimeOutTime();
  92. LoginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = %u;", GetAccountId());
  93. }
  94. InitializeQueryCallbackParameters();
  95. }
  96. /// WorldSession destructor
  97. WorldSession::~WorldSession()
  98. {
  99. ///- unload player if not unloaded
  100. if (_player)
  101. LogoutPlayer (true);
  102. /// - If have unclosed socket, close it
  103. if (m_Socket)
  104. {
  105. m_Socket->CloseSocket ();
  106. m_Socket->RemoveReference ();
  107. m_Socket = NULL;
  108. }
  109. ///- empty incoming packet queue
  110. WorldPacket* packet = NULL;
  111. while (_recvQueue.next(packet))
  112. delete packet;
  113. LoginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = %u;", GetAccountId());
  114. }
  115. void WorldSession::SizeError(WorldPacket const &packet, uint32 size) const
  116. {
  117. sLog->outError("Client (account %u) send packet %s (%u) with size " SIZEFMTD " but expected %u (attempt to crash server?), skipped",
  118. GetAccountId(), LookupOpcodeName(packet.GetOpcode()), packet.GetOpcode(), packet.size(), size);
  119. }
  120. /// Get the player name
  121. char const* WorldSession::GetPlayerName() const
  122. {
  123. return GetPlayer() ? GetPlayer()->GetName() : "<none>";
  124. }
  125. /// Send a packet to the client
  126. void WorldSession::SendPacket(WorldPacket const* packet)
  127. {
  128. if (!m_Socket)
  129. return;
  130. #ifdef TRINITY_DEBUG
  131. // Code for network use statistic
  132. static uint64 sendPacketCount = 0;
  133. static uint64 sendPacketBytes = 0;
  134. static time_t firstTime = time(NULL);
  135. static time_t lastTime = firstTime; // next 60 secs start time
  136. static uint64 sendLastPacketCount = 0;
  137. static uint64 sendLastPacketBytes = 0;
  138. time_t cur_time = time(NULL);
  139. if ((cur_time - lastTime) < 60)
  140. {
  141. sendPacketCount+=1;
  142. sendPacketBytes+=packet->size();
  143. sendLastPacketCount+=1;
  144. sendLastPacketBytes+=packet->size();
  145. }
  146. else
  147. {
  148. uint64 minTime = uint64(cur_time - lastTime);
  149. uint64 fullTime = uint64(lastTime - firstTime);
  150. 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));
  151. 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);
  152. lastTime = cur_time;
  153. sendLastPacketCount = 1;
  154. sendLastPacketBytes = packet->wpos(); // wpos is real written size
  155. }
  156. #endif // !TRINITY_DEBUG
  157. if (m_Socket->SendPacket (*packet) == -1)
  158. m_Socket->CloseSocket ();
  159. }
  160. /// Add an incoming packet to the queue
  161. void WorldSession::QueuePacket(WorldPacket* new_packet)
  162. {
  163. _recvQueue.add(new_packet);
  164. }
  165. /// Logging helper for unexpected opcodes
  166. void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, const char* status, const char *reason)
  167. {
  168. sLog->outError("SESSION (account: %u, guidlow: %u, char: %s): received unexpected opcode %s (0x%.4X, status: %s) %s",
  169. GetAccountId(), m_GUIDLow, _player ? _player->GetName() : "<none>",
  170. LookupOpcodeName(packet->GetOpcode()), packet->GetOpcode(), status, reason);
  171. }
  172. /// Logging helper for unexpected opcodes
  173. void WorldSession::LogUnprocessedTail(WorldPacket* packet)
  174. {
  175. sLog->outError("SESSION: opcode %s (0x%.4X) have unprocessed tail data (read stop at %u from %u)",
  176. LookupOpcodeName(packet->GetOpcode()), packet->GetOpcode(), uint32(packet->rpos()), uint32(packet->wpos()));
  177. packet->print_storage();
  178. }
  179. /// Update the WorldSession (triggered by World update)
  180. bool WorldSession::Update(uint32 diff, PacketFilter& updater)
  181. {
  182. /// Update Timeout timer.
  183. UpdateTimeOutTime(diff);
  184. ///- Before we process anything:
  185. /// If necessary, kick the player from the character select screen
  186. if (IsConnectionIdle())
  187. m_Socket->CloseSocket();
  188. ///- Retrieve packets from the receive queue and call the appropriate handlers
  189. /// not process packets if socket already closed
  190. WorldPacket* packet = NULL;
  191. while (m_Socket && !m_Socket->IsClosed() && _recvQueue.next(packet, updater))
  192. {
  193. if (packet->GetOpcode() >= NUM_MSG_TYPES)
  194. {
  195. sLog->outError("SESSION: received non-existed opcode %s (0x%.4X)", LookupOpcodeName(packet->GetOpcode()), packet->GetOpcode());
  196. sScriptMgr->OnUnknownPacketReceive(m_Socket, WorldPacket(*packet));
  197. }
  198. else
  199. {
  200. OpcodeHandler &opHandle = opcodeTable[packet->GetOpcode()];
  201. try
  202. {
  203. switch (opHandle.status)
  204. {
  205. case STATUS_LOGGEDIN:
  206. if (!_player)
  207. {
  208. // skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
  209. if (!m_playerRecentlyLogout)
  210. LogUnexpectedOpcode(packet, "STATUS_LOGGEDIN", "the player has not logged in yet");
  211. }
  212. else if (_player->IsInWorld())
  213. {
  214. sScriptMgr->OnPacketReceive(m_Socket, WorldPacket(*packet));
  215. (this->*opHandle.handler)(*packet);
  216. if (sLog->IsOutDebug() && packet->rpos() < packet->wpos())
  217. LogUnprocessedTail(packet);
  218. }
  219. // lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
  220. break;
  221. case STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT:
  222. if (!_player && !m_playerRecentlyLogout)
  223. LogUnexpectedOpcode(packet, "STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT",
  224. "the player has not logged in yet and not recently logout");
  225. else
  226. {
  227. // not expected _player or must checked in packet hanlder
  228. sScriptMgr->OnPacketReceive(m_Socket, WorldPacket(*packet));
  229. (this->*opHandle.handler)(*packet);
  230. if (sLog->IsOutDebug() && packet->rpos() < packet->wpos())
  231. LogUnprocessedTail(packet);
  232. }
  233. break;
  234. case STATUS_TRANSFER:
  235. if (!_player)
  236. LogUnexpectedOpcode(packet, "STATUS_TRANSFER", "the player has not logged in yet");
  237. else if (_player->IsInWorld())
  238. LogUnexpectedOpcode(packet, "STATUS_TRANSFER", "the player is still in world");
  239. else
  240. {
  241. sScriptMgr->OnPacketReceive(m_Socket, WorldPacket(*packet));
  242. (this->*opHandle.handler)(*packet);
  243. if (sLog->IsOutDebug() && packet->rpos() < packet->wpos())
  244. LogUnprocessedTail(packet);
  245. }
  246. break;
  247. case STATUS_AUTHED:
  248. // prevent cheating with skip queue wait
  249. if (m_inQueue)
  250. {
  251. LogUnexpectedOpcode(packet, "STATUS_AUTHED", "the player not pass queue yet");
  252. break;
  253. }
  254. // single from authed time opcodes send in to after logout time
  255. // and before other STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT opcodes.
  256. if (packet->GetOpcode() != CMSG_SET_ACTIVE_VOICE_CHANNEL)
  257. m_playerRecentlyLogout = false;
  258. sScriptMgr->OnPacketReceive(m_Socket, WorldPacket(*packet));
  259. (this->*opHandle.handler)(*packet);
  260. if (sLog->IsOutDebug() && packet->rpos() < packet->wpos())
  261. LogUnprocessedTail(packet);
  262. break;
  263. case STATUS_NEVER:
  264. sLog->outError("SESSION (account: %u, guidlow: %u, char: %s): received not allowed opcode %s (0x%.4X)",
  265. GetAccountId(), m_GUIDLow, _player ? _player->GetName() : "<none>",
  266. LookupOpcodeName(packet->GetOpcode()), packet->GetOpcode());
  267. break;
  268. case STATUS_UNHANDLED:
  269. sLog->outDebug(LOG_FILTER_NETWORKIO, "SESSION (account: %u, guidlow: %u, char: %s): received not handled opcode %s (0x%.4X)",
  270. GetAccountId(), m_GUIDLow, _player ? _player->GetName() : "<none>",
  271. LookupOpcodeName(packet->GetOpcode()), packet->GetOpcode());
  272. break;
  273. }
  274. }
  275. catch(ByteBufferException &)
  276. {
  277. sLog->outError("WorldSession::Update ByteBufferException occured while parsing a packet (opcode: %u) from client %s, accountid=%i. Skipped packet.",
  278. packet->GetOpcode(), GetRemoteAddress().c_str(), GetAccountId());
  279. if (sLog->IsOutDebug())
  280. {
  281. sLog->outDebug(LOG_FILTER_NETWORKIO, "Dumping error causing packet:");
  282. packet->hexlike();
  283. }
  284. }
  285. }
  286. delete packet;
  287. }
  288. ProcessQueryCallbacks();
  289. //check if we are safe to proceed with logout
  290. //logout procedure should happen only in World::UpdateSessions() method!!!
  291. if (updater.ProcessLogout())
  292. {
  293. time_t currTime = time(NULL);
  294. ///- If necessary, log the player out
  295. if (ShouldLogOut(currTime) && !m_playerLoading)
  296. LogoutPlayer(true);
  297. ///- Cleanup socket pointer if need
  298. if (m_Socket && m_Socket->IsClosed())
  299. {
  300. m_Socket->RemoveReference();
  301. m_Socket = NULL;
  302. }
  303. if (!m_Socket)
  304. return false; //Will remove this session from the world session map
  305. }
  306. return true;
  307. }
  308. /// %Log the player out
  309. void WorldSession::LogoutPlayer(bool Save)
  310. {
  311. // finish pending transfers before starting the logout
  312. while (_player && _player->IsBeingTeleportedFar())
  313. HandleMoveWorldportAckOpcode();
  314. m_playerLogout = true;
  315. m_playerSave = Save;
  316. if (_player)
  317. {
  318. if (uint64 lguid = GetPlayer()->GetLootGUID())
  319. DoLootRelease(lguid);
  320. ///- If the player just died before logging out, make him appear as a ghost
  321. //FIXME: logout must be delayed in case lost connection with client in time of combat
  322. if (_player->GetDeathTimer())
  323. {
  324. _player->getHostileRefManager().deleteReferences();
  325. _player->BuildPlayerRepop();
  326. _player->RepopAtGraveyard();
  327. }
  328. else if (!_player->getAttackers().empty())
  329. {
  330. _player->CombatStop();
  331. _player->getHostileRefManager().setOnlineOfflineState(false);
  332. _player->RemoveAllAurasOnDeath();
  333. // build set of player who attack _player or who have pet attacking of _player
  334. std::set<Player*> aset;
  335. for (Unit::AttackerSet::const_iterator itr = _player->getAttackers().begin(); itr != _player->getAttackers().end(); ++itr)
  336. {
  337. Unit* owner = (*itr)->GetOwner(); // including player controlled case
  338. if (owner && owner->GetTypeId() == TYPEID_PLAYER)
  339. aset.insert(owner->ToPlayer());
  340. else if ((*itr)->GetTypeId() == TYPEID_PLAYER)
  341. aset.insert((Player*)(*itr));
  342. }
  343. _player->SetPvPDeath(!aset.empty());
  344. _player->KillPlayer();
  345. _player->BuildPlayerRepop();
  346. _player->RepopAtGraveyard();
  347. // give honor to all attackers from set like group case
  348. for (std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr)
  349. (*itr)->RewardHonor(_player, aset.size());
  350. // give bg rewards and update counters like kill by first from attackers
  351. // this can't be called for all attackers.
  352. if (!aset.empty())
  353. if (Battleground* bg = _player->GetBattleground())
  354. bg->HandleKillPlayer(_player, *aset.begin());
  355. }
  356. else if (_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
  357. {
  358. // this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
  359. _player->RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT);
  360. _player->KillPlayer();
  361. _player->BuildPlayerRepop();
  362. _player->RepopAtGraveyard();
  363. }
  364. else if (_player->HasPendingBind())
  365. {
  366. _player->RepopAtGraveyard();
  367. _player->SetPendingBind(0, 0);
  368. }
  369. //drop a flag if player is carrying it
  370. if (Battleground* bg = _player->GetBattleground())
  371. bg->EventPlayerLoggedOut(_player);
  372. ///- Teleport to home if the player is in an invalid instance
  373. if (!_player->m_InstanceValid && !_player->isGameMaster())
  374. _player->TeleportTo(_player->m_homebindMapId, _player->m_homebindX, _player->m_homebindY, _player->m_homebindZ, _player->GetOrientation());
  375. sOutdoorPvPMgr->HandlePlayerLeaveZone(_player, _player->GetZoneId());
  376. for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
  377. {
  378. if (BattlegroundQueueTypeId bgQueueTypeId = _player->GetBattlegroundQueueTypeId(i))
  379. {
  380. _player->RemoveBattlegroundQueueId(bgQueueTypeId);
  381. sBattlegroundMgr->m_BattlegroundQueues[ bgQueueTypeId ].RemovePlayer(_player->GetGUID(), true);
  382. }
  383. }
  384. // Repop at GraveYard or other player far teleport will prevent saving player because of not present map
  385. // Teleport player immediately for correct player save
  386. while (_player->IsBeingTeleportedFar())
  387. HandleMoveWorldportAckOpcode();
  388. ///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
  389. if (Guild* pGuild = sGuildMgr->GetGuildById(_player->GetGuildId()))
  390. pGuild->HandleMemberLogout(this);
  391. ///- Remove pet
  392. _player->RemovePet(NULL, PET_SAVE_AS_CURRENT, true);
  393. ///- empty buyback items and save the player in the database
  394. // some save parts only correctly work in case player present in map/player_lists (pets, etc)
  395. if (Save)
  396. {
  397. uint32 eslot;
  398. for (int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; ++j)
  399. {
  400. eslot = j - BUYBACK_SLOT_START;
  401. _player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0);
  402. _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
  403. _player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
  404. }
  405. _player->SaveToDB();
  406. }
  407. ///- Leave all channels before player delete...
  408. _player->CleanupChannels();
  409. ///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
  410. _player->UninviteFromGroup();
  411. // remove player from the group if he is:
  412. // a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
  413. if (_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
  414. _player->RemoveFromGroup();
  415. ///- Send update to group and reset stored max enchanting level
  416. if (_player->GetGroup())
  417. {
  418. _player->GetGroup()->SendUpdate();
  419. _player->GetGroup()->ResetMaxEnchantingLevel();
  420. }
  421. ///- Broadcast a logout message to the player's friends
  422. sSocialMgr->SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUIDLow(), true);
  423. sSocialMgr->RemovePlayerSocial (_player->GetGUIDLow ());
  424. // Call script hook before deletion
  425. sScriptMgr->OnPlayerLogout(GetPlayer());
  426. ///- Remove the player from the world
  427. // the player may not be in the world when logging out
  428. // e.g if he got disconnected during a transfer to another map
  429. // calls to GetMap in this case may cause crashes
  430. _player->CleanupsBeforeDelete();
  431. sLog->outChar("Account: %d (IP: %s) Logout Character:[%s] (GUID: %u)", GetAccountId(), GetRemoteAddress().c_str(), _player->GetName() , _player->GetGUIDLow());
  432. Map* _map = _player->GetMap();
  433. _map->Remove(_player, true);
  434. SetPlayer(NULL); // deleted in Remove call
  435. ///- Send the 'logout complete' packet to the client
  436. WorldPacket data(SMSG_LOGOUT_COMPLETE, 0);
  437. SendPacket(&data);
  438. ///- Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
  439. //No SQL injection as AccountId is uint32
  440. CharacterDatabase.PExecute("UPDATE characters SET online = 0 WHERE account = '%u'", GetAccountId());
  441. sLog->outDebug(LOG_FILTER_NETWORKIO, "SESSION: Sent SMSG_LOGOUT_COMPLETE Message");
  442. }
  443. m_playerLogout = false;
  444. m_playerSave = false;
  445. m_playerRecentlyLogout = true;
  446. LogoutRequest(0);
  447. }
  448. /// Kick a player out of the World
  449. void WorldSession::KickPlayer()
  450. {
  451. if (m_Socket)
  452. m_Socket->CloseSocket();
  453. }
  454. void WorldSession::SendNotification(const char *format, ...)
  455. {
  456. if (format)
  457. {
  458. va_list ap;
  459. char szStr[1024];
  460. szStr[0] = '\0';
  461. va_start(ap, format);
  462. vsnprintf(szStr, 1024, format, ap);
  463. va_end(ap);
  464. WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr) + 1));
  465. data << szStr;
  466. SendPacket(&data);
  467. }
  468. }
  469. void WorldSession::SendNotification(uint32 string_id, ...)
  470. {
  471. char const* format = GetTrinityString(string_id);
  472. if (format)
  473. {
  474. va_list ap;
  475. char szStr[1024];
  476. szStr[0] = '\0';
  477. va_start(ap, string_id);
  478. vsnprintf(szStr, 1024, format, ap);
  479. va_end(ap);
  480. WorldPacket data(SMSG_NOTIFICATION, (strlen(szStr) + 1));
  481. data << szStr;
  482. SendPacket(&data);
  483. }
  484. }
  485. const char *WorldSession::GetTrinityString(int32 entry) const
  486. {
  487. return sObjectMgr->GetTrinityString(entry, GetSessionDbLocaleIndex());
  488. }
  489. void WorldSession::Handle_NULL(WorldPacket& recvPacket)
  490. {
  491. sLog->outError("SESSION: received unhandled opcode %s (0x%.4X)", LookupOpcodeName(recvPacket.GetOpcode()), recvPacket.GetOpcode());
  492. }
  493. void WorldSession::Handle_EarlyProccess(WorldPacket& recvPacket)
  494. {
  495. sLog->outError("SESSION: received opcode %s (0x%.4X) that must be processed in WorldSocket::OnRead", LookupOpcodeName(recvPacket.GetOpcode()), recvPacket.GetOpcode());
  496. }
  497. void WorldSession::Handle_ServerSide(WorldPacket& recvPacket)
  498. {
  499. sLog->outError("SESSION: received server-side opcode %s (0x%.4X)", LookupOpcodeName(recvPacket.GetOpcode()), recvPacket.GetOpcode());
  500. }
  501. void WorldSession::Handle_Deprecated(WorldPacket& recvPacket)
  502. {
  503. sLog->outError("SESSION: received deprecated opcode %s (0x%.4X)", LookupOpcodeName(recvPacket.GetOpcode()), recvPacket.GetOpcode());
  504. }
  505. void WorldSession::SendAuthWaitQue(uint32 position)
  506. {
  507. if (position == 0)
  508. {
  509. WorldPacket packet(SMSG_AUTH_RESPONSE, 1);
  510. packet << uint8(AUTH_OK);
  511. SendPacket(&packet);
  512. }
  513. else
  514. {
  515. WorldPacket packet(SMSG_AUTH_RESPONSE, 6);
  516. packet << uint8(AUTH_WAIT_QUEUE);
  517. packet << uint32(position);
  518. packet << uint8(0); // unk
  519. SendPacket(&packet);
  520. }
  521. }
  522. void WorldSession::LoadGlobalAccountData()
  523. {
  524. PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_LOAD_ACCOUNT_DATA);
  525. stmt->setUInt32(0, GetAccountId());
  526. LoadAccountData(CharacterDatabase.Query(stmt), GLOBAL_CACHE_MASK);
  527. }
  528. void WorldSession::LoadAccountData(PreparedQueryResult result, uint32 mask)
  529. {
  530. for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
  531. if (mask & (1 << i))
  532. m_accountData[i] = AccountData();
  533. if (!result)
  534. return;
  535. do
  536. {
  537. Field* fields = result->Fetch();
  538. uint32 type = fields[0].GetUInt8();
  539. if (type >= NUM_ACCOUNT_DATA_TYPES)
  540. {
  541. sLog->outError("Table `%s` have invalid account data type (%u), ignore.", mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
  542. continue;
  543. }
  544. if ((mask & (1 << type)) == 0)
  545. {
  546. sLog->outError("Table `%s` have non appropriate for table account data type (%u), ignore.", mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
  547. continue;
  548. }
  549. m_accountData[type].Time = time_t(fields[1].GetUInt32());
  550. m_accountData[type].Data = fields[2].GetString();
  551. }
  552. while (result->NextRow());
  553. }
  554. void WorldSession::SetAccountData(AccountDataType type, time_t tm, std::string data)
  555. {
  556. uint32 id = 0;
  557. uint32 index = 0;
  558. if ((1 << type) & GLOBAL_CACHE_MASK)
  559. {
  560. id = GetAccountId();
  561. index = CHAR_SET_ACCOUNT_DATA;
  562. }
  563. else
  564. {
  565. // _player can be NULL and packet received after logout but m_GUID still store correct guid
  566. if (!m_GUIDLow)
  567. return;
  568. id = m_GUIDLow;
  569. index = CHAR_SET_PLAYER_ACCOUNT_DATA;
  570. }
  571. PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(index);
  572. stmt->setUInt32(0, id);
  573. stmt->setUInt8 (1, type);
  574. stmt->setUInt32(2, uint32(tm));
  575. stmt->setString(3, data);
  576. CharacterDatabase.Execute(stmt);
  577. m_accountData[type].Time = tm;
  578. m_accountData[type].Data = data;
  579. }
  580. void WorldSession::SendAccountDataTimes(uint32 mask)
  581. {
  582. WorldPacket data(SMSG_ACCOUNT_DATA_TIMES, 4 + 1 + 4 + 8 * 4); // changed in WotLK
  583. data << uint32(time(NULL)); // unix time of something
  584. data << uint8(1);
  585. data << uint32(mask); // type mask
  586. for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
  587. if (mask & (1 << i))
  588. data << uint32(GetAccountData(AccountDataType(i))->Time);// also unix time
  589. SendPacket(&data);
  590. }
  591. void WorldSession::LoadTutorialsData()
  592. {
  593. memset(m_Tutorials, 0, sizeof(uint32) * MAX_ACCOUNT_TUTORIAL_VALUES);
  594. PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_LOAD_TUTORIALS);
  595. stmt->setUInt32(0, GetAccountId());
  596. if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
  597. for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
  598. m_Tutorials[i] = (*result)[i].GetUInt32();
  599. m_TutorialsChanged = false;
  600. }
  601. void WorldSession::SendTutorialsData()
  602. {
  603. WorldPacket data(SMSG_TUTORIAL_FLAGS, 4 * MAX_ACCOUNT_TUTORIAL_VALUES);
  604. for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
  605. data << m_Tutorials[i];
  606. SendPacket(&data);
  607. }
  608. void WorldSession::SaveTutorialsData(SQLTransaction &trans)
  609. {
  610. if (!m_TutorialsChanged)
  611. return;
  612. PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_GET_HAS_TUTORIALS);
  613. stmt->setUInt32(0, GetAccountId());
  614. bool hasTutorials = !CharacterDatabase.Query(stmt).null();
  615. // Modify data in DB
  616. stmt = CharacterDatabase.GetPreparedStatement(hasTutorials ? CHAR_SET_TUTORIALS : CHAR_ADD_TUTORIALS);
  617. for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
  618. stmt->setUInt32(i, m_Tutorials[i]);
  619. stmt->setUInt32(MAX_ACCOUNT_TUTORIAL_VALUES, GetAccountId());
  620. trans->Append(stmt);
  621. m_TutorialsChanged = false;
  622. }
  623. void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo* mi)
  624. {
  625. data >> mi->flags;
  626. data >> mi->flags2;
  627. data >> mi->time;
  628. data >> mi->pos.PositionXYZOStream();
  629. if (mi->HasMovementFlag(MOVEMENTFLAG_ONTRANSPORT))
  630. {
  631. data.readPackGUID(mi->t_guid);
  632. data >> mi->t_pos.PositionXYZOStream();
  633. data >> mi->t_time;
  634. data >> mi->t_seat;
  635. if (mi->HasExtraMovementFlag(MOVEMENTFLAG2_INTERPOLATED_MOVEMENT))
  636. data >> mi->t_time2;
  637. if (mi->pos.m_positionX != mi->t_pos.m_positionX)
  638. if (GetPlayer()->GetTransport())
  639. GetPlayer()->GetTransport()->UpdatePosition(mi);
  640. }
  641. if (mi->HasMovementFlag(MovementFlags(MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING)) || (mi->HasExtraMovementFlag(MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING)))
  642. data >> mi->pitch;
  643. data >> mi->fallTime;
  644. if (mi->HasMovementFlag(MOVEMENTFLAG_JUMPING))
  645. {
  646. data >> mi->j_zspeed;
  647. data >> mi->j_sinAngle;
  648. data >> mi->j_cosAngle;
  649. data >> mi->j_xyspeed;
  650. }
  651. if (mi->HasMovementFlag(MOVEMENTFLAG_SPLINE_ELEVATION))
  652. data >> mi->splineElevation;
  653. // This must be a packet spoofing attempt. MOVEMENTFLAG_ROOT sent from the client is not valid,
  654. // and when used in conjunction with any of the moving movement flags such as MOVEMENTFLAG_FORWARD
  655. // it will freeze clients that receive this player's movement info.
  656. if (mi->HasMovementFlag(MOVEMENTFLAG_ROOT))
  657. mi->flags &= ~MOVEMENTFLAG_ROOT;
  658. // Cannot hover and jump at the same time
  659. if (mi->HasMovementFlag(MOVEMENTFLAG_HOVER) && mi->HasMovementFlag(MOVEMENTFLAG_JUMPING))
  660. mi->flags &= ~MOVEMENTFLAG_JUMPING;
  661. // Cannot ascend and descend at the same time
  662. if (mi->HasMovementFlag(MOVEMENTFLAG_ASCENDING) && mi->HasMovementFlag(MOVEMENTFLAG_DESCENDING))
  663. mi->flags &= ~(MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING);
  664. // Cannot move left and right at the same time
  665. if (mi->HasMovementFlag(MOVEMENTFLAG_LEFT) && mi->HasMovementFlag(MOVEMENTFLAG_RIGHT))
  666. mi->flags &= ~(MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT);
  667. // Cannot strafe left and right at the same time
  668. if (mi->HasMovementFlag(MOVEMENTFLAG_STRAFE_LEFT) && mi->HasMovementFlag(MOVEMENTFLAG_STRAFE_RIGHT))
  669. mi->flags &= ~(MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT);
  670. // Cannot pitch up and down at the same time
  671. if (mi->HasMovementFlag(MOVEMENTFLAG_PITCH_UP) && mi->HasMovementFlag(MOVEMENTFLAG_PITCH_DOWN))
  672. mi->flags &= ~(MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN);
  673. // Cannot move forwards and backwards at the same time
  674. if (mi->HasMovementFlag(MOVEMENTFLAG_FORWARD) && mi->HasMovementFlag(MOVEMENTFLAG_BACKWARD))
  675. mi->flags &= ~(MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD);
  676. }
  677. void WorldSession::WriteMovementInfo(WorldPacket* data, MovementInfo* mi)
  678. {
  679. data->appendPackGUID(mi->guid);
  680. *data << mi->flags;
  681. *data << mi->flags2;
  682. *data << mi->time;
  683. *data << mi->pos.PositionXYZOStream();
  684. if (mi->HasMovementFlag(MOVEMENTFLAG_ONTRANSPORT))
  685. {
  686. data->appendPackGUID(mi->t_guid);
  687. *data << mi->t_pos.PositionXYZOStream();
  688. *data << mi->t_time;
  689. *data << mi->t_seat;
  690. }
  691. if (mi->HasMovementFlag(MovementFlags(MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING)) || mi->HasExtraMovementFlag(MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING))
  692. *data << mi->pitch;
  693. *data << mi->fallTime;
  694. if (mi->HasMovementFlag(MOVEMENTFLAG_JUMPING))
  695. {
  696. *data << mi->j_zspeed;
  697. *data << mi->j_sinAngle;
  698. *data << mi->j_cosAngle;
  699. *data << mi->j_xyspeed;
  700. }
  701. if (mi->HasMovementFlag(MOVEMENTFLAG_SPLINE_ELEVATION))
  702. *data << mi->splineElevation;
  703. }
  704. void WorldSession::ReadAddonsInfo(WorldPacket &data)
  705. {
  706. if (data.rpos() + 4 > data.size())
  707. return;
  708. uint32 size;
  709. data >> size;
  710. if (!size)
  711. return;
  712. if (size > 0xFFFFF)
  713. {
  714. sLog->outError("WorldSession::ReadAddonsInfo addon info too big, size %u", size);
  715. return;
  716. }
  717. uLongf uSize = size;
  718. uint32 pos = data.rpos();
  719. ByteBuffer addonInfo;
  720. addonInfo.resize(size);
  721. if (uncompress(const_cast<uint8 *>(addonInfo.contents()), &uSize, const_cast<uint8 *>(data.contents() + pos), data.size() - pos) == Z_OK)
  722. {
  723. uint32 addonsCount;
  724. addonInfo >> addonsCount; // addons count
  725. for (uint32 i = 0; i < addonsCount; ++i)
  726. {
  727. std::string addonName;
  728. uint8 enabled;
  729. uint32 crc, unk1;
  730. // check next addon data format correctness
  731. if (addonInfo.rpos() + 1 > addonInfo.size())
  732. return;
  733. addonInfo >> addonName;
  734. addonInfo >> enabled >> crc >> unk1;
  735. sLog->outDetail("ADDON: Name: %s, Enabled: 0x%x, CRC: 0x%x, Unknown2: 0x%x", addonName.c_str(), enabled, crc, unk1);
  736. AddonInfo addon(addonName, enabled, crc, 2, true);
  737. SavedAddon const* savedAddon = AddonMgr::GetAddonInfo(addonName);
  738. if (savedAddon)
  739. {
  740. bool match = true;
  741. if (addon.CRC != savedAddon->CRC)
  742. match = false;
  743. if (!match)
  744. sLog->outDetail("ADDON: %s was known, but didn't match known CRC (0x%x)!", addon.Name.c_str(), savedAddon->CRC);
  745. else
  746. sLog->outDetail("ADDON: %s was known, CRC is correct (0x%x)", addon.Name.c_str(), savedAddon->CRC);
  747. }
  748. else
  749. {
  750. AddonMgr::SaveAddon(addon);
  751. sLog->outDetail("ADDON: %s (0x%x) was not known, saving...", addon.Name.c_str(), addon.CRC);
  752. }
  753. // TODO: Find out when to not use CRC/pubkey, and other possible states.
  754. m_addonsList.push_back(addon);
  755. }
  756. uint32 currentTime;
  757. addonInfo >> currentTime;
  758. sLog->outDebug(LOG_FILTER_NETWORKIO, "ADDON: CurrentTime: %u", currentTime);
  759. if (addonInfo.rpos() != addonInfo.size())
  760. sLog->outDebug(LOG_FILTER_NETWORKIO, "packet under-read!");
  761. }
  762. else
  763. sLog->outError("Addon packet uncompress error!");
  764. }
  765. void WorldSession::SendAddonsInfo()
  766. {
  767. uint8 addonPublicKey[256] =
  768. {
  769. 0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54,
  770. 0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75,
  771. 0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34,
  772. 0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8,
  773. 0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8,
  774. 0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A,
  775. 0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3,
  776. 0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9,
  777. 0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22,
  778. 0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E,
  779. 0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB,
  780. 0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7,
  781. 0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0,
  782. 0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6,
  783. 0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A,
  784. 0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2
  785. };
  786. WorldPacket data(SMSG_ADDON_INFO, 4);
  787. for (AddonsList::iterator itr = m_addonsList.begin(); itr != m_addonsList.end(); ++itr)
  788. {
  789. data << uint8(itr->State);
  790. uint8 crcpub = itr->UsePublicKeyOrCRC;
  791. data << uint8(crcpub);
  792. if (crcpub)
  793. {
  794. uint8 usepk = (itr->CRC != STANDARD_ADDON_CRC); // If addon is Standard addon CRC
  795. data << uint8(usepk);
  796. if (usepk) // if CRC is wrong, add public key (client need it)
  797. {
  798. sLog->outDetail("ADDON: CRC (0x%x) for addon %s is wrong (does not match expected 0x%x), sending pubkey",
  799. itr->CRC, itr->Name.c_str(), STANDARD_ADDON_CRC);
  800. data.append(addonPublicKey, sizeof(addonPublicKey));
  801. }
  802. data << uint32(0); // TODO: Find out the meaning of this.
  803. }
  804. uint8 unk3 = 0; // 0 is sent here
  805. data << uint8(unk3);
  806. if (unk3)
  807. {
  808. // String, length 256 (null terminated)
  809. data << uint8(0);
  810. }
  811. }
  812. m_addonsList.clear();
  813. data << uint32(0); // count for an unknown for loop
  814. SendPacket(&data);
  815. }
  816. void WorldSession::SetPlayer(Player* plr)
  817. {
  818. _player = plr;
  819. // set m_GUID that can be used while player loggined and later until m_playerRecentlyLogout not reset
  820. if (_player)
  821. m_GUIDLow = _player->GetGUIDLow();
  822. }
  823. void WorldSession::InitializeQueryCallbackParameters()
  824. {
  825. // Callback parameters that have pointers in them should be properly
  826. // initialized to NULL here.
  827. _charCreateCallback.SetParam(NULL);
  828. }
  829. void WorldSession::ProcessQueryCallbacks()
  830. {
  831. QueryResult result;
  832. //! HandleNameQueryOpcode
  833. while (!_nameQueryCallbacks.is_empty())
  834. {
  835. QueryResultFuture lResult;
  836. ACE_Time_Value timeout = ACE_Time_Value::zero;
  837. if (_nameQueryCallbacks.next_readable(lResult, &timeout) != 1)
  838. break;
  839. if (lResult.ready())
  840. {
  841. lResult.get(result);
  842. SendNameQueryOpcodeFromDBCallBack(result);
  843. lResult.cancel();
  844. }
  845. }
  846. //! HandleCharEnumOpcode
  847. if (_charEnumCallback.ready())
  848. {
  849. _charEnumCallback.get(result);
  850. HandleCharEnum(result);
  851. _charEnumCallback.cancel();
  852. }
  853. if (_charCreateCallback.IsReady())
  854. {
  855. PreparedQueryResult pResult;
  856. _charCreateCallback.GetResult(pResult);
  857. HandleCharCreateCallback(pResult, _charCreateCallback.GetParam());
  858. // Don't call FreeResult() here, the callback handler will do that depending on the events in the callback chain
  859. }
  860. //! HandlePlayerLoginOpcode
  861. if (_charLoginCallback.ready())
  862. {
  863. SQLQueryHolder* param;
  864. _charLoginCallback.get(param);
  865. HandlePlayerLogin((LoginQueryHolder*)param);
  866. _charLoginCallback.cancel();
  867. }
  868. //! HandleAddFriendOpcode
  869. if (_addFriendCallback.IsReady())
  870. {
  871. std::string param = _addFriendCallback.GetParam();
  872. _addFriendCallback.GetResult(result);
  873. HandleAddFriendOpcodeCallBack(result, param);
  874. _addFriendCallback.FreeResult();
  875. }
  876. //- HandleCharRenameOpcode
  877. if (_charRenameCallback.IsReady())
  878. {
  879. std::string param = _charRenameCallback.GetParam();
  880. _charRenameCallback.GetResult(result);
  881. HandleChangePlayerNameOpcodeCallBack(result, param);
  882. _charRenameCallback.FreeResult();
  883. }
  884. //- HandleCharAddIgnoreOpcode
  885. if (_addIgnoreCallback.ready())
  886. {
  887. _addIgnoreCallback.get(result);
  888. HandleAddIgnoreOpcodeCallBack(result);
  889. _addIgnoreCallback.cancel();
  890. }
  891. //- SendStabledPet
  892. if (_sendStabledPetCallback.IsReady())
  893. {
  894. uint64 param = _sendStabledPetCallback.GetParam();
  895. _sendStabledPetCallback.GetResult(result);
  896. SendStablePetCallback(result, param);
  897. _sendStabledPetCallback.FreeResult();
  898. }
  899. //- HandleStablePet
  900. if (_stablePetCallback.ready())
  901. {
  902. _stablePetCallback.get(result);
  903. HandleStablePetCallback(result);
  904. _stablePetCallback.cancel();
  905. }
  906. //- HandleUnstablePet
  907. if (_unstablePetCallback.IsReady())
  908. {
  909. uint32 param = _unstablePetCallback.GetParam();
  910. _unstablePetCallback.GetResult(result);
  911. HandleUnstablePetCallback(result, param);
  912. _unstablePetCallback.FreeResult();
  913. }
  914. //- HandleStableSwapPet
  915. if (_stableSwapCallback.IsReady())
  916. {
  917. uint32 param = _stableSwapCallback.GetParam();
  918. _stableSwapCallback.GetResult(result);
  919. HandleStableSwapPetCallback(result, param);
  920. _stableSwapCallback.FreeResult();
  921. }
  922. }