-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathWorldSession.cpp
1715 lines (1456 loc) · 69.4 KB
/
WorldSession.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation; either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/** \file
\ingroup u2w
*/
#include "WorldSession.h"
#include "AccountMgr.h"
#include "BattlegroundMgr.h"
#include "BanMgr.h"
#include "CharacterPackets.h"
#include "Common.h"
#include "DatabaseEnv.h"
#include "GameTime.h"
#include "Group.h"
#include "Guild.h"
#include "GuildMgr.h"
#include "Hyperlinks.h"
#include "Log.h"
#include "MapMgr.h"
#include "Metric.h"
#include "ObjectAccessor.h"
#include "ObjectMgr.h"
#include "Opcodes.h"
#include "OutdoorPvPMgr.h"
#include "PacketUtilities.h"
#include "Pet.h"
#include "Player.h"
#include "QueryHolder.h"
#include "ScriptMgr.h"
#include "SocialMgr.h"
#include "Transport.h"
#include "Tokenize.h"
#include "Vehicle.h"
#include "WardenWin.h"
#include "World.h"
#include "WorldPacket.h"
#include "WorldSocket.h"
#include "WorldState.h"
#include <zlib.h>
namespace
{
std::string const DefaultPlayerName = "<none>";
}
bool MapSessionFilter::Process(WorldPacket* packet)
{
ClientOpcodeHandler const* opHandle = opcodeTable[static_cast<OpcodeClient>(packet->GetOpcode())];
//let's check if our has an anxiety disorder can be really processed in Map::Update()
if (opHandle->ProcessingPlace == PROCESS_INPLACE)
return true;
//we do not process thread-unsafe packets
if (opHandle->ProcessingPlace == PROCESS_THREADUNSAFE)
return false;
Player* player = m_pSession->GetPlayer();
if (!player)
return false;
//in Map::Update() we do not process packets where player is not in world!
return player->IsInWorld();
}
//we should process ALL packets when player is not in world/logged in
//OR packet handler is not thread-safe!
bool WorldSessionFilter::Process(WorldPacket* packet)
{
ClientOpcodeHandler const* opHandle = opcodeTable[static_cast<OpcodeClient>(packet->GetOpcode())];
//check if packet handler is supposed to be safe
if (opHandle->ProcessingPlace == PROCESS_INPLACE)
return true;
//thread-unsafe packets should be processed in World::UpdateSessions()
if (opHandle->ProcessingPlace == PROCESS_THREADUNSAFE)
return true;
//no player attached? -> our client! ^^
Player* player = m_pSession->GetPlayer();
if (!player)
return true;
//lets process all packets for non-in-the-world player
return !player->IsInWorld();
}
/// WorldSession constructor
WorldSession::WorldSession(uint32 id, std::string&& name, std::shared_ptr<WorldSocket> sock, AccountTypes sec, uint8 expansion,
time_t mute_time, LocaleConstant locale, uint32 recruiter, bool isARecruiter, bool skipQueue, uint32 TotalTime) :
m_muteTime(mute_time),
m_timeOutTime(0),
AntiDOS(this),
m_GUIDLow(0),
_player(nullptr),
m_Socket(sock),
_security(sec),
_skipQueue(skipQueue),
_accountId(id),
_accountName(std::move(name)),
m_expansion(expansion),
m_total_time(TotalTime),
_logoutTime(0),
m_inQueue(false),
m_playerLoading(false),
m_playerLogout(false),
m_playerRecentlyLogout(false),
m_playerSave(false),
m_sessionDbcLocale(sWorld->GetDefaultDbcLocale()),
m_sessionDbLocaleIndex(locale),
m_latency(0),
m_TutorialsChanged(false),
recruiterId(recruiter),
isRecruiter(isARecruiter),
m_currentVendorEntry(0),
_calendarEventCreationCooldown(0),
_addonMessageReceiveCount(0),
_timeSyncClockDeltaQueue(6),
_timeSyncClockDelta(0),
_pendingTimeSyncRequests()
{
memset(m_Tutorials, 0, sizeof(m_Tutorials));
_offlineTime = 0;
_kicked = false;
_timeSyncNextCounter = 0;
_timeSyncTimer = 0;
if (sock)
{
m_Address = sock->GetRemoteIpAddress().to_string();
ResetTimeOutTime(false);
LoginDatabase.Execute("UPDATE account SET online = 1 WHERE id = {};", GetAccountId()); // One-time query
}
}
/// WorldSession destructor
WorldSession::~WorldSession()
{
LoginDatabase.Execute("UPDATE account SET totaltime = {} WHERE id = {}", GetTotalTime(), GetAccountId());
///- unload player if not unloaded
if (_player)
LogoutPlayer(true);
/// - If have unclosed socket, close it
if (m_Socket)
{
m_Socket->CloseSocket();
m_Socket = nullptr;
}
///- empty incoming packet queue
WorldPacket* packet = nullptr;
while (_recvQueue.next(packet))
delete packet;
LoginDatabase.Execute("UPDATE account SET online = 0 WHERE id = {};", GetAccountId()); // One-time query
}
bool WorldSession::IsGMAccount() const
{
return GetSecurity() >= SEC_GAMEMASTER;
}
std::string const& WorldSession::GetPlayerName() const
{
return _player ? _player->GetName() : DefaultPlayerName;
}
std::string WorldSession::GetPlayerInfo() const
{
std::ostringstream ss;
ss << "[Player: ";
if (!m_playerLoading && _player)
{
ss << _player->GetName() << ' ' << _player->GetGUID().ToString() << ", ";
}
ss << "Account: " << GetAccountId() << "]";
return ss.str();
}
void WorldSession::SendAreaTriggerMessage(std::string_view str)
{
std::vector<std::string_view> lines = Acore::Tokenize(str, '\n', true);
for (std::string_view line : lines)
{
uint32 length = line.size() + 1;
WorldPacket data(SMSG_AREA_TRIGGER_MESSAGE, 4 + length);
data << length;
data << line.data();
SendPacket(&data);
}
}
/// Get player guid if available. Use for logging purposes only
ObjectGuid::LowType WorldSession::GetGuidLow() const
{
return GetPlayer() ? GetPlayer()->GetGUID().GetCounter() : 0;
}
/// Send a packet to the client
void WorldSession::SendPacket(WorldPacket const* packet)
{
if (!m_Socket)
return;
#if defined(ACORE_DEBUG)
// Code for network use statistic
static uint64 sendPacketCount = 0;
static uint64 sendPacketBytes = 0;
static time_t firstTime = GameTime::GetGameTime().count();
static time_t lastTime = firstTime; // next 60 secs start time
static uint64 sendLastPacketCount = 0;
static uint64 sendLastPacketBytes = 0;
time_t cur_time = GameTime::GetGameTime().count();
if ((cur_time - lastTime) < 60)
{
sendPacketCount += 1;
sendPacketBytes += packet->size();
sendLastPacketCount += 1;
sendLastPacketBytes += packet->size();
}
else
{
uint64 minTime = uint64(cur_time - lastTime);
uint64 fullTime = uint64(lastTime - firstTime);
LOG_DEBUG("network", "Send all time packets count: {} bytes: {} avr.count/sec: {} avr.bytes/sec: {} time: {}", sendPacketCount, sendPacketBytes, float(sendPacketCount) / fullTime, float(sendPacketBytes) / fullTime, uint32(fullTime));
LOG_DEBUG("network", "Send last min packets count: {} bytes: {} avr.count/sec: {} avr.bytes/sec: {}", sendLastPacketCount, sendLastPacketBytes, float(sendLastPacketCount) / minTime, float(sendLastPacketBytes) / minTime);
lastTime = cur_time;
sendLastPacketCount = 1;
sendLastPacketBytes = packet->wpos(); // wpos is real written size
}
#endif // !ACORE_DEBUG
if (!sScriptMgr->CanPacketSend(this, *packet))
{
return;
}
m_Socket->SendPacket(*packet);
}
/// Add an incoming packet to the queue
void WorldSession::QueuePacket(WorldPacket* new_packet)
{
_recvQueue.add(new_packet);
}
/// Logging helper for unexpected opcodes
void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, char const* status, const char* reason)
{
LOG_ERROR("network.opcode", "Received unexpected opcode {} Status: {} Reason: {} from {}",
GetOpcodeNameForLogging(static_cast<OpcodeClient>(packet->GetOpcode())), status, reason, GetPlayerInfo());
}
/// Logging helper for unexpected opcodes
void WorldSession::LogUnprocessedTail(WorldPacket* packet)
{
if (!sLog->ShouldLog("network.opcode", LogLevel::LOG_LEVEL_TRACE) || packet->rpos() >= packet->wpos())
return;
LOG_TRACE("network.opcode", "Unprocessed tail data (read stop at {} from {}) Opcode {} from {}",
uint32(packet->rpos()), uint32(packet->wpos()), GetOpcodeNameForLogging(static_cast<OpcodeClient>(packet->GetOpcode())), GetPlayerInfo());
packet->print_storage();
}
/// Update the WorldSession (triggered by World update)
bool WorldSession::Update(uint32 diff, PacketFilter& updater)
{
///- Before we process anything:
/// If necessary, kick the player because the client didn't send anything for too long
/// (or they've been idling in character select)
if (sWorld->getBoolConfig(CONFIG_CLOSE_IDLE_CONNECTIONS) && IsConnectionIdle() && m_Socket)
m_Socket->CloseSocket();
if (updater.ProcessUnsafe())
UpdateTimeOutTime(diff);
HandleTeleportTimeout(updater.ProcessUnsafe());
///- Retrieve packets from the receive queue and call the appropriate handlers
/// not process packets if socket already closed
WorldPacket* packet = nullptr;
//! Delete packet after processing by default
bool deletePacket = true;
std::vector<WorldPacket*> requeuePackets;
uint32 processedPackets = 0;
time_t currentTime = GameTime::GetGameTime().count();
constexpr uint32 MAX_PROCESSED_PACKETS_IN_SAME_WORLDSESSION_UPDATE = 150;
while (m_Socket && _recvQueue.next(packet, updater))
{
OpcodeClient opcode = static_cast<OpcodeClient>(packet->GetOpcode());
ClientOpcodeHandler const* opHandle = opcodeTable[opcode];
METRIC_DETAILED_TIMER("worldsession_update_opcode_time", METRIC_TAG("opcode", opHandle->Name));
LOG_DEBUG("network", "message id {} ({}) under READ", opcode, opHandle->Name);
try
{
switch (opHandle->Status)
{
case STATUS_LOGGEDIN:
if (!_player)
{
// skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
//! If player didn't log out a while ago, it means packets are being sent while the server does not recognize
//! the client to be in world yet. We will re-add the packets to the bottom of the queue and process them later.
if (!m_playerRecentlyLogout)
{
requeuePackets.push_back(packet);
deletePacket = false;
LOG_DEBUG("network", "Delaying processing of message with status STATUS_LOGGEDIN: No players in the world for account id {}", GetAccountId());
}
}
else if (_player->IsInWorld())
{
if (AntiDOS.EvaluateOpcode(*packet, currentTime))
{
if (!sScriptMgr->CanPacketReceive(this, *packet))
{
break;
}
opHandle->Call(this, *packet);
LogUnprocessedTail(packet);
}
else
processedPackets = MAX_PROCESSED_PACKETS_IN_SAME_WORLDSESSION_UPDATE; // break out of packet processing loop
}
// lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
break;
case STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT:
if (!_player && !m_playerRecentlyLogout) // There's a short delay between _player = null and m_playerRecentlyLogout = true during logout
{
LogUnexpectedOpcode(packet, "STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT",
"the player has not logged in yet and not recently logout");
}
else if (AntiDOS.EvaluateOpcode(*packet, currentTime))
{
// not expected _player or must checked in packet hanlder
if (!sScriptMgr->CanPacketReceive(this, *packet))
break;
opHandle->Call(this, *packet);
LogUnprocessedTail(packet);
}
else
processedPackets = MAX_PROCESSED_PACKETS_IN_SAME_WORLDSESSION_UPDATE; // break out of packet processing loop
break;
case STATUS_TRANSFER:
if (_player && !_player->IsInWorld() && AntiDOS.EvaluateOpcode(*packet, currentTime))
{
if (!sScriptMgr->CanPacketReceive(this, *packet))
{
break;
}
opHandle->Call(this, *packet);
LogUnprocessedTail(packet);
}
else
processedPackets = MAX_PROCESSED_PACKETS_IN_SAME_WORLDSESSION_UPDATE; // break out of packet processing loop
break;
case STATUS_AUTHED:
if (m_inQueue) // prevent cheating
break;
// some auth opcodes can be recieved before STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT opcodes
// however when we recieve CMSG_CHAR_ENUM we are surely no longer during the logout process.
if (packet->GetOpcode() == CMSG_CHAR_ENUM)
m_playerRecentlyLogout = false;
if (AntiDOS.EvaluateOpcode(*packet, currentTime))
{
if (!sScriptMgr->CanPacketReceive(this, *packet))
{
break;
}
opHandle->Call(this, *packet);
LogUnprocessedTail(packet);
}
else
processedPackets = MAX_PROCESSED_PACKETS_IN_SAME_WORLDSESSION_UPDATE; // break out of packet processing loop
break;
case STATUS_NEVER:
LOG_ERROR("network.opcode", "Received not allowed opcode {} from {}",
GetOpcodeNameForLogging(static_cast<OpcodeClient>(packet->GetOpcode())), GetPlayerInfo());
break;
case STATUS_UNHANDLED:
LOG_DEBUG("network.opcode", "Received not handled opcode {} from {}",
GetOpcodeNameForLogging(static_cast<OpcodeClient>(packet->GetOpcode())), GetPlayerInfo());
break;
}
}
catch (WorldPackets::InvalidHyperlinkException const& ihe)
{
LOG_ERROR("network", "{} sent {} with an invalid link:\n{}", GetPlayerInfo(),
GetOpcodeNameForLogging(static_cast<OpcodeClient>(packet->GetOpcode())), ihe.GetInvalidValue());
if (sWorld->getIntConfig(CONFIG_CHAT_STRICT_LINK_CHECKING_KICK))
{
KickPlayer("WorldSession::Update Invalid chat link");
}
}
catch (WorldPackets::IllegalHyperlinkException const& ihe)
{
LOG_ERROR("network", "{} sent {} which illegally contained a hyperlink:\n{}", GetPlayerInfo(),
GetOpcodeNameForLogging(static_cast<OpcodeClient>(packet->GetOpcode())), ihe.GetInvalidValue());
if (sWorld->getIntConfig(CONFIG_CHAT_STRICT_LINK_CHECKING_KICK))
{
KickPlayer("WorldSession::Update Illegal chat link");
}
}
catch (WorldPackets::PacketArrayMaxCapacityException const& pamce)
{
LOG_ERROR("network", "PacketArrayMaxCapacityException: {} while parsing {} from {}.",
pamce.what(), GetOpcodeNameForLogging(static_cast<OpcodeClient>(packet->GetOpcode())), GetPlayerInfo());
}
catch (ByteBufferException const&)
{
LOG_ERROR("network", "WorldSession::Update ByteBufferException occured while parsing a packet (opcode: {}) from client {}, accountid={}. Skipped packet.", packet->GetOpcode(), GetRemoteAddress(), GetAccountId());
if (sLog->ShouldLog("network", LogLevel::LOG_LEVEL_DEBUG))
{
LOG_DEBUG("network", "Dumping error causing packet:");
packet->hexlike();
}
}
if (deletePacket)
delete packet;
deletePacket = true;
processedPackets++;
//process only a max amout of packets in 1 Update() call.
//Any leftover will be processed in next update
if (processedPackets > MAX_PROCESSED_PACKETS_IN_SAME_WORLDSESSION_UPDATE)
break;
}
_recvQueue.readd(requeuePackets.begin(), requeuePackets.end());
METRIC_VALUE("processed_packets", processedPackets);
METRIC_VALUE("addon_messages", _addonMessageReceiveCount.load());
_addonMessageReceiveCount = 0;
if (!updater.ProcessUnsafe()) // <=> updater is of type MapSessionFilter
{
// Send time sync packet every 10s.
if (_timeSyncTimer > 0)
{
if (diff >= _timeSyncTimer)
{
SendTimeSync();
}
else
{
_timeSyncTimer -= diff;
}
}
}
ProcessQueryCallbacks();
//check if we are safe to proceed with logout
//logout procedure should happen only in World::UpdateSessions() method!!!
if (updater.ProcessUnsafe())
{
if (m_Socket && m_Socket->IsOpen() && _warden)
{
_warden->Update(diff);
}
if (ShouldLogOut(currentTime) && !m_playerLoading)
{
LogoutPlayer(true);
}
if (m_Socket && !m_Socket->IsOpen())
{
if (GetPlayer() && _warden)
_warden->Update(diff);
m_Socket = nullptr;
}
if (!m_Socket)
{
return false; //Will remove this session from the world session map
}
}
return true;
}
bool WorldSession::HandleSocketClosed()
{
if (m_Socket && !m_Socket->IsOpen() && !IsKicked() && GetPlayer() && !PlayerLogout() && GetPlayer()->m_taxi.empty() && GetPlayer()->IsInWorld() && !World::IsStopped())
{
m_Socket = nullptr;
GetPlayer()->TradeCancel(false);
return true;
}
return false;
}
bool WorldSession::IsSocketClosed() const
{
return !m_Socket || !m_Socket->IsOpen();
}
void WorldSession::HandleTeleportTimeout(bool updateInSessions)
{
// pussywizard: handle teleport ack timeout
if (m_Socket && m_Socket->IsOpen() && GetPlayer() && GetPlayer()->IsBeingTeleported())
{
time_t currTime = GameTime::GetGameTime().count();
if (updateInSessions) // session update from World::UpdateSessions
{
if (GetPlayer()->IsBeingTeleportedFar() && GetPlayer()->GetSemaphoreTeleportFar() + sWorld->getIntConfig(CONFIG_TELEPORT_TIMEOUT_FAR) < currTime)
while (GetPlayer() && GetPlayer()->IsBeingTeleportedFar())
HandleMoveWorldportAck();
}
else // session update from Map::Update
{
if (GetPlayer()->IsBeingTeleportedNear() && GetPlayer()->GetSemaphoreTeleportNear() + sWorld->getIntConfig(CONFIG_TELEPORT_TIMEOUT_NEAR) < currTime)
while (GetPlayer() && GetPlayer()->IsInWorld() && GetPlayer()->IsBeingTeleportedNear())
{
Player* plMover = GetPlayer()->m_mover->ToPlayer();
if (!plMover)
break;
WorldPacket pkt(MSG_MOVE_TELEPORT_ACK, 20);
pkt << plMover->GetPackGUID();
pkt << uint32(0); // flags
pkt << uint32(0); // time
HandleMoveTeleportAck(pkt);
}
}
}
}
/// %Log the player out
void WorldSession::LogoutPlayer(bool save)
{
// finish pending transfers before starting the logout
while (_player && _player->IsBeingTeleportedFar())
HandleMoveWorldportAck();
m_playerLogout = true;
m_playerSave = save;
if (_player)
{
//! Call script hook before other logout events
sScriptMgr->OnBeforePlayerLogout(_player);
if (ObjectGuid lguid = _player->GetLootGUID())
DoLootRelease(lguid);
///- If the player just died before logging out, make him appear as a ghost
//FIXME: logout must be delayed in case lost connection with client in time of combat
if (_player->GetDeathTimer())
{
_player->getHostileRefMgr().deleteReferences(true);
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
}
else if (_player->HasSpiritOfRedemptionAura())
{
// this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
_player->RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT);
_player->KillPlayer();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
}
else if (_player->HasPendingBind())
{
_player->RepopAtGraveyard();
_player->SetPendingBind(0, 0);
}
// pussywizard: leave whole bg on logout (character stays ingame when necessary)
// pussywizard: GetBattleground() checked inside
_player->LeaveBattleground();
// pussywizard: checked first time
if (!_player->IsBeingTeleportedFar() && !_player->m_InstanceValid && !_player->IsGameMaster())
_player->RepopAtGraveyard();
sOutdoorPvPMgr->HandlePlayerLeaveZone(_player, _player->GetZoneId());
sWorldState->HandlePlayerLeaveZone(_player, static_cast<WorldStateZoneId>(_player->GetZoneId()));
// pussywizard: remove from battleground queues on logout
for (int i = 0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
if (BattlegroundQueueTypeId bgQueueTypeId = _player->GetBattlegroundQueueTypeId(i))
{
// track if player logs out after invited to join BG
if (_player->IsInvitedForBattlegroundInstance())
{
if (sWorld->getBoolConfig(CONFIG_BATTLEGROUND_TRACK_DESERTERS))
{
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_DESERTER_TRACK);
stmt->SetData(0, _player->GetGUID().GetCounter());
stmt->SetData(1, BG_DESERTION_TYPE_INVITE_LOGOUT);
CharacterDatabase.Execute(stmt);
}
sScriptMgr->OnBattlegroundDesertion(_player, BG_DESERTION_TYPE_INVITE_LOGOUT);
}
if (bgQueueTypeId >= BATTLEGROUND_QUEUE_2v2 && bgQueueTypeId < MAX_BATTLEGROUND_QUEUE_TYPES && _player->IsInvitedForBattlegroundQueueType(bgQueueTypeId))
sScriptMgr->OnBattlegroundDesertion(_player, ARENA_DESERTION_TYPE_INVITE_LOGOUT);
_player->RemoveBattlegroundQueueId(bgQueueTypeId);
sBattlegroundMgr->GetBattlegroundQueue(bgQueueTypeId).RemovePlayer(_player->GetGUID(), true);
}
///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
if (Guild* guild = sGuildMgr->GetGuildById(_player->GetGuildId()))
guild->HandleMemberLogout(this);
///- Remove pet
_player->RemovePet(nullptr, PET_SAVE_AS_CURRENT);
// pussywizard: on logout remove auras that are removed at map change (before saving to db)
// there are some positive auras from boss encounters that can be kept by logging out and logging in after boss is dead, and may be used on next bosses
_player->RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
///- If the player is in a group and LeaveGroupOnLogout is enabled or if the player is invited to a group, remove him. If the group is then only 1 person, disband the group.
if (!_player->GetGroup() || sWorld->getBoolConfig(CONFIG_LEAVE_GROUP_ON_LOGOUT))
_player->UninviteFromGroup();
// remove player from the group if he is:
// a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected) d) LeaveGroupOnLogout is enabled
if (_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && !_player->GetGroup()->isLFGGroup() && m_Socket && sWorld->getBoolConfig(CONFIG_LEAVE_GROUP_ON_LOGOUT))
_player->RemoveFromGroup();
// pussywizard: checked second time after being removed from a group
if (!_player->IsBeingTeleportedFar() && !_player->m_InstanceValid && !_player->IsGameMaster())
_player->RepopAtGraveyard();
// Repop at GraveYard or other player far teleport will prevent saving player because of not present map
// Teleport player immediately for correct player save
while (_player && _player->IsBeingTeleportedFar())
HandleMoveWorldportAck();
///- empty buyback items and save the player in the database
// some save parts only correctly work in case player present in map/player_lists (pets, etc)
if (save)
{
uint32 eslot;
for (int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; ++j)
{
eslot = j - BUYBACK_SLOT_START;
_player->SetGuidValue(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), ObjectGuid::Empty);
_player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
_player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
}
_player->SaveToDB(false, true);
}
///- Leave all channels before player delete...
_player->CleanupChannels();
//! Send update to group and reset stored max enchanting level
if (_player->GetGroup())
{
_player->GetGroup()->SendUpdate();
_player->GetGroup()->ResetMaxEnchantingLevel();
if (_player->GetMap()->IsDungeon() || _player->GetMap()->IsRaidOrHeroicDungeon())
{
Map::PlayerList const &playerList = _player->GetMap()->GetPlayers();
if (playerList.IsEmpty())
_player->TeleportToEntryPoint();
}
}
//! Broadcast a logout message to the player's friends
sSocialMgr->SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUID(), true);
sSocialMgr->RemovePlayerSocial(_player->GetGUID());
//! Call script hook before deletion
sScriptMgr->OnPlayerLogout(_player);
METRIC_EVENT("player_events", "Logout", _player->GetName());
LOG_INFO("entities.player", "Account: {} (IP: {}) Logout Character:[{}] ({}) Level: {}",
GetAccountId(), GetRemoteAddress(), _player->GetName(), _player->GetGUID().ToString(), _player->GetLevel());
//! Remove the player from the world
// the player may not be in the world when logging out
// e.g if he got disconnected during a transfer to another map
// calls to GetMap in this case may cause crashes
_player->CleanupsBeforeDelete();
if (Map* _map = _player->FindMap())
{
_map->RemovePlayerFromMap(_player, true);
_map->AfterPlayerUnlinkFromMap();
}
SetPlayer(nullptr); // pointer already deleted
//! Send the 'logout complete' packet to the client
//! Client will respond by sending 3x CMSG_CANCEL_TRADE, which we currently dont handle
SendPacket(WorldPackets::Character::LogoutComplete().Write());
LOG_DEBUG("network", "SESSION: Sent SMSG_LOGOUT_COMPLETE Message");
//! Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ACCOUNT_ONLINE);
stmt->SetData(0, GetAccountId());
CharacterDatabase.Execute(stmt);
}
m_playerLogout = false;
m_playerSave = false;
m_playerRecentlyLogout = true;
SetLogoutStartTime(0);
}
/// Kick a player out of the World
void WorldSession::KickPlayer(std::string const& reason, bool setKicked)
{
if (m_Socket)
{
LOG_INFO("network.kick", "Account: {} Character: '{}' {} kicked with reason: {}", GetAccountId(), _player ? _player->GetName() : "<none>",
_player ? _player->GetGUID().ToString() : "", reason);
m_Socket->CloseSocket();
}
if (setKicked)
SetKicked(true); // pussywizard: the session won't be left ingame for 60 seconds and to also kick offline session
}
bool WorldSession::ValidateHyperlinksAndMaybeKick(std::string_view str)
{
if (Acore::Hyperlinks::CheckAllLinks(str))
return true;
LOG_ERROR("network", "Player {} {} sent a message with an invalid link:\n{}", GetPlayer()->GetName(),
GetPlayer()->GetGUID().ToString(), str);
if (sWorld->getIntConfig(CONFIG_CHAT_STRICT_LINK_CHECKING_KICK))
KickPlayer("WorldSession::ValidateHyperlinksAndMaybeKick Invalid chat link");
return false;
}
bool WorldSession::DisallowHyperlinksAndMaybeKick(std::string_view str)
{
if (str.find('|') == std::string_view::npos)
return true;
LOG_ERROR("network", "Player {} {} sent a message which illegally contained a hyperlink:\n{}", GetPlayer()->GetName(),
GetPlayer()->GetGUID().ToString(), str);
if (sWorld->getIntConfig(CONFIG_CHAT_STRICT_LINK_CHECKING_KICK))
KickPlayer("WorldSession::DisallowHyperlinksAndMaybeKick Illegal chat link");
return false;
}
char const* WorldSession::GetAcoreString(uint32 entry) const
{
return sObjectMgr->GetAcoreString(entry, GetSessionDbLocaleIndex());
}
std::string const* WorldSession::GetModuleString(std::string module, uint32 id) const
{
return sObjectMgr->GetModuleString(module, id, GetSessionDbLocaleIndex());
}
void WorldSession::Handle_NULL(WorldPacket& null)
{
LOG_ERROR("network.opcode", "Received unhandled opcode {} from {}",
GetOpcodeNameForLogging(static_cast<OpcodeClient>(null.GetOpcode())), GetPlayerInfo());
}
void WorldSession::Handle_EarlyProccess(WorldPacket& recvPacket)
{
LOG_ERROR("network.opcode", "Received opcode {} that must be processed in WorldSocket::ReadDataHandler from {}",
GetOpcodeNameForLogging(static_cast<OpcodeClient>(recvPacket.GetOpcode())), GetPlayerInfo());
}
void WorldSession::Handle_ServerSide(WorldPacket& recvPacket)
{
LOG_ERROR("network.opcode", "Received server-side opcode {} from {}",
GetOpcodeNameForLogging(static_cast<OpcodeServer>(recvPacket.GetOpcode())), GetPlayerInfo());
}
void WorldSession::Handle_Deprecated(WorldPacket& recvPacket)
{
LOG_ERROR("network.opcode", "Received deprecated opcode {} from {}",
GetOpcodeNameForLogging(static_cast<OpcodeClient>(recvPacket.GetOpcode())), GetPlayerInfo());
}
void WorldSession::SendAuthWaitQueue(uint32 position)
{
if (position == 0)
{
WorldPacket packet(SMSG_AUTH_RESPONSE, 1);
packet << uint8(AUTH_OK);
SendPacket(&packet);
}
else
{
WorldPacket packet(SMSG_AUTH_RESPONSE, 6);
packet << uint8(AUTH_WAIT_QUEUE);
packet << uint32(position);
packet << uint8(0); // unk
SendPacket(&packet);
}
}
void WorldSession::LoadAccountData(PreparedQueryResult result, uint32 mask)
{
for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
if (mask & (1 << i))
m_accountData[i] = AccountData();
if (!result)
return;
do
{
Field* fields = result->Fetch();
uint32 type = fields[0].Get<uint8>();
if (type >= NUM_ACCOUNT_DATA_TYPES)
{
LOG_ERROR("network", "Table `{}` have invalid account data type ({}), ignore.", mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
continue;
}
if ((mask & (1 << type)) == 0)
{
LOG_ERROR("network", "Table `{}` have non appropriate for table account data type ({}), ignore.", mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
continue;
}
m_accountData[type].Time = time_t(fields[1].Get<uint32>());
m_accountData[type].Data = fields[2].Get<std::string>();
} while (result->NextRow());
}
void WorldSession::SetAccountData(AccountDataType type, time_t tm, std::string const& data)
{
uint32 id = 0;
CharacterDatabaseStatements index;
if ((1 << type) & GLOBAL_CACHE_MASK)
{
id = GetAccountId();
index = CHAR_REP_ACCOUNT_DATA;
}
else
{
// _player can be nullptr and packet received after logout but m_GUID still store correct guid
if (!m_GUIDLow)
return;
id = m_GUIDLow;
index = CHAR_REP_PLAYER_ACCOUNT_DATA;
}
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(index);
stmt->SetData(0, id);
stmt->SetData(1, type);
stmt->SetData(2, uint32(tm));
stmt->SetData(3, data);
CharacterDatabase.Execute(stmt);
m_accountData[type].Time = tm;
m_accountData[type].Data = data;
}
void WorldSession::SendAccountDataTimes(uint32 mask)
{
WorldPacket data(SMSG_ACCOUNT_DATA_TIMES, 4 + 1 + 4 + 8 * 4); // changed in WotLK
data << uint32(GameTime::GetGameTime().count()); // unix time of something
data << uint8(1);
data << uint32(mask); // type mask
for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
if (mask & (1 << i))
data << uint32(GetAccountData(AccountDataType(i))->Time);// also unix time
SendPacket(&data);
}
void WorldSession::LoadTutorialsData(PreparedQueryResult result)
{
memset(m_Tutorials, 0, sizeof(uint32) * MAX_ACCOUNT_TUTORIAL_VALUES);
if (result)
{
for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
{
m_Tutorials[i] = (*result)[i].Get<uint32>();
}
}
m_TutorialsChanged = false;
}
void WorldSession::SendTutorialsData()
{
WorldPacket data(SMSG_TUTORIAL_FLAGS, 4 * MAX_ACCOUNT_TUTORIAL_VALUES);
for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
data << m_Tutorials[i];
SendPacket(&data);
}
void WorldSession::SaveTutorialsData(CharacterDatabaseTransaction trans)
{
if (!m_TutorialsChanged)
return;
CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_HAS_TUTORIALS);
stmt->SetData(0, GetAccountId());
bool hasTutorials = bool(CharacterDatabase.Query(stmt));
stmt = CharacterDatabase.GetPreparedStatement(hasTutorials ? CHAR_UPD_TUTORIALS : CHAR_INS_TUTORIALS);
for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
stmt->SetData(i, m_Tutorials[i]);
stmt->SetData(MAX_ACCOUNT_TUTORIAL_VALUES, GetAccountId());
trans->Append(stmt);
m_TutorialsChanged = false;
}
void WorldSession::ReadMovementInfo(WorldPacket& data, MovementInfo* mi)
{
data >> mi->flags;
data >> mi->flags2;
data >> mi->time;
data >> mi->pos.PositionXYZOStream();
if (mi->HasMovementFlag(MOVEMENTFLAG_ONTRANSPORT))
{
data >> mi->transport.guid.ReadAsPacked();
data >> mi->transport.pos.PositionXYZOStream();
data >> mi->transport.time;
data >> mi->transport.seat;
if (mi->HasExtraMovementFlag(MOVEMENTFLAG2_INTERPOLATED_MOVEMENT))
data >> mi->transport.time2;
}
if (mi->HasMovementFlag(MovementFlags(MOVEMENTFLAG_SWIMMING | MOVEMENTFLAG_FLYING)) || (mi->HasExtraMovementFlag(MOVEMENTFLAG2_ALWAYS_ALLOW_PITCHING)))
data >> mi->pitch;
data >> mi->fallTime;
if (mi->HasMovementFlag(MOVEMENTFLAG_FALLING))
{
data >> mi->jump.zspeed;
data >> mi->jump.sinAngle;
data >> mi->jump.cosAngle;
data >> mi->jump.xyspeed;