mirror of
https://github.com/DarkflameUniverse/DarkflameServer.git
synced 2026-10-18 18:52:48 +00:00
refactor: common and auth packets as structs
Adds CommonPackets (ServiceType::COMMON): ClientVersionConfirm (the client's handshake, with the handler that logs it and answers), ServerVersionConfirm, DisconnectNotify and GeneralNotify (layout from the 1.10.64 client's PacketHandler_MSG_SERVER_GENERAL_NOTIFY; DLU does not send it yet). AuthPackets::LoginRequest reads the login and keeps the old login logic in its Handle; ClientPackets::LoginResponse (with the Stamp list) replaces the hand written response, and AuthPackets::SendLoginResponse fills it from the settings as before. dServer::Disconnect writes a DisconnectNotify. AuthServer's if-chain and WorldServer's COMMON case become CommonPackets::Handle / AuthPackets::Handle, dispatch maps that read the struct, drop and log it if it does not deserialize, then Handle. HandleHandshake and SendHandshake are gone. No wire change. Verified against a frozen verbatim copy of the old functions (tests/dGameTests/dNetTests/Legacy): the old handshake and login handlers and the new dispatchers are fed the same packets and must send identical bytes to the same address (same RNG seed for the session key), over grids of versions, service types, ports, response codes, error messages, IPs and stamp lists; plus hand computed golden bytes, round trips, truncation checks, and a deliberate field width mutation that made the tests fail. The only behaviour difference: truncated handshake and login packets are now dropped instead of handled with whatever was read. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,9 @@ list(APPEND DGAMETEST_SOURCES ${DCOMPONENTS_TESTS})
|
||||
add_subdirectory(dGameMessagesTests)
|
||||
list(APPEND DGAMETEST_SOURCES ${DGAMEMESSAGES_TESTS})
|
||||
|
||||
add_subdirectory(dNetTests)
|
||||
list(APPEND DGAMETEST_SOURCES ${DNET_TESTS})
|
||||
|
||||
file(COPY ${GAMEMESSAGE_TESTBITSTREAMS} DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
|
||||
file(COPY ${COMPONENT_TEST_DATA} DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
|
||||
|
||||
@@ -27,7 +30,7 @@ if(APPLE)
|
||||
endif()
|
||||
|
||||
target_link_libraries(dGameTests ${COMMON_LIBRARIES} GTest::gtest_main
|
||||
dGame dScripts dPhysics Detour Recast tinyxml2 dWorldServer dZoneManager dChatFilter dNavigation)
|
||||
dGame dScripts dPhysics Detour Recast tinyxml2 dWorldServer dZoneManager dChatFilter dNavigation bcrypt MD5)
|
||||
|
||||
# Discover the tests
|
||||
gtest_discover_tests(dGameTests)
|
||||
|
||||
9
tests/dGameTests/dNetTests/CMakeLists.txt
Normal file
9
tests/dGameTests/dNetTests/CMakeLists.txt
Normal file
@@ -0,0 +1,9 @@
|
||||
SET(DNET_TESTS
|
||||
"CommonAuthPacketsTests.cpp")
|
||||
|
||||
# Get the folder name and prepend it to the files above
|
||||
get_filename_component(thisFolderName ${CMAKE_CURRENT_SOURCE_DIR} NAME)
|
||||
list(TRANSFORM DNET_TESTS PREPEND "${thisFolderName}/")
|
||||
|
||||
# Export to parent scope
|
||||
set(DNET_TESTS ${DNET_TESTS} PARENT_SCOPE)
|
||||
299
tests/dGameTests/dNetTests/CommonAuthPacketsTests.cpp
Normal file
299
tests/dGameTests/dNetTests/CommonAuthPacketsTests.cpp
Normal file
@@ -0,0 +1,299 @@
|
||||
#include "AuthPackets.h"
|
||||
#include "ClientPackets.h"
|
||||
#include "CommonPackets.h"
|
||||
#include "GameDependencies.h"
|
||||
#include "PacketTestUtils.h"
|
||||
#include "Legacy/CommonAuthPacketsLegacy.h"
|
||||
|
||||
#include "eLoginResponse.h"
|
||||
#include "eServerDisconnectIdentifiers.h"
|
||||
#include "magic_enum.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
using namespace PacketTestUtils;
|
||||
|
||||
namespace {
|
||||
SystemAddress TestAddress(uint16_t port = 1234) {
|
||||
SystemAddress address;
|
||||
address.binaryAddress = 0x0100007F;
|
||||
address.port = port;
|
||||
return address;
|
||||
}
|
||||
|
||||
// Runs a handler on a copy of the packet (header included), the way the servers receive it.
|
||||
Packet MakePacket(RakNet::BitStream& bitStream, const SystemAddress& sysAddr) {
|
||||
Packet packet{};
|
||||
packet.systemAddress = sysAddr;
|
||||
packet.data = bitStream.GetData();
|
||||
packet.length = bitStream.GetNumberOfBytesUsed();
|
||||
packet.bitSize = bitStream.GetNumberOfBitsUsed();
|
||||
return packet;
|
||||
}
|
||||
|
||||
// Reads the header like the servers do and hands the rest to a dispatcher.
|
||||
void Dispatch(RakNet::BitStream& packetBytes, const SystemAddress& sysAddr, const std::function<void(RakNet::BitStream&, const SystemAddress&, uint32_t)>& handler) {
|
||||
RakNet::BitStream inStream(packetBytes.GetData(), packetBytes.GetNumberOfBytesUsed(), false);
|
||||
LUBitStream header;
|
||||
ASSERT_TRUE(header.ReadHeader(inStream));
|
||||
handler(inStream, sysAddr, header.internalPacketID);
|
||||
}
|
||||
|
||||
void ExpectSamePackets(const std::vector<CapturedPacket>& expected, const std::vector<CapturedPacket>& actual) {
|
||||
ASSERT_FALSE(expected.empty());
|
||||
ASSERT_EQ(expected.size(), actual.size());
|
||||
for (size_t i = 0; i < expected.size(); i++) {
|
||||
EXPECT_PACKET_EQ(FromCapture(expected[i]), FromCapture(actual[i]));
|
||||
EXPECT_EQ(expected[i].sysAddr, actual[i].sysAddr);
|
||||
EXPECT_EQ(expected[i].broadcast, actual[i].broadcast);
|
||||
}
|
||||
}
|
||||
|
||||
// Runs both, retrying if the second changed while they ran (stamps carry time(nullptr)).
|
||||
void ExpectSameOutput(const std::function<void()>& legacy, const std::function<void()>& converted) {
|
||||
for (int attempt = 0; attempt < 3; attempt++) {
|
||||
const auto before = std::time(nullptr);
|
||||
Game::randomEngine.seed(1234);
|
||||
const auto expected = Capture(legacy);
|
||||
Game::randomEngine.seed(1234);
|
||||
const auto actual = Capture(converted);
|
||||
if (before != std::time(nullptr)) continue;
|
||||
ExpectSamePackets(expected, actual);
|
||||
return;
|
||||
}
|
||||
FAIL() << "the clock kept changing seconds while comparing";
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
T RoundTrip(const T& packet) {
|
||||
RakNet::BitStream first;
|
||||
packet.WritePacket(first);
|
||||
T copy;
|
||||
EXPECT_TRUE(copy.ReadHeader(first));
|
||||
EXPECT_TRUE(copy.Deserialize(first));
|
||||
EXPECT_EQ(first.GetNumberOfUnreadBits(), 0);
|
||||
RakNet::BitStream second;
|
||||
copy.WritePacket(second);
|
||||
EXPECT_PACKET_EQ(FromBitStream(first), FromBitStream(second));
|
||||
return copy;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void ExpectTruncatedFails(const T& packet) {
|
||||
RakNet::BitStream full;
|
||||
packet.WritePacket(full);
|
||||
const auto bytes = full.GetNumberOfBytesUsed();
|
||||
for (uint32_t cut = 8; cut < bytes; cut++) {
|
||||
RakNet::BitStream truncated(full.GetData(), cut, true);
|
||||
T copy;
|
||||
ASSERT_TRUE(copy.ReadHeader(truncated));
|
||||
EXPECT_FALSE(copy.Deserialize(truncated)) << "cut at " << cut << " of " << bytes;
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<std::string> g_Strings = { "", "a", "Hello World", "user_name-01", std::string(40, 'x'), std::string(300, 'y') };
|
||||
}
|
||||
|
||||
class CommonAuthPacketsTests : public GameDependenciesTest {
|
||||
protected:
|
||||
void SetUp() override { SetUpDependencies(); }
|
||||
void TearDown() override { TearDownDependencies(); }
|
||||
};
|
||||
|
||||
TEST_F(CommonAuthPacketsTests, VersionConfirmHandshakeMatchesLegacy) {
|
||||
for (const uint32_t netVersion : { 0u, 171022u, 0xFFFFFFFFu }) {
|
||||
for (const auto serviceType : { ServiceType::CLIENT, ServiceType::AUTH, static_cast<ServiceType>(0xFFFF) }) {
|
||||
for (const uint16_t port : { uint16_t{ 0 }, uint16_t{ 1234 }, uint16_t{ 0xFFFF } }) {
|
||||
CommonPackets::ClientVersionConfirm request;
|
||||
request.netVersion = netVersion;
|
||||
request.unknown = 0x12345678;
|
||||
request.serviceType = serviceType;
|
||||
request.processID = 4321;
|
||||
request.port = port;
|
||||
request.unknown2 = LUString("127.0.0.1");
|
||||
RakNet::BitStream bytes;
|
||||
request.WritePacket(bytes);
|
||||
const auto sysAddr = TestAddress();
|
||||
|
||||
ExpectSameOutput(
|
||||
[&] { auto packet = MakePacket(bytes, sysAddr); LegacyAuthPackets::HandleHandshake(Game::server, &packet); },
|
||||
[&] { Dispatch(bytes, sysAddr, CommonPackets::Handle); });
|
||||
|
||||
const auto copy = RoundTrip(request);
|
||||
EXPECT_EQ(copy.netVersion, netVersion);
|
||||
EXPECT_EQ(copy.serviceType, serviceType);
|
||||
EXPECT_EQ(copy.port, port);
|
||||
EXPECT_EQ(copy.unknown2.string, "127.0.0.1");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(CommonAuthPacketsTests, ServerVersionConfirmMatchesLegacy) {
|
||||
for (const auto serviceType : { ServiceType::AUTH, ServiceType::WORLD, ServiceType::CHAT }) {
|
||||
const auto sysAddr = TestAddress();
|
||||
ExpectSameOutput(
|
||||
[&] { LegacyAuthPackets::SendHandshake(Game::server, sysAddr, "ignored", 1, serviceType); },
|
||||
[&] {
|
||||
CommonPackets::ServerVersionConfirm response;
|
||||
response.serviceType = static_cast<uint32_t>(serviceType);
|
||||
response.Send(sysAddr);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(CommonAuthPacketsTests, VersionConfirmGoldenBytes) {
|
||||
CommonPackets::ServerVersionConfirm response;
|
||||
response.serviceType = static_cast<uint32_t>(ServiceType::WORLD);
|
||||
RakNet::BitStream bytes;
|
||||
response.WritePacket(bytes);
|
||||
// 0x53 | COMMON u16 | VERSION_CONFIRM u32 | pad | 171022 | 861228100 | WORLD u32 | 219818307120 u64
|
||||
EXPECT_PACKET_EQ(FromHex("53 00 00 00 00 00 00 00 0e 9c 02 00 44 4c 55 33 04 00 00 00 30 2e 31 2e 33 00 00 00"), FromBitStream(bytes));
|
||||
RoundTrip(response);
|
||||
|
||||
CommonPackets::ClientVersionConfirm request;
|
||||
request.netVersion = 171022;
|
||||
request.serviceType = ServiceType::CLIENT;
|
||||
request.processID = 0x11223344;
|
||||
request.port = 0x5566;
|
||||
RakNet::BitStream requestBytes;
|
||||
request.WritePacket(requestBytes);
|
||||
std::string zeros;
|
||||
for (int i = 0; i < 33; i++) zeros += " 00";
|
||||
// ... | 171022 | unknown 0 | CLIENT u16 | pad u16 | process id | port | 33 byte string
|
||||
EXPECT_PACKET_EQ(FromHex("53 00 00 00 00 00 00 00 0e 9c 02 00 00 00 00 00 05 00 00 00 44 33 22 11 66 55" + zeros), FromBitStream(requestBytes));
|
||||
ExpectTruncatedFails(request);
|
||||
}
|
||||
|
||||
TEST_F(CommonAuthPacketsTests, DisconnectNotifyMatchesLegacy) {
|
||||
for (const auto id : magic_enum::enum_values<eServerDisconnectIdentifiers>()) {
|
||||
RakNet::BitStream expected;
|
||||
LegacyAuthPackets::WriteDisconnectNotify(expected, id);
|
||||
CommonPackets::DisconnectNotify notify;
|
||||
notify.disconnectID = id;
|
||||
RakNet::BitStream actual;
|
||||
notify.WritePacket(actual);
|
||||
EXPECT_PACKET_EQ(FromBitStream(expected), FromBitStream(actual));
|
||||
EXPECT_EQ(RoundTrip(notify).disconnectID, id);
|
||||
}
|
||||
|
||||
CommonPackets::DisconnectNotify kick;
|
||||
kick.disconnectID = eServerDisconnectIdentifiers::KICK;
|
||||
RakNet::BitStream bytes;
|
||||
kick.WritePacket(bytes);
|
||||
EXPECT_PACKET_EQ(FromHex("53 00 00 01 00 00 00 00 0b 00 00 00"), FromBitStream(bytes));
|
||||
ExpectTruncatedFails(kick);
|
||||
}
|
||||
|
||||
TEST_F(CommonAuthPacketsTests, GeneralNotifyGoldenAndRoundTrip) {
|
||||
CommonPackets::GeneralNotify notify;
|
||||
notify.notifyType = 0;
|
||||
notify.showMessageBox = true;
|
||||
RakNet::BitStream bytes;
|
||||
notify.WritePacket(bytes);
|
||||
EXPECT_PACKET_EQ(FromHex("53 00 00 02 00 00 00 00 00 00 00 00 01"), FromBitStream(bytes));
|
||||
const auto copy = RoundTrip(notify);
|
||||
EXPECT_EQ(copy.notifyType, 0);
|
||||
EXPECT_TRUE(copy.showMessageBox);
|
||||
ExpectTruncatedFails(notify);
|
||||
}
|
||||
|
||||
TEST_F(CommonAuthPacketsTests, LoginResponseMatchesLegacy) {
|
||||
// Event gating comes from the config; environment variables override it
|
||||
setenv("EVENT_1", "Event One", 1);
|
||||
setenv("EVENT_8", std::string(40, 'e').c_str(), 1);
|
||||
setenv("VERSION_MINOR", "99", 1);
|
||||
|
||||
const std::vector<eLoginResponse> codes = { eLoginResponse::GENERAL_FAILED, eLoginResponse::BANNED, eLoginResponse::PERMISSIONS_NOT_HIGH_ENOUGH, eLoginResponse::INVALID_USER, eLoginResponse::WRONG_PASS, eLoginResponse::ACCOUNT_LOCKED };
|
||||
for (const auto code : codes) {
|
||||
for (const auto& text : g_Strings) {
|
||||
for (const size_t stampCount : { size_t{ 0 }, size_t{ 1 }, size_t{ 5 } }) {
|
||||
std::vector<Stamp> legacyStamps;
|
||||
for (size_t i = 0; i < stampCount; i++) legacyStamps.emplace_back(static_cast<eStamps>(i), static_cast<uint32_t>(i * 3), 1000 + i);
|
||||
auto stamps = legacyStamps;
|
||||
const auto sysAddr = TestAddress();
|
||||
ExpectSameOutput(
|
||||
[&] { auto copy = legacyStamps; LegacyAuthPackets::SendLoginResponse(Game::server, sysAddr, code, text, text, 2001, "user", copy); },
|
||||
[&] { auto copy = stamps; AuthPackets::SendLoginResponse(Game::server, sysAddr, code, text, text, 2001, "user", copy); });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsetenv("EVENT_1");
|
||||
unsetenv("EVENT_8");
|
||||
unsetenv("VERSION_MINOR");
|
||||
}
|
||||
|
||||
TEST_F(CommonAuthPacketsTests, LoginResponseRoundTrip) {
|
||||
ClientPackets::LoginResponse response;
|
||||
response.responseCode = eLoginResponse::SUCCESS;
|
||||
response.events[0] = LUString("Talk_Like_A_Pirate");
|
||||
response.versionMajor = 1;
|
||||
response.versionCurrent = 10;
|
||||
response.versionMinor = 64;
|
||||
response.userKey = LUWString("0123456789abcdef0123456789abcdef");
|
||||
response.worldServerIP = LUString("192.168.1.2");
|
||||
response.worldServerPort = 2000;
|
||||
response.errorMessage = "Something went wrong";
|
||||
response.stamps = { Stamp(eStamps::PASSPORT_AUTH_START, 0, 5), Stamp(eStamps::NO_WORLD_SERVER, 1, 6) };
|
||||
const auto copy = RoundTrip(response);
|
||||
EXPECT_EQ(copy.responseCode, eLoginResponse::SUCCESS);
|
||||
EXPECT_EQ(copy.events[0].string, "Talk_Like_A_Pirate");
|
||||
EXPECT_EQ(copy.versionMinor, 64);
|
||||
EXPECT_EQ(copy.worldServerIP.string, "192.168.1.2");
|
||||
EXPECT_EQ(copy.worldServerPort, 2000);
|
||||
EXPECT_EQ(copy.cdnTicket.string, ClientPackets::LoginResponse::DEFAULT_CDN_TICKET);
|
||||
EXPECT_EQ(copy.localization.string, "US");
|
||||
EXPECT_EQ(copy.errorMessage, "Something went wrong");
|
||||
ASSERT_EQ(copy.stamps.size(), 2);
|
||||
EXPECT_EQ(copy.stamps[1].type, eStamps::NO_WORLD_SERVER);
|
||||
EXPECT_EQ(copy.stamps[1].timestamp, 6);
|
||||
ExpectTruncatedFails(response);
|
||||
|
||||
response.errorMessage.clear();
|
||||
response.stamps.clear();
|
||||
EXPECT_TRUE(RoundTrip(response).errorMessage.empty());
|
||||
}
|
||||
|
||||
TEST_F(CommonAuthPacketsTests, LoginRequestMatchesLegacy) {
|
||||
for (const auto& username : g_Strings) {
|
||||
AuthPackets::LoginRequest request;
|
||||
request.username = LUWString(username);
|
||||
request.password = LUWString(std::string("hunter2"), 41);
|
||||
request.localeID = LanguageCodeID::en_US;
|
||||
request.clientOS = ClientOS::WINDOWS;
|
||||
request.memoryStats = LUWString(std::string("Memory"), 256);
|
||||
request.videoCard = LUWString(std::string("Video card"), 128);
|
||||
request.numberOfProcessors = 8;
|
||||
request.processorType = 586;
|
||||
request.processorLevel = 6;
|
||||
request.processorRevision = 0x3a09;
|
||||
request.osVersionInfoSize = 148;
|
||||
request.majorVersion = 6;
|
||||
request.minorVersion = 1;
|
||||
request.buildNumber = 7601;
|
||||
request.platformID = 2;
|
||||
RakNet::BitStream bytes;
|
||||
request.WritePacket(bytes);
|
||||
const auto sysAddr = TestAddress();
|
||||
|
||||
// The test database knows no accounts, so both answer INVALID_USER
|
||||
ExpectSameOutput(
|
||||
[&] { auto packet = MakePacket(bytes, sysAddr); LegacyAuthPackets::HandleLoginRequest(Game::server, &packet); },
|
||||
[&] { Dispatch(bytes, sysAddr, AuthPackets::Handle); });
|
||||
|
||||
const auto copy = RoundTrip(request);
|
||||
EXPECT_EQ(copy.username.GetAsString(), username.substr(0, 33));
|
||||
EXPECT_EQ(copy.password.GetAsString(), "hunter2");
|
||||
EXPECT_EQ(copy.localeID, LanguageCodeID::en_US);
|
||||
EXPECT_EQ(copy.buildNumber, 7601);
|
||||
EXPECT_EQ(copy.platformID, 2);
|
||||
ExpectTruncatedFails(request);
|
||||
}
|
||||
}
|
||||
339
tests/dGameTests/dNetTests/Legacy/CommonAuthPacketsLegacy.h
Normal file
339
tests/dGameTests/dNetTests/Legacy/CommonAuthPacketsLegacy.h
Normal file
@@ -0,0 +1,339 @@
|
||||
#ifndef COMMONAUTHPACKETSLEGACY_H
|
||||
#define COMMONAUTHPACKETSLEGACY_H
|
||||
|
||||
// FROZEN ORACLE - DO NOT EDIT.
|
||||
// Verbatim copies of the hand written functions that CommonPackets / AuthPackets::LoginRequest /
|
||||
// ClientPackets::LoginResponse replaced (dNet/AuthPackets.cpp and dNet/dServer.cpp before the conversion).
|
||||
// Only the namespace changed (and calls to its own functions name the new namespace).
|
||||
// The byte-equality tests run the same inputs through these and through the new structs and require
|
||||
// identical bytes, so the wire format is pinned even after the production code is deleted.
|
||||
|
||||
#include "AuthPackets.h"
|
||||
#include "BitStreamUtils.h"
|
||||
#include "ClientPackets.h"
|
||||
#include "Database.h"
|
||||
#include "dClient/ClientVersion.h"
|
||||
#include "dCommonVars.h"
|
||||
#include "dConfig.h"
|
||||
#include "dServer.h"
|
||||
#include "eGameMasterLevel.h"
|
||||
#include "eLoginResponse.h"
|
||||
#include "eServerDisconnectIdentifiers.h"
|
||||
#include "Game.h"
|
||||
#include "GeneralUtils.h"
|
||||
#include "Logger.h"
|
||||
#include "MD5.h"
|
||||
#include "MessageType/Client.h"
|
||||
#include "MessageType/Master.h"
|
||||
#include "MessageType/Server.h"
|
||||
#include "ServiceType.h"
|
||||
#include "StringifiedEnum.h"
|
||||
#include "ZoneInstanceManager.h"
|
||||
|
||||
#include <bcrypt/BCrypt.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <ctime>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace LegacyAuthPackets {
|
||||
inline std::vector<uint32_t> claimCodes;
|
||||
|
||||
inline std::string CleanReceivedString(const std::string& str) {
|
||||
std::string toReturn = str;
|
||||
const auto removed = std::ranges::find_if(toReturn, [](unsigned char c) { return isprint(c) == 0 && isblank(c) == 0; });
|
||||
toReturn.erase(removed, toReturn.end());
|
||||
return toReturn;
|
||||
}
|
||||
|
||||
inline void SendHandshake(dServer* server, const SystemAddress& sysAddr, const std::string& nextServerIP, uint16_t nextServerPort, const ServiceType serverType) {
|
||||
RakNet::BitStream bitStream;
|
||||
BitStreamUtils::WriteHeader(bitStream, ServiceType::COMMON, MessageType::Server::VERSION_CONFIRM);
|
||||
|
||||
const auto& clientNetVersionString = Game::config->GetValue("client_net_version");
|
||||
const uint32_t clientNetVersion = GeneralUtils::TryParse<uint32_t>(clientNetVersionString).value_or(171022);
|
||||
|
||||
bitStream.Write<uint32_t>(clientNetVersion);
|
||||
bitStream.Write<uint32_t>(861228100);
|
||||
bitStream.Write(static_cast<uint32_t>(serverType));
|
||||
bitStream.Write<uint64_t>(219818307120);
|
||||
|
||||
server->Send(bitStream, sysAddr, false);
|
||||
}
|
||||
|
||||
inline void HandleHandshake(dServer* server, Packet* packet) {
|
||||
CINSTREAM_SKIP_HEADER
|
||||
uint32_t clientVersion = 0;
|
||||
inStream.Read(clientVersion);
|
||||
inStream.IgnoreBytes(4);
|
||||
|
||||
ServiceType serviceType;
|
||||
inStream.Read(serviceType);
|
||||
if (serviceType != ServiceType::CLIENT) LOG("WARNING: Service is not a Client!");
|
||||
inStream.IgnoreBytes(2);
|
||||
|
||||
uint32_t processID;
|
||||
inStream.Read(processID);
|
||||
|
||||
uint16_t port;
|
||||
inStream.Read(port);
|
||||
if (port != packet->systemAddress.port) LOG("WARNING: Port written in packet does not match the port the client is connecting over!");
|
||||
|
||||
inStream.IgnoreBytes(33);
|
||||
|
||||
LOG_DEBUG("Client Data [Version: %i, Service: %s, Process: %u, Port: %u, Sysaddr Port: %u]", clientVersion, StringifiedEnum::ToString(serviceType).data(), processID, port, packet->systemAddress.port);
|
||||
|
||||
SendHandshake(server, packet->systemAddress, server->GetIP(), server->GetPort(), server->GetServerType());
|
||||
}
|
||||
|
||||
inline void SendLoginResponse(dServer* server, const SystemAddress& sysAddr, eLoginResponse responseCode, const std::string& errorMsg, const std::string& wServerIP, uint16_t wServerPort, std::string username, std::vector<Stamp>& stamps) {
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_IM_LOGIN_START, 1);
|
||||
RakNet::BitStream loginResponse;
|
||||
BitStreamUtils::WriteHeader(loginResponse, ServiceType::CLIENT, MessageType::Client::LOGIN_RESPONSE);
|
||||
|
||||
loginResponse.Write(responseCode);
|
||||
|
||||
// Event Gating
|
||||
loginResponse.Write(LUString(Game::config->GetValue("event_1")));
|
||||
loginResponse.Write(LUString(Game::config->GetValue("event_2")));
|
||||
loginResponse.Write(LUString(Game::config->GetValue("event_3")));
|
||||
loginResponse.Write(LUString(Game::config->GetValue("event_4")));
|
||||
loginResponse.Write(LUString(Game::config->GetValue("event_5")));
|
||||
loginResponse.Write(LUString(Game::config->GetValue("event_6")));
|
||||
loginResponse.Write(LUString(Game::config->GetValue("event_7")));
|
||||
loginResponse.Write(LUString(Game::config->GetValue("event_8")));
|
||||
|
||||
const uint16_t version_major =
|
||||
GeneralUtils::TryParse<uint16_t>(Game::config->GetValue("version_major")).value_or(ClientVersion::major);
|
||||
const uint16_t version_current =
|
||||
GeneralUtils::TryParse<uint16_t>(Game::config->GetValue("version_current")).value_or(ClientVersion::current);
|
||||
const uint16_t version_minor =
|
||||
GeneralUtils::TryParse<uint16_t>(Game::config->GetValue("version_minor")).value_or(ClientVersion::minor);
|
||||
|
||||
loginResponse.Write(version_major);
|
||||
loginResponse.Write(version_current);
|
||||
loginResponse.Write(version_minor);
|
||||
|
||||
// Writes the user key
|
||||
uint32_t sessionKey = GeneralUtils::GenerateRandomNumber<uint32_t>();
|
||||
std::string userHash = std::to_string(sessionKey);
|
||||
userHash = md5(userHash);
|
||||
loginResponse.Write(LUWString(userHash));
|
||||
|
||||
// World Server IP
|
||||
loginResponse.Write(LUString(wServerIP));
|
||||
// Chat Server IP (unused)
|
||||
loginResponse.Write(LUString(""));
|
||||
|
||||
// World Server Redirect port
|
||||
loginResponse.Write(wServerPort);
|
||||
// Char Server Redirect port (unused)
|
||||
loginResponse.Write(static_cast<uint16_t>(0));
|
||||
|
||||
// CDN Key
|
||||
loginResponse.Write(LUString(""));
|
||||
|
||||
// CDN Ticket
|
||||
loginResponse.Write(LUString("00000000-0000-0000-0000-000000000000", 37));
|
||||
|
||||
// Language
|
||||
loginResponse.Write(Language::en_US);
|
||||
|
||||
// Write the localization
|
||||
loginResponse.Write(LUString("US", 3));
|
||||
|
||||
loginResponse.Write<uint8_t>(false); // Just upgraded from F2P
|
||||
loginResponse.Write<uint8_t>(false); // User is F2P
|
||||
loginResponse.Write<uint64_t>(0); // Time Remaining in F2P
|
||||
|
||||
// Write custom error message
|
||||
loginResponse.Write<uint16_t>(errorMsg.length());
|
||||
loginResponse.Write(LUWString(errorMsg, static_cast<uint32_t>(errorMsg.length())));
|
||||
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_WORLD_COMMUNICATION_FINISH, 1);
|
||||
|
||||
loginResponse.Write<uint32_t>((sizeof(Stamp) * stamps.size()) + sizeof(uint32_t));
|
||||
for (auto& stamp : stamps) stamp.Serialize(loginResponse);
|
||||
|
||||
server->Send(loginResponse, sysAddr, false);
|
||||
//Inform the master server that we've created a session for this user:
|
||||
if (responseCode == eLoginResponse::SUCCESS) {
|
||||
CBITSTREAM;
|
||||
BitStreamUtils::WriteHeader(bitStream, ServiceType::MASTER, MessageType::Master::SET_SESSION_KEY);
|
||||
bitStream.Write(sessionKey);
|
||||
bitStream.Write(LUString(username));
|
||||
server->SendToMaster(bitStream);
|
||||
|
||||
LOG("Set session key for user %s", username.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
inline void HandleLoginRequest(dServer* server, Packet* packet) {
|
||||
CINSTREAM_SKIP_HEADER;
|
||||
|
||||
std::vector<Stamp> stamps;
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_START, 0);
|
||||
|
||||
LUWString usernameLUString;
|
||||
inStream.Read(usernameLUString);
|
||||
const auto username = usernameLUString.GetAsString();
|
||||
|
||||
LUWString password(41);
|
||||
inStream.Read(password);
|
||||
|
||||
LanguageCodeID locale_id;
|
||||
inStream.Read(locale_id);
|
||||
LOG_DEBUG("Locale ID: %s", StringifiedEnum::ToString(locale_id).data());
|
||||
|
||||
ClientOS clientOS;
|
||||
inStream.Read(clientOS);
|
||||
LOG_DEBUG("Operating System: %s", StringifiedEnum::ToString(clientOS).data());
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_CLIENT_OS, 0);
|
||||
|
||||
LUWString memoryStats(256);
|
||||
inStream.Read(memoryStats);
|
||||
LOG_DEBUG("Memory Stats [%s]", CleanReceivedString(memoryStats.GetAsString()).c_str());
|
||||
|
||||
LUWString videoCard(128);
|
||||
inStream.Read(videoCard);
|
||||
LOG_DEBUG("VideoCard Info: [%s]", CleanReceivedString(videoCard.GetAsString()).c_str());
|
||||
|
||||
// Processor/CPU info
|
||||
uint32_t numOfProcessors;
|
||||
inStream.Read(numOfProcessors);
|
||||
uint32_t processorType;
|
||||
inStream.Read(processorType);
|
||||
uint16_t processorLevel;
|
||||
inStream.Read(processorLevel);
|
||||
uint16_t processorRevision;
|
||||
inStream.Read(processorRevision);
|
||||
LOG_DEBUG("CPU Info: [#Processors: %i, Processor Type: %i, Processor Level: %i, Processor Revision: %i]", numOfProcessors, processorType, processorLevel, processorRevision);
|
||||
|
||||
// OS Info
|
||||
uint32_t osVersionInfoSize;
|
||||
inStream.Read(osVersionInfoSize);
|
||||
uint32_t majorVersion;
|
||||
inStream.Read(majorVersion);
|
||||
uint32_t minorVersion;
|
||||
inStream.Read(minorVersion);
|
||||
uint32_t buildNumber;
|
||||
inStream.Read(buildNumber);
|
||||
uint32_t platformID;
|
||||
inStream.Read(platformID);
|
||||
LOG_DEBUG("OS Info: [Size: %i, Major: %i, Minor %i, Buid#: %i, platformID: %i]", osVersionInfoSize, majorVersion, minorVersion, buildNumber, platformID);
|
||||
|
||||
// Fetch account details
|
||||
auto accountInfo = Database::Get()->GetAccountInfo(username);
|
||||
|
||||
if (!accountInfo) {
|
||||
LOG("No user by name %s found!", username.c_str());
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_ERROR, 1);
|
||||
LegacyAuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::INVALID_USER, "", "", 2001, username, stamps);
|
||||
return;
|
||||
}
|
||||
|
||||
// The password first: someone who doesn't know it learns nothing about the account (ban details, lock, play key),
|
||||
// and a failed attempt changes nothing (an expired ban is only lifted for the real owner)
|
||||
if (::bcrypt_checkpw(password.GetAsString().c_str(), accountInfo->bcryptPassword.c_str()) != 0) {
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_ERROR, 1);
|
||||
LegacyAuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::WRONG_PASS, "", "", 2001, username, stamps);
|
||||
LOG("Wrong password used");
|
||||
return;
|
||||
}
|
||||
|
||||
//If we aren't running in live mode, then only GMs are allowed to enter:
|
||||
if (Game::config->GetValue<bool>("closed_to_non_devs", false) && accountInfo->maxGmLevel == eGameMasterLevel::CIVILIAN) {
|
||||
stamps.emplace_back(eStamps::GM_REQUIRED, 1);
|
||||
LegacyAuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::PERMISSIONS_NOT_HIGH_ENOUGH, "The server is currently only open to developers.", "", 2001, username, stamps);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Game::config->GetValue("dont_use_keys") != "1" && accountInfo->maxGmLevel == eGameMasterLevel::CIVILIAN) {
|
||||
//Check to see if we have a play key:
|
||||
if (accountInfo->playKeyId == 0) {
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_ERROR, 1);
|
||||
LegacyAuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::PERMISSIONS_NOT_HIGH_ENOUGH, "Your account doesn't have a play key associated with it!", "", 2001, username, stamps);
|
||||
LOG("User %s tried to log in, but they don't have a play key.", username.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
//Check if the play key is _valid_:
|
||||
auto playKeyStatus = Database::Get()->IsPlaykeyActive(accountInfo->playKeyId);
|
||||
|
||||
if (!playKeyStatus) {
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_ERROR, 1);
|
||||
LegacyAuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::PERMISSIONS_NOT_HIGH_ENOUGH, "Your account doesn't have a valid play key associated with it!", "", 2001, username, stamps);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!playKeyStatus.value()) {
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_ERROR, 1);
|
||||
LegacyAuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::PERMISSIONS_NOT_HIGH_ENOUGH, "Your play key has been disabled.", "", 2001, username, stamps);
|
||||
LOG("User %s tried to log in, but their play key was disabled", username.c_str());
|
||||
return;
|
||||
}
|
||||
} else if (Game::config->GetValue("dont_use_keys") == "1" || accountInfo->maxGmLevel > eGameMasterLevel::CIVILIAN){
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_BYPASS, 1);
|
||||
}
|
||||
|
||||
// A temporary ban that has run out is lifted as the player logs in
|
||||
if (accountInfo->banned && accountInfo->banExpires > 0 && accountInfo->banExpires <= static_cast<int64_t>(std::time(nullptr))) {
|
||||
Database::Get()->SetAccountBan(accountInfo->id, false, 0, "");
|
||||
Database::Get()->InsertAccountNote({ 0, accountInfo->id, "unban", "Temporary ban ended", "[server]", static_cast<int64_t>(std::time(nullptr)) });
|
||||
accountInfo->banned = false;
|
||||
LOG("Temporary ban of %s ended", username.c_str());
|
||||
}
|
||||
|
||||
if (accountInfo->banned) {
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_ERROR, 1);
|
||||
std::string message;
|
||||
if (accountInfo->banExpires > 0) {
|
||||
char until[32];
|
||||
const std::time_t expires = accountInfo->banExpires;
|
||||
std::strftime(until, sizeof(until), "%Y-%m-%d %H:%M UTC", std::gmtime(&expires));
|
||||
message = std::string("You are banned until ") + until + ".";
|
||||
}
|
||||
if (!accountInfo->banReason.empty()) message += (message.empty() ? "" : " ") + std::string("Reason: ") + accountInfo->banReason;
|
||||
LegacyAuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::BANNED, message, "", 2001, username, stamps);
|
||||
return;
|
||||
}
|
||||
|
||||
if (accountInfo->locked) {
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_ERROR, 1);
|
||||
LegacyAuthPackets::SendLoginResponse(server, packet->systemAddress, eLoginResponse::ACCOUNT_LOCKED, "", "", 2001, username, stamps);
|
||||
return;
|
||||
}
|
||||
|
||||
{
|
||||
SystemAddress system = packet->systemAddress; //Copy the sysAddr before the Packet gets destroyed from main
|
||||
|
||||
// Where accounts log in from, so staff can see accounts that share a connection (log_login_addresses, on by default)
|
||||
if (Game::config->GetValue("log_login_addresses") != "0") {
|
||||
Database::Get()->RecordLoginAddress(accountInfo->id, system.ToString(false), static_cast<int64_t>(std::time(nullptr)));
|
||||
}
|
||||
|
||||
if (!server->GetIsConnectedToMaster()) {
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_WORLD_DISCONNECT, 1);
|
||||
LegacyAuthPackets::SendLoginResponse(server, system, eLoginResponse::GENERAL_FAILED, "", "", 0, username, stamps);
|
||||
return;
|
||||
}
|
||||
stamps.emplace_back(eStamps::PASSPORT_AUTH_WORLD_SESSION_CONFIRM_TO_AUTH, 1);
|
||||
ZoneInstanceManager::Instance()->RequestZoneTransfer(server, 0, 0, false, [system, server, username, stamps](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string zoneIP, uint16_t zonePort) mutable {
|
||||
LegacyAuthPackets::SendLoginResponse(server, system, eLoginResponse::SUCCESS, "", zoneIP, zonePort, username, stamps);
|
||||
});
|
||||
}
|
||||
|
||||
for(auto const code: claimCodes){
|
||||
Database::Get()->InsertRewardCode(accountInfo->id, code);
|
||||
}
|
||||
}
|
||||
|
||||
// dServer::Disconnect, the part that built the packet (it then sent it with mPeer->Send and closed the connection).
|
||||
inline void WriteDisconnectNotify(RakNet::BitStream& bitStream, eServerDisconnectIdentifiers disconNotifyID) {
|
||||
BitStreamUtils::WriteHeader(bitStream, ServiceType::COMMON, MessageType::Server::DISCONNECT_NOTIFY);
|
||||
bitStream.Write(disconNotifyID);
|
||||
}
|
||||
}
|
||||
|
||||
#endif // COMMONAUTHPACKETSLEGACY_H
|
||||
Reference in New Issue
Block a user