refactor(Core/Game): restyle game lib with astyle (#3466)

This commit is contained in:
Kargatum
2020-10-12 15:08:15 +07:00
committed by GitHub
parent e99b526e17
commit a2b26272d2
338 changed files with 52196 additions and 50944 deletions

View File

@@ -846,9 +846,9 @@ enum Opcodes
SMSG_INSTANCE_DIFFICULTY = 0x33B,
MSG_GM_RESETINSTANCELIMIT = 0x33C,
SMSG_MOTD = 0x33D,
SMSG_MOVE_SET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY= 0x33E,
SMSG_MOVE_UNSET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY= 0x33F,
CMSG_MOVE_SET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY_ACK= 0x340,
SMSG_MOVE_SET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY = 0x33E,
SMSG_MOVE_UNSET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY = 0x33F,
CMSG_MOVE_SET_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY_ACK = 0x340,
MSG_MOVE_START_SWIM_CHEAT = 0x341,
MSG_MOVE_STOP_SWIM_CHEAT = 0x342,
SMSG_MOVE_SET_CAN_FLY = 0x343,
@@ -858,7 +858,7 @@ enum Opcodes
CMSG_SOCKET_GEMS = 0x347,
CMSG_ARENA_TEAM_CREATE = 0x348,
SMSG_ARENA_TEAM_COMMAND_RESULT = 0x349,
MSG_MOVE_UPDATE_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY= 0x34A,
MSG_MOVE_UPDATE_CAN_TRANSITION_BETWEEN_SWIM_AND_FLY = 0x34A,
CMSG_ARENA_TEAM_QUERY = 0x34B,
SMSG_ARENA_TEAM_QUERY_RESPONSE = 0x34C,
CMSG_ARENA_TEAM_ROSTER = 0x34D,
@@ -1274,7 +1274,7 @@ enum Opcodes
CMSG_BATTLEFIELD_MGR_EXIT_REQUEST = 0x4E7,
SMSG_BATTLEFIELD_MGR_STATE_CHANGE = 0x4E8, // uint32, uint32
CMSG_BATTLEFIELD_MANAGER_ADVANCE_STATE = 0x4E9,
CMSG_BATTLEFIELD_MANAGER_SET_NEXT_TRANSITION_TIME= 0x4EA,
CMSG_BATTLEFIELD_MANAGER_SET_NEXT_TRANSITION_TIME = 0x4EA,
MSG_SET_RAID_DIFFICULTY = 0x4EB,
CMSG_TOGGLE_XP_GAIN = 0x4EC,
SMSG_TOGGLE_XP_GAIN = 0x4ED, // enable/disable XP gain console message

View File

@@ -33,7 +33,7 @@ void PacketLog::Initialize()
std::string logsDir = sConfigMgr->GetStringDefault("LogsDir", "");
if (!logsDir.empty())
if ((logsDir.at(logsDir.length()-1) != '/') && (logsDir.at(logsDir.length()-1) != '\\'))
if ((logsDir.at(logsDir.length() - 1) != '/') && (logsDir.at(logsDir.length() - 1) != '\\'))
logsDir.push_back('/');
std::string logname = sConfigMgr->GetStringDefault("PacketLogFile", "");
@@ -43,7 +43,7 @@ void PacketLog::Initialize()
void PacketLog::LogPacket(WorldPacket const& packet, Direction direction)
{
ByteBuffer data(4+4+4+1+packet.size());
ByteBuffer data(4 + 4 + 4 + 1 + packet.size());
data << int32(packet.GetOpcode());
data << int32(packet.size());
data << uint32(time(nullptr));

View File

@@ -19,19 +19,19 @@ class WorldPacket;
class PacketLog
{
private:
PacketLog();
~PacketLog();
private:
PacketLog();
~PacketLog();
public:
static PacketLog* instance();
public:
static PacketLog* instance();
void Initialize();
bool CanLogPacket() const { return (_file != nullptr); }
void LogPacket(WorldPacket const& packet, Direction direction);
void Initialize();
bool CanLogPacket() const { return (_file != nullptr); }
void LogPacket(WorldPacket const& packet, Direction direction);
private:
FILE* _file;
private:
FILE* _file;
};
#define sPacketLog PacketLog::instance()

View File

@@ -39,7 +39,8 @@
#include "LuaEngine.h"
#endif
namespace {
namespace
{
std::string const DefaultPlayerName = "<none>";
@@ -167,7 +168,7 @@ WorldSession::~WorldSession()
LoginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = %u;", GetAccountId()); // One-time query
}
std::string const & WorldSession::GetPlayerName() const
std::string const& WorldSession::GetPlayerName() const
{
return _player != NULL ? _player->GetName() : DefaultPlayerName;
}
@@ -177,8 +178,8 @@ std::string WorldSession::GetPlayerInfo() const
std::ostringstream ss;
ss << "[Player: " << GetPlayerName()
<< " (Guid: " << (_player != NULL ? _player->GetGUID() : 0)
<< ", Account: " << GetAccountId() << ")]";
<< " (Guid: " << (_player != NULL ? _player->GetGUID() : 0)
<< ", Account: " << GetAccountId() << ")]";
return ss.str();
}
@@ -279,7 +280,7 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater)
}
else
{
OpcodeHandler &opHandle = opcodeTable[packet->GetOpcode()];
OpcodeHandler& opHandle = opcodeTable[packet->GetOpcode()];
try
{
switch (opHandle.status)
@@ -312,10 +313,10 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater)
movementPacket = nullptr;
}
sScriptMgr->OnPacketReceive(this, *packet);
#ifdef ELUNA
#ifdef ELUNA
if (!sEluna->OnPacketReceive(this, *packet))
break;
#endif
#endif
(this->*opHandle.handler)(*packet);
}
break;
@@ -328,10 +329,10 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater)
movementPacket = nullptr;
}
sScriptMgr->OnPacketReceive(this, *packet);
#ifdef ELUNA
#ifdef ELUNA
if (!sEluna->OnPacketReceive(this, *packet))
break;
#endif
#endif
(this->*opHandle.handler)(*packet);
}
break;
@@ -342,10 +343,10 @@ bool WorldSession::Update(uint32 diff, PacketFilter& updater)
if (AntiDOS.EvaluateOpcode(*packet, currentTime))
{
sScriptMgr->OnPacketReceive(this, *packet);
#ifdef ELUNA
#ifdef ELUNA
if (!sEluna->OnPacketReceive(this, *packet))
break;
#endif
#endif
(this->*opHandle.handler)(*packet);
}
break;
@@ -568,7 +569,7 @@ void WorldSession::LogoutPlayer(bool save)
_player->GetGroup()->SendUpdate();
_player->GetGroup()->ResetMaxEnchantingLevel();
Map::PlayerList const &playerList = _player->GetMap()->GetPlayers();
Map::PlayerList const& playerList = _player->GetMap()->GetPlayers();
if (_player->GetMap()->IsDungeon() || _player->GetMap()->IsRaidOrHeroicDungeon())
if (playerList.isEmpty())
@@ -627,7 +628,7 @@ void WorldSession::KickPlayer(std::string const& reason, bool setKicked)
SetKicked(true); // pussywizard: the session won't be left ingame for 60 seconds and to also kick offline session
}
void WorldSession::SendNotification(const char *format, ...)
void WorldSession::SendNotification(const char* format, ...)
{
if (format)
{
@@ -805,7 +806,7 @@ void WorldSession::SendTutorialsData()
SendPacket(&data);
}
void WorldSession::SaveTutorialsData(SQLTransaction &trans)
void WorldSession::SaveTutorialsData(SQLTransaction& trans)
{
if (!m_TutorialsChanged)
return;
@@ -824,7 +825,7 @@ void WorldSession::SaveTutorialsData(SQLTransaction &trans)
m_TutorialsChanged = false;
}
void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo* mi)
void WorldSession::ReadMovementInfo(WorldPacket& data, MovementInfo* mi)
{
data >> mi->flags;
data >> mi->flags2;
@@ -879,46 +880,46 @@ void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo* mi)
#endif
/*! This must be a packet spoofing attempt. MOVEMENTFLAG_ROOT sent from the client is not valid
in conjunction with any of the moving movement flags such as MOVEMENTFLAG_FORWARD.
It will freeze clients that receive this player's movement info.
*/
/*! This must be a packet spoofing attempt. MOVEMENTFLAG_ROOT sent from the client is not valid
in conjunction with any of the moving movement flags such as MOVEMENTFLAG_FORWARD.
It will freeze clients that receive this player's movement info.
*/
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_ROOT),
MOVEMENTFLAG_ROOT);
MOVEMENTFLAG_ROOT);
//! Cannot hover without SPELL_AURA_HOVER
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_HOVER) && !GetPlayer()->HasAuraType(SPELL_AURA_HOVER),
MOVEMENTFLAG_HOVER);
MOVEMENTFLAG_HOVER);
//! Cannot ascend and descend at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_ASCENDING) && mi->HasMovementFlag(MOVEMENTFLAG_DESCENDING),
MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING);
MOVEMENTFLAG_ASCENDING | MOVEMENTFLAG_DESCENDING);
//! Cannot move left and right at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_LEFT) && mi->HasMovementFlag(MOVEMENTFLAG_RIGHT),
MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT);
MOVEMENTFLAG_LEFT | MOVEMENTFLAG_RIGHT);
//! Cannot strafe left and right at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_STRAFE_LEFT) && mi->HasMovementFlag(MOVEMENTFLAG_STRAFE_RIGHT),
MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT);
MOVEMENTFLAG_STRAFE_LEFT | MOVEMENTFLAG_STRAFE_RIGHT);
//! Cannot pitch up and down at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_PITCH_UP) && mi->HasMovementFlag(MOVEMENTFLAG_PITCH_DOWN),
MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN);
MOVEMENTFLAG_PITCH_UP | MOVEMENTFLAG_PITCH_DOWN);
//! Cannot move forwards and backwards at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_FORWARD) && mi->HasMovementFlag(MOVEMENTFLAG_BACKWARD),
MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD);
MOVEMENTFLAG_FORWARD | MOVEMENTFLAG_BACKWARD);
//! Cannot walk on water without SPELL_AURA_WATER_WALK
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_WATERWALKING) &&
!GetPlayer()->HasAuraType(SPELL_AURA_WATER_WALK) &&
!GetPlayer()->HasAuraType(SPELL_AURA_GHOST),
MOVEMENTFLAG_WATERWALKING);
!GetPlayer()->HasAuraType(SPELL_AURA_WATER_WALK) &&
!GetPlayer()->HasAuraType(SPELL_AURA_GHOST),
MOVEMENTFLAG_WATERWALKING);
//! Cannot feather fall without SPELL_AURA_FEATHER_FALL
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_FALLING_SLOW) && !GetPlayer()->HasAuraType(SPELL_AURA_FEATHER_FALL),
MOVEMENTFLAG_FALLING_SLOW);
MOVEMENTFLAG_FALLING_SLOW);
/*! Cannot fly if no fly auras present. Exception is being a GM.
Note that we check for account level instead of Player::IsGameMaster() because in some
@@ -928,15 +929,15 @@ void WorldSession::ReadMovementInfo(WorldPacket &data, MovementInfo* mi)
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_FLYING | MOVEMENTFLAG_CAN_FLY) && GetSecurity() == SEC_PLAYER && !GetPlayer()->m_mover->HasAuraType(SPELL_AURA_FLY) && !GetPlayer()->m_mover->HasAuraType(SPELL_AURA_MOD_INCREASE_MOUNTED_FLIGHT_SPEED),
MOVEMENTFLAG_FLYING | MOVEMENTFLAG_CAN_FLY);
MOVEMENTFLAG_FLYING | MOVEMENTFLAG_CAN_FLY);
//! Cannot fly and fall at the same time
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_CAN_FLY | MOVEMENTFLAG_DISABLE_GRAVITY) && mi->HasMovementFlag(MOVEMENTFLAG_FALLING),
MOVEMENTFLAG_FALLING);
MOVEMENTFLAG_FALLING);
REMOVE_VIOLATING_FLAGS(mi->HasMovementFlag(MOVEMENTFLAG_SPLINE_ENABLED) &&
(!GetPlayer()->movespline->Initialized() || GetPlayer()->movespline->Finalized()), MOVEMENTFLAG_SPLINE_ENABLED);
(!GetPlayer()->movespline->Initialized() || GetPlayer()->movespline->Finalized()), MOVEMENTFLAG_SPLINE_ENABLED);
#undef REMOVE_VIOLATING_FLAGS
}
@@ -979,7 +980,7 @@ void WorldSession::WriteMovementInfo(WorldPacket* data, MovementInfo* mi)
*data << mi->splineElevation;
}
void WorldSession::ReadAddonsInfo(WorldPacket &data)
void WorldSession::ReadAddonsInfo(WorldPacket& data)
{
if (data.rpos() + 4 > data.size())
return;
@@ -1357,39 +1358,39 @@ bool WorldSession::DosProtection::EvaluateOpcode(WorldPacket& p, time_t time) co
return true;
sLog->outString("AntiDOS: Account %u, IP: %s, Ping: %u, Character %s, flooding packet (opc: %s (0x%X), count: %u)",
Session->GetAccountId(), Session->GetRemoteAddress().c_str(), Session->GetLatency(),
Session->GetPlayerName().c_str(), opcodeTable[p.GetOpcode()].name, p.GetOpcode(), packetCounter.amountCounter);
Session->GetAccountId(), Session->GetRemoteAddress().c_str(), Session->GetLatency(),
Session->GetPlayerName().c_str(), opcodeTable[p.GetOpcode()].name, p.GetOpcode(), packetCounter.amountCounter);
switch (_policy)
{
case POLICY_LOG:
return true;
case POLICY_KICK:
{
sLog->outString("AntiDOS: Player %s kicked!", Session->GetPlayerName().c_str());
Session->KickPlayer();
return false;
}
case POLICY_BAN:
{
uint32 bm = sWorld->getIntConfig(CONFIG_PACKET_SPOOF_BANMODE);
uint32 duration = sWorld->getIntConfig(CONFIG_PACKET_SPOOF_BANDURATION); // in seconds
std::string nameOrIp = "";
switch (bm)
{
case 0: // Ban account
(void)AccountMgr::GetName(Session->GetAccountId(), nameOrIp);
sBan->BanAccount(nameOrIp, std::to_string(duration), "DOS (Packet Flooding/Spoofing", "Server: AutoDOS");
break;
case 1: // Ban ip
nameOrIp = Session->GetRemoteAddress();
sBan->BanIP(nameOrIp, std::to_string(duration), "DOS (Packet Flooding/Spoofing", "Server: AutoDOS");
break;
sLog->outString("AntiDOS: Player %s kicked!", Session->GetPlayerName().c_str());
Session->KickPlayer();
return false;
}
case POLICY_BAN:
{
uint32 bm = sWorld->getIntConfig(CONFIG_PACKET_SPOOF_BANMODE);
uint32 duration = sWorld->getIntConfig(CONFIG_PACKET_SPOOF_BANDURATION); // in seconds
std::string nameOrIp = "";
switch (bm)
{
case 0: // Ban account
(void)AccountMgr::GetName(Session->GetAccountId(), nameOrIp);
sBan->BanAccount(nameOrIp, std::to_string(duration), "DOS (Packet Flooding/Spoofing", "Server: AutoDOS");
break;
case 1: // Ban ip
nameOrIp = Session->GetRemoteAddress();
sBan->BanIP(nameOrIp, std::to_string(duration), "DOS (Packet Flooding/Spoofing", "Server: AutoDOS");
break;
}
sLog->outString("AntiDOS: Player automatically banned for %u seconds.", duration);
return false;
}
sLog->outString("AntiDOS: Player automatically banned for %u seconds.", duration);
return false;
}
default: // invalid policy
return true;
}
@@ -1490,12 +1491,12 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co
case CMSG_FORCE_WALK_SPEED_CHANGE_ACK: // not profiled
case CMSG_FORCE_TURN_RATE_CHANGE_ACK: // not profiled
case CMSG_FORCE_PITCH_RATE_CHANGE_ACK: // not profiled
{
// "0" is a magic number meaning there's no limit for the opcode.
// All the opcodes above must cause little CPU usage and no sync/async database queries at all
maxPacketCounterAllowed = 0;
break;
}
{
// "0" is a magic number meaning there's no limit for the opcode.
// All the opcodes above must cause little CPU usage and no sync/async database queries at all
maxPacketCounterAllowed = 0;
break;
}
case CMSG_QUESTGIVER_ACCEPT_QUEST: // 0 4
case CMSG_QUESTLOG_REMOVE_QUEST: // 0 4
@@ -1508,10 +1509,10 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co
case CMSG_PLAYER_VEHICLE_ENTER: // 0 8
case CMSG_LEARN_PREVIEW_TALENTS_PET: // not profiled
case MSG_MOVE_HEARTBEAT:
{
maxPacketCounterAllowed = 200;
break;
}
{
maxPacketCounterAllowed = 200;
break;
}
case CMSG_GUILD_SET_PUBLIC_NOTE: // 1 2 1 async db query
case CMSG_GUILD_SET_OFFICER_NOTE: // 1 2 1 async db query
@@ -1522,25 +1523,25 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co
case CMSG_GAMEOBJ_REPORT_USE: // not profiled
case CMSG_GAMEOBJ_USE: // not profiled
case MSG_PETITION_DECLINE: // not profiled
{
maxPacketCounterAllowed = 50;
break;
}
{
maxPacketCounterAllowed = 50;
break;
}
case CMSG_QUEST_POI_QUERY: // 0 25 very high upload bandwidth usage
{
maxPacketCounterAllowed = MAX_QUEST_LOG_SIZE;
break;
}
{
maxPacketCounterAllowed = MAX_QUEST_LOG_SIZE;
break;
}
case CMSG_GM_REPORT_LAG: // 1 3 1 async db query
case CMSG_SPELLCLICK: // not profiled
case CMSG_REMOVE_GLYPH: // not profiled
case CMSG_DISMISS_CONTROLLED_VEHICLE: // not profiled
{
maxPacketCounterAllowed = 20;
break;
}
{
maxPacketCounterAllowed = 20;
break;
}
case CMSG_PETITION_SIGN: // 9 4 2 sync 1 async db queries
case CMSG_TURN_IN_PETITION: // 8 5.5 2 sync db query
@@ -1569,10 +1570,10 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co
case CMSG_SOCKET_GEMS: // not profiled
case CMSG_WRAP_ITEM: // not profiled
case CMSG_REPORT_PVP_AFK: // not profiled
{
maxPacketCounterAllowed = 10;
break;
}
{
maxPacketCounterAllowed = 10;
break;
}
case CMSG_CHAR_CREATE: // 7 5 3 async db queries
case CMSG_CHAR_ENUM: // 22 3 2 async db queries
@@ -1620,22 +1621,22 @@ uint32 WorldSession::DosProtection::GetMaxPacketCounterAllowed(uint16 opcode) co
case MSG_SET_RAID_DIFFICULTY: // not profiled
case MSG_PARTY_ASSIGNMENT: // not profiled
case MSG_RAID_READY_CHECK: // not profiled
{
maxPacketCounterAllowed = 3;
break;
}
{
maxPacketCounterAllowed = 3;
break;
}
case CMSG_ITEM_REFUND_INFO: // not profiled
{
maxPacketCounterAllowed = PLAYER_SLOTS_COUNT;
break;
}
{
maxPacketCounterAllowed = PLAYER_SLOTS_COUNT;
break;
}
default:
{
maxPacketCounterAllowed = 100;
break;
}
{
maxPacketCounterAllowed = 100;
break;
}
}
return maxPacketCounterAllowed;

File diff suppressed because it is too large Load Diff

View File

@@ -51,23 +51,23 @@ struct ServerPktHeader
*/
ServerPktHeader(uint32 size, uint16 cmd) : size(size)
{
uint8 headerIndex=0;
uint8 headerIndex = 0;
if (isLargePacket())
{
sLog->outDebug(LOG_FILTER_NETWORKIO, "initializing large server to client packet. Size: %u, cmd: %u", size, cmd);
header[headerIndex++] = 0x80|(0xFF &(size>>16));
header[headerIndex++] = 0x80 | (0xFF & (size >> 16));
}
header[headerIndex++] = 0xFF &(size>>8);
header[headerIndex++] = 0xFF &size;
header[headerIndex++] = 0xFF & (size >> 8);
header[headerIndex++] = 0xFF & size;
header[headerIndex++] = 0xFF & cmd;
header[headerIndex++] = 0xFF & (cmd>>8);
header[headerIndex++] = 0xFF & (cmd >> 8);
}
uint8 getHeaderLength()
{
// cmd = 2 bytes, size= 2||3bytes
return 2+(isLargePacket()?3:2);
return 2 + (isLargePacket() ? 3 : 2);
}
bool isLargePacket() const
@@ -92,15 +92,15 @@ struct ClientPktHeader
#endif
WorldSocket::WorldSocket(void): WorldHandler(),
m_LastPingTime(SystemTimePoint::min()), m_OverSpeedPings(0), m_Session(0),
m_RecvWPct(0), m_RecvPct(), m_Header(sizeof (ClientPktHeader)),
m_OutBuffer(0), m_OutBufferSize(65536), m_OutActive(false),
m_Seed(static_cast<uint32> (rand32()))
m_LastPingTime(SystemTimePoint::min()), m_OverSpeedPings(0), m_Session(0),
m_RecvWPct(0), m_RecvPct(), m_Header(sizeof (ClientPktHeader)),
m_OutBuffer(0), m_OutBufferSize(65536), m_OutActive(false),
m_Seed(static_cast<uint32> (rand32()))
{
reference_counting_policy().value (ACE_Event_Handler::Reference_Counting_Policy::ENABLED);
msg_queue()->high_water_mark(8*1024*1024);
msg_queue()->low_water_mark(8*1024*1024);
msg_queue()->high_water_mark(8 * 1024 * 1024);
msg_queue()->low_water_mark(8 * 1024 * 1024);
}
WorldSocket::~WorldSocket(void)
@@ -158,7 +158,7 @@ int WorldSocket::SendPacket(WorldPacket const& pct)
if (sPacketLog->CanLogPacket())
sPacketLog->LogPacket(pct, SERVER_TO_CLIENT);
ServerPktHeader header(pct.size()+2, pct.GetOpcode());
ServerPktHeader header(pct.size() + 2, pct.GetOpcode());
m_Crypt.EncryptSend ((uint8*)header.header, header.getHeaderLength());
if (m_OutBuffer->space() >= pct.size() + header.getHeaderLength() && msg_queue()->is_empty())
@@ -204,7 +204,7 @@ long WorldSocket::RemoveReference(void)
return static_cast<long> (remove_reference());
}
int WorldSocket::open(void *a)
int WorldSocket::open(void* a)
{
ACE_UNUSED_ARG (a);
@@ -282,29 +282,29 @@ int WorldSocket::handle_input(ACE_HANDLE)
switch (handle_input_missing_data())
{
case -1 :
{
if ((errno == EWOULDBLOCK) ||
(errno == EAGAIN))
{
return Update(); // interesting line, isn't it ?
if ((errno == EWOULDBLOCK) ||
(errno == EAGAIN))
{
return Update(); // interesting line, isn't it ?
}
#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS)
sLog->outStaticDebug("WorldSocket::handle_input: Peer error closing connection errno = %s", ACE_OS::strerror (errno));
#endif
errno = ECONNRESET;
return -1;
}
#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS)
sLog->outStaticDebug("WorldSocket::handle_input: Peer error closing connection errno = %s", ACE_OS::strerror (errno));
#endif
errno = ECONNRESET;
return -1;
}
case 0:
{
{
#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS)
sLog->outStaticDebug("WorldSocket::handle_input: Peer has closed connection");
sLog->outStaticDebug("WorldSocket::handle_input: Peer has closed connection");
#endif
errno = ECONNRESET;
return -1;
}
errno = ECONNRESET;
return -1;
}
case 1:
return 1;
default:
@@ -533,12 +533,12 @@ int WorldSocket::handle_input_missing_data(void)
char buf [4096];
ACE_Data_Block db (sizeof (buf),
ACE_Message_Block::MB_DATA,
buf,
0,
0,
ACE_Message_Block::DONT_DELETE,
0);
ACE_Message_Block::MB_DATA,
buf,
0,
0,
ACE_Message_Block::DONT_DELETE,
0);
ACE_Message_Block message_block(&db,
ACE_Message_Block::DONT_DELETE,
@@ -547,7 +547,7 @@ int WorldSocket::handle_input_missing_data(void)
const size_t recv_size = message_block.space();
const ssize_t n = peer().recv (message_block.wr_ptr(),
recv_size);
recv_size);
if (n <= 0)
return int(n);
@@ -627,7 +627,7 @@ int WorldSocket::cancel_wakeup_output(GuardType& g)
g.release();
if (reactor()->cancel_wakeup
(this, ACE_Event_Handler::WRITE_MASK) == -1)
(this, ACE_Event_Handler::WRITE_MASK) == -1)
{
// would be good to store errno from reactor with errno guard
sLog->outError("WorldSocket::cancel_wakeup_output");
@@ -647,7 +647,7 @@ int WorldSocket::schedule_wakeup_output(GuardType& g)
g.release();
if (reactor()->schedule_wakeup
(this, ACE_Event_Handler::WRITE_MASK) == -1)
(this, ACE_Event_Handler::WRITE_MASK) == -1)
{
sLog->outError("WorldSocket::schedule_wakeup_output");
return -1;
@@ -677,15 +677,15 @@ int WorldSocket::ProcessIncoming(WorldPacket* new_pct)
switch (opcode)
{
case CMSG_PING:
{
try
{
return HandlePing(*new_pct);
try
{
return HandlePing(*new_pct);
}
catch (ByteBufferPositionException const&) {}
sLog->outError("WorldSocket::ReadDataHandler(): client sent malformed CMSG_PING");
return -1;
}
catch (ByteBufferPositionException const&) {}
sLog->outError("WorldSocket::ReadDataHandler(): client sent malformed CMSG_PING");
return -1;
}
case CMSG_AUTH_SESSION:
if (m_Session)
{
@@ -693,36 +693,36 @@ int WorldSocket::ProcessIncoming(WorldPacket* new_pct)
return -1;
}
return HandleAuthSession (*new_pct);
case CMSG_KEEP_ALIVE:
case CMSG_KEEP_ALIVE:
if (m_Session)
m_Session->ResetTimeOutTime(true);
return 0;
default:
{
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
if (m_Session != nullptr)
{
// Our Idle timer will reset on any non PING opcodes.
// Catches people idling on the login screen and any lingering ingame connections.
m_Session->ResetTimeOutTime(false);
ACE_GUARD_RETURN (LockType, Guard, m_SessionLock, -1);
// OK, give the packet to WorldSession
aptr.release();
m_Session->QueuePacket (new_pct);
return 0;
if (m_Session != nullptr)
{
// Our Idle timer will reset on any non PING opcodes.
// Catches people idling on the login screen and any lingering ingame connections.
m_Session->ResetTimeOutTime(false);
// OK, give the packet to WorldSession
aptr.release();
m_Session->QueuePacket (new_pct);
return 0;
}
else
{
sLog->outError("WorldSocket::ProcessIncoming: Client not authed opcode = %u", uint32(opcode));
return -1;
}
}
else
{
sLog->outError("WorldSocket::ProcessIncoming: Client not authed opcode = %u", uint32(opcode));
return -1;
}
}
}
}
catch (ByteBufferException const&)
{
sLog->outError("WorldSocket::ProcessIncoming ByteBufferException occured while parsing an instant handled packet (opcode: %u) from client %s, accountid=%i. Disconnected client.", opcode, GetRemoteAddress().c_str(), m_Session?m_Session->GetAccountId():-1);
sLog->outError("WorldSocket::ProcessIncoming ByteBufferException occured while parsing an instant handled packet (opcode: %u) from client %s, accountid=%i. Disconnected client.", opcode, GetRemoteAddress().c_str(), m_Session ? m_Session->GetAccountId() : -1);
if (sLog->IsOutDebug())
{
sLog->outDebug(LOG_FILTER_NETWORKIO, "Dumping error causing packet:");
@@ -940,9 +940,9 @@ int WorldSocket::HandleAuthSession(WorldPacket& recvPacket)
uint32 seed = m_Seed;
sha.UpdateData (account);
sha.UpdateData ((uint8 *) & t, 4);
sha.UpdateData ((uint8 *) & clientSeed, 4);
sha.UpdateData ((uint8 *) & seed, 4);
sha.UpdateData ((uint8*) & t, 4);
sha.UpdateData ((uint8*) & clientSeed, 4);
sha.UpdateData ((uint8*) & seed, 4);
sha.UpdateBigNumbers (&k, nullptr);
sha.Finalize();
@@ -959,8 +959,8 @@ int WorldSocket::HandleAuthSession(WorldPacket& recvPacket)
#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS)
sLog->outStaticDebug("WorldSocket::HandleAuthSession: Client '%s' authenticated successfully from %s.",
account.c_str(),
address.c_str());
account.c_str(),
address.c_str());
#endif
// Check if this user is by any chance a recruiter
stmt = LoginDatabase.GetPreparedStatement(LOGIN_SEL_ACCOUNT_RECRUITER);
@@ -1005,7 +1005,7 @@ int WorldSocket::HandleAuthSession(WorldPacket& recvPacket)
SendPacket(packet);
sLog->outError("WorldSocket::HandleAuthSession: Client %s requested connecting with realm id %u but this realm has id %u set in config.",
address.c_str(), realm, realmID);
address.c_str(), realm, realmID);
sScriptMgr->OnFailedAccountLogin(id);
return -1;
}
@@ -1044,7 +1044,7 @@ int WorldSocket::HandlePing(WorldPacket& recvPacket)
else
{
auto now = std::chrono::system_clock::now();
Seconds seconds = std::chrono::duration_cast<Seconds>(now - m_LastPingTime);
Seconds seconds = std::chrono::duration_cast<Seconds>(now - m_LastPingTime);
m_LastPingTime = now;
if (seconds.count() < 27)
@@ -1061,10 +1061,10 @@ int WorldSocket::HandlePing(WorldPacket& recvPacket)
{
Player* _player = m_Session->GetPlayer();
sLog->outError("WorldSocket::HandlePing: Player (account: %u, GUID: %u, name: %s) kicked for over-speed pings (address: %s)",
m_Session->GetAccountId(),
_player ? _player->GetGUIDLow() : 0,
_player ? _player->GetName().c_str() : "<none>",
GetRemoteAddress().c_str());
m_Session->GetAccountId(),
_player ? _player->GetGUIDLow() : 0,
_player ? _player->GetName().c_str() : "<none>",
GetRemoteAddress().c_str());
return -1;
}
@@ -1086,10 +1086,10 @@ int WorldSocket::HandlePing(WorldPacket& recvPacket)
else
{
sLog->outError("WorldSocket::HandlePing: peer sent CMSG_PING, "
"but is not authenticated or got recently kicked, "
" address = %s",
GetRemoteAddress().c_str());
return -1;
"but is not authenticated or got recently kicked, "
" address = %s",
GetRemoteAddress().c_str());
return -1;
}
}

View File

@@ -74,124 +74,124 @@ typedef ACE_Svc_Handler<ACE_SOCK_STREAM, ACE_NULL_SYNCH> WorldHandler;
*/
class WorldSocket : public WorldHandler
{
public:
WorldSocket (void);
virtual ~WorldSocket (void);
public:
WorldSocket (void);
virtual ~WorldSocket (void);
friend class WorldSocketMgr;
friend class WorldSocketMgr;
/// Mutex type used for various synchronizations.
typedef ACE_Thread_Mutex LockType;
typedef ACE_Guard<LockType> GuardType;
/// Mutex type used for various synchronizations.
typedef ACE_Thread_Mutex LockType;
typedef ACE_Guard<LockType> GuardType;
/// Check if socket is closed.
bool IsClosed (void) const;
/// Check if socket is closed.
bool IsClosed (void) const;
/// Close the socket.
void CloseSocket(std::string const& reason);
/// Close the socket.
void CloseSocket(std::string const& reason);
/// Get address of connected peer.
const std::string& GetRemoteAddress (void) const;
/// Get address of connected peer.
const std::string& GetRemoteAddress (void) const;
/// Send A packet on the socket, this function is reentrant.
/// @param pct packet to send
/// @return -1 of failure
int SendPacket(const WorldPacket& pct);
/// Send A packet on the socket, this function is reentrant.
/// @param pct packet to send
/// @return -1 of failure
int SendPacket(const WorldPacket& pct);
/// Add reference to this object.
long AddReference (void);
/// Add reference to this object.
long AddReference (void);
/// Remove reference to this object.
long RemoveReference (void);
/// Remove reference to this object.
long RemoveReference (void);
/// things called by ACE framework.
/// things called by ACE framework.
/// Called on open, the void* is the acceptor.
virtual int open (void *);
/// Called on open, the void* is the acceptor.
virtual int open (void*);
/// Called on failures inside of the acceptor, don't call from your code.
virtual int close (u_long);
/// Called on failures inside of the acceptor, don't call from your code.
virtual int close (u_long);
/// Called when we can read from the socket.
virtual int handle_input (ACE_HANDLE = ACE_INVALID_HANDLE);
/// Called when we can read from the socket.
virtual int handle_input (ACE_HANDLE = ACE_INVALID_HANDLE);
/// Called when the socket can write.
virtual int handle_output (ACE_HANDLE = ACE_INVALID_HANDLE);
/// Called when the socket can write.
virtual int handle_output (ACE_HANDLE = ACE_INVALID_HANDLE);
/// Called when connection is closed or error happens.
virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE,
ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK);
/// Called when connection is closed or error happens.
virtual int handle_close (ACE_HANDLE = ACE_INVALID_HANDLE,
ACE_Reactor_Mask = ACE_Event_Handler::ALL_EVENTS_MASK);
/// Called by WorldSocketMgr/ReactorRunnable.
int Update (void);
/// Called by WorldSocketMgr/ReactorRunnable.
int Update (void);
private:
/// Helper functions for processing incoming data.
int handle_input_header (void);
int handle_input_payload (void);
int handle_input_missing_data (void);
private:
/// Helper functions for processing incoming data.
int handle_input_header (void);
int handle_input_payload (void);
int handle_input_missing_data (void);
/// Help functions to mark/unmark the socket for output.
/// @param g the guard is for m_OutBufferLock, the function will release it
int cancel_wakeup_output (GuardType& g);
int schedule_wakeup_output (GuardType& g);
/// Help functions to mark/unmark the socket for output.
/// @param g the guard is for m_OutBufferLock, the function will release it
int cancel_wakeup_output (GuardType& g);
int schedule_wakeup_output (GuardType& g);
/// Drain the queue if its not empty.
int handle_output_queue (GuardType& g);
/// Drain the queue if its not empty.
int handle_output_queue (GuardType& g);
/// process one incoming packet.
/// @param new_pct received packet, note that you need to delete it.
int ProcessIncoming (WorldPacket* new_pct);
/// process one incoming packet.
/// @param new_pct received packet, note that you need to delete it.
int ProcessIncoming (WorldPacket* new_pct);
/// Called by ProcessIncoming() on CMSG_AUTH_SESSION.
int HandleAuthSession (WorldPacket& recvPacket);
/// Called by ProcessIncoming() on CMSG_AUTH_SESSION.
int HandleAuthSession (WorldPacket& recvPacket);
/// Called by ProcessIncoming() on CMSG_PING.
int HandlePing (WorldPacket& recvPacket);
/// Called by ProcessIncoming() on CMSG_PING.
int HandlePing (WorldPacket& recvPacket);
private:
/// Time in which the last ping was received
SystemTimePoint m_LastPingTime;
private:
/// Time in which the last ping was received
SystemTimePoint m_LastPingTime;
/// Keep track of over-speed pings, to prevent ping flood.
uint32 m_OverSpeedPings;
/// Keep track of over-speed pings, to prevent ping flood.
uint32 m_OverSpeedPings;
/// Address of the remote peer
std::string m_Address;
/// Address of the remote peer
std::string m_Address;
/// Class used for managing encryption of the headers
AuthCrypt m_Crypt;
/// Class used for managing encryption of the headers
AuthCrypt m_Crypt;
/// Mutex lock to protect m_Session
LockType m_SessionLock;
/// Mutex lock to protect m_Session
LockType m_SessionLock;
/// Session to which received packets are routed
WorldSession* m_Session;
/// Session to which received packets are routed
WorldSession* m_Session;
/// here are stored the fragments of the received data
WorldPacket* m_RecvWPct;
/// here are stored the fragments of the received data
WorldPacket* m_RecvWPct;
/// This block actually refers to m_RecvWPct contents,
/// which allows easy and safe writing to it.
/// It wont free memory when its deleted. m_RecvWPct takes care of freeing.
ACE_Message_Block m_RecvPct;
/// This block actually refers to m_RecvWPct contents,
/// which allows easy and safe writing to it.
/// It wont free memory when its deleted. m_RecvWPct takes care of freeing.
ACE_Message_Block m_RecvPct;
/// Fragment of the received header.
ACE_Message_Block m_Header;
/// Fragment of the received header.
ACE_Message_Block m_Header;
/// Mutex for protecting output related data.
LockType m_OutBufferLock;
/// Mutex for protecting output related data.
LockType m_OutBufferLock;
/// Buffer used for writing output.
ACE_Message_Block* m_OutBuffer;
/// Buffer used for writing output.
ACE_Message_Block* m_OutBuffer;
/// Size of the m_OutBuffer.
size_t m_OutBufferSize;
/// Size of the m_OutBuffer.
size_t m_OutBufferSize;
/// True if the socket is registered with the reactor for output
bool m_OutActive;
/// True if the socket is registered with the reactor for output
bool m_OutActive;
uint32 m_Seed;
uint32 m_Seed;
};

View File

@@ -42,166 +42,166 @@
*/
class ReactorRunnable : protected ACE_Task_Base
{
public:
public:
ReactorRunnable() :
m_Reactor(0),
m_Connections(0),
m_ThreadId(-1)
ReactorRunnable() :
m_Reactor(0),
m_Connections(0),
m_ThreadId(-1)
{
ACE_Reactor_Impl* imp;
#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
imp = new ACE_Dev_Poll_Reactor();
imp->max_notify_iterations (128);
imp->restart (1);
#else
imp = new ACE_TP_Reactor();
imp->max_notify_iterations (128);
#endif
m_Reactor = new ACE_Reactor (imp, 1);
}
virtual ~ReactorRunnable()
{
Stop();
Wait();
delete m_Reactor;
}
void Stop()
{
m_Reactor->end_reactor_event_loop();
}
int Start()
{
if (m_ThreadId != -1)
return -1;
return (m_ThreadId = activate());
}
void Wait() { ACE_Task_Base::wait(); }
long Connections()
{
return m_Connections;
}
int AddSocket (WorldSocket* sock)
{
ACORE_GUARD(ACE_Thread_Mutex, m_NewSockets_Lock);
++m_Connections;
sock->AddReference();
sock->reactor (m_Reactor);
m_NewSockets.insert (sock);
sScriptMgr->OnSocketOpen(sock);
return 0;
}
ACE_Reactor* GetReactor()
{
return m_Reactor;
}
protected:
void AddNewSockets()
{
ACORE_GUARD(ACE_Thread_Mutex, m_NewSockets_Lock);
if (m_NewSockets.empty())
return;
for (SocketSet::const_iterator i = m_NewSockets.begin(); i != m_NewSockets.end(); ++i)
{
ACE_Reactor_Impl* imp;
WorldSocket* sock = (*i);
#if defined (ACE_HAS_EVENT_POLL) || defined (ACE_HAS_DEV_POLL)
imp = new ACE_Dev_Poll_Reactor();
imp->max_notify_iterations (128);
imp->restart (1);
#else
imp = new ACE_TP_Reactor();
imp->max_notify_iterations (128);
#endif
m_Reactor = new ACE_Reactor (imp, 1);
}
virtual ~ReactorRunnable()
{
Stop();
Wait();
delete m_Reactor;
}
void Stop()
{
m_Reactor->end_reactor_event_loop();
}
int Start()
{
if (m_ThreadId != -1)
return -1;
return (m_ThreadId = activate());
}
void Wait() { ACE_Task_Base::wait(); }
long Connections()
{
return m_Connections;
}
int AddSocket (WorldSocket* sock)
{
ACORE_GUARD(ACE_Thread_Mutex, m_NewSockets_Lock);
++m_Connections;
sock->AddReference();
sock->reactor (m_Reactor);
m_NewSockets.insert (sock);
sScriptMgr->OnSocketOpen(sock);
return 0;
}
ACE_Reactor* GetReactor()
{
return m_Reactor;
}
protected:
void AddNewSockets()
{
ACORE_GUARD(ACE_Thread_Mutex, m_NewSockets_Lock);
if (m_NewSockets.empty())
return;
for (SocketSet::const_iterator i = m_NewSockets.begin(); i != m_NewSockets.end(); ++i)
if (sock->IsClosed())
{
WorldSocket* sock = (*i);
sScriptMgr->OnSocketClose(sock, true);
if (sock->IsClosed())
sock->RemoveReference();
--m_Connections;
}
else
m_Sockets.insert (sock);
}
m_NewSockets.clear();
}
virtual int svc()
{
#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS)
sLog->outStaticDebug ("Network Thread Starting");
#endif
ACE_ASSERT (m_Reactor);
SocketSet::iterator i, t;
while (!m_Reactor->reactor_event_loop_done())
{
// dont be too smart to move this outside the loop
// the run_reactor_event_loop will modify interval
ACE_Time_Value interval (0, 10000);
if (m_Reactor->run_reactor_event_loop (interval) == -1)
break;
AddNewSockets();
for (i = m_Sockets.begin(); i != m_Sockets.end();)
{
if ((*i)->Update() == -1)
{
sScriptMgr->OnSocketClose(sock, true);
t = i;
++i;
sock->RemoveReference();
(*t)->CloseSocket("svc()");
sScriptMgr->OnSocketClose((*t), false);
(*t)->RemoveReference();
--m_Connections;
m_Sockets.erase (t);
}
else
m_Sockets.insert (sock);
++i;
}
m_NewSockets.clear();
}
virtual int svc()
{
#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS)
sLog->outStaticDebug ("Network Thread Starting");
sLog->outStaticDebug ("Network Thread exits");
#endif
ACE_ASSERT (m_Reactor);
return 0;
}
SocketSet::iterator i, t;
private:
typedef std::atomic<int> AtomicInt;
typedef std::set<WorldSocket*> SocketSet;
while (!m_Reactor->reactor_event_loop_done())
{
// dont be too smart to move this outside the loop
// the run_reactor_event_loop will modify interval
ACE_Time_Value interval (0, 10000);
ACE_Reactor* m_Reactor;
AtomicInt m_Connections;
int m_ThreadId;
if (m_Reactor->run_reactor_event_loop (interval) == -1)
break;
SocketSet m_Sockets;
AddNewSockets();
for (i = m_Sockets.begin(); i != m_Sockets.end();)
{
if ((*i)->Update() == -1)
{
t = i;
++i;
(*t)->CloseSocket("svc()");
sScriptMgr->OnSocketClose((*t), false);
(*t)->RemoveReference();
--m_Connections;
m_Sockets.erase (t);
}
else
++i;
}
}
#if defined(ENABLE_EXTRAS) && defined(ENABLE_EXTRA_LOGS)
sLog->outStaticDebug ("Network Thread exits");
#endif
return 0;
}
private:
typedef std::atomic<int> AtomicInt;
typedef std::set<WorldSocket*> SocketSet;
ACE_Reactor* m_Reactor;
AtomicInt m_Connections;
int m_ThreadId;
SocketSet m_Sockets;
SocketSet m_NewSockets;
ACE_Thread_Mutex m_NewSockets_Lock;
SocketSet m_NewSockets;
ACE_Thread_Mutex m_NewSockets_Lock;
};
WorldSocketMgr::WorldSocketMgr() :
@@ -322,9 +322,9 @@ WorldSocketMgr::OnSocketOpen (WorldSocket* sock)
if (m_SockOutKBuff >= 0)
{
if (sock->peer().set_option (SOL_SOCKET,
SO_SNDBUF,
(void*) & m_SockOutKBuff,
sizeof (int)) == -1 && errno != ENOTSUP)
SO_SNDBUF,
(void*) & m_SockOutKBuff,
sizeof (int)) == -1 && errno != ENOTSUP)
{
sLog->outError("WorldSocketMgr::OnSocketOpen set_option SO_SNDBUF");
return -1;
@@ -337,9 +337,9 @@ WorldSocketMgr::OnSocketOpen (WorldSocket* sock)
if (m_UseNoDelay)
{
if (sock->peer().set_option (ACE_IPPROTO_TCP,
TCP_NODELAY,
(void*)&ndoption,
sizeof (int)) == -1)
TCP_NODELAY,
(void*)&ndoption,
sizeof (int)) == -1)
{
sLog->outError("WorldSocketMgr::OnSocketOpen: peer().set_option TCP_NODELAY errno = %s", ACE_OS::strerror (errno));
return -1;

View File

@@ -28,7 +28,7 @@ public:
friend class WorldSocket;
static WorldSocketMgr* instance();
/// Start network, listen at address:port .
int StartNetwork(uint16 port, const char* address);