Skip to content

Commit

Permalink
improve: some fixes and adjustments (#2980)
Browse files Browse the repository at this point in the history
Fixes:
• In the solution build
• In the debug build
• Check for race id 0 in prey and taskhunting
• Fixes in pop_front of some queues
• Fix in Argon2::parseBitShift for debug build
• Fix in NetworkMessage functions for debug build

• Added try/catch in IOLoginData::savePlayer to avoid unhandled
exceptions
• New caseInsensitiveCompare function for use in some ongoing pull
requests
  • Loading branch information
dudantas authored Oct 17, 2024
1 parent e70c8c5 commit f05fb5d
Show file tree
Hide file tree
Showing 11 changed files with 85 additions and 70 deletions.
16 changes: 12 additions & 4 deletions src/io/functions/iologindata_load_player.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,10 @@ void IOLoginDataLoad::loadPlayerPreyClass(std::shared_ptr<Player> player, DBResu
query << "SELECT * FROM `player_prey` WHERE `player_id` = " << player->getGUID();
if ((result = db.storeQuery(query.str()))) {
do {
auto selectedRaceId = result->getNumber<uint16_t>("raceid");
if (selectedRaceId == 0) {
continue;
}
auto slot = std::make_unique<PreySlot>(static_cast<PreySlot_t>(result->getNumber<uint16_t>("slot")));
auto state = static_cast<PreyDataState_t>(result->getNumber<uint16_t>("state"));
if (slot->id == PreySlot_Two && state == PreyDataState_Locked) {
Expand All @@ -745,7 +749,7 @@ void IOLoginDataLoad::loadPlayerPreyClass(std::shared_ptr<Player> player, DBResu
} else {
slot->state = state;
}
slot->selectedRaceId = result->getNumber<uint16_t>("raceid");
slot->selectedRaceId = selectedRaceId;
slot->option = static_cast<PreyOption_t>(result->getNumber<uint16_t>("option"));
slot->bonus = static_cast<PreyBonus_t>(result->getNumber<uint16_t>("bonus_type"));
slot->bonusRarity = static_cast<uint8_t>(result->getNumber<uint16_t>("bonus_rarity"));
Expand Down Expand Up @@ -781,6 +785,10 @@ void IOLoginDataLoad::loadPlayerTaskHuntingClass(std::shared_ptr<Player> player,
query << "SELECT * FROM `player_taskhunt` WHERE `player_id` = " << player->getGUID();
if ((result = db.storeQuery(query.str()))) {
do {
auto selectedRaceId = result->getNumber<uint16_t>("raceid");
if (selectedRaceId == 0) {
continue;
}
auto slot = std::make_unique<TaskHuntingSlot>(static_cast<PreySlot_t>(result->getNumber<uint16_t>("slot")));
auto state = static_cast<PreyTaskDataState_t>(result->getNumber<uint16_t>("state"));
if (slot->id == PreySlot_Two && state == PreyTaskDataState_Locked) {
Expand All @@ -792,7 +800,7 @@ void IOLoginDataLoad::loadPlayerTaskHuntingClass(std::shared_ptr<Player> player,
} else {
slot->state = state;
}
slot->selectedRaceId = result->getNumber<uint16_t>("raceid");
slot->selectedRaceId = selectedRaceId;
slot->upgrade = result->getNumber<bool>("upgrade");
slot->rarity = static_cast<uint8_t>(result->getNumber<uint16_t>("rarity"));
slot->currentKills = result->getNumber<uint16_t>("kills");
Expand Down Expand Up @@ -827,7 +835,7 @@ void IOLoginDataLoad::loadPlayerForgeHistory(std::shared_ptr<Player> player, DBR

std::ostringstream query;
query << "SELECT * FROM `forge_history` WHERE `player_id` = " << player->getGUID();
if (result = Database::getInstance().storeQuery(query.str())) {
if ((result = Database::getInstance().storeQuery(query.str()))) {
do {
auto actionEnum = magic_enum::enum_value<ForgeAction_t>(result->getNumber<uint16_t>("action_type"));
ForgeHistory history;
Expand All @@ -853,7 +861,7 @@ void IOLoginDataLoad::loadPlayerBosstiary(std::shared_ptr<Player> player, DBResu

std::ostringstream query;
query << "SELECT * FROM `player_bosstiary` WHERE `player_id` = " << player->getGUID();
if (result = Database::getInstance().storeQuery(query.str())) {
if ((result = Database::getInstance().storeQuery(query.str()))) {
do {
player->setSlotBossId(1, result->getNumber<uint16_t>("bossIdSlotOne"));
player->setSlotBossId(2, result->getNumber<uint16_t>("bossIdSlotTwo"));
Expand Down
4 changes: 3 additions & 1 deletion src/io/functions/iologindata_save_player.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,6 @@ bool IOLoginDataSave::saveItems(std::shared_ptr<Player> player, const ItemBlockL
const ContainerBlock &cb = queue.front();
std::shared_ptr<Container> container = cb.first;
int32_t parentId = cb.second;
queue.pop_front();

if (!container) {
continue; // Check for null container
Expand Down Expand Up @@ -137,6 +136,9 @@ bool IOLoginDataSave::saveItems(std::shared_ptr<Player> player, const ItemBlockL
return false;
}
}

// Removes the object after processing everything, avoiding memory usage after freeing
queue.pop_front();
}

// Execute query
Expand Down
18 changes: 12 additions & 6 deletions src/io/iologindata.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -202,15 +202,21 @@ bool IOLoginData::loadPlayer(std::shared_ptr<Player> player, DBResult_ptr result
}

bool IOLoginData::savePlayer(std::shared_ptr<Player> player) {
bool success = DBTransaction::executeWithinTransaction([player]() {
return savePlayerGuard(player);
});
try {
bool success = DBTransaction::executeWithinTransaction([player]() {
return savePlayerGuard(player);
});

if (!success) {
g_logger().error("[{}] Error occurred saving player", __FUNCTION__);
}

if (!success) {
g_logger().error("[{}] Error occurred saving player", __FUNCTION__);
return success;
} catch (const DatabaseException &e) {
g_logger().error("[{}] Exception occurred: {}", __FUNCTION__, e.what());
}

return success;
return false;
}

bool IOLoginData::savePlayerGuard(std::shared_ptr<Player> player) {
Expand Down
2 changes: 1 addition & 1 deletion src/security/argon.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ void Argon2::updateConstants() {
}

uint32_t Argon2::parseBitShift(const std::string &bitShiftStr) const {
static const std::regex pattern(R"(^\s*(\d+)\s*<<\s*(\d+)\s*$)");
static const std::regex pattern(R"(^\s*(\d+)\s*<<\s*(\d+)\s*$)", std::regex_constants::ECMAScript | std::regex_constants::icase);
std::smatch match;

if (!std::regex_match(bitShiftStr, match, pattern)) {
Expand Down
17 changes: 6 additions & 11 deletions src/server/network/message/networkmessage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,7 @@ void NetworkMessage::addString(const std::string &value, const std::source_locat
auto len = static_cast<uint16_t>(stringLen);
add<uint16_t>(len);
// Using to copy the string into the buffer
auto it = std::ranges::copy(value, buffer.begin() + info.position);
g_logger().trace("First value copied from sourceSpan: {}, second value copied from sourceSpan: {}", *it.in, *it.out);
std::ranges::copy(value, buffer.begin() + info.position);
info.position += stringLen;
info.length += stringLen;
}
Expand Down Expand Up @@ -211,8 +210,7 @@ void NetworkMessage::addBytes(const char* bytes, size_t size) {
return;
}

auto it = std::ranges::copy(bytes, bytes + size, buffer.begin() + info.position);
g_logger().trace("First value copied from sourceSpan: {}, second value copied from sourceSpan: {}", *it.in, *it.out);
std::ranges::copy(std::span(bytes, size), buffer.begin() + info.position);
info.position += size;
info.length += size;
}
Expand Down Expand Up @@ -293,13 +291,10 @@ void NetworkMessage::append(const NetworkMessage &other) {
return;
}

// Create a span for the source data (from the other message)
std::span<const unsigned char> sourceSpan(other.getBuffer() + otherStartPos, otherLength);
// Create a span for the destination in the current buffer
std::span<unsigned char> destSpan(buffer.data() + info.position, otherLength);
// Copy the data from the source span to the destination span
auto it = std::ranges::copy(sourceSpan, destSpan.begin());
g_logger().trace("First value copied from sourceSpan: {}, second value copied from sourceSpan: {}", *it.in, *it.out);
std::ranges::copy(
std::span<const unsigned char>(other.getBuffer() + otherStartPos, otherLength),
buffer.data() + info.position
);

// Update the buffer information
info.length += otherLength;
Expand Down
11 changes: 6 additions & 5 deletions src/server/network/protocol/protocolgame.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6091,16 +6091,17 @@ void ProtocolGame::sendTradeItemRequest(const std::string &traderName, std::shar
std::list<std::shared_ptr<Container>> listContainer { tradeContainer };
std::list<std::shared_ptr<Item>> itemList { tradeContainer };
while (!listContainer.empty()) {
std::shared_ptr<Container> container = listContainer.front();
listContainer.pop_front();

for (const std::shared_ptr<Item> &containerItem : container->getItemList()) {
std::shared_ptr<Container> tmpContainer = containerItem->getContainer();
const auto &container = listContainer.front();
for (const auto &containerItem : container->getItemList()) {
const auto &tmpContainer = containerItem->getContainer();
if (tmpContainer) {
listContainer.push_back(tmpContainer);
}
itemList.push_back(containerItem);
}

// Removes the object after processing everything, avoiding memory usage after freeing
listContainer.pop_front();
}

msg.addByte(itemList.size());
Expand Down
7 changes: 4 additions & 3 deletions src/server/network/webhook/webhook.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ void Webhook::sendWebhook() {
return;
}

auto task = webhooks.front();
const auto &task = webhooks.front();

std::string response_body;
auto response_code = sendRequest(task->url.c_str(), task->payload.c_str(), &response_body);
Expand All @@ -162,8 +162,6 @@ void Webhook::sendWebhook() {
return;
}

webhooks.pop_front();

if (response_code >= 300) {
g_logger().error(
"Failed to send webhook message, error code: {} response body: {} request body: {}",
Expand All @@ -176,4 +174,7 @@ void Webhook::sendWebhook() {
}

g_logger().debug("Webhook successfully sent to {}", task->url);

// Removes the object after processing everything, avoiding memory usage after freeing
webhooks.pop_front();
}
15 changes: 15 additions & 0 deletions src/utils/tools.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1952,3 +1952,18 @@ uint8_t convertWheelGemAffinityToDomain(uint8_t affinity) {
return 0;
}
}

bool caseInsensitiveCompare(std::string_view str1, std::string_view str2, size_t length /*= std::string_view::npos*/) {
if (length == std::string_view::npos) {
if (str1.size() != str2.size()) {
return false;
}
length = str1.size();
} else {
length = std::min({ length, str1.size(), str2.size() });
}

return std::equal(str1.begin(), str1.begin() + length, str2.begin(), [](char c1, char c2) {
return std::tolower(static_cast<unsigned char>(c1)) == std::tolower(static_cast<unsigned char>(c2));
});
}
2 changes: 2 additions & 0 deletions src/utils/tools.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,5 @@ template <typename EnumType, typename UnderlyingType = std::underlying_type_t<En
EnumType enumFromValue(UnderlyingType value) {
return static_cast<EnumType>(value);
}

bool caseInsensitiveCompare(std::string_view str1, std::string_view str2, size_t length = std::string_view::npos);
4 changes: 2 additions & 2 deletions vcproj/canary.vcxproj
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@
<IncludeInUnityFile>true</IncludeInUnityFile>
<OpenMPSupport>true</OpenMPSupport>
<LanguageStandard_C>Default</LanguageStandard_C>
<AdditionalOptions>/Zc:__cplusplus /fsanitize=address %(AdditionalOptions)</AdditionalOptions>
<AdditionalOptions>/Zc:__cplusplus /fsanitize=address /utf-8 %(AdditionalOptions)</AdditionalOptions>
<PreprocessorDefinitions>_DISABLE_VECTOR_ANNOTATION;_DISABLE_STRING_ANNOTATION;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeader>Use</PrecompiledHeader>
</ClCompile>
Expand Down Expand Up @@ -552,7 +552,7 @@
<WholeProgramOptimization>true</WholeProgramOptimization>
<IncludeInUnityFile>true</IncludeInUnityFile>
<OpenMPSupport>true</OpenMPSupport>
<AdditionalOptions>/Zc:__cplusplus %(AdditionalOptions)</AdditionalOptions>
<AdditionalOptions>/Zc:__cplusplus /utf-8 %(AdditionalOptions)</AdditionalOptions>
<PreprocessorDefinitions>_DISABLE_VECTOR_ANNOTATION;_DISABLE_STRING_ANNOTATION;NDEBUG;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PrecompiledHeader>Use</PrecompiledHeader>
</ClCompile>
Expand Down
59 changes: 22 additions & 37 deletions vcproj/settings.props
Original file line number Diff line number Diff line change
Expand Up @@ -8,59 +8,37 @@
_WIN32_WINNT=0x0501;
BUILD_TYPE="RelWithDebInfo";
</PREPROCESSOR_DEFS>
<CANARY_LIBDEPS>
<CANARY_COMMON_LIBDEPS>
comctl32.lib;
User32.lib;
WS2_32.lib;
pugixml.lib;
libprotobuf.lib;
lua51.lib;
mpir.lib;
libmariadb.lib;
abseil_dll.lib;
argon2.lib;
</CANARY_COMMON_LIBDEPS>
<CANARY_LIBDEPS>
$(CANARY_COMMON_LIBDEPS);
libprotobuf.lib;
zlib.lib;
libcurl.lib;
fmt.lib;
spdlog.lib;
abseil_dll.lib;
argon2.lib;
opentelemetry_common.lib;
opentelemetry_exporter_in_memory.lib;
opentelemetry_exporter_ostream_logs.lib;
opentelemetry_exporter_ostream_metrics.lib;
opentelemetry_exporter_ostream_span.lib;
opentelemetry_exporter_otlp_http.lib;
opentelemetry_exporter_otlp_http_client.lib;
opentelemetry_exporter_otlp_http_log.lib;
opentelemetry_exporter_otlp_http_metric.lib;
opentelemetry_exporter_prometheus.lib;
opentelemetry_http_client_curl.lib;
opentelemetry_logs.lib;
opentelemetry_metrics.lib;
opentelemetry_otlp_recordable.lib;
opentelemetry_proto.lib;
opentelemetry_resources.lib;
opentelemetry_trace.lib;
opentelemetry_version.lib;
prometheus-cpp-core.lib;
prometheus-cpp-pull.lib;
civetweb.lib;
civetweb-cpp.lib
</CANARY_LIBDEPS>
<CANARY_LIBDEPS_D>
comctl32.lib;
User32.lib;
WS2_32.lib;
pugixml.lib;
$(CANARY_COMMON_LIBDEPS);
libprotobufd.lib;
lua51.lib;
mpir.lib;
libmariadb.lib;
zlibd.lib;
libcurl-d.lib;
fmtd.lib;
spdlogd.lib;
abseil_dll.lib;
argon2.lib;
</CANARY_LIBDEPS_D>
</PropertyGroup>

<PropertyGroup Condition="'$(FEATURE_METRICS)' == 'true'">
<OPENTELEMETRY_LIBS>
opentelemetry_common.lib;
opentelemetry_exporter_in_memory.lib;
opentelemetry_exporter_ostream_logs.lib;
Expand All @@ -79,13 +57,19 @@
opentelemetry_resources.lib;
opentelemetry_trace.lib;
opentelemetry_version.lib;
prometheus-cpp-core.lib;
prometheus-cpp-pull;
civetweb.lib;
civetweb-cpp.lib
</CANARY_LIBDEPS_D>
civetweb-cpp.lib;
</OPENTELEMETRY_LIBS>
<CANARY_LIBDEPS>$(CANARY_LIBDEPS);$(OPENTELEMETRY_LIBS)</CANARY_LIBDEPS>
<CANARY_LIBDEPS_D>$(CANARY_LIBDEPS_D);$(OPENTELEMETRY_LIBS)</CANARY_LIBDEPS_D>
</PropertyGroup>

<PropertyGroup>
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>

<ItemDefinitionGroup>
<ClCompile>
<WarningLevel>Level3</WarningLevel>
Expand All @@ -101,6 +85,7 @@
<EntryPointSymbol>mainCRTStartup</EntryPointSymbol>
</Link>
</ItemDefinitionGroup>

<ItemGroup>
<BuildMacro Include="PREPROCESSOR_DEFS">
<Value>$(PREPROCESSOR_DEFS)</Value>
Expand Down

0 comments on commit f05fb5d

Please sign in to comment.