From 5311879370a263b5d07606947bb617468961594d Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Sun, 25 May 2025 12:42:52 +0200 Subject: [PATCH 01/11] Added Async stuff --- CMakeLists.txt | 14 ++-- common/src/Async/Async.cpp | 21 ++++++ common/src/Async/Async.h | 16 +++++ common/src/Async/AsyncUnorderedMap.cpp | 1 + common/src/Async/AsyncUnorderedMap.h | 52 ++++++++++++++ common/src/Async/AsyncVector.cpp | 11 +++ common/src/Async/AsyncVector.h | 25 +++++++ .../src/Network}/PackagingSystem.cpp | 0 .../src/Network}/PackagingSystem.h | 0 {server/src => common/src/Network}/Packets.h | 0 server/CMakeLists.txt | 5 ++ server/src/MessageHandler.cpp | 68 ++++++++++--------- server/src/MessageHandler.h | 14 ++-- server/src/ServerManager.cpp | 17 ++--- server/src/ServerManager.h | 4 +- src/Logic/GameThreadWorker.cpp | 12 +++- src/Logic/GameThreadWorker.h | 5 +- src/Network/Client.h | 4 +- src/Network/MessageHandler.cpp | 47 +++++-------- src/Network/MessageHandler.h | 10 +-- src/Wrapper/OCNpc.cpp | 7 ++ src/Wrapper/OCNpc.h | 1 + src/dllmain.cpp | 10 +-- 23 files changed, 245 insertions(+), 99 deletions(-) create mode 100644 common/src/Async/Async.cpp create mode 100644 common/src/Async/Async.h create mode 100644 common/src/Async/AsyncUnorderedMap.cpp create mode 100644 common/src/Async/AsyncUnorderedMap.h create mode 100644 common/src/Async/AsyncVector.cpp create mode 100644 common/src/Async/AsyncVector.h rename {server/src => common/src/Network}/PackagingSystem.cpp (100%) rename {server/src => common/src/Network}/PackagingSystem.h (100%) rename {server/src => common/src/Network}/Packets.h (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 655b4c3..d9e047d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,12 +51,12 @@ endif() set(MINHOOK_DIR ${CMAKE_SOURCE_DIR}/MinHook) # Suche alle .cpp-Dateien im aktuellen Verzeichnis -file(GLOB SOURCES "src/*.cpp") -file(GLOB MODELS_SOURCES "src/Models/*.cpp") -file(GLOB LOGIC_SOURCES "src/Logic/*.cpp") -file(GLOB WRAPPER_SOURCES "src/Wrapper/*.cpp") -file(GLOB NETWORK_SOURCES "src/Network/*.cpp") -file(GLOB PACKET_SOURCES "server/src/PackagingSystem.cpp") # Single file from server +file(GLOB_RECURSE SOURCES "src/*.cpp") +file(GLOB_RECURSE COMMON_SOURCES "common/src/*.cpp") + +list(APPEND SOURCES ${COMMON_SOURCES}) +include_directories("common/src/") + # Dear ImGui Quellen und Header definieren set(IMGUI_DIR ${CMAKE_SOURCE_DIR}/imgui) @@ -91,7 +91,7 @@ set(MINHOOK_LIB ${MINHOOK_DIR}/libMinHook.x86.lib) #endif() # Bibliothek erstellen (DLL) -add_library(MyDLL SHARED ${SOURCES} ${IMGUI_SOURCES} ${MODELS_SOURCES} ${LOGIC_SOURCES} ${WRAPPER_SOURCES} ${NETWORK_SOURCES} ${PACKET_SOURCES}) +add_library(MyDLL SHARED ${SOURCES} ${IMGUI_SOURCES}) # Include-Verzeichnisse hinzufügen target_include_directories(MyDLL PUBLIC diff --git a/common/src/Async/Async.cpp b/common/src/Async/Async.cpp new file mode 100644 index 0000000..e533ac0 --- /dev/null +++ b/common/src/Async/Async.cpp @@ -0,0 +1,21 @@ +#include "Async.h" + +std::mutex Async::mtxPrint; + +void Async::PrintLn(std::string str) // STATIC +{ + std::lock_guard lock(mtxPrint); + std::cout << str << "\n"; +} + +void Async::Print(std::string str) // STATIC +{ + std::lock_guard lock(mtxPrint); + std::cout << str << "\n"; +} + +void Async::Cerr(std::string str) // STATIC +{ + std::lock_guard lock(mtxPrint); + std::cerr << str << "\n"; +} \ No newline at end of file diff --git a/common/src/Async/Async.h b/common/src/Async/Async.h new file mode 100644 index 0000000..8b9dc93 --- /dev/null +++ b/common/src/Async/Async.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +class Async { + + public: + static void PrintLn(std::string str); + static void Print(std::string str); + static void Cerr(std::string str) ; + + private: + static std::mutex mtxPrint; + +}; \ No newline at end of file diff --git a/common/src/Async/AsyncUnorderedMap.cpp b/common/src/Async/AsyncUnorderedMap.cpp new file mode 100644 index 0000000..5d819cf --- /dev/null +++ b/common/src/Async/AsyncUnorderedMap.cpp @@ -0,0 +1 @@ +#include "AsyncUnorderedMap.h" \ No newline at end of file diff --git a/common/src/Async/AsyncUnorderedMap.h b/common/src/Async/AsyncUnorderedMap.h new file mode 100644 index 0000000..88bb040 --- /dev/null +++ b/common/src/Async/AsyncUnorderedMap.h @@ -0,0 +1,52 @@ +#pragma once +#include +#include +#include + +template +class AsyncUnorderedMap { + public: + void append(T1 key, T2 value) { + std::lock_guard lock(this->mtxMap); + map.insert({key, value}); + } + + void remove(T1 key) { + std::lock_guard lock(this->mtxMap); + map.erase(key); + } + + bool existsItem(T1 key) { + std::lock_guard lock(this->mtxMap); + auto it = map.find(key); + if (it != map.end()) + return true; + + return false; + } + + std::optional> find(const T1& key) { + auto it = map.find(key); + if(it != map.end()) + return it->second; + else + return std::nullopt; + } + + std::unordered_map *getUnorderedMap() { + return &this->map; + } + + std::mutex &getMutex() { + return mtxMap; + } + /*T at(); + int size();*/ + + /*void lock(); + void unlock();*/ + + private: + std::unordered_map map; + std::mutex mtxMap; +}; diff --git a/common/src/Async/AsyncVector.cpp b/common/src/Async/AsyncVector.cpp new file mode 100644 index 0000000..e865139 --- /dev/null +++ b/common/src/Async/AsyncVector.cpp @@ -0,0 +1,11 @@ +#include "AsyncVector.h" + +template +void AsyncVector::append(T item) { + std::lock_guard lock(this->mtxList); +} + +template +std::vector *AsyncVector::getVector() { + return &this->list; +} \ No newline at end of file diff --git a/common/src/Async/AsyncVector.h b/common/src/Async/AsyncVector.h new file mode 100644 index 0000000..c7c2245 --- /dev/null +++ b/common/src/Async/AsyncVector.h @@ -0,0 +1,25 @@ +#pragma once + +#include +#include + + +/* NOT FINISHED */ +template +class AsyncVector { + public: + void append(T item); + /*void remove(T item); + bool existsItem(T item); + + T at(); + int size();*/ + + std::vector *getVector(); + + /*void lock(); + void unlock();*/ + private: + std::vector list; + std::mutex mtxList; +}; \ No newline at end of file diff --git a/server/src/PackagingSystem.cpp b/common/src/Network/PackagingSystem.cpp similarity index 100% rename from server/src/PackagingSystem.cpp rename to common/src/Network/PackagingSystem.cpp diff --git a/server/src/PackagingSystem.h b/common/src/Network/PackagingSystem.h similarity index 100% rename from server/src/PackagingSystem.h rename to common/src/Network/PackagingSystem.h diff --git a/server/src/Packets.h b/common/src/Network/Packets.h similarity index 100% rename from server/src/Packets.h rename to common/src/Network/Packets.h diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index f268d92..8c799de 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -26,6 +26,11 @@ endif() # Automatisch alle .cpp-Dateien aus src/ einbinden file(GLOB_RECURSE SOURCES "src/*.cpp") +# Automatisch alle .cpp-Dateien aus ../common/ einbinden +file(GLOB_RECURSE COMMON_SOURCES "../common/src/*.cpp") +list(APPEND SOURCES ${COMMON_SOURCES}) +include_directories("../common/src/") + # Füge das ausführbare Ziel hinzu add_executable(${PROJECT_NAME} ${SOURCES}) diff --git a/server/src/MessageHandler.cpp b/server/src/MessageHandler.cpp index 5bbe6c9..e0d1d8e 100644 --- a/server/src/MessageHandler.cpp +++ b/server/src/MessageHandler.cpp @@ -1,6 +1,6 @@ #include "MessageHandler.h" -MessageHandler::MessageHandler(std::unordered_map &clients, udp::socket &socket) +MessageHandler::MessageHandler(AsyncUnorderedMap &clients, udp::socket &socket) { this->clients = &clients; this->pSocket = &socket; @@ -14,8 +14,8 @@ void MessageHandler::handleBuffer(udp::endpoint &clientEndpoint, std::string buf int id = PackagingSystem::ReadPacketId(buffer); Packets::ClientPacket packetId = static_cast(id); - std::cout << "ID: " << id << std::endl; - std::cout << "Message: " << buffer << std::endl; + Async::PrintLn( "ID: " + std::to_string(id) ); + Async::PrintLn( "Message: " + buffer ); switch (packetId) { @@ -29,8 +29,7 @@ void MessageHandler::handleBuffer(udp::endpoint &clientEndpoint, std::string buf clientSharesAnimations(clientEndpoint, buffer); break; default: - std::cout << "Unknown Paket...\n" - << std::endl; + Async::PrintLn("Unknown Paket..."); break; } } @@ -38,7 +37,7 @@ void MessageHandler::handleBuffer(udp::endpoint &clientEndpoint, std::string buf void MessageHandler::clientRepondsHeartbeat(udp::endpoint &clientEndpoint, std::string &buffer) { std::string clientPortIp = getClientUniqueString(clientEndpoint); - std::cout << clientPortIp << " responded to Heartbeat Request\n"; + Async::PrintLn( clientPortIp + " responded to Heartbeat Request"); } void MessageHandler::clientSharesPosition(udp::endpoint &clientEndpoint, std::string &buffer) @@ -82,41 +81,37 @@ void MessageHandler::sendMessage(udp::endpoint &clientEndpoint, std::string buff pSocket->async_send_to( boost::asio::buffer(*packetPtr), clientEndpoint, - [packetPtr, clientEndpoint](boost::system::error_code ec, std::size_t bytes_sent) + [this, packetPtr, clientEndpoint](boost::system::error_code ec, std::size_t bytes_sent) { - if (ec) - { - std::cerr << "Async send error to " << clientEndpoint << ": " << ec.message() << std::endl; - } - else - { - std::cout << "Gesendet (" << bytes_sent << " Bytes) an " << clientEndpoint << std::endl; - std::cout << *packetPtr << std::endl; + if (ec){ + //std::cerr << "Async send error to " << clientEndpoint << ": " << ec.message() << std::endl; + Async::Cerr ("Async send error to " + endpointToString(clientEndpoint) + ": " + ec.message()); + } else { + Async::PrintLn ("Gesendet (" + std::to_string(bytes_sent) + " Bytes) an " + endpointToString(clientEndpoint)); + Async::PrintLn(*packetPtr); } }); } void MessageHandler::sendToAllExceptSender(udp::endpoint &senderEndpoint, std::string buffer) { - std::lock_guard lock(clients_mutex); - for (auto it = clients->begin(); it != clients->end(); ++it) + std::lock_guard lock(clients->getMutex()); + for (auto it = clients->getUnorderedMap()->begin(); it != clients->getUnorderedMap()->end(); ++it) { - if (senderEndpoint != it->second.endpoint) + //if (senderEndpoint != it->second.endpoint) // Uncomment for main branch sendMessage(it->second.endpoint, buffer); } } + void MessageHandler::removeClient(udp::endpoint &clientEndpoint) { - std::lock_guard lock(clients_mutex); std::string clientPortIp = getClientUniqueString(clientEndpoint); - auto it = clients->find(clientPortIp); - if (it != clients->end()) - { - clients->erase(it); - } + if(clients->existsItem(clientPortIp)) + clients->remove(clientPortIp); + std::lock_guard lock(clients->getMutex()); // Telling the Clients to remove unreachable client - for (auto &pair : *clients) + for (auto &pair : *clients->getUnorderedMap()) { PackagingSystem clientToRemove(Packets::ServerPacket::serverRemoveClient); clientToRemove.addString(clientPortIp); @@ -128,28 +123,31 @@ void MessageHandler::removeClient(udp::endpoint &clientEndpoint) void MessageHandler::addNewClient(udp::endpoint &clientEndpoint) { - std::lock_guard lock(clients_mutex); std::string clientPortIp = getClientUniqueString(clientEndpoint); CommonStructures::ClientInfo clientInfo; clientInfo.endpoint = clientEndpoint; clientInfo.lastResponse = std::chrono::high_resolution_clock::now(); - auto [it, inserted] = clients->try_emplace(clientPortIp, clientInfo); + /*auto [it, inserted] = clients->try_emplace(clientPortIp, clientInfo); if (inserted) - std::cout << "Added new Client: " << clientPortIp << "\n"; + Async::PrintLn( "Added new Client: " + clientPortIp );*/ + if(clients->existsItem(clientPortIp)) + return; + + clients->append(clientPortIp, clientInfo); + Async::PrintLn( "Added new Client: " + clientPortIp ); updateConsoleTitle(); } void MessageHandler::updateLastResponse(udp::endpoint &clientEndpoint) { - std::lock_guard lock(clients_mutex); std::string clientPortIp = getClientUniqueString(clientEndpoint); auto it = clients->find(clientPortIp); - if (it != clients->end()) - it->second.lastResponse = std::chrono::high_resolution_clock::now(); + if (it) + it->get().lastResponse = std::chrono::high_resolution_clock::now(); } std::string MessageHandler::getClientUniqueString(udp::endpoint &clientEndpoint) @@ -161,6 +159,12 @@ std::string MessageHandler::getClientUniqueString(udp::endpoint &clientEndpoint) void MessageHandler::updateConsoleTitle() { - std::string title = "Players: " + std::to_string(clients->size()); + std::string title = "Players: " + std::to_string(clients->getUnorderedMap()->size()); SetConsoleTitle(title.c_str()); +} + +std::string MessageHandler::endpointToString(const udp::endpoint &clientEndpoint){ + std::string endpointStr = clientEndpoint.address().to_string(); + endpointStr += ":" + std::to_string(clientEndpoint.port()); + return endpointStr; } \ No newline at end of file diff --git a/server/src/MessageHandler.h b/server/src/MessageHandler.h index 838ba04..8eef14a 100644 --- a/server/src/MessageHandler.h +++ b/server/src/MessageHandler.h @@ -5,27 +5,29 @@ #include //#include "Data.h" -#include "Packets.h" -#include "PackagingSystem.h" #include "CommonStructures.h" +#include "../../common/src/Network/Packets.h" +#include "../../common/src/Network/PackagingSystem.h" +#include "../../common/src/Async/AsyncUnorderedMap.h" +#include "../../common/src/Async/Async.h" + using boost::asio::ip::udp; class MessageHandler { public: - MessageHandler(std::unordered_map &clients, udp::socket &socket); + MessageHandler(AsyncUnorderedMap &clients, udp::socket &socket); void handleBuffer(udp::endpoint &clientEndpoint, std::string buffer); void removeClient(udp::endpoint &clientEndpoint); void sendMessage(udp::endpoint &clientEndpoint, std::string buffer); void sendToAllExceptSender(udp::endpoint &senderEndpoint, std::string buffer); - std::mutex clients_mutex; private: - std::unordered_map *clients; + AsyncUnorderedMap *clients; udp::socket * pSocket; void clientRepondsHeartbeat(udp::endpoint &clientEndpoint, std::string &buffer); @@ -41,4 +43,6 @@ class MessageHandler std::string getClientUniqueString(udp::endpoint &clientEndpoint); void updateConsoleTitle(); + + std::string endpointToString(const udp::endpoint &clientEndpoint); }; \ No newline at end of file diff --git a/server/src/ServerManager.cpp b/server/src/ServerManager.cpp index 85095b6..06ef840 100644 --- a/server/src/ServerManager.cpp +++ b/server/src/ServerManager.cpp @@ -22,7 +22,7 @@ void ServerManager::start_receive() { if (!error) { - std::cout << "Received something: " << bytes_received << " bytes\n"; + Async::PrintLn( "Received something: " + std::to_string(bytes_received) + " bytes"); boost::asio::post(*processing_context, [this, buffer, sender_endpoint, bytes_received]() { std::string receivedPackage(buffer->data(), bytes_received); @@ -30,15 +30,16 @@ void ServerManager::start_receive() messageHandler->handleBuffer(*sender_endpoint, receivedPackage); }); - // Starte den nächsten Empfang mit einem neuen Buffer! + // repeat receiving start_receive(); } else { - std::cerr << "\nError receiving: " << error.message() << "\n"; + Async::PrintLn( "\nError receiving: " + error.message()); + //std::cerr << "\nError receiving: " << error.message() << "\n"; messageHandler->removeClient(*sender_endpoint); - // Starte erneut den Empfang + // repeat receiving start_receive(); } }); @@ -48,8 +49,8 @@ void ServerManager::watchingHeartbeat() { while(serverRunning) { std::queue endpointsToRemove; { - std::lock_guard lock(messageHandler->clients_mutex); - for (auto it = clients.begin(); it != clients.end(); ++it) + std::lock_guard lock(clients.getMutex()); + for (auto it = clients.getUnorderedMap()->begin(); it != clients.getUnorderedMap()->end(); ++it) { auto currentTime = std::chrono::high_resolution_clock::now(); std::chrono::duration elapsed = currentTime - it->second.lastResponse; @@ -59,8 +60,8 @@ void ServerManager::watchingHeartbeat() { endpointsToRemove.push(it->second.endpoint); //messageHandler->removeClient(it->second.endpoint); } else if( durrationInSec >= 5) { - std::cout << "Elapsed Time: " << durrationInSec << " seconds" << std::endl; - + //std::cout << "Elapsed Time: " << durrationInSec << " seconds" << std::endl; + Async::PrintLn( "Elapsed Time: " + std::to_string(durrationInSec) + " seconds"); // Sending every 5 Seconds a Heartbeat request if(durrationInSec % 5 == 0){ PackagingSystem heartbeatRequest(Packets::ServerPacket::serverRequestHeartbeat); diff --git a/server/src/ServerManager.h b/server/src/ServerManager.h index f9ad1b8..681f1ff 100644 --- a/server/src/ServerManager.h +++ b/server/src/ServerManager.h @@ -7,6 +7,8 @@ #include "MessageHandler.h" #include "CommonStructures.h" +#include "../../common/src/Async/AsyncUnorderedMap.h" + using boost::asio::ip::udp; class ServerManager { @@ -17,7 +19,7 @@ class ServerManager { private: udp::socket socket; boost::asio::io_context *processing_context; - std::unordered_map clients; + AsyncUnorderedMap clients; bool serverRunning = false; diff --git a/src/Logic/GameThreadWorker.cpp b/src/Logic/GameThreadWorker.cpp index f5f799f..48a2429 100644 --- a/src/Logic/GameThreadWorker.cpp +++ b/src/Logic/GameThreadWorker.cpp @@ -2,7 +2,7 @@ GameThreadWorker::GameThreadWorker() { - clients = new std::unordered_map(); + clients = new AsyncUnorderedMap(); messageHandler = new MessageHandler(clients); pMainPlayer = new Npc(ADDR_PLAYERBASE); } @@ -39,9 +39,12 @@ void GameThreadWorker::processMessages() } } //Npc *npc; +//int *ii = new int; void GameThreadWorker::checkGameState(){ // Checks if player is in range of an other player to render him - for (const auto& pair : *clients) { + std::unordered_map copyOfClients = *clients->getUnorderedMap(); + + for (const auto& pair : copyOfClients) { if (pMainPlayer->oCNpc->getDistanceToVob(pair.second->oCNpc) < 4500 && pair.second->oCNpc->getHomeWorld() == 0) { void *add = OCWorld::AddVob(pair.second->oCNpc); @@ -52,6 +55,9 @@ void GameThreadWorker::checkGameState(){ /* ################ Custom Shit Here################# */ if (GetAsyncKeyState(VK_RSHIFT) < 0) { - + std::cout << "# PRINTING " << "\n"; + zSTRING * str = new zSTRING(""); + str = pMainPlayer->oCNpc->getName(0); + std::cout << "NAME: " << str->getStr() << "\n"; } } \ No newline at end of file diff --git a/src/Logic/GameThreadWorker.h b/src/Logic/GameThreadWorker.h index 596d8c7..920b834 100644 --- a/src/Logic/GameThreadWorker.h +++ b/src/Logic/GameThreadWorker.h @@ -13,6 +13,8 @@ #include "../Network/Client.h" #include "../Network/MessageHandler.h" +#include "../common/src/Async/AsyncUnorderedMap.h" + class Client; class Npc; class MessageHandler; @@ -42,8 +44,7 @@ class GameThreadWorker { /** * @brief Pointer to a map containing active NPC clients, indexed by their IP/Port combination. */ - std::unordered_map *clients; - + AsyncUnorderedMap *clients; ~GameThreadWorker(); diff --git a/src/Network/Client.h b/src/Network/Client.h index 43bf89a..9ced23f 100644 --- a/src/Network/Client.h +++ b/src/Network/Client.h @@ -5,8 +5,8 @@ #include #include -#include "../server/src/PackagingSystem.h" -#include "../server/src/Packets.h" +#include "../common/src/Network/PackagingSystem.h" +#include "../common/src/Network/Packets.h" #include "../Logic/GameThreadWorker.h" #include "../Models/Npc.h" diff --git a/src/Network/MessageHandler.cpp b/src/Network/MessageHandler.cpp index e882ba0..2215a41 100644 --- a/src/Network/MessageHandler.cpp +++ b/src/Network/MessageHandler.cpp @@ -1,6 +1,6 @@ #include "MessageHandler.h" -MessageHandler::MessageHandler(std::unordered_map *pClients) : pClients(pClients) +MessageHandler::MessageHandler(AsyncUnorderedMap *pClients) : pClients(pClients) { } void MessageHandler::setClient(Client &client) @@ -51,7 +51,6 @@ void MessageHandler::handleServerRequestsHeartbeat(std::string &buffer) void MessageHandler::handleServerDistributePosition(std::string &buffer) { - bool playerExists = false; std::string receivedKey = PackagingSystem::ReadItem(buffer); float x = PackagingSystem::ReadItem(buffer); float z = PackagingSystem::ReadItem(buffer); @@ -61,14 +60,9 @@ void MessageHandler::handleServerDistributePosition(std::string &buffer) float pitch = PackagingSystem::ReadItem(buffer); float roll = PackagingSystem::ReadItem(buffer); - std::lock_guard lock(clientsMutex); - auto it = pClients->find(receivedKey); - if (it != pClients->end()) - playerExists = true; - - if (playerExists) - { - Npc *value = it->second; + auto it = pClients->find(receivedKey); + if(it) { + Npc *value = it.value(); zMAT4 matrix; value->oCNpc->getTrafoModelNodeToWorld(&matrix, 0); @@ -79,7 +73,7 @@ void MessageHandler::handleServerDistributePosition(std::string &buffer) value->setZ(z); value->setY(y); return; - } + } // Creating a new Npc Npc *value = new Npc(); @@ -91,22 +85,19 @@ void MessageHandler::handleServerDistributePosition(std::string &buffer) value->oCNpc->enableWithdCoords(x, z, y); // New Client inserted - pClients->insert({receivedKey, value}); + pClients->append(receivedKey, value); } void MessageHandler::handleServerDistributeAnimations(std::string &buffer) { - bool playerExists = false; - std::string receivedKey = PackagingSystem::ReadItem(buffer); // data.names.at(0); - std::lock_guard lock(clientsMutex); - auto it = pClients->find(receivedKey); - if (it != pClients->end()) - playerExists = true; + std::string receivedKey = PackagingSystem::ReadItem(buffer); - if (!playerExists) + auto it = pClients->find(receivedKey); + if(!it) { return; + } - Npc *value = it->second; + Npc *value = it.value(); DataStructures::LastAnimation npcLastAnim = value->getLastAnimation(); DataStructures::LastAnimation npcNewAnim; zCModel *npcModel = new zCModel(value->oCNpc->getModel()); @@ -139,19 +130,17 @@ void MessageHandler::handleServerDistributeAnimations(std::string &buffer) } } -/*##################### TODO: TEST IF THIS WORKS !!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ + void MessageHandler::handleServerRemoveClient(std::string &buffer) { - bool playerExists = false; std::string receivedKey = PackagingSystem::ReadItem(buffer); // data.names.at(0); - std::lock_guard lock(clientsMutex); - auto it = pClients->find(receivedKey); - if (it != pClients->end()) - { - OCWorld::RemoveVob(it->second->oCNpc); - pClients->erase(receivedKey); + + auto it = pClients->find(receivedKey); + if(it) { + OCWorld::RemoveVob(it.value()); + pClients->remove(receivedKey); std::cout << "Removed VOB\n"; - } + } } void MessageHandler::handleServerDistributeRotations(std::string &buffer) diff --git a/src/Network/MessageHandler.h b/src/Network/MessageHandler.h index 9bcbce6..b728c72 100644 --- a/src/Network/MessageHandler.h +++ b/src/Network/MessageHandler.h @@ -7,8 +7,9 @@ #include "../Network/Client.h" #include "../Models/Npc.h" #include "../Wrapper/zCModel.h" -#include "../../server/src/Packets.h" -#include "../../server/src/PackagingSystem.h" +#include "../common/src/Network/Packets.h" +#include "../common/src/Network/PackagingSystem.h" +#include "../common/src/Async/AsyncUnorderedMap.h" class Client; /** @@ -25,7 +26,7 @@ class MessageHandler * @brief Constructs a MessageHandler instance. * @param pClients Pointer to a map storing connected NPCs, indexed by their unique identifier. */ - MessageHandler(std::unordered_map *pClients); + MessageHandler(AsyncUnorderedMap *pClients); /** * @brief Processes an incoming packet string. * @param stringPacket The raw packet data received from the server. @@ -40,9 +41,8 @@ class MessageHandler void setClient(Client &client); private: - std::unordered_map *pClients; ///< Pointer to the map storing NPCs currently in the game. + AsyncUnorderedMap *pClients; ///< Pointer to the map storing NPCs currently in the game. Client *pClient; ///< Pointer to the Client instance for sending and receiving messages. - std::mutex clientsMutex; ///< Mutex for thread-safe access to the clients map. void handleServerHandshakeAccept(std::string &buffer); void handleServerRequestsHeartbeat(std::string &buffer); diff --git a/src/Wrapper/OCNpc.cpp b/src/Wrapper/OCNpc.cpp index e91ac8e..e00ffbe 100644 --- a/src/Wrapper/OCNpc.cpp +++ b/src/Wrapper/OCNpc.cpp @@ -170,6 +170,13 @@ void OCNpc::addVobToWorld_CorrectParentDependencies(){ addVobToWorld_CorrectParentDependenciesRef(this); } + +zSTRING *OCNpc::getName(int value){ + using _GetName = zSTRING *(__thiscall *)(void *pThis, int value); + _GetName getNameRef = reinterpret_cast<_GetName>(0x68d0b0); + return getNameRef(this, value); + +} /*int OCNpc::applyOverlay(char *animName) { zSTRING *name = new zSTRING(animName); diff --git a/src/Wrapper/OCNpc.h b/src/Wrapper/OCNpc.h index 84deca6..e829ddb 100644 --- a/src/Wrapper/OCNpc.h +++ b/src/Wrapper/OCNpc.h @@ -113,6 +113,7 @@ class OCNpc void addVobToWorld_CorrectParentDependencies(); + zSTRING *getName(int value); /*int applyOverlay(char * animName); void setBodyState(int param1); diff --git a/src/dllmain.cpp b/src/dllmain.cpp index 705bac4..6b29536 100644 --- a/src/dllmain.cpp +++ b/src/dllmain.cpp @@ -191,13 +191,13 @@ DWORD WINAPI MainThread() DataChangeNotifier notifier(&client); while (!GetAsyncKeyState(VK_END) & 1) { - /*if (GetAsyncKeyState(VK_DOWN) < 0)*/{ + /*if (GetAsyncKeyState(VK_DOWN) < 0){ notifier.sendChanges(); - } - //notifier.sendChanges(); + }*/ + notifier.sendChanges(); - // give imGui the players Information - //imGuiData.clients = *gameThreadManager->clients; + // give imGui players Information + imGuiData.clients = *gameThreadWorker->clients->getUnorderedMap(); Sleep(80); } io_thread.join(); From 53748193d2b88db87bb9850cd4c571c15906a4ff Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Fri, 13 Jun 2025 14:40:34 +0200 Subject: [PATCH 02/11] Added Name --- CMakeLists.txt | 7 +- common/lib/inih/README.txt | 1 + common/lib/inih/ini.c | 328 +++++++++++++++++++++++++ common/lib/inih/ini.h | 189 ++++++++++++++ common/src/Async/Async.cpp | 6 +- common/src/Async/Async.h | 6 +- common/src/IniManager.cpp | 44 ++++ common/src/IniManager.h | 67 +++++ common/src/Network/PackagingSystem.cpp | 2 +- common/src/Network/PackagingSystem.h | 1 - common/src/Network/Packets.h | 14 +- server/src/CommonStructures.h | 4 +- server/src/MessageHandler.cpp | 67 ++++- server/src/MessageHandler.h | 5 +- src/Logic/GameThreadWorker.cpp | 21 +- src/Logic/ImGuiManager.cpp | 2 +- src/Models/Npc.cpp | 11 + src/Models/Npc.h | 3 + src/Network/Client.cpp | 29 ++- src/Network/Client.h | 9 +- src/Network/MessageHandler.cpp | 111 ++++++--- src/Network/MessageHandler.h | 6 +- src/Wrapper/OCNpc.cpp | 23 +- src/Wrapper/OCNpc.h | 50 ++-- src/Wrapper/basic_string.cpp | 1 + src/Wrapper/basic_string.h | 143 +++++++++++ src/Wrapper/zCModel.cpp | 10 +- src/Wrapper/zSTRING.cpp | 32 +-- src/Wrapper/zSTRING.h | 33 ++- src/dllmain.cpp | 22 +- 30 files changed, 1103 insertions(+), 144 deletions(-) create mode 100644 common/lib/inih/README.txt create mode 100644 common/lib/inih/ini.c create mode 100644 common/lib/inih/ini.h create mode 100644 common/src/IniManager.cpp create mode 100644 common/src/IniManager.h create mode 100644 src/Wrapper/basic_string.cpp create mode 100644 src/Wrapper/basic_string.h diff --git a/CMakeLists.txt b/CMakeLists.txt index d9e047d..e9b8ba6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -72,6 +72,11 @@ set(IMGUI_SOURCES ${IMGUI_BACKENDS_DIR}/imgui_impl_win32.cpp ) +# inih +set(INIH_SOURCES + ${CMAKE_SOURCE_DIR}/common/lib/inih/ini.c +) + # MinHook Quellen und Bibliotheken set(MINHOOK_LIB ${MINHOOK_DIR}/libMinHook.x86.lib) @@ -91,7 +96,7 @@ set(MINHOOK_LIB ${MINHOOK_DIR}/libMinHook.x86.lib) #endif() # Bibliothek erstellen (DLL) -add_library(MyDLL SHARED ${SOURCES} ${IMGUI_SOURCES}) +add_library(MyDLL SHARED ${SOURCES} ${IMGUI_SOURCES} ${INIH_SOURCES}) # Include-Verzeichnisse hinzufügen target_include_directories(MyDLL PUBLIC diff --git a/common/lib/inih/README.txt b/common/lib/inih/README.txt new file mode 100644 index 0000000..131e763 --- /dev/null +++ b/common/lib/inih/README.txt @@ -0,0 +1 @@ +# https://github.com/benhoyt/inih \ No newline at end of file diff --git a/common/lib/inih/ini.c b/common/lib/inih/ini.c new file mode 100644 index 0000000..421e492 --- /dev/null +++ b/common/lib/inih/ini.c @@ -0,0 +1,328 @@ +/* inih -- simple .INI file parser + +SPDX-License-Identifier: BSD-3-Clause + +Copyright (C) 2009-2020, Ben Hoyt + +inih is released under the New BSD license (see LICENSE.txt). Go to the project +home page for more info: + +https://github.com/benhoyt/inih + +*/ + +#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) +#define _CRT_SECURE_NO_WARNINGS +#endif + +#include +#include +#include + +#include "ini.h" + +#if !INI_USE_STACK +#if INI_CUSTOM_ALLOCATOR +#include +void* ini_malloc(size_t size); +void ini_free(void* ptr); +void* ini_realloc(void* ptr, size_t size); +#else +#include +#define ini_malloc malloc +#define ini_free free +#define ini_realloc realloc +#endif +#endif + +#define MAX_SECTION 50 +#define MAX_NAME 50 + +/* Used by ini_parse_string() to keep track of string parsing state. */ +typedef struct { + const char* ptr; + size_t num_left; +} ini_parse_string_ctx; + +/* Strip whitespace chars off end of given string, in place. Return s. */ +static char* ini_rstrip(char* s) +{ + char* p = s + strlen(s); + while (p > s && isspace((unsigned char)(*--p))) + *p = '\0'; + return s; +} + +/* Return pointer to first non-whitespace char in given string. */ +static char* ini_lskip(const char* s) +{ + while (*s && isspace((unsigned char)(*s))) + s++; + return (char*)s; +} + +/* Return pointer to first char (of chars) or inline comment in given string, + or pointer to NUL at end of string if neither found. Inline comment must + be prefixed by a whitespace character to register as a comment. */ +static char* ini_find_chars_or_comment(const char* s, const char* chars) +{ +#if INI_ALLOW_INLINE_COMMENTS + int was_space = 0; + while (*s && (!chars || !strchr(chars, *s)) && + !(was_space && strchr(INI_INLINE_COMMENT_PREFIXES, *s))) { + was_space = isspace((unsigned char)(*s)); + s++; + } +#else + while (*s && (!chars || !strchr(chars, *s))) { + s++; + } +#endif + return (char*)s; +} + +/* Similar to strncpy, but ensures dest (size bytes) is + NUL-terminated, and doesn't pad with NULs. */ +static char* ini_strncpy0(char* dest, const char* src, size_t size) +{ + /* Could use strncpy internally, but it causes gcc warnings (see issue #91) */ + size_t i; + for (i = 0; i < size - 1 && src[i]; i++) + dest[i] = src[i]; + dest[i] = '\0'; + return dest; +} + +/* See documentation in header file. */ +int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler, + void* user) +{ + /* Uses a fair bit of stack (use heap instead if you need to) */ +#if INI_USE_STACK + char line[INI_MAX_LINE]; + size_t max_line = INI_MAX_LINE; +#else + char* line; + size_t max_line = INI_INITIAL_ALLOC; +#endif +#if INI_ALLOW_REALLOC && !INI_USE_STACK + char* new_line; +#endif + char section[MAX_SECTION] = ""; +#if INI_ALLOW_MULTILINE + char prev_name[MAX_NAME] = ""; +#endif + + size_t offset; + char* start; + char* end; + char* name; + char* value; + int lineno = 0; + int error = 0; + char abyss[16]; /* Used to consume input when a line is too long. */ + +#if !INI_USE_STACK + line = (char*)ini_malloc(INI_INITIAL_ALLOC); + if (!line) { + return -2; + } +#endif + +#if INI_HANDLER_LINENO +#define HANDLER(u, s, n, v) handler(u, s, n, v, lineno) +#else +#define HANDLER(u, s, n, v) handler(u, s, n, v) +#endif + + /* Scan through stream line by line */ + while (reader(line, (int)max_line, stream) != NULL) { + offset = strlen(line); + +#if INI_ALLOW_REALLOC && !INI_USE_STACK + while (offset == max_line - 1 && line[offset - 1] != '\n') { + max_line *= 2; + if (max_line > INI_MAX_LINE) + max_line = INI_MAX_LINE; + new_line = ini_realloc(line, max_line); + if (!new_line) { + ini_free(line); + return -2; + } + line = new_line; + if (reader(line + offset, (int)(max_line - offset), stream) == NULL) + break; + offset += strlen(line + offset); + if (max_line >= INI_MAX_LINE) + break; + } +#endif + + lineno++; + + /* If line exceeded INI_MAX_LINE bytes, discard till end of line. */ + if (offset == max_line - 1 && line[offset - 1] != '\n') { + while (reader(abyss, sizeof(abyss), stream) != NULL) { + if (!error) + error = lineno; + if (abyss[strlen(abyss) - 1] == '\n') + break; + } + } + + start = line; +#if INI_ALLOW_BOM + if (lineno == 1 && (unsigned char)start[0] == 0xEF && + (unsigned char)start[1] == 0xBB && + (unsigned char)start[2] == 0xBF) { + start += 3; + } +#endif + start = ini_rstrip(ini_lskip(start)); + + if (strchr(INI_START_COMMENT_PREFIXES, *start)) { + /* Start-of-line comment */ + } +#if INI_ALLOW_MULTILINE + else if (*prev_name && *start && start > line) { +#if INI_ALLOW_INLINE_COMMENTS + end = ini_find_chars_or_comment(start, NULL); + if (*end) + *end = '\0'; + ini_rstrip(start); +#endif + /* Non-blank line with leading whitespace, treat as continuation + of previous name's value (as per Python configparser). */ + if (!HANDLER(user, section, prev_name, start) && !error) + error = lineno; + } +#endif + else if (*start == '[') { + /* A "[section]" line */ + end = ini_find_chars_or_comment(start + 1, "]"); + if (*end == ']') { + *end = '\0'; + ini_strncpy0(section, start + 1, sizeof(section)); +#if INI_ALLOW_MULTILINE + *prev_name = '\0'; +#endif +#if INI_CALL_HANDLER_ON_NEW_SECTION + if (!HANDLER(user, section, NULL, NULL) && !error) + error = lineno; +#endif + } + else if (!error) { + /* No ']' found on section line */ + error = lineno; + } + } + else if (*start) { + /* Not a comment, must be a name[=:]value pair */ + end = ini_find_chars_or_comment(start, "=:"); + if (*end == '=' || *end == ':') { + *end = '\0'; + name = ini_rstrip(start); + value = end + 1; +#if INI_ALLOW_INLINE_COMMENTS + end = ini_find_chars_or_comment(value, NULL); + if (*end) + *end = '\0'; +#endif + value = ini_lskip(value); + ini_rstrip(value); + +#if INI_ALLOW_MULTILINE + ini_strncpy0(prev_name, name, sizeof(prev_name)); +#endif + /* Valid name[=:]value pair found, call handler */ + if (!HANDLER(user, section, name, value) && !error) + error = lineno; + } + else if (!error) { + /* No '=' or ':' found on name[=:]value line */ +#if INI_ALLOW_NO_VALUE + *end = '\0'; + name = ini_rstrip(start); + if (!HANDLER(user, section, name, NULL) && !error) + error = lineno; +#else + error = lineno; +#endif + } + } + +#if INI_STOP_ON_FIRST_ERROR + if (error) + break; +#endif + } + +#if !INI_USE_STACK + ini_free(line); +#endif + + return error; +} + +/* See documentation in header file. */ +int ini_parse_file(FILE* file, ini_handler handler, void* user) +{ + return ini_parse_stream((ini_reader)fgets, file, handler, user); +} + +/* See documentation in header file. */ +int ini_parse(const char* filename, ini_handler handler, void* user) +{ + FILE* file; + int error; + + file = fopen(filename, "r"); + if (!file) + return -1; + error = ini_parse_file(file, handler, user); + fclose(file); + return error; +} + +/* An ini_reader function to read the next line from a string buffer. This + is the fgets() equivalent used by ini_parse_string(). */ +static char* ini_reader_string(char* str, int num, void* stream) { + ini_parse_string_ctx* ctx = (ini_parse_string_ctx*)stream; + const char* ctx_ptr = ctx->ptr; + size_t ctx_num_left = ctx->num_left; + char* strp = str; + char c; + + if (ctx_num_left == 0 || num < 2) + return NULL; + + while (num > 1 && ctx_num_left != 0) { + c = *ctx_ptr++; + ctx_num_left--; + *strp++ = c; + if (c == '\n') + break; + num--; + } + + *strp = '\0'; + ctx->ptr = ctx_ptr; + ctx->num_left = ctx_num_left; + return str; +} + +/* See documentation in header file. */ +int ini_parse_string(const char* string, ini_handler handler, void* user) { + return ini_parse_string_length(string, strlen(string), handler, user); +} + +/* See documentation in header file. */ +int ini_parse_string_length(const char* string, size_t length, + ini_handler handler, void* user) { + ini_parse_string_ctx ctx; + + ctx.ptr = string; + ctx.num_left = length; + return ini_parse_stream((ini_reader)ini_reader_string, &ctx, handler, + user); +} diff --git a/common/lib/inih/ini.h b/common/lib/inih/ini.h new file mode 100644 index 0000000..29f007c --- /dev/null +++ b/common/lib/inih/ini.h @@ -0,0 +1,189 @@ +/* inih -- simple .INI file parser + +SPDX-License-Identifier: BSD-3-Clause + +Copyright (C) 2009-2020, Ben Hoyt + +inih is released under the New BSD license (see LICENSE.txt). Go to the project +home page for more info: + +https://github.com/benhoyt/inih + +*/ + +#ifndef INI_H +#define INI_H + +/* Make this header file easier to include in C++ code */ +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/* Nonzero if ini_handler callback should accept lineno parameter. */ +#ifndef INI_HANDLER_LINENO +#define INI_HANDLER_LINENO 0 +#endif + +/* Visibility symbols, required for Windows DLLs */ +#ifndef INI_API +#if defined _WIN32 || defined __CYGWIN__ +# ifdef INI_SHARED_LIB +# ifdef INI_SHARED_LIB_BUILDING +# define INI_API __declspec(dllexport) +# else +# define INI_API __declspec(dllimport) +# endif +# else +# define INI_API +# endif +#else +# if defined(__GNUC__) && __GNUC__ >= 4 +# define INI_API __attribute__ ((visibility ("default"))) +# else +# define INI_API +# endif +#endif +#endif + +/* Typedef for prototype of handler function. + + Note that even though the value parameter has type "const char*", the user + may cast to "char*" and modify its content, as the value is not used again + after the call to ini_handler. This is not true of section and name -- + those must not be modified. +*/ +#if INI_HANDLER_LINENO +typedef int (*ini_handler)(void* user, const char* section, + const char* name, const char* value, + int lineno); +#else +typedef int (*ini_handler)(void* user, const char* section, + const char* name, const char* value); +#endif + +/* Typedef for prototype of fgets-style reader function. */ +typedef char* (*ini_reader)(char* str, int num, void* stream); + +/* Parse given INI-style file. May have [section]s, name=value pairs + (whitespace stripped), and comments starting with ';' (semicolon). Section + is "" if name=value pair parsed before any section heading. name:value + pairs are also supported as a concession to Python's configparser. + + For each name=value pair parsed, call handler function with given user + pointer as well as section, name, and value (data only valid for duration + of handler call). Handler should return nonzero on success, zero on error. + + Returns 0 on success, line number of first error on parse error (doesn't + stop on first error), -1 on file open error, or -2 on memory allocation + error (only when INI_USE_STACK is zero). +*/ +INI_API int ini_parse(const char* filename, ini_handler handler, void* user); + +/* Same as ini_parse(), but takes a FILE* instead of filename. This doesn't + close the file when it's finished -- the caller must do that. */ +INI_API int ini_parse_file(FILE* file, ini_handler handler, void* user); + +/* Same as ini_parse(), but takes an ini_reader function pointer instead of + filename. Used for implementing custom or string-based I/O (see also + ini_parse_string). */ +INI_API int ini_parse_stream(ini_reader reader, void* stream, ini_handler handler, + void* user); + +/* Same as ini_parse(), but takes a zero-terminated string with the INI data + instead of a file. Useful for parsing INI data from a network socket or + which is already in memory. */ +INI_API int ini_parse_string(const char* string, ini_handler handler, void* user); + +/* Same as ini_parse_string(), but takes a string and its length, avoiding + strlen(). Useful for parsing INI data from a network socket or which is + already in memory, or interfacing with C++ std::string_view. */ +INI_API int ini_parse_string_length(const char* string, size_t length, ini_handler handler, void* user); + +/* Nonzero to allow multi-line value parsing, in the style of Python's + configparser. If allowed, ini_parse() will call the handler with the same + name for each subsequent line parsed. */ +#ifndef INI_ALLOW_MULTILINE +#define INI_ALLOW_MULTILINE 1 +#endif + +/* Nonzero to allow a UTF-8 BOM sequence (0xEF 0xBB 0xBF) at the start of + the file. See https://github.com/benhoyt/inih/issues/21 */ +#ifndef INI_ALLOW_BOM +#define INI_ALLOW_BOM 1 +#endif + +/* Chars that begin a start-of-line comment. Per Python configparser, allow + both ; and # comments at the start of a line by default. */ +#ifndef INI_START_COMMENT_PREFIXES +#define INI_START_COMMENT_PREFIXES ";#" +#endif + +/* Nonzero to allow inline comments (with valid inline comment characters + specified by INI_INLINE_COMMENT_PREFIXES). Set to 0 to turn off and match + Python 3.2+ configparser behaviour. */ +#ifndef INI_ALLOW_INLINE_COMMENTS +#define INI_ALLOW_INLINE_COMMENTS 1 +#endif +#ifndef INI_INLINE_COMMENT_PREFIXES +#define INI_INLINE_COMMENT_PREFIXES ";" +#endif + +/* Nonzero to use stack for line buffer, zero to use heap (malloc/free). */ +#ifndef INI_USE_STACK +#define INI_USE_STACK 1 +#endif + +/* Maximum line length for any line in INI file (stack or heap). Note that + this must be 3 more than the longest line (due to '\r', '\n', and '\0'). */ +#ifndef INI_MAX_LINE +#define INI_MAX_LINE 200 +#endif + +/* Nonzero to allow heap line buffer to grow via realloc(), zero for a + fixed-size buffer of INI_MAX_LINE bytes. Only applies if INI_USE_STACK is + zero. */ +#ifndef INI_ALLOW_REALLOC +#define INI_ALLOW_REALLOC 0 +#endif + +/* Initial size in bytes for heap line buffer. Only applies if INI_USE_STACK + is zero. */ +#ifndef INI_INITIAL_ALLOC +#define INI_INITIAL_ALLOC 200 +#endif + +/* Stop parsing on first error (default is to keep parsing). */ +#ifndef INI_STOP_ON_FIRST_ERROR +#define INI_STOP_ON_FIRST_ERROR 0 +#endif + +/* Nonzero to call the handler at the start of each new section (with + name and value NULL). Default is to only call the handler on + each name=value pair. */ +#ifndef INI_CALL_HANDLER_ON_NEW_SECTION +#define INI_CALL_HANDLER_ON_NEW_SECTION 0 +#endif + +/* Nonzero to allow a name without a value (no '=' or ':' on the line) and + call the handler with value NULL in this case. Default is to treat + no-value lines as an error. */ +#ifndef INI_ALLOW_NO_VALUE +#define INI_ALLOW_NO_VALUE 0 +#endif + +/* Nonzero to use custom ini_malloc, ini_free, and ini_realloc memory + allocation functions (INI_USE_STACK must also be 0). These functions must + have the same signatures as malloc/free/realloc and behave in a similar + way. ini_realloc is only needed if INI_ALLOW_REALLOC is set. */ +#ifndef INI_CUSTOM_ALLOCATOR +#define INI_CUSTOM_ALLOCATOR 0 +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* INI_H */ diff --git a/common/src/Async/Async.cpp b/common/src/Async/Async.cpp index e533ac0..6eb1882 100644 --- a/common/src/Async/Async.cpp +++ b/common/src/Async/Async.cpp @@ -2,19 +2,19 @@ std::mutex Async::mtxPrint; -void Async::PrintLn(std::string str) // STATIC +void Async::PrintLn(const std::string &str) // STATIC { std::lock_guard lock(mtxPrint); std::cout << str << "\n"; } -void Async::Print(std::string str) // STATIC +void Async::Print(const std::string &str) // STATIC { std::lock_guard lock(mtxPrint); std::cout << str << "\n"; } -void Async::Cerr(std::string str) // STATIC +void Async::Cerr(const std::string &str) // STATIC { std::lock_guard lock(mtxPrint); std::cerr << str << "\n"; diff --git a/common/src/Async/Async.h b/common/src/Async/Async.h index 8b9dc93..dc95fc6 100644 --- a/common/src/Async/Async.h +++ b/common/src/Async/Async.h @@ -6,9 +6,9 @@ class Async { public: - static void PrintLn(std::string str); - static void Print(std::string str); - static void Cerr(std::string str) ; + static void PrintLn(const std::string &str); + static void Print(const std::string &str); + static void Cerr(const std::string &str) ; private: static std::mutex mtxPrint; diff --git a/common/src/IniManager.cpp b/common/src/IniManager.cpp new file mode 100644 index 0000000..fdda510 --- /dev/null +++ b/common/src/IniManager.cpp @@ -0,0 +1,44 @@ +#include "IniManager.h" +#include +#include + +std::string IniManager::GetItem(const char * file, std::string item) // STATIC +{ + std::map config; + if (ini_parse(file, handler, &config) < 0) { + std::cerr << "Can not load config.ini\n"; + return "ERROR"; + } + + return config[item]; +} + +int IniManager::handler(void *user, const char *section, const char *name, const char *value) // STATIC +{ + std::map *config = reinterpret_cast *>(user); + std::string key = std::string(section) + "." + name; + (*config)[key] = value; + return 1; +} + +bool IniManager::CreateConfigIfMissing(const std::string& path) // STATIC +{ + writeConfig(path); + + if (std::filesystem::exists(path)) + return true; + + return false; +} + +void IniManager::writeConfig(const std::string& path) // STATIC +{ + if (std::filesystem::exists(path)) + return; + + std::ofstream out(path); + out << "[General]\n"; + out << "username = Player1\n"; + out << "server_ip = 127.0.0.1\n"; + out << "server_port = 12345\n"; +} \ No newline at end of file diff --git a/common/src/IniManager.h b/common/src/IniManager.h new file mode 100644 index 0000000..936b6be --- /dev/null +++ b/common/src/IniManager.h @@ -0,0 +1,67 @@ +#pragma once + +#include +#include + +#include "../lib/inih/ini.h" + +/** + * @class IniManager + * @brief Manages reading and writing of configuration files in INI format. + * + * This class uses the INIH library to parse INI files and provides utility functions + * to read specific configuration values or create a default configuration if one doesn't exist. + */ +class IniManager { + public: + /** + * @brief Default filename for the client configuration file. + */ + static constexpr char * CLIENT_CONFIG_FILE = "gpr_config.ini"; + + /** + * @brief Retrieves a specific configuration item from an INI file. + * + * @param file Path to the INI file. + * @param item Key in the format "Section.Key" (e.g., "General.username"). + * @return The corresponding value as a string, or an empty string if not found. + */ + static std::string GetItem(const char * file, std::string item); + + /** + * @brief Creates a default Config if it is missing. + * @return Returns a false if Config could not be created. + */ + static bool CreateConfigIfMissing(const std::string& path); + + /** + * @class Item + * @brief Contains predefined keys for accessing configuration values. + */ + class Item + { + public: + static constexpr char * GENERAL_USERNAME = "General.username"; + static constexpr char * GENERAL_SERVER_IP = "General.server_ip"; + static constexpr char * GENERAL_SERVER_PORT = "General.server_port"; + }; + + private: + /** + * @brief Internal handler used as a callback for the INIH parser. + * + * @param user Pointer to user-defined data (e.g., a std::map). + * @param section Section name from the INI file (e.g., "General"). + * @param name Key name within the section. + * @param value Corresponding value. + * @return 1 on success, 0 on failure. + */ + static int handler(void* user, const char* section, const char* name, const char* value); + + /** + * @brief Writes a default configuration to the specified file if it does not already exist. + * + * @param path Path to the configuration file. + */ + static void writeConfig(const std::string& path); +}; \ No newline at end of file diff --git a/common/src/Network/PackagingSystem.cpp b/common/src/Network/PackagingSystem.cpp index 1a958a3..5012225 100644 --- a/common/src/Network/PackagingSystem.cpp +++ b/common/src/Network/PackagingSystem.cpp @@ -144,7 +144,7 @@ void PackagingSystem::addItemAtBeginning(std::string item) { } PackagingSystem::~PackagingSystem() { - delete[] mPacketBufferPtr; + } template int PackagingSystem::ReadItem(std::string&); diff --git a/common/src/Network/PackagingSystem.h b/common/src/Network/PackagingSystem.h index ecb64a1..6279f18 100644 --- a/common/src/Network/PackagingSystem.h +++ b/common/src/Network/PackagingSystem.h @@ -72,7 +72,6 @@ class PackagingSystem private: std::string mPacket; ///< The internal string storing the packet data. - char *mPacketBufferPtr = nullptr; int mPacketId = 0; /** diff --git a/common/src/Network/Packets.h b/common/src/Network/Packets.h index 2f16cae..7032c63 100644 --- a/common/src/Network/Packets.h +++ b/common/src/Network/Packets.h @@ -3,13 +3,12 @@ namespace Packets { enum ServerPacket { serverHandshakeAccept = 100, + serverNewClientConnected, serverRequestHeartbeat, serverDistributePosition, serverDistributeAnimations, serverRemoveClient - - //serverSendHeartbeatRequest = 200 - + }; enum ClientPacket { @@ -17,11 +16,6 @@ namespace Packets { clientResponseHeartbeat, clientSharePosition, clientShareAnimations - //clientSendHeartbeat = 200 + }; -} - - -/*namespace ServerPacket { - -}*/ \ No newline at end of file +} \ No newline at end of file diff --git a/server/src/CommonStructures.h b/server/src/CommonStructures.h index 68ba27d..6b83fb5 100644 --- a/server/src/CommonStructures.h +++ b/server/src/CommonStructures.h @@ -4,11 +4,9 @@ using boost::asio::ip::udp; namespace CommonStructures { - struct ClientInfo { udp::endpoint endpoint; - //std::time_t lastResponse; std::chrono::steady_clock::time_point lastResponse; + std::string username; }; - } \ No newline at end of file diff --git a/server/src/MessageHandler.cpp b/server/src/MessageHandler.cpp index e0d1d8e..d2be1ab 100644 --- a/server/src/MessageHandler.cpp +++ b/server/src/MessageHandler.cpp @@ -8,17 +8,29 @@ MessageHandler::MessageHandler(AsyncUnorderedMap(id); Async::PrintLn( "ID: " + std::to_string(id) ); Async::PrintLn( "Message: " + buffer ); + // Add new Player + if(!isClientRegistered(clientEndpoint)){ + if(packetId != Packets::ClientPacket::clientHandshakeRequest) + return; + + clientHandshakeRequest(clientEndpoint, buffer); + updateLastResponse(clientEndpoint); + return; + } + + + updateLastResponse(clientEndpoint); switch (packetId) { + /*case Packets::ClientPacket::clientHandshakeRequest: + clientHandshakeRequest(clientEndpoint, buffer); + break;*/ case Packets::ClientPacket::clientResponseHeartbeat: clientRepondsHeartbeat(clientEndpoint, buffer); break; @@ -34,6 +46,45 @@ void MessageHandler::handleBuffer(udp::endpoint &clientEndpoint, std::string buf } } +bool MessageHandler::isClientRegistered(udp::endpoint &clientEndpoint){ + std::string clientPortIp = getClientUniqueString(clientEndpoint); + auto it = clients->find(clientPortIp); + if (it) + return true; + return false; +} + +void MessageHandler::clientHandshakeRequest(udp::endpoint &clientEndpoint, std::string &buffer) +{ + std::string username = PackagingSystem::ReadItem(buffer); + if(!addNewClient(clientEndpoint, username)) { + return; + } + + std::string clientPortIp = getClientUniqueString(clientEndpoint); + Async::PrintLn( clientPortIp + ", " +username+" Handshake Success"); + + PackagingSystem handshakePacket(Packets::ServerPacket::serverHandshakeAccept); + handshakePacket.addString("success"); + + std::string serializedPacket = handshakePacket.serializePacket(); + sendMessage(clientEndpoint, serializedPacket); + + // TODO: Continue Here to share the Name of the new Client to the other clients!! + PackagingSystem helloInfo(Packets::ServerPacket::serverNewClientConnected); + + helloInfo.addString(clientPortIp); + helloInfo.addString(username); + helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); + helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); + helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); + helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); + helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); + helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); + + sendToAllExceptSender(clientEndpoint, helloInfo.serializePacket()); +} + void MessageHandler::clientRepondsHeartbeat(udp::endpoint &clientEndpoint, std::string &buffer) { std::string clientPortIp = getClientUniqueString(clientEndpoint); @@ -121,24 +172,28 @@ void MessageHandler::removeClient(udp::endpoint &clientEndpoint) updateConsoleTitle(); } -void MessageHandler::addNewClient(udp::endpoint &clientEndpoint) +bool MessageHandler::addNewClient(udp::endpoint &clientEndpoint, std::string &username) { std::string clientPortIp = getClientUniqueString(clientEndpoint); + if(clients->existsItem(clientPortIp)) + return false; + CommonStructures::ClientInfo clientInfo; clientInfo.endpoint = clientEndpoint; clientInfo.lastResponse = std::chrono::high_resolution_clock::now(); + clientInfo.username = username; /*auto [it, inserted] = clients->try_emplace(clientPortIp, clientInfo); if (inserted) Async::PrintLn( "Added new Client: " + clientPortIp );*/ - if(clients->existsItem(clientPortIp)) - return; + clients->append(clientPortIp, clientInfo); Async::PrintLn( "Added new Client: " + clientPortIp ); updateConsoleTitle(); + return true; } void MessageHandler::updateLastResponse(udp::endpoint &clientEndpoint) diff --git a/server/src/MessageHandler.h b/server/src/MessageHandler.h index 8eef14a..2091e1c 100644 --- a/server/src/MessageHandler.h +++ b/server/src/MessageHandler.h @@ -30,14 +30,15 @@ class MessageHandler AsyncUnorderedMap *clients; udp::socket * pSocket; + void clientHandshakeRequest(udp::endpoint &clientEndpoint, std::string &buffer); void clientRepondsHeartbeat(udp::endpoint &clientEndpoint, std::string &buffer); void clientSharesPosition(udp::endpoint &clientEndpoint, std::string &buffer); void clientSharesAnimations(udp::endpoint &clientEndpoint, std::string &buffer); + bool isClientRegistered(udp::endpoint &clientEndpoint); - - void addNewClient(udp::endpoint &clientEndpoint); + bool addNewClient(udp::endpoint &clientEndpoint, std::string &username); void updateLastResponse(udp::endpoint &clientEndpoint); std::string getClientUniqueString(udp::endpoint &clientEndpoint); diff --git a/src/Logic/GameThreadWorker.cpp b/src/Logic/GameThreadWorker.cpp index 48a2429..4028d27 100644 --- a/src/Logic/GameThreadWorker.cpp +++ b/src/Logic/GameThreadWorker.cpp @@ -1,4 +1,5 @@ #include "GameThreadWorker.h" +#include GameThreadWorker::GameThreadWorker() { @@ -38,10 +39,10 @@ void GameThreadWorker::processMessages() removeTask(); } } -//Npc *npc; -//int *ii = new int; + +Npc *npc; void GameThreadWorker::checkGameState(){ - // Checks if player is in range of an other player to render him + /* ## Checks if player is in range of an other player to render him ## */ std::unordered_map copyOfClients = *clients->getUnorderedMap(); for (const auto& pair : copyOfClients) { @@ -55,9 +56,15 @@ void GameThreadWorker::checkGameState(){ /* ################ Custom Shit Here################# */ if (GetAsyncKeyState(VK_RSHIFT) < 0) { - std::cout << "# PRINTING " << "\n"; - zSTRING * str = new zSTRING(""); - str = pMainPlayer->oCNpc->getName(0); - std::cout << "NAME: " << str->getStr() << "\n"; + if(npc == nullptr) { + npc = new Npc(); + npc->setCurrentHealth(10); + npc->setMaxHealth(10); + npc->oCNpc->setVisualWithString("HUMANS.MDS"); + npc->oCNpc->setAdditionalVisuals("hum_body_Naked0", 9, 0, "Hum_Head_Pony", 2, 0, -1); + + npc->oCNpc->enableWithdCoords(pMainPlayer->getX(), pMainPlayer->getZ(), pMainPlayer->getY()); + + } } } \ No newline at end of file diff --git a/src/Logic/ImGuiManager.cpp b/src/Logic/ImGuiManager.cpp index 6a4e15e..78967c1 100644 --- a/src/Logic/ImGuiManager.cpp +++ b/src/Logic/ImGuiManager.cpp @@ -42,7 +42,7 @@ void ImGuiManager::showContent(ImGuiData imGuiData) std::string posZ = std::to_string(valueNpc->getZ()); std::string posY = std::to_string(valueNpc->getY()); - ImGui::Text(valueKey.c_str()); + ImGui::Text(valueNpc->getName().c_str()); ImGui::Text(("\t" + posX).c_str()); ImGui::Text(("\t" + posZ).c_str()); ImGui::Text(("\t" + posY).c_str()); diff --git a/src/Models/Npc.cpp b/src/Models/Npc.cpp index fb3302e..d11be8c 100644 --- a/src/Models/Npc.cpp +++ b/src/Models/Npc.cpp @@ -42,6 +42,17 @@ void Npc::setPlayerPosition(float x, float y, float z) setZ(z); } +void Npc::setName(std::string name) +{ + basic_string * n = (basic_string*)((char*)this->oCNpc + 0x108);//(basic_string*)((char*)this->oCNpc + 0x108); + *n = name.c_str(); +} +std::string Npc::getName() +{ + basic_string * n = (basic_string*)((char*)this->oCNpc + 0x108); + return n->c_str(); +} + void Npc::tpToOldCamp() { // this->setPlayerPosition(-8334.085f, 11636.9f, -1185.910f); diff --git a/src/Models/Npc.h b/src/Models/Npc.h index 77d9ac4..15950ce 100644 --- a/src/Models/Npc.h +++ b/src/Models/Npc.h @@ -19,6 +19,9 @@ class Npc OCNpc *oCNpc; + void setName(std::string name); + std::string getName(); + void healPlayerBy(int HP); void tpToOldCamp(); void superJump(); diff --git a/src/Network/Client.cpp b/src/Network/Client.cpp index 9699831..8d8f268 100644 --- a/src/Network/Client.cpp +++ b/src/Network/Client.cpp @@ -1,7 +1,7 @@ #include "Client.h" -Client::Client(boost::asio::io_context &io_context, const std::string &host, const std::string &port, GameThreadWorker *gameThreadWorker) - : socket_(io_context), resolver_(io_context), server_endpoint_(*resolver_.resolve(udp::v4(), host, port).begin()) +Client::Client(boost::asio::io_context &io_context, const std::string &username, const std::string &host, const std::string &port, GameThreadWorker *gameThreadWorker) + : socket_(io_context), resolver_(io_context), username(username), server_endpoint_(*resolver_.resolve(udp::v4(), host, port).begin()) { this->gameThreadWorker = gameThreadWorker; @@ -69,6 +69,31 @@ void Client::start_receive() }); } +void Client::setConnected() { + this->connected = true; +} + +const bool Client::isConnected() const { + return connected; +} + +void Client::sendHandshakeRequest() { + PackagingSystem packetHandshake(Packets::ClientPacket::clientHandshakeRequest); + packetHandshake.addString(this->username); + + DataStructures::LastPosition lasPos = mainPlayer->getLastPosition(); + packetHandshake.addFloatPointNumber(lasPos.x + 90, 2); + packetHandshake.addFloatPointNumber(lasPos.z, 2); + packetHandshake.addFloatPointNumber(lasPos.y + 90, 2); + + packetHandshake.addFloatPointNumber(lasPos.yaw, 2); + packetHandshake.addFloatPointNumber(lasPos.pitch, 2); + packetHandshake.addFloatPointNumber(lasPos.roll, 2); + + std::string bufferStr = packetHandshake.serializePacket(); + this->send_message(bufferStr); +} + void Client::sendPlayerPosition() { DataStructures::LastPosition lasPos = mainPlayer->getLastPosition(); diff --git a/src/Network/Client.h b/src/Network/Client.h index 9ced23f..1b5255a 100644 --- a/src/Network/Client.h +++ b/src/Network/Client.h @@ -31,21 +31,26 @@ class Client * @param port The server port number. * @param gameThreadWorker Pointer to the game thread worker for processing game-related tasks. */ - Client(boost::asio::io_context &io_context, const std::string &host, const std::string &port, GameThreadWorker *gameThreadWorker); + Client(boost::asio::io_context &io_context, const std::string &username, const std::string &host, const std::string &port, GameThreadWorker *gameThreadWorker); ~Client(); void send_message(const std::string &message); + + void sendHandshakeRequest(); void sendPlayerPosition(); void sendPlayerAnimation(); void sendPlayerRotation(); Npc *getMainPlayer(); + void setConnected(); + const bool isConnected() const; + private: GameThreadWorker *gameThreadWorker; Npc *mainPlayer = new Npc(ADDR_PLAYERBASE); - + std::string username; udp::socket socket_; udp::resolver resolver_; udp::endpoint server_endpoint_; diff --git a/src/Network/MessageHandler.cpp b/src/Network/MessageHandler.cpp index 2215a41..a6b64cf 100644 --- a/src/Network/MessageHandler.cpp +++ b/src/Network/MessageHandler.cpp @@ -17,6 +17,9 @@ void MessageHandler::managePacket(std::string stringPacket) case Packets::ServerPacket::serverHandshakeAccept: handleServerHandshakeAccept(stringPacket); break; + case Packets::ServerPacket::serverNewClientConnected: + handleServerNewClientConnected(stringPacket); + break; case Packets::ServerPacket::serverRequestHeartbeat: handleServerRequestsHeartbeat(stringPacket); break; @@ -33,12 +36,59 @@ void MessageHandler::managePacket(std::string stringPacket) handleServerDistributeRotations(stringPacket); break;*/ default: - std::cout << "\n\tWeird... Unknown Packet....\n"; + Async::PrintLn("\n\tWeird... Unknown Packet....\n"); } } void MessageHandler::handleServerHandshakeAccept(std::string &buffer) { + std::string handshakeAnswer = PackagingSystem::ReadItem(buffer); + + if (handshakeAnswer != "success") + { + return; + } + Async::PrintLn("HANDSHAKE SUCCESS!!"); + this->pClient->setConnected(); +} + +void MessageHandler::handleServerNewClientConnected(std::string &buffer) +{ + std::string receivedKey = PackagingSystem::ReadItem(buffer); + std::string name = PackagingSystem::ReadItem(buffer); + float x = PackagingSystem::ReadItem(buffer); + float z = PackagingSystem::ReadItem(buffer); + float y = PackagingSystem::ReadItem(buffer); + + float yaw = PackagingSystem::ReadItem(buffer); + float pitch = PackagingSystem::ReadItem(buffer); + float roll = PackagingSystem::ReadItem(buffer); + + // Creating a new Npc + Npc *value = new Npc(); + value->setCurrentHealth(10); + value->setMaxHealth(10); + value->oCNpc->setVisualWithString("HUMANS.MDS"); + value->oCNpc->setAdditionalVisuals("hum_body_Naked0", 9, 0, "Hum_Head_Pony", 2, 0, -1); + + + value->setName(name); + + + zMAT4 matrix; + value->oCNpc->getTrafoModelNodeToWorld(&matrix, 0); + + matrix.MakeRotationY(yaw); + value->oCNpc->setTrafo(&matrix); + + value->setX(x); + value->setZ(z); + value->setY(y); + + value->oCNpc->enableWithdCoords(x, z, y); + + // New Client inserted + pClients->append(receivedKey, value); } void MessageHandler::handleServerRequestsHeartbeat(std::string &buffer) @@ -60,32 +110,21 @@ void MessageHandler::handleServerDistributePosition(std::string &buffer) float pitch = PackagingSystem::ReadItem(buffer); float roll = PackagingSystem::ReadItem(buffer); - auto it = pClients->find(receivedKey); - if(it) { - Npc *value = it.value(); - zMAT4 matrix; - value->oCNpc->getTrafoModelNodeToWorld(&matrix, 0); - - matrix.MakeRotationY(yaw); - value->oCNpc->setTrafo(&matrix); - - value->setX(x); - value->setZ(z); - value->setY(y); + auto it = pClients->find(receivedKey); + if (!it) return; - } - // Creating a new Npc - Npc *value = new Npc(); - value->setCurrentHealth(10); - value->setMaxHealth(10); - value->oCNpc->setVisualWithString("HUMANS.MDS"); - value->oCNpc->setAdditionalVisuals("hum_body_Naked0", 9, 0, "Hum_Head_Pony", 2, 0, -1); - value->oCNpc->enableWithdCoords(x, z, y); + Npc *value = it.value(); + zMAT4 matrix; + value->oCNpc->getTrafoModelNodeToWorld(&matrix, 0); - // New Client inserted - pClients->append(receivedKey, value); + matrix.MakeRotationY(yaw); + value->oCNpc->setTrafo(&matrix); + + value->setX(x); + value->setZ(z); + value->setY(y); } void MessageHandler::handleServerDistributeAnimations(std::string &buffer) @@ -93,7 +132,8 @@ void MessageHandler::handleServerDistributeAnimations(std::string &buffer) std::string receivedKey = PackagingSystem::ReadItem(buffer); auto it = pClients->find(receivedKey); - if(!it) { + if (!it) + { return; } @@ -109,7 +149,8 @@ void MessageHandler::handleServerDistributeAnimations(std::string &buffer) npcNewAnim.animationIds.push_back(PackagingSystem::ReadItem(buffer)); } - for (auto &newId : npcNewAnim.animationIds) { + for (auto &newId : npcNewAnim.animationIds) + { npcModel->startAniInt(newId, 0); } @@ -118,11 +159,13 @@ void MessageHandler::handleServerDistributeAnimations(std::string &buffer) bool found = false; for (auto &newId : npcNewAnim.animationIds) { - if(lastId == newId) { + if (lastId == newId) + { found = true; } } - if(!found) { + if (!found) + { void *aniActive = npcModel->getActiveAni(lastId); if (aniActive) npcModel->stopAnimationInt(lastId); @@ -130,17 +173,17 @@ void MessageHandler::handleServerDistributeAnimations(std::string &buffer) } } - void MessageHandler::handleServerRemoveClient(std::string &buffer) { std::string receivedKey = PackagingSystem::ReadItem(buffer); // data.names.at(0); - auto it = pClients->find(receivedKey); - if(it) { - OCWorld::RemoveVob(it.value()); - pClients->remove(receivedKey); - std::cout << "Removed VOB\n"; - } + auto it = pClients->find(receivedKey); + if (!it) + return; + + OCWorld::RemoveVob(it.value()); + pClients->remove(receivedKey); + Async::PrintLn("Removed VOB\n"); } void MessageHandler::handleServerDistributeRotations(std::string &buffer) diff --git a/src/Network/MessageHandler.h b/src/Network/MessageHandler.h index b728c72..f723706 100644 --- a/src/Network/MessageHandler.h +++ b/src/Network/MessageHandler.h @@ -4,12 +4,13 @@ #include #include -#include "../Network/Client.h" #include "../Models/Npc.h" #include "../Wrapper/zCModel.h" +#include "../Network/Client.h" #include "../common/src/Network/Packets.h" #include "../common/src/Network/PackagingSystem.h" #include "../common/src/Async/AsyncUnorderedMap.h" +#include "../common/src/Async/Async.h" class Client; /** @@ -43,8 +44,11 @@ class MessageHandler private: AsyncUnorderedMap *pClients; ///< Pointer to the map storing NPCs currently in the game. Client *pClient; ///< Pointer to the Client instance for sending and receiving messages. + + //bool isClientRegistered(udp::endpoint &clientEndpoint); void handleServerHandshakeAccept(std::string &buffer); + void handleServerNewClientConnected(std::string &buffer); void handleServerRequestsHeartbeat(std::string &buffer); void handleServerDistributePosition(std::string &buffer); void handleServerDistributeAnimations(std::string &buffer); diff --git a/src/Wrapper/OCNpc.cpp b/src/Wrapper/OCNpc.cpp index e00ffbe..36bd368 100644 --- a/src/Wrapper/OCNpc.cpp +++ b/src/Wrapper/OCNpc.cpp @@ -29,7 +29,7 @@ void OCNpc::setVisualWithString(char *visual) using _SetVisualWithString = void(__thiscall *)(void *pThis, zSTRING *visual); _SetVisualWithString setVisualWithStringRef = reinterpret_cast<_SetVisualWithString>(0x5d6fa0); - zSTRING *visualString = new zSTRING(visual); + zSTRING *visualString = zSTRING::CreateNewzSTRING(visual); //new zSTRING(visual); setVisualWithStringRef(this, visualString); } @@ -38,8 +38,8 @@ void OCNpc::setAdditionalVisuals(char *textureBody, int param2, int param3, char using _SetAdditionalVisuals = void(__thiscall *)(void *pThis, zSTRING *textureBody, int param2, int param3, zSTRING *textureHead, int param5, int param6, int param7); _SetAdditionalVisuals setAdditionalVisualsRef = reinterpret_cast<_SetAdditionalVisuals>(0x694ef0); - zSTRING *body = new zSTRING(textureBody); // "Sca_Body", hum_body_Naked0 - zSTRING *head = new zSTRING(textureHead); // "", Hum_Head_Pony + zSTRING *body = zSTRING::CreateNewzSTRING(textureBody); //new zSTRING(textureBody); // "Sca_Body", hum_body_Naked0 + zSTRING *head = zSTRING::CreateNewzSTRING(textureHead); //new zSTRING(textureHead); // "", Hum_Head_Pony setAdditionalVisualsRef(this, body, param2, param3, head, param5, param6, param7); } @@ -49,7 +49,7 @@ void OCNpc::setVobName(char *vobName) using _SetVobName = void(__thiscall *)(void *pThis, zSTRING *vobName); _SetVobName setVobNameRef = reinterpret_cast<_SetVobName>(0x5d4970); - zSTRING *name = new zSTRING(vobName); + zSTRING *name = zSTRING::CreateNewzSTRING(vobName);// new zSTRING(vobName); setVobNameRef(this, name); } @@ -58,7 +58,7 @@ void OCNpc::setByScriptInstance(char *nameS, int param2) using _SetByScriptInstance = int(__thiscall *)(void *pThis, zSTRING *visual, int param2); _SetByScriptInstance setByScriptInstanceRef = reinterpret_cast<_SetByScriptInstance>(0x6a1bf0); - zSTRING *name = new zSTRING(nameS); + zSTRING *name = zSTRING::CreateNewzSTRING(nameS);//new zSTRING(nameS); setByScriptInstanceRef(this, name, param2); } @@ -171,12 +171,15 @@ void OCNpc::addVobToWorld_CorrectParentDependencies(){ addVobToWorld_CorrectParentDependenciesRef(this); } -zSTRING *OCNpc::getName(int value){ - using _GetName = zSTRING *(__thiscall *)(void *pThis, int value); - _GetName getNameRef = reinterpret_cast<_GetName>(0x68d0b0); - return getNameRef(this, value); +/*zSTRING *OCNpc::getName(zSTRING * name){ + zSTRING * nS = zSTRING::CreateNewzSTRING(""); + using _GetName = zSTRING* (__thiscall *)(void* pThis, zSTRING* name); + _GetName getNameRef = reinterpret_cast<_GetName>(0x68D0B0); + return getNameRef(this, nS); -} + //zSTRING* namePtr = (zSTRING*)((char*)this + 0x108); + //return namePtr; +}*/ /*int OCNpc::applyOverlay(char *animName) { zSTRING *name = new zSTRING(animName); diff --git a/src/Wrapper/OCNpc.h b/src/Wrapper/OCNpc.h index e829ddb..a9663eb 100644 --- a/src/Wrapper/OCNpc.h +++ b/src/Wrapper/OCNpc.h @@ -34,28 +34,40 @@ class OCNpc class Offset { public: - static constexpr uintptr_t POS_X = 0x48; // float - static constexpr uintptr_t POS_Z = 0x58; // float - static constexpr uintptr_t POS_Y = 0x68; // float - - static constexpr uintptr_t CURRENT_HEALTH = 0x184; // int - static constexpr uintptr_t MAX_HEALTH = 0x188; // int - - static constexpr uintptr_t MAX_MANA = 0x190; // int - static constexpr uintptr_t CURRENT_MANA = 0x18C; // int - - static constexpr uintptr_t STRENGTH = 0x194; // int - static constexpr uintptr_t EXPERTISE = 0x198; // int - - static constexpr uintptr_t LEVEL = 0x1EC; // int - static constexpr uintptr_t EXPERIENCE_NEXT_LEVEL = 0x31C; // int - static constexpr uintptr_t CURRENT_EXPERIENCE = 0x320; // int + // float + static constexpr uintptr_t POS_X = 0x48; + // float + static constexpr uintptr_t POS_Z = 0x58; + // float + static constexpr uintptr_t POS_Y = 0x68; + + // int + static constexpr uintptr_t CURRENT_HEALTH = 0x184; + // int + static constexpr uintptr_t MAX_HEALTH = 0x188; + + // int + static constexpr uintptr_t MAX_MANA = 0x190; + // int + static constexpr uintptr_t CURRENT_MANA = 0x18C; + + // int + static constexpr uintptr_t STRENGTH = 0x194; + // int + static constexpr uintptr_t EXPERTISE = 0x198; + + // int + static constexpr uintptr_t LEVEL = 0x1EC; + // int + static constexpr uintptr_t EXPERIENCE_NEXT_LEVEL = 0x31C; + // int + static constexpr uintptr_t CURRENT_EXPERIENCE = 0x320; }; + /** * @brief Creates a new NPC instance. * @return Pointer to the newly created NPC. */ - static OCNpc *CreateNewNpc(); /** * @brief Creates an NPC instance from an existing memory address. @@ -113,7 +125,9 @@ class OCNpc void addVobToWorld_CorrectParentDependencies(); - zSTRING *getName(int value); + + //zSTRING *getName(zSTRING * name); + /*int applyOverlay(char * animName); void setBodyState(int param1); diff --git a/src/Wrapper/basic_string.cpp b/src/Wrapper/basic_string.cpp new file mode 100644 index 0000000..04902c5 --- /dev/null +++ b/src/Wrapper/basic_string.cpp @@ -0,0 +1 @@ +#include "basic_string.h" \ No newline at end of file diff --git a/src/Wrapper/basic_string.h b/src/Wrapper/basic_string.h new file mode 100644 index 0000000..7524b3a --- /dev/null +++ b/src/Wrapper/basic_string.h @@ -0,0 +1,143 @@ +#pragma once +#include +#include +#include +#include + +class basic_string { +public: + void* unusedAllocator; + char* data; + uint32_t length; + uint32_t capacity; + + basic_string() { + initEmpty(); + } + + basic_string(const char* str) { + assign(str); + } + + basic_string(const basic_string& other) { + copyFrom(other); + } + + ~basic_string() { + tidy(); + } + + basic_string& operator=(const basic_string& other) { + if (this != &other) + copyFrom(other); + return *this; + } + + basic_string& operator=(const char* str) { + assign(str); + return *this; + } + + const char* c_str() const { + return data ? data : ""; + } + + size_t size() const { + return length; + } + + void verifyInternal(const basic_string& str) const { + printf("Data: %p\n", str.data); + printf("Length: %u\n", str.length); + printf("Capacity: %u\n", str.capacity); + if (str.data) { + printf("Data[-1]: 0x%02X\n", (unsigned char)str.data[-1]); + printf("String: \"%s\"\n", str.data); + } + } + +private: + void initEmpty() { + char* raw = new char[2]; + raw[0] = (char)0xFE; + raw[1] = '\0'; + + data = raw + 1; + length = 0; + capacity = 0; + } + + void assign(const char* str) { + tidy(); + + if (!str || str[0] == '\0') { + initEmpty(); + return; + } + + length = static_cast(std::strlen(str)); + capacity = length; + + data = allocate(capacity); + std::memcpy(data, str, length + 1); + } + + void copyFrom(const basic_string& other) { + tidy(); + + if (other.data && getRefCount(other.data) < 0xFE) { + data = other.data; + length = other.length; + capacity = other.capacity; + incrementRefCount(data); + } else if (other.length > 0) { + length = other.length; + capacity = other.capacity; + data = allocate(capacity); + std::memcpy(data, other.data, length + 1); + } else { + initEmpty(); + } + } + + void tidy() { + if (data) { + if (getRefCount(data) < 0xFE) { + decrementRefCount(data); + } else { + delete[] (data - 1); + } + } + data = nullptr; + length = 0; + capacity = 0; + } + + char* allocate(size_t size) { + char* raw = new char[size + 2]; + raw[0] = (char)0xFE; + raw[size + 1] = '\0'; + return raw + 1; + } + + uint8_t getRefCount(const char* str) const { + assert(str); + return *(reinterpret_cast(str) - 1); + } + + void setRefCount(char* str, uint8_t count) { + *(reinterpret_cast(str) - 1) = count; + } + + void incrementRefCount(char* str) { + uint8_t& ref = *(reinterpret_cast(str) - 1); + if (ref < 0xFE) ref++; + } + + void decrementRefCount(char* str) { + uint8_t& ref = *(reinterpret_cast(str) - 1); + if (--ref == 0) { + delete[] (str - 1); + } + } +}; \ No newline at end of file diff --git a/src/Wrapper/zCModel.cpp b/src/Wrapper/zCModel.cpp index 4d4a2e9..fdb2052 100644 --- a/src/Wrapper/zCModel.cpp +++ b/src/Wrapper/zCModel.cpp @@ -24,17 +24,17 @@ void *zCModel::getAddress() const } void zCModel::startAnimation(char * animName){ - zSTRING * animNameZStr = new zSTRING(animName); + zSTRING * animNameZStr = zSTRING::CreateNewzSTRING(animName); //new zSTRING(animName); startAnimationRef(pThis, animNameZStr); } int zCModel::isAnimationActive(char * animName){ - zSTRING * animNameZStr = new zSTRING(animName); + zSTRING * animNameZStr = zSTRING::CreateNewzSTRING(animName); //new zSTRING(animName); return isAnimationActiveRef(pThis, animNameZStr); } void zCModel::stopAnimation(char * animName){ - zSTRING * animNameZStr = new zSTRING(animName); + zSTRING * animNameZStr = zSTRING::CreateNewzSTRING(animName); //new zSTRING(animName); stopAnimationRef(pThis, animNameZStr); } @@ -53,7 +53,7 @@ void * zCModel::getAniFromAniID(int id){ } int zCModel::SearchAniIndex(char * aniName){ - zSTRING * aniNameZ = new zSTRING(aniName); + zSTRING * aniNameZ = zSTRING::CreateNewzSTRING(aniName); //new zSTRING(aniName); return searchAniINdexRef(aniNameZ); } @@ -65,5 +65,5 @@ void zCModel::showAniList(int param){ showAniListRef(pThis, param); } std::string zCModel::getAnyAnimation(){ - return getAnyAnimationRef(pThis)->getStr(); + return getAnyAnimationRef(pThis)->stdString(); } \ No newline at end of file diff --git a/src/Wrapper/zSTRING.cpp b/src/Wrapper/zSTRING.cpp index 158a8e8..61af1a3 100644 --- a/src/Wrapper/zSTRING.cpp +++ b/src/Wrapper/zSTRING.cpp @@ -1,30 +1,20 @@ #include "zSTRING.h" -typedef void(__thiscall *_zSTRINGCtor)(void *pThis, char *str); -_zSTRINGCtor zSTRINGCTor; - -zSTRING::zSTRING() : data(nullptr), length(0), capacity(0) { - -} -zSTRING::zSTRING(char * str) : data(nullptr), length(0), capacity(0) { - zSTRINGCTor = (_zSTRINGCtor)(0x4013a0); - zSTRINGCTor(this, str); -} +zSTRING* zSTRING::CreateNewzSTRING(char * str){ // STATIC + void* raw = ::operator new(sizeof(zSTRING)); + using _CTor = zSTRING*(__thiscall *)(void *pThis, char * text); + _CTor ctor = reinterpret_cast<_CTor>(0x004013A0); + ctor(raw, str); -// Wrapper für den ursprünglichen Konstruktor -void zSTRING::initialize(char *str) -{ - zSTRINGCTor = (_zSTRINGCtor)(0x4013a0); - zSTRINGCTor(this, str); + //return u; + return reinterpret_cast(raw); } -std::string zSTRING::getStr() +void zSTRING::Assign(zSTRING* str, char* text) // STATIC { - return std::string(data ? data : "-") + " " + std::to_string(length) + " " + std::to_string(capacity); -} + using _zSTRINGAssign = zSTRING* (__thiscall*)(zSTRING* thisPtr, char *param_1); + _zSTRINGAssign assign = reinterpret_cast<_zSTRINGAssign>(0x004c5820); -void zSTRING::setString(char *str) -{ - this->data = str; + assign(str, text); } \ No newline at end of file diff --git a/src/Wrapper/zSTRING.h b/src/Wrapper/zSTRING.h index ce30ce8..e7542d0 100644 --- a/src/Wrapper/zSTRING.h +++ b/src/Wrapper/zSTRING.h @@ -3,20 +3,31 @@ #include #include +#include "basic_string.h" + class zSTRING { - private: - unsigned int length; - unsigned int capacity; - char* data; +private: + void* vftable; + basic_string basicStr; - public: - zSTRING(); - zSTRING(char* str); - // Wrapper für den ursprünglichen Konstruktor - void initialize(char* str); + static void Assign(zSTRING* str, char* text); +public: + static zSTRING* CreateNewzSTRING(char* str); + + zSTRING& operator=(char* str) { + Assign(this, str); + return *this; + } - std::string getStr(); + const char* c_str() const { + return basicStr.data ? basicStr.data : ""; + } - void setString(char * str); + const std::string stdString() const { + return basicStr.data ? basicStr.data : ""; + } + const uint32_t length() const { + return basicStr.length; + } }; \ No newline at end of file diff --git a/src/dllmain.cpp b/src/dllmain.cpp index 6b29536..97b1861 100644 --- a/src/dllmain.cpp +++ b/src/dllmain.cpp @@ -12,6 +12,8 @@ #include "Logic/ImGuiManager.h" #include "Logic/sMain.h" #include "Network/DataChangeNotifier.h" +#include "../common/src/IniManager.h" + // Globals HINSTANCE dll_handle; @@ -153,6 +155,15 @@ DWORD WINAPI MainThread() { SetupConsole(); + // ######### INI STUFF ######### + if(!IniManager::CreateConfigIfMissing(IniManager::CLIENT_CONFIG_FILE)) + return -1; + + std::string username = IniManager::GetItem(IniManager::CLIENT_CONFIG_FILE, IniManager::Item::GENERAL_USERNAME); + std::string serverIp = IniManager::GetItem(IniManager::CLIENT_CONFIG_FILE, IniManager::Item::GENERAL_SERVER_IP); + std::string serverPort = IniManager::GetItem(IniManager::CLIENT_CONFIG_FILE, IniManager::Item::GENERAL_SERVER_PORT); + // ########################### + std::cout << "Starting MAIN...\n" << std::endl; @@ -182,7 +193,7 @@ DWORD WINAPI MainThread() boost::asio::io_context io_context; // create Client - Client client(io_context, "127.0.0.1", "12345", gameThreadWorker); + Client client(io_context, username, serverIp, serverPort, gameThreadWorker); // mainloop for receiving messages std::thread io_thread([&io_context]() { io_context.run(); }); @@ -194,7 +205,14 @@ DWORD WINAPI MainThread() /*if (GetAsyncKeyState(VK_DOWN) < 0){ notifier.sendChanges(); }*/ - notifier.sendChanges(); + if(client.isConnected()){ + notifier.sendChanges(); + } else { + client.sendHandshakeRequest(); + while(!client.isConnected()){ + Sleep(100); + } + } // give imGui players Information imGuiData.clients = *gameThreadWorker->clients->getUnorderedMap(); From 9ee16e9a05c984ba3b9ea5e9c24318932fda64e7 Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Sat, 14 Jun 2025 11:59:43 +0200 Subject: [PATCH 03/11] connection bug fix --- server/CMakeLists.txt | 7 ++- server/src/CommonStructures.h | 16 ++++++ server/src/MessageHandler.cpp | 92 ++++++++++++++++++++++++++++------ src/Network/MessageHandler.cpp | 1 + 4 files changed, 100 insertions(+), 16 deletions(-) diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index 8c799de..60a63c9 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -23,6 +23,11 @@ else() message(FATAL_ERROR "Boost konnte nicht gefunden werden") endif() +# inih +set(INIH_SOURCES + ${CMAKE_SOURCE_DIR}/../common/lib/inih/ini.c +) + # Automatisch alle .cpp-Dateien aus src/ einbinden file(GLOB_RECURSE SOURCES "src/*.cpp") @@ -32,7 +37,7 @@ list(APPEND SOURCES ${COMMON_SOURCES}) include_directories("../common/src/") # Füge das ausführbare Ziel hinzu -add_executable(${PROJECT_NAME} ${SOURCES}) +add_executable(${PROJECT_NAME} ${SOURCES} ${INIH_SOURCES}) # Boost einbinden target_include_directories(${PROJECT_NAME} PRIVATE ${Boost_INCLUDE_DIRS}) diff --git a/server/src/CommonStructures.h b/server/src/CommonStructures.h index 6b83fb5..8b95443 100644 --- a/server/src/CommonStructures.h +++ b/server/src/CommonStructures.h @@ -4,9 +4,25 @@ using boost::asio::ip::udp; namespace CommonStructures { + struct PlayerPosition { + float posX; + float posZ; + float posY; + }; + + struct PlayerRotaion { + float yaw; + float pitch; + float roll; + + }; + struct ClientInfo { udp::endpoint endpoint; std::chrono::steady_clock::time_point lastResponse; std::string username; + + PlayerPosition position; + PlayerRotaion rotation; }; } \ No newline at end of file diff --git a/server/src/MessageHandler.cpp b/server/src/MessageHandler.cpp index d2be1ab..c76caa5 100644 --- a/server/src/MessageHandler.cpp +++ b/server/src/MessageHandler.cpp @@ -57,11 +57,33 @@ bool MessageHandler::isClientRegistered(udp::endpoint &clientEndpoint){ void MessageHandler::clientHandshakeRequest(udp::endpoint &clientEndpoint, std::string &buffer) { std::string username = PackagingSystem::ReadItem(buffer); - if(!addNewClient(clientEndpoint, username)) { - return; - } + // ###### ADD NEW CLIENT ###### std::string clientPortIp = getClientUniqueString(clientEndpoint); + + if(clients->existsItem(clientPortIp)) + return; + + CommonStructures::ClientInfo clientInfo; + clientInfo.endpoint = clientEndpoint; + clientInfo.lastResponse = std::chrono::high_resolution_clock::now(); + clientInfo.username = username; + + clientInfo.position.posX = PackagingSystem::ReadItem(buffer); + clientInfo.position.posZ = PackagingSystem::ReadItem(buffer); + clientInfo.position.posY = PackagingSystem::ReadItem(buffer); + clientInfo.rotation.yaw = PackagingSystem::ReadItem(buffer); + clientInfo.rotation.pitch = PackagingSystem::ReadItem(buffer); + clientInfo.rotation.roll = PackagingSystem::ReadItem(buffer); + + clients->append(clientPortIp, clientInfo); + Async::PrintLn( "Added new Client: " + clientPortIp ); + + updateConsoleTitle(); + + // ################################### + + // ###### SEND CLIENT THAT CONNECTION IS ESTABLISHED ###### Async::PrintLn( clientPortIp + ", " +username+" Handshake Success"); PackagingSystem handshakePacket(Packets::ServerPacket::serverHandshakeAccept); @@ -69,20 +91,48 @@ void MessageHandler::clientHandshakeRequest(udp::endpoint &clientEndpoint, std:: std::string serializedPacket = handshakePacket.serializePacket(); sendMessage(clientEndpoint, serializedPacket); + // ################################### + // ###### SEND CLIENT EVERYONE ELSE ###### // TODO: Continue Here to share the Name of the new Client to the other clients!! PackagingSystem helloInfo(Packets::ServerPacket::serverNewClientConnected); helloInfo.addString(clientPortIp); helloInfo.addString(username); - helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); - helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); - helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); - helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); - helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); - helloInfo.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); + helloInfo.addFloatPointNumber(clientInfo.position.posX, 2); + helloInfo.addFloatPointNumber(clientInfo.position.posZ, 2); + helloInfo.addFloatPointNumber(clientInfo.position.posY, 2); + helloInfo.addFloatPointNumber(clientInfo.rotation.yaw, 2); + helloInfo.addFloatPointNumber(clientInfo.rotation.pitch, 2); + helloInfo.addFloatPointNumber(clientInfo.rotation.roll, 2); sendToAllExceptSender(clientEndpoint, helloInfo.serializePacket()); + + // ################################### + + // ###### SEND EVERYONE ELSE TO CLIENT ###### + { + std::lock_guard lock(clients->getMutex()); + for (auto it = clients->getUnorderedMap()->begin(); it != clients->getUnorderedMap()->end(); ++it) + { + if(it->first == clientPortIp) + continue; + + PackagingSystem playerInfo(Packets::ServerPacket::serverNewClientConnected); + + playerInfo.addString(it->first); + playerInfo.addString(it->second.username); + playerInfo.addFloatPointNumber(it->second.position.posX, 2); + playerInfo.addFloatPointNumber(it->second.position.posZ, 2); + playerInfo.addFloatPointNumber(it->second.position.posY, 2); + playerInfo.addFloatPointNumber(it->second.rotation.yaw, 2); + playerInfo.addFloatPointNumber(it->second.rotation.pitch, 2); + playerInfo.addFloatPointNumber(it->second.rotation.roll, 2); + + sendMessage(clientEndpoint, playerInfo.serializePacket()); + } + } + // ################################### } void MessageHandler::clientRepondsHeartbeat(udp::endpoint &clientEndpoint, std::string &buffer) @@ -95,14 +145,24 @@ void MessageHandler::clientSharesPosition(udp::endpoint &clientEndpoint, std::st { std::string clientPortIp = getClientUniqueString(clientEndpoint); + auto it = clients->find(clientPortIp); + if (!it) + return; + it->get().position.posX = PackagingSystem::ReadItem(buffer); + it->get().position.posZ = PackagingSystem::ReadItem(buffer); + it->get().position.posY = PackagingSystem::ReadItem(buffer); + it->get().rotation.yaw = PackagingSystem::ReadItem(buffer); + it->get().rotation.pitch = PackagingSystem::ReadItem(buffer); + it->get().rotation.roll = PackagingSystem::ReadItem(buffer); + PackagingSystem positionPacket(Packets::ServerPacket::serverDistributePosition); positionPacket.addString(clientPortIp); - positionPacket.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); - positionPacket.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); - positionPacket.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); - positionPacket.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); - positionPacket.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); - positionPacket.addFloatPointNumber(PackagingSystem::ReadItem(buffer), 2); + positionPacket.addFloatPointNumber(it->get().position.posX, 2); + positionPacket.addFloatPointNumber(it->get().position.posZ, 2); + positionPacket.addFloatPointNumber(it->get().position.posY, 2); + positionPacket.addFloatPointNumber(it->get().rotation.yaw, 2); + positionPacket.addFloatPointNumber(it->get().rotation.pitch, 2); + positionPacket.addFloatPointNumber(it->get().rotation.roll, 2); std::string serializedPacket = positionPacket.serializePacket(); @@ -143,6 +203,8 @@ void MessageHandler::sendMessage(udp::endpoint &clientEndpoint, std::string buff } }); } + +/// NEEDS A REWORK void MessageHandler::sendToAllExceptSender(udp::endpoint &senderEndpoint, std::string buffer) { std::lock_guard lock(clients->getMutex()); diff --git a/src/Network/MessageHandler.cpp b/src/Network/MessageHandler.cpp index a6b64cf..f62b13b 100644 --- a/src/Network/MessageHandler.cpp +++ b/src/Network/MessageHandler.cpp @@ -49,6 +49,7 @@ void MessageHandler::handleServerHandshakeAccept(std::string &buffer) return; } Async::PrintLn("HANDSHAKE SUCCESS!!"); + this->pClient->setConnected(); } From 4c86f3872d70b9aa4c075be4b8d5b2a66a008338 Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Wed, 18 Jun 2025 18:17:31 +0200 Subject: [PATCH 04/11] added visible equippment --- MonitoringServer/CMakeLists.txt | 0 MonitoringServer/src/main.cpp | 9 ++ common/src/Network/Packets.h | 4 +- server/src/CommonStructures.h | 8 +- server/src/MessageHandler.cpp | 36 ++++++ server/src/MessageHandler.h | 2 +- server/src/Monitoring/MonitoringClient.cpp | 10 ++ server/src/Monitoring/MonitoringClient.h | 14 +++ server/src/ServerManager.cpp | 3 + server/src/ServerManager.h | 4 + server/src/main.cpp | 1 + src/Logic/GameThreadWorker.cpp | 72 +++++++++++- src/Models/DataStructures.h | 16 +++ src/Models/Npc.cpp | 23 +++- src/Models/Npc.h | 1 + src/Network/Client.cpp | 19 +++ src/Network/Client.h | 1 + src/Network/DataChangeNotifier.cpp | 6 + src/Network/DataChangeNotifier.h | 1 + src/Network/MessageHandler.cpp | 80 ++++++++++++- src/Network/MessageHandler.h | 1 + src/Wrapper/OCNpc.cpp | 127 +++++++++++++++++++-- src/Wrapper/OCNpc.h | 29 ++++- src/Wrapper/oCItem.cpp | 66 +++++++++++ src/Wrapper/oCItem.h | 25 ++++ src/Wrapper/oCMsgWeapon.cpp | 15 +++ src/Wrapper/oCMsgWeapon.h | 10 ++ src/Wrapper/oCObjectFactory.cpp | 29 +++++ src/Wrapper/oCObjectFactory.h | 20 ++++ src/Wrapper/zSTRING.cpp | 6 +- src/Wrapper/zSTRING.h | 2 +- 31 files changed, 618 insertions(+), 22 deletions(-) create mode 100644 MonitoringServer/CMakeLists.txt create mode 100644 MonitoringServer/src/main.cpp create mode 100644 server/src/Monitoring/MonitoringClient.cpp create mode 100644 server/src/Monitoring/MonitoringClient.h create mode 100644 src/Wrapper/oCItem.cpp create mode 100644 src/Wrapper/oCItem.h create mode 100644 src/Wrapper/oCMsgWeapon.cpp create mode 100644 src/Wrapper/oCMsgWeapon.h create mode 100644 src/Wrapper/oCObjectFactory.cpp create mode 100644 src/Wrapper/oCObjectFactory.h diff --git a/MonitoringServer/CMakeLists.txt b/MonitoringServer/CMakeLists.txt new file mode 100644 index 0000000..e69de29 diff --git a/MonitoringServer/src/main.cpp b/MonitoringServer/src/main.cpp new file mode 100644 index 0000000..3c44e80 --- /dev/null +++ b/MonitoringServer/src/main.cpp @@ -0,0 +1,9 @@ + + +// UDP-Server - receiving Server-Data from server. +// RestAPI(Crow) - offering Data received from UDP Server + +int main() { + + return 0; +} \ No newline at end of file diff --git a/common/src/Network/Packets.h b/common/src/Network/Packets.h index 7032c63..b32a85e 100644 --- a/common/src/Network/Packets.h +++ b/common/src/Network/Packets.h @@ -7,6 +7,7 @@ namespace Packets { serverRequestHeartbeat, serverDistributePosition, serverDistributeAnimations, + serverDistributeEquip, serverRemoveClient }; @@ -15,7 +16,8 @@ namespace Packets { clientHandshakeRequest = 100, clientResponseHeartbeat, clientSharePosition, - clientShareAnimations + clientShareAnimations, + clientShareEquip }; } \ No newline at end of file diff --git a/server/src/CommonStructures.h b/server/src/CommonStructures.h index 8b95443..2c0d9dc 100644 --- a/server/src/CommonStructures.h +++ b/server/src/CommonStructures.h @@ -4,6 +4,12 @@ using boost::asio::ip::udp; namespace CommonStructures { + struct PlayerEquipment { + std::string meleeWeaponInstanceName; + std::string rangedWeaponInstanceName; + std::string armorInstanceName; + }; + struct PlayerPosition { float posX; float posZ; @@ -14,7 +20,6 @@ namespace CommonStructures { float yaw; float pitch; float roll; - }; struct ClientInfo { @@ -24,5 +29,6 @@ namespace CommonStructures { PlayerPosition position; PlayerRotaion rotation; + PlayerEquipment equip; }; } \ No newline at end of file diff --git a/server/src/MessageHandler.cpp b/server/src/MessageHandler.cpp index c76caa5..df558a7 100644 --- a/server/src/MessageHandler.cpp +++ b/server/src/MessageHandler.cpp @@ -40,6 +40,9 @@ void MessageHandler::handleBuffer(udp::endpoint &clientEndpoint, std::string buf case Packets::ClientPacket::clientShareAnimations: clientSharesAnimations(clientEndpoint, buffer); break; + case Packets::ClientPacket::clientShareEquip: + clientSharesEquip(clientEndpoint, buffer); + break; default: Async::PrintLn("Unknown Paket..."); break; @@ -76,6 +79,10 @@ void MessageHandler::clientHandshakeRequest(udp::endpoint &clientEndpoint, std:: clientInfo.rotation.pitch = PackagingSystem::ReadItem(buffer); clientInfo.rotation.roll = PackagingSystem::ReadItem(buffer); + clientInfo.equip.meleeWeaponInstanceName = PackagingSystem::ReadItem(buffer); + clientInfo.equip.rangedWeaponInstanceName = PackagingSystem::ReadItem(buffer); + clientInfo.equip.armorInstanceName = PackagingSystem::ReadItem(buffer); + clients->append(clientPortIp, clientInfo); Async::PrintLn( "Added new Client: " + clientPortIp ); @@ -105,6 +112,9 @@ void MessageHandler::clientHandshakeRequest(udp::endpoint &clientEndpoint, std:: helloInfo.addFloatPointNumber(clientInfo.rotation.yaw, 2); helloInfo.addFloatPointNumber(clientInfo.rotation.pitch, 2); helloInfo.addFloatPointNumber(clientInfo.rotation.roll, 2); + helloInfo.addString(clientInfo.equip.meleeWeaponInstanceName); + helloInfo.addString(clientInfo.equip.rangedWeaponInstanceName); + helloInfo.addString(clientInfo.equip.armorInstanceName); sendToAllExceptSender(clientEndpoint, helloInfo.serializePacket()); @@ -128,6 +138,9 @@ void MessageHandler::clientHandshakeRequest(udp::endpoint &clientEndpoint, std:: playerInfo.addFloatPointNumber(it->second.rotation.yaw, 2); playerInfo.addFloatPointNumber(it->second.rotation.pitch, 2); playerInfo.addFloatPointNumber(it->second.rotation.roll, 2); + playerInfo.addString(it->second.equip.meleeWeaponInstanceName); + playerInfo.addString(it->second.equip.rangedWeaponInstanceName); + playerInfo.addString(it->second.equip.armorInstanceName); sendMessage(clientEndpoint, playerInfo.serializePacket()); } @@ -186,6 +199,29 @@ void MessageHandler::clientSharesAnimations(udp::endpoint &clientEndpoint, std:: sendToAllExceptSender(clientEndpoint, animationPacket.serializePacket()); } +void MessageHandler::clientSharesEquip(udp::endpoint &clientEndpoint, std::string &buffer) +{ + auto safeBuffer = std::make_shared(buffer); + std::string clientPortIp = getClientUniqueString(clientEndpoint); + + auto it = clients->find(clientPortIp); + if (!it) + return; + + it->get().equip.meleeWeaponInstanceName = PackagingSystem::ReadItem(buffer); + it->get().equip.rangedWeaponInstanceName = PackagingSystem::ReadItem(buffer); + it->get().equip.armorInstanceName = PackagingSystem::ReadItem(buffer); + + PackagingSystem equipPacket(Packets::ServerPacket::serverDistributeEquip); + equipPacket.addString(clientPortIp); + equipPacket.addString(it->get().equip.meleeWeaponInstanceName); + equipPacket.addString(it->get().equip.rangedWeaponInstanceName); + equipPacket.addString(it->get().equip.armorInstanceName); + + sendToAllExceptSender(clientEndpoint, equipPacket.serializePacket()); +} + + void MessageHandler::sendMessage(udp::endpoint &clientEndpoint, std::string buffer) { auto packetPtr = std::make_shared(buffer); diff --git a/server/src/MessageHandler.h b/server/src/MessageHandler.h index 2091e1c..370c698 100644 --- a/server/src/MessageHandler.h +++ b/server/src/MessageHandler.h @@ -34,7 +34,7 @@ class MessageHandler void clientRepondsHeartbeat(udp::endpoint &clientEndpoint, std::string &buffer); void clientSharesPosition(udp::endpoint &clientEndpoint, std::string &buffer); void clientSharesAnimations(udp::endpoint &clientEndpoint, std::string &buffer); - + void clientSharesEquip(udp::endpoint &clientEndpoint, std::string &buffer); bool isClientRegistered(udp::endpoint &clientEndpoint); diff --git a/server/src/Monitoring/MonitoringClient.cpp b/server/src/Monitoring/MonitoringClient.cpp new file mode 100644 index 0000000..6ae5cfe --- /dev/null +++ b/server/src/Monitoring/MonitoringClient.cpp @@ -0,0 +1,10 @@ +#include "MonitoringClient.h" + +MonitoringClient::MonitoringClient(AsyncUnorderedMap *clients) : pClients(clients) +{ + +} + +void MonitoringClient::startingMonitoringClient(){ + +} \ No newline at end of file diff --git a/server/src/Monitoring/MonitoringClient.h b/server/src/Monitoring/MonitoringClient.h new file mode 100644 index 0000000..0bf08f8 --- /dev/null +++ b/server/src/Monitoring/MonitoringClient.h @@ -0,0 +1,14 @@ +#pragma once + +#include "../CommonStructures.h" +#include "../../../common/src/Async/AsyncUnorderedMap.h" +class MonitoringClient { + + public: + MonitoringClient(AsyncUnorderedMap *clients); + + private: + AsyncUnorderedMap *pClients; + + void startingMonitoringClient(); +}; \ No newline at end of file diff --git a/server/src/ServerManager.cpp b/server/src/ServerManager.cpp index 06ef840..95e25ae 100644 --- a/server/src/ServerManager.cpp +++ b/server/src/ServerManager.cpp @@ -9,6 +9,9 @@ ServerManager::ServerManager(boost::asio::io_context &io_context, boost::asio::i messageHandler = new MessageHandler(clients, socket); start_receive(); + + + monitor = std::make_unique(&clients); } void ServerManager::start_receive() diff --git a/server/src/ServerManager.h b/server/src/ServerManager.h index 681f1ff..961f71e 100644 --- a/server/src/ServerManager.h +++ b/server/src/ServerManager.h @@ -7,6 +7,8 @@ #include "MessageHandler.h" #include "CommonStructures.h" +#include "Monitoring/MonitoringClient.h" + #include "../../common/src/Async/AsyncUnorderedMap.h" using boost::asio::ip::udp; @@ -25,4 +27,6 @@ class ServerManager { MessageHandler *messageHandler; void start_receive(); + + std::unique_ptr monitor; }; \ No newline at end of file diff --git a/server/src/main.cpp b/server/src/main.cpp index 1c4ff53..8243986 100644 --- a/server/src/main.cpp +++ b/server/src/main.cpp @@ -7,6 +7,7 @@ #include "ServerManager.h" #include "MessageHandler.h" +//#include "../../common/src/IniManager.h" using boost::asio::ip::udp; diff --git a/src/Logic/GameThreadWorker.cpp b/src/Logic/GameThreadWorker.cpp index 4028d27..03a7d59 100644 --- a/src/Logic/GameThreadWorker.cpp +++ b/src/Logic/GameThreadWorker.cpp @@ -39,6 +39,8 @@ void GameThreadWorker::processMessages() removeTask(); } } +#include "../Wrapper/oCItem.h" +#include "../Wrapper/oCMsgWeapon.h" Npc *npc; void GameThreadWorker::checkGameState(){ @@ -56,15 +58,83 @@ void GameThreadWorker::checkGameState(){ /* ################ Custom Shit Here################# */ if (GetAsyncKeyState(VK_RSHIFT) < 0) { + std::cout << "--- ITEM STUFF ---- " << "\n"; + oCItem * armor = pMainPlayer->oCNpc->getEquippedArmor(); + oCItem * melee = pMainPlayer->oCNpc->getEquippedMeleeWeapon(); + oCItem * ranged = pMainPlayer->oCNpc->getEquippedRangedWeapon(); + + std::cout << "Armor Address: " << armor << "\n"; + std::cout << "Armor Name: " << armor->getName() << "\n"; + zSTRING * zArmor = armor->getInstanceName(); + zSTRING * zMelee = melee->getInstanceName(); + zSTRING * zRanged = ranged->getInstanceName(); + std::cout << "zArmor Instance Name: " << zArmor->stdString() << "\n"; + std::cout << "zMelee Instance Name: " << zMelee->stdString() << "\n"; + std::cout << "zRanged Instance Name: " << zRanged->stdString() << "\n"; + + oCItem * npcArmor = oCItem::CreateoCItem(); + npcArmor->setByScriptInstance(zArmor->c_str()); + oCItem * npcMelee = oCItem::CreateoCItem(); + npcMelee->setByScriptInstance(zMelee->c_str()); + oCItem * npcRanged = oCItem::CreateoCItem(); + npcRanged->setByScriptInstance(zRanged->c_str()); + //npcRanged->setFlag(4); //0x40000000, 0x800000 + //npcMelee->setFlag(2); + + std::cout << "CUSTOM Address : " << npcArmor << "\n"; + std::cout << "CUSTOM Name: " << npcArmor->getName() << "\n"; + + std::cout << "CUSTOM Address : " << npcMelee << "\n"; + std::cout << "CUSTOM Name: " << npcMelee->getName() << "\n"; + + std::cout << "CUSTOM Address : " << npcRanged << "\n"; + std::cout << "CUSTOM Name: " << npcRanged->getName() << "\n"; + std::cout << "---- -------- ---- " << "\n"; + + + /*oCItem * current = pMainPlayer->oCNpc->getWeapon(); + if(current) { + std::cout << "current Address : " << current << "\n"; + std::cout << "current Name: " << current->getName() << "\n"; + } else { + std::cout << "current EMPTY!\n"; + }*/ + if(npc == nullptr) { npc = new Npc(); npc->setCurrentHealth(10); npc->setMaxHealth(10); npc->oCNpc->setVisualWithString("HUMANS.MDS"); npc->oCNpc->setAdditionalVisuals("hum_body_Naked0", 9, 0, "Hum_Head_Pony", 2, 0, -1); - + //npc->oCNpc->setTalentValue(0, 10); // Strength + //npc->oCNpc->setTalentValue(1, 10); //Dexterity + npc->oCNpc->callVariable(OCNpc::Offset::DEXTERITY) = 10; + npc->oCNpc->callVariable(OCNpc::Offset::STRENGTH) = 10; npc->oCNpc->enableWithdCoords(pMainPlayer->getX(), pMainPlayer->getZ(), pMainPlayer->getY()); + npc->setName("Steve"); + + + //npc->oCNpc->putInInv(npcRanged); + //npc->oCNpc->putInInv(npcMelee); + + npc->oCNpc->equip(npcArmor); + npc->oCNpc->equipItem(npcMelee); + npc->oCNpc->equip(npcRanged); + + //npc->oCNpc->equipBestWeapon(2); + //npc->oCNpc->equipBestWeapon(4); + + /*oCMsgWeapon * w = oCMsgWeapon::CreateoCMsgWeapon(4, 0, 0); + int ka = npc->oCNpc->EV_DrawWeapon1(w); + std::cout << "KA: " << std::to_string(ka) << "\n"; */ + + + /*nnpc->oCNpc->putInInv(npcArmor); + npc->oCNpc->putInInv(npcRanged); + npc->oCNpc->putInInv(npcMelee);*/ + + //npc->oCNpc->equipItem(npcRanged); } } } \ No newline at end of file diff --git a/src/Models/DataStructures.h b/src/Models/DataStructures.h index 516857a..09de6f3 100644 --- a/src/Models/DataStructures.h +++ b/src/Models/DataStructures.h @@ -52,6 +52,22 @@ namespace DataStructures { } }; + struct LastEquip { + std::string meleeWeaponInstanceName = ""; + std::string rangedWeaponInstanceName = ""; + std::string armorInstanceName = ""; + + bool isSame(LastEquip lastEquip) { + if(lastEquip.meleeWeaponInstanceName == meleeWeaponInstanceName && lastEquip.rangedWeaponInstanceName == rangedWeaponInstanceName && lastEquip.armorInstanceName == armorInstanceName) + return true; + + meleeWeaponInstanceName = lastEquip.meleeWeaponInstanceName; + rangedWeaponInstanceName = lastEquip.rangedWeaponInstanceName; + armorInstanceName = lastEquip.armorInstanceName; + return false; + } + }; + struct LastRotation { float yaw = 0; float pitch = 0; diff --git a/src/Models/Npc.cpp b/src/Models/Npc.cpp index d11be8c..6b6606f 100644 --- a/src/Models/Npc.cpp +++ b/src/Models/Npc.cpp @@ -152,7 +152,7 @@ int Npc::getExpertise() if (!isPlayerLoaded()) return 0; - return oCNpc->callVariable(OCNpc::Offset::EXPERTISE); + return oCNpc->callVariable(OCNpc::Offset::DEXTERITY); } float Npc::getX() @@ -254,6 +254,27 @@ DataStructures::LastAnimation Npc::getLastAnimation() { return retLastAnim; } +DataStructures::LastEquip Npc::getLastEquip() { + DataStructures::LastEquip retLastEquip; + + if(oCNpc->getEquippedMeleeWeapon()) + retLastEquip.meleeWeaponInstanceName = oCNpc->getEquippedMeleeWeapon()->getInstanceName()->stdString(); + else + retLastEquip.meleeWeaponInstanceName = ""; + + if(oCNpc->getEquippedRangedWeapon()) + retLastEquip.rangedWeaponInstanceName = oCNpc->getEquippedRangedWeapon()->getInstanceName()->stdString(); + else + retLastEquip.rangedWeaponInstanceName = ""; + + if(oCNpc->getEquippedArmor()) + retLastEquip.armorInstanceName = oCNpc->getEquippedArmor()->getInstanceName()->stdString(); + else + retLastEquip.armorInstanceName = ""; + + return retLastEquip; +} + DataStructures::LastRotation Npc::getLastRotation(){ DataStructures::LastRotation retLastRot; diff --git a/src/Models/Npc.h b/src/Models/Npc.h index 15950ce..40b34d0 100644 --- a/src/Models/Npc.h +++ b/src/Models/Npc.h @@ -57,5 +57,6 @@ class Npc DataStructures::LastPosition getLastPosition(); DataStructures::LastAnimation getLastAnimation(); + DataStructures::LastEquip getLastEquip(); DataStructures::LastRotation getLastRotation(); }; \ No newline at end of file diff --git a/src/Network/Client.cpp b/src/Network/Client.cpp index 8d8f268..b63bd50 100644 --- a/src/Network/Client.cpp +++ b/src/Network/Client.cpp @@ -90,6 +90,11 @@ void Client::sendHandshakeRequest() { packetHandshake.addFloatPointNumber(lasPos.pitch, 2); packetHandshake.addFloatPointNumber(lasPos.roll, 2); + DataStructures::LastEquip lastEquip = mainPlayer->getLastEquip(); + packetHandshake.addString(lastEquip.meleeWeaponInstanceName); + packetHandshake.addString(lastEquip.rangedWeaponInstanceName); + packetHandshake.addString(lastEquip.armorInstanceName); + std::string bufferStr = packetHandshake.serializePacket(); this->send_message(bufferStr); } @@ -127,6 +132,20 @@ void Client::sendPlayerAnimation() this->send_message(bufferStr); } +void Client::sendPlayerEquip() +{ + DataStructures::LastEquip lastEquip = mainPlayer->getLastEquip(); + + PackagingSystem packetEquip(Packets::ClientPacket::clientShareEquip); + + packetEquip.addString(lastEquip.meleeWeaponInstanceName); + packetEquip.addString(lastEquip.rangedWeaponInstanceName); + packetEquip.addString(lastEquip.armorInstanceName); + + std::string bufferStr = packetEquip.serializePacket(); + this->send_message(bufferStr); +} + void Client::sendPlayerRotation() { /*Data data; data.id = ClientPacket::clientShareRotation; diff --git a/src/Network/Client.h b/src/Network/Client.h index 1b5255a..fe10f98 100644 --- a/src/Network/Client.h +++ b/src/Network/Client.h @@ -40,6 +40,7 @@ class Client void sendHandshakeRequest(); void sendPlayerPosition(); void sendPlayerAnimation(); + void sendPlayerEquip(); void sendPlayerRotation(); Npc *getMainPlayer(); diff --git a/src/Network/DataChangeNotifier.cpp b/src/Network/DataChangeNotifier.cpp index c4e7abb..6fe647d 100644 --- a/src/Network/DataChangeNotifier.cpp +++ b/src/Network/DataChangeNotifier.cpp @@ -21,6 +21,12 @@ void DataChangeNotifier::initListValues() { } }); + playerState.push_back( [this]() { + DataStructures::LastEquip retLastEquip = pMainPlayer->getLastEquip(); + if(!playerLastEquip.isSame(retLastEquip)) { + pClient->sendPlayerEquip(); + } + }); /*playerState.push_back( [this]() { DataStructures::LastRotation retLastRot = pMainPlayer->getLastRotation(); if(!playerLastRotation.isSame(retLastRot)) { diff --git a/src/Network/DataChangeNotifier.h b/src/Network/DataChangeNotifier.h index 43a05b4..db69bf0 100644 --- a/src/Network/DataChangeNotifier.h +++ b/src/Network/DataChangeNotifier.h @@ -47,5 +47,6 @@ class DataChangeNotifier DataStructures::LastPosition playerLastPos; DataStructures::LastAnimation playerLastAnim; + DataStructures::LastEquip playerLastEquip; DataStructures::LastRotation playerLastRotation; }; \ No newline at end of file diff --git a/src/Network/MessageHandler.cpp b/src/Network/MessageHandler.cpp index f62b13b..90b3a3e 100644 --- a/src/Network/MessageHandler.cpp +++ b/src/Network/MessageHandler.cpp @@ -29,6 +29,9 @@ void MessageHandler::managePacket(std::string stringPacket) case Packets::ServerPacket::serverDistributeAnimations: handleServerDistributeAnimations(stringPacket); break; + case Packets::ServerPacket::serverDistributeEquip: + handleServerDistributeEquip(stringPacket); + break; case Packets::ServerPacket::serverRemoveClient: handleServerRemoveClient(stringPacket); break; @@ -65,17 +68,20 @@ void MessageHandler::handleServerNewClientConnected(std::string &buffer) float pitch = PackagingSystem::ReadItem(buffer); float roll = PackagingSystem::ReadItem(buffer); + std::string melee = PackagingSystem::ReadItem(buffer); + std::string ranged = PackagingSystem::ReadItem(buffer); + std::string armor = PackagingSystem::ReadItem(buffer); + // Creating a new Npc Npc *value = new Npc(); value->setCurrentHealth(10); value->setMaxHealth(10); value->oCNpc->setVisualWithString("HUMANS.MDS"); value->oCNpc->setAdditionalVisuals("hum_body_Naked0", 9, 0, "Hum_Head_Pony", 2, 0, -1); - - + value->oCNpc->callVariable(OCNpc::Offset::DEXTERITY) = 50; + value->oCNpc->callVariable(OCNpc::Offset::STRENGTH) = 50; value->setName(name); - zMAT4 matrix; value->oCNpc->getTrafoModelNodeToWorld(&matrix, 0); @@ -85,9 +91,21 @@ void MessageHandler::handleServerNewClientConnected(std::string &buffer) value->setX(x); value->setZ(z); value->setY(y); - value->oCNpc->enableWithdCoords(x, z, y); + + + + PackagingSystem internEquipAnswer(Packets::ServerPacket::serverDistributeEquip); + internEquipAnswer.addString(receivedKey); + internEquipAnswer.addString(melee); + internEquipAnswer.addString(ranged); + internEquipAnswer.addString(armor); + std::string internEquipAnswertemp = internEquipAnswer.serializePacket(); + PackagingSystem::ReadPacketId(internEquipAnswertemp);// have to remove it + handleServerDistributeEquip(internEquipAnswertemp); + + // New Client inserted pClients->append(receivedKey, value); } @@ -115,7 +133,6 @@ void MessageHandler::handleServerDistributePosition(std::string &buffer) if (!it) return; - Npc *value = it.value(); zMAT4 matrix; value->oCNpc->getTrafoModelNodeToWorld(&matrix, 0); @@ -174,6 +191,59 @@ void MessageHandler::handleServerDistributeAnimations(std::string &buffer) } } +void MessageHandler::handleServerDistributeEquip(std::string &buffer) +{ + std::string receivedKey = PackagingSystem::ReadItem(buffer); + std::string melee = PackagingSystem::ReadItem(buffer); + std::string ranged = PackagingSystem::ReadItem(buffer); + std::string armor = PackagingSystem::ReadItem(buffer); + + + auto it = pClients->find(receivedKey); + if (!it) + { + return; + } + + Npc *value = it.value(); + + DataStructures::LastEquip currentEquip = value->getLastEquip(); + + + if(armor == "" && currentEquip.armorInstanceName != "") { + value->oCNpc->unequipItem(value->oCNpc->getEquippedArmor()); + } else if(armor != "" ){ + if(currentEquip.armorInstanceName != "") { + value->oCNpc->unequipItem(value->oCNpc->getEquippedArmor()); + } + oCItem * newArmor = oCItem::CreateoCItem(); + newArmor->setByScriptInstance(armor.c_str()); + value->oCNpc->equipArmor(newArmor); + } + + if(ranged == "" && currentEquip.rangedWeaponInstanceName != "") { + value->oCNpc->unequipItem(value->oCNpc->getEquippedRangedWeapon()); + } else if(ranged != "" ){ + if(currentEquip.rangedWeaponInstanceName != "") { + value->oCNpc->unequipItem(value->oCNpc->getEquippedRangedWeapon()); + } + oCItem * newRanged = oCItem::CreateoCItem(); + newRanged->setByScriptInstance(ranged.c_str()); + value->oCNpc->equip(newRanged); + } + + if(melee == "" && currentEquip.meleeWeaponInstanceName != "") { + value->oCNpc->unequipItem(value->oCNpc->getEquippedMeleeWeapon()); + } else if(melee != "" ){ + if(currentEquip.meleeWeaponInstanceName != "") { + value->oCNpc->unequipItem(value->oCNpc->getEquippedMeleeWeapon()); + } + oCItem * newMelee = oCItem::CreateoCItem(); + newMelee->setByScriptInstance(melee.c_str()); + value->oCNpc->equipWeapon(newMelee); + } +} + void MessageHandler::handleServerRemoveClient(std::string &buffer) { std::string receivedKey = PackagingSystem::ReadItem(buffer); // data.names.at(0); diff --git a/src/Network/MessageHandler.h b/src/Network/MessageHandler.h index f723706..e55103b 100644 --- a/src/Network/MessageHandler.h +++ b/src/Network/MessageHandler.h @@ -52,6 +52,7 @@ class MessageHandler void handleServerRequestsHeartbeat(std::string &buffer); void handleServerDistributePosition(std::string &buffer); void handleServerDistributeAnimations(std::string &buffer); + void handleServerDistributeEquip(std::string &buffer); void handleServerDistributeRotations(std::string &buffer); void handleServerRemoveClient(std::string &buffer); }; \ No newline at end of file diff --git a/src/Wrapper/OCNpc.cpp b/src/Wrapper/OCNpc.cpp index 36bd368..82dbd8d 100644 --- a/src/Wrapper/OCNpc.cpp +++ b/src/Wrapper/OCNpc.cpp @@ -1,17 +1,18 @@ #include "OCNpc.h" -struct OCObjectFactory +/*struct OCObjectFactory { typedef void *(__thiscall *_CreateNPC)(void *pThis, int param); _CreateNPC createNpc; void *pThis = *(void **)0x82c114; -} oCObjectFactory; +} oCObjectFactory;*/ OCNpc * OCNpc::CreateNewNpc() // STATIC { - oCObjectFactory.createNpc = (OCObjectFactory::_CreateNPC)(0x6c8560); - OCNpc * npc = (OCNpc *)oCObjectFactory.createNpc(oCObjectFactory.pThis, -1); + /*oCObjectFactory.createNpc = (OCObjectFactory::_CreateNPC)(0x6c8560); + OCNpc * npc = (OCNpc *)oCObjectFactory.createNpc(oCObjectFactory.pThis, -1);*/ + OCNpc * npc = oCObjectFactory::CreateNpc(); std::cout << "Pointer of NPC: " << npc << "\n"; return npc; } @@ -171,11 +172,123 @@ void OCNpc::addVobToWorld_CorrectParentDependencies(){ addVobToWorld_CorrectParentDependenciesRef(this); } -/*zSTRING *OCNpc::getName(zSTRING * name){ +oCItem * OCNpc::getEquippedArmor() { + using _GetEquippedArmor = oCItem*(__thiscall *)(void *pThis); + _GetEquippedArmor getEquippedArmorRef = reinterpret_cast<_GetEquippedArmor>(0x6947a0); + + return getEquippedArmorRef(this); +} + +oCItem * OCNpc::getEquippedMeleeWeapon(){ + using _GetEquippedMeleeWeapon = oCItem*(__thiscall *)(void *pThis); + _GetEquippedMeleeWeapon getEquippedMeleeWeaponRef = reinterpret_cast<_GetEquippedMeleeWeapon>(0x694580); + + return getEquippedMeleeWeaponRef(this); +} + +oCItem * OCNpc::getEquippedRangedWeapon(){ + using _GetEquippedRangedWeapon = oCItem*(__thiscall *)(void *pThis); + _GetEquippedRangedWeapon getEquippedRangedWeaponRef = reinterpret_cast<_GetEquippedRangedWeapon>(0x694690); + + return getEquippedRangedWeaponRef(this); +} + +void OCNpc::equipArmor(oCItem * armor) +{ + using _EquipArmor = void(__thiscall *)(void *pThis, oCItem * armor); + _EquipArmor equipArmorRef = reinterpret_cast<_EquipArmor>(0x697080); + equipArmorRef(this, armor); +} + +void OCNpc::equipItem(oCItem * item) +{ + using _EquipItem = void(__thiscall *)(void *pThis, oCItem * item); + _EquipItem equipItemRef = reinterpret_cast<_EquipItem>(0x68f940); + equipItemRef(this, item); +} + +void OCNpc::equip(oCItem * item) +{ + using _Equip = void(__thiscall *)(void *pThis, oCItem * item); + _Equip equipRef = reinterpret_cast<_Equip>(0x6968f0); + equipRef(this, item); +} + +void OCNpc::equipWeapon(oCItem * weapon) +{ + using _EquipItem = void(__thiscall *)(void *pThis, oCItem * item); + _EquipItem equipItemRef = reinterpret_cast<_EquipItem>(0x696c20); + equipItemRef(this, weapon); +} + +void OCNpc::equipBestWeapon(int param1) +{ + using _EquipBestWeapon = void(__thiscall *)(void *pThis, int param1); + _EquipBestWeapon equipBestWeaponRef = reinterpret_cast<_EquipBestWeapon>(0x6aa220); + equipBestWeaponRef(this, param1); +} + +void OCNpc::equipFarWeapon(oCItem * weapon) +{ + using _EquipItem = void(__thiscall *)(void *pThis, oCItem * item); + _EquipItem equipItemRef = reinterpret_cast<_EquipItem>(0x696f00); + equipItemRef(this, weapon); +} + +void OCNpc::unequipItem(oCItem * item) +{ + using _UnequipItem = void(__thiscall *)(void *pThis, oCItem * item); + _UnequipItem unequipItemRef = reinterpret_cast<_UnequipItem>(0x68fbc0); + unequipItemRef(this, item); +} + + +oCItem * OCNpc::putInInv(oCItem * item) +{ + using _PutInInv = oCItem*(__thiscall *)(void *pThis, oCItem * item); + _PutInInv putInInvRef = reinterpret_cast<_PutInInv>(0x6a4ff0); + + return putInInvRef(this, item); + +} + +int OCNpc::EV_DrawWeapon1(oCMsgWeapon * msgWeapon) +{ + using _EV_DrawWeapon1 = int(__thiscall *)(void *pThis, oCMsgWeapon * msgWeapon); + _EV_DrawWeapon1 EV_DrawWeapon1Ref = reinterpret_cast<_EV_DrawWeapon1>(0x6a8b80); + + return EV_DrawWeapon1Ref(this, msgWeapon); +} + +// returns the weapon in the fighting slot +oCItem * OCNpc::getWeapon() +{ + using _GetWeapon = oCItem*(__thiscall *)(void *pThis); + _GetWeapon getWeaponRef = reinterpret_cast<_GetWeapon>(0x6943f0); + + return getWeaponRef(this); +} + +int OCNpc::useItem(oCItem * item) +{ + using _UseItem = int(__thiscall *)(void *pThis, oCItem * item); + _UseItem useItemRef = reinterpret_cast<_UseItem>(0x698810); + + return useItemRef(this, item); +} + +void OCNpc::setTalentValue(int talentIndex, int value) +{ + using _SetTalentValue = void(__thiscall *)(void *pThis, int talentIndex, int value); + _SetTalentValue setTalentValueRef = reinterpret_cast<_SetTalentValue>(0x68e370); + setTalentValueRef(this, talentIndex, value); +} + +/*zSTRING *OCNpc::getName2(){ zSTRING * nS = zSTRING::CreateNewzSTRING(""); - using _GetName = zSTRING* (__thiscall *)(void* pThis, zSTRING* name); + using _GetName = zSTRING* (__thiscall *)(void* pThis); _GetName getNameRef = reinterpret_cast<_GetName>(0x68D0B0); - return getNameRef(this, nS); + return getNameRef(this); //zSTRING* namePtr = (zSTRING*)((char*)this + 0x108); //return namePtr; diff --git a/src/Wrapper/OCNpc.h b/src/Wrapper/OCNpc.h index a9663eb..956084a 100644 --- a/src/Wrapper/OCNpc.h +++ b/src/Wrapper/OCNpc.h @@ -5,7 +5,11 @@ #include "ZVec3.h" #include "zSTRING.h" #include "zMAT4.h" +#include "oCObjectFactory.h" +#include "oCItem.h" +#include "oCMsgWeapon.h" +class oCItem; /** * @brief Base memory address for the main player's NPC instance. * @@ -54,7 +58,7 @@ class OCNpc // int static constexpr uintptr_t STRENGTH = 0x194; // int - static constexpr uintptr_t EXPERTISE = 0x198; + static constexpr uintptr_t DEXTERITY = 0x198; // int static constexpr uintptr_t LEVEL = 0x1EC; @@ -125,8 +129,29 @@ class OCNpc void addVobToWorld_CorrectParentDependencies(); + oCItem * getEquippedArmor(); + oCItem * getEquippedMeleeWeapon(); + oCItem * getEquippedRangedWeapon(); - //zSTRING *getName(zSTRING * name); + void equipArmor(oCItem * armor); + void equipItem(oCItem * item); + void equipWeapon(oCItem * weapon); + void equipFarWeapon(oCItem * weapon); + void equip(oCItem * item); + void equipBestWeapon(int param1); + + void unequipItem(oCItem * item); + + oCItem * putInInv(oCItem * item); + + int EV_DrawWeapon1(oCMsgWeapon * msgWeapon); + + oCItem * getWeapon(); + + int useItem(oCItem * item); + + void setTalentValue(int talentIndex, int value); + //zSTRING *getName2(); /*int applyOverlay(char * animName); diff --git a/src/Wrapper/oCItem.cpp b/src/Wrapper/oCItem.cpp new file mode 100644 index 0000000..121d65c --- /dev/null +++ b/src/Wrapper/oCItem.cpp @@ -0,0 +1,66 @@ +#include "oCItem.h" + +oCItem * oCItem::CreateoCItem(int itemId){ + /*void* raw = ::operator new(0x2fc); // Thas the size of 0CItem + + using _CTor = oCItem*(__thiscall *)(void *pThis); + _CTor ctor = reinterpret_cast<_CTor>(0x00670de0); + ctor(raw); + + return reinterpret_cast(raw);*/ + oCItem * item = oCObjectFactory::CreateItem(itemId); + return item; +} + +void oCItem::initByScript(int id, int ka) +{ + using _InitByScript = void(__thiscall *)(void *pThis, int param1, int param2); + _InitByScript initByScriptRef = reinterpret_cast<_InitByScript>(0x671660); + + initByScriptRef(this, id, ka); +} + +int oCItem::setByScriptInstance(const char * name) +{ + using _SetByScriptInstance = int(__thiscall *)(void *pThis, zSTRING * instanceName, int param2); + _SetByScriptInstance setByScriptInstanceRef = reinterpret_cast<_SetByScriptInstance>(0x6731b0); + + zSTRING * s = zSTRING::CreateNewzSTRING(name); + return setByScriptInstanceRef(this, s, -1); +} + +void oCItem::setName(std::string name) +{ + basic_string * n = (basic_string*)((char*)this + 0x108); + *n = name.c_str(); +} + +std::string oCItem::getName() +{ + basic_string * n = (basic_string*)((char*)this + 0x108); + return n->c_str(); +} + +zSTRING * oCItem::getInstanceName() +{ + zSTRING * name = zSTRING::CreateNewzSTRING(""); + using _GetInstanceName = zSTRING*(__thiscall *)(void *pThis, zSTRING* name); + _GetInstanceName getInstanceNameRef = reinterpret_cast<_GetInstanceName>(0x6731f0); + + return getInstanceNameRef(this, name); +} + +void oCItem::setFlag(int flag) +{ +/* + 0x2 Melee Weapon + 0x4 Ranged Weapon + 0x40000000 Currently equipped + 0x400000 Potion + 0x800 Ring +*/ + using _SetFlag = void(__thiscall *)(void *pThis, int flag); + _SetFlag setFlagRef = reinterpret_cast<_SetFlag>(0x672000); + + setFlagRef(this, flag); +} \ No newline at end of file diff --git a/src/Wrapper/oCItem.h b/src/Wrapper/oCItem.h new file mode 100644 index 0000000..19899ea --- /dev/null +++ b/src/Wrapper/oCItem.h @@ -0,0 +1,25 @@ +#pragma once + +#include + +#include "basic_string.h" +#include "oCObjectFactory.h" + +class oCItem { + + public: + static oCItem * CreateoCItem(int itemId = -1); + + void initByScript(int id, int ka); + int setByScriptInstance(const char * name); + void setName(std::string name); + std::string getName(); + + zSTRING * getInstanceName(); + + void setFlag(int flag); + + private: + + +}; \ No newline at end of file diff --git a/src/Wrapper/oCMsgWeapon.cpp b/src/Wrapper/oCMsgWeapon.cpp new file mode 100644 index 0000000..e0ccc8c --- /dev/null +++ b/src/Wrapper/oCMsgWeapon.cpp @@ -0,0 +1,15 @@ +#include "oCMsgWeapon.h" + + +oCMsgWeapon * oCMsgWeapon::CreateoCMsgWeapon(int tWeaponSubType, int param2, int param3) // STATIC +{ + + void* raw = ::operator new(0x50); // size of this objekt '0x50' + + using _CTor = oCMsgWeapon*(__thiscall *)(void *pThis, int tWeaponSubType, int param2, int param3); + _CTor ctor = reinterpret_cast<_CTor>(0x006bf630); + ctor(raw, tWeaponSubType, param2, param3); + + //return u; + return reinterpret_cast(raw); +} \ No newline at end of file diff --git a/src/Wrapper/oCMsgWeapon.h b/src/Wrapper/oCMsgWeapon.h new file mode 100644 index 0000000..c537e34 --- /dev/null +++ b/src/Wrapper/oCMsgWeapon.h @@ -0,0 +1,10 @@ +#pragma once + + +class oCMsgWeapon { + public: + static oCMsgWeapon * CreateoCMsgWeapon(int tWeaponSubType, int param2, int param3); + + +}; + diff --git a/src/Wrapper/oCObjectFactory.cpp b/src/Wrapper/oCObjectFactory.cpp new file mode 100644 index 0000000..912ecdf --- /dev/null +++ b/src/Wrapper/oCObjectFactory.cpp @@ -0,0 +1,29 @@ +#include "oCObjectFactory.h" +/*struct OCObjectFactory +{ + typedef void *(__thiscall *_CreateNPC)(void *pThis, int param); + _CreateNPC createNpc; + + void *pThis = *(void **)0x82c114; +} oCObjectFactory;*/ + +OCNpc * oCObjectFactory::CreateNpc() // STATIC +{ + using _CreateNPC = OCNpc*(__thiscall *)(void *pThis, int param); + _CreateNPC createNpcRef = reinterpret_cast<_CreateNPC>(0x6c8560); + + return createNpcRef(getOCObjectFactoryAddress(), -1); +} + +oCItem * oCObjectFactory::CreateItem(int scriptId) // STATIC +{ + using _CreateItem = oCItem*(__thiscall *)(void *pThis, int param); + _CreateItem createItemRef = reinterpret_cast<_CreateItem>(0x6c8660); + + return createItemRef(getOCObjectFactoryAddress(), scriptId); +} + + +void * oCObjectFactory::getOCObjectFactoryAddress(){// STATIC + return *(void **)0x82c114; +} \ No newline at end of file diff --git a/src/Wrapper/oCObjectFactory.h b/src/Wrapper/oCObjectFactory.h new file mode 100644 index 0000000..e209014 --- /dev/null +++ b/src/Wrapper/oCObjectFactory.h @@ -0,0 +1,20 @@ +#pragma once + +#include "OCNpc.h" + +class OCNpc; +class oCItem; + +class oCObjectFactory { + + public: + static OCNpc * CreateNpc(); + + /// @brief Creates an Item depending on the Id + /// @param scriptId if you just want an Item instance use -1 else use itemId + /// @return new Item Instance + static oCItem * CreateItem(int scriptId); + private: + static void * getOCObjectFactoryAddress(); + //void *pThis = *(void **)0x82c114; +}; \ No newline at end of file diff --git a/src/Wrapper/zSTRING.cpp b/src/Wrapper/zSTRING.cpp index 61af1a3..08dc295 100644 --- a/src/Wrapper/zSTRING.cpp +++ b/src/Wrapper/zSTRING.cpp @@ -1,11 +1,13 @@ #include "zSTRING.h" -zSTRING* zSTRING::CreateNewzSTRING(char * str){ // STATIC +zSTRING* zSTRING::CreateNewzSTRING(const char * str){ // STATIC void* raw = ::operator new(sizeof(zSTRING)); using _CTor = zSTRING*(__thiscall *)(void *pThis, char * text); _CTor ctor = reinterpret_cast<_CTor>(0x004013A0); - ctor(raw, str); + + char * nameNotConst = _strdup(str); + ctor(raw, nameNotConst); //return u; return reinterpret_cast(raw); diff --git a/src/Wrapper/zSTRING.h b/src/Wrapper/zSTRING.h index e7542d0..1161ef4 100644 --- a/src/Wrapper/zSTRING.h +++ b/src/Wrapper/zSTRING.h @@ -12,7 +12,7 @@ class zSTRING { static void Assign(zSTRING* str, char* text); public: - static zSTRING* CreateNewzSTRING(char* str); + static zSTRING* CreateNewzSTRING(const char* str); zSTRING& operator=(char* str) { Assign(this, str); From 5dc57d3389130171b5cc57f4fc55bfb9f54942a5 Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Thu, 19 Jun 2025 20:04:52 +0200 Subject: [PATCH 05/11] Added Status-RestAPI and config --- MonitoringServer/CMakeLists.txt | 55 + MonitoringServer/src/IniData.h | 40 + MonitoringServer/src/main.cpp | 96 +- common/lib/cpp-httplib/README.txt | 1 + common/lib/cpp-httplib/httplib.h | 10562 +++++++++++++++++++ common/src/IniManager.cpp | 22 - common/src/IniManager.h | 31 - server/src/CommonStructures.h | 11 + server/src/IniData.h | 49 + server/src/Monitoring/MonitoringClient.cpp | 27 +- server/src/Monitoring/MonitoringClient.h | 15 +- server/src/ServerManager.cpp | 24 +- server/src/ServerManager.h | 6 +- server/src/main.cpp | 39 +- src/Models/IniData.h | 49 + src/dllmain.cpp | 10 +- 16 files changed, 10960 insertions(+), 77 deletions(-) create mode 100644 MonitoringServer/src/IniData.h create mode 100644 common/lib/cpp-httplib/README.txt create mode 100644 common/lib/cpp-httplib/httplib.h create mode 100644 server/src/IniData.h create mode 100644 src/Models/IniData.h diff --git a/MonitoringServer/CMakeLists.txt b/MonitoringServer/CMakeLists.txt index e69de29..c7be6d5 100644 --- a/MonitoringServer/CMakeLists.txt +++ b/MonitoringServer/CMakeLists.txt @@ -0,0 +1,55 @@ +cmake_minimum_required(VERSION 3.15) +project(MonitoringServer) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +if(WIN32) + # Windows 10 + add_definitions(-D_WIN32_WINNT=0x0A00) + + # ASIO-path + set(ASIO_INCLUDE_DIR "C:/Program Files (x86)/asio-1.34.2/include") + + # Crow-path + set(CMAKE_PREFIX_PATH "C:/Program Files (x86)/crow-install") +endif() + + +find_package(Crow REQUIRED) + +# Optional +# find_package(OpenSSL REQUIRED) +# find_package(ZLIB REQUIRED) + + +file(GLOB_RECURSE SOURCES CONFIGURE_DEPENDS + src/*.cpp + src/*.h + src/*.hpp +) + +# inih +set(INIH_SOURCES + ${CMAKE_SOURCE_DIR}/../common/lib/inih/ini.c +) + +# Automatisch alle .cpp-Dateien aus ../common/ einbinden +file(GLOB_RECURSE COMMON_SOURCES "../common/src/*.cpp") +list(APPEND SOURCES ${COMMON_SOURCES}) +include_directories("../common/src/") + +# --- Executable --- +add_executable(MonitoringServer ${SOURCES} ${INIH_SOURCES}) +target_include_directories(MonitoringServer PRIVATE src) + +# --- link Libraries --- +target_link_libraries(MonitoringServer + PRIVATE + Crow::Crow + # OpenSSL::SSL + # OpenSSL::Crypto + # ZLIB::ZLIB +) + +# install(TARGETS MonitoringServer DESTINATION bin) diff --git a/MonitoringServer/src/IniData.h b/MonitoringServer/src/IniData.h new file mode 100644 index 0000000..1486606 --- /dev/null +++ b/MonitoringServer/src/IniData.h @@ -0,0 +1,40 @@ +#pragma once + +#include +#include +#include + +class IniData { + public: + static constexpr char * CONFIG_FILE = "config.ini"; + + class Item + { + public: + static constexpr char * GENERAL_SERVER_IP = "General.server_ip"; + static constexpr char * GENERAL_SERVER_PORT = "General.server_port"; + }; + + static bool CreateConfigIfMissing(const std::string& path) // STATIC + { + writeConfig(path); + + if (std::filesystem::exists(path)) + return true; + + return false; + } + + private: + static void writeConfig(const std::string& path) + { + if (std::filesystem::exists(path)) + return; + + std::ofstream out(path); + out << "[General]\n"; + out << "server_ip = 127.0.0.1\n"; + out << "server_port = 18080\n\n"; + } + +}; \ No newline at end of file diff --git a/MonitoringServer/src/main.cpp b/MonitoringServer/src/main.cpp index 3c44e80..28866b0 100644 --- a/MonitoringServer/src/main.cpp +++ b/MonitoringServer/src/main.cpp @@ -1,9 +1,97 @@ +#include +#include +#include "../../common/src/IniManager.h" -// UDP-Server - receiving Server-Data from server. -// RestAPI(Crow) - offering Data received from UDP Server +#include "IniData.h" -int main() { +#include "crow.h" +//#include "crow_all.h" - return 0; +class IniManager; + +std::string ascii = R"( + ____ _____ ____ _____ __ __ _ _ + | _ \| ____/ ___|_ _| | \/ | ___ _ __ (_) |_ ___ _ __ + | |_) | _| \___ \ | | | |\/| |/ _ \| '_ \| | __/ _ \| '__| + | _ <| |___ ___) || | | | | | (_) | | | | | || (_) | | + |_| \_\_____|____/ |_| |_| |_|\___/|_| |_|_|\__\___/|_| +)"; + +std::mutex mtx_serverData; + +struct Ini { + std::string serverIp = "127.0.0.1"; + int serverPort = 18080; +} config; + +struct GothicServerData { + std::string status = "offline"; + int playerCount = 0; + +} serverData; + +Ini getConfigData(); + + +/*This RestAPI receives every 5 Seconds a Message from the GothicServer, if there is no answer for more than 7 Seconds, +this RestAPI-Sever answers with an Offline-Status. +*/ +int main() +{ + std::cout << ascii << "\n\n"; + Ini configData = getConfigData(); + + crow::SimpleApp app; //define your crow application + + auto lastResponse = std::chrono::high_resolution_clock::now(); + + // GET /status + CROW_ROUTE(app, "/status").methods("GET"_method)([&lastResponse] { + auto currentTime = std::chrono::high_resolution_clock::now(); + std::chrono::duration elapsed = currentTime - lastResponse; + int durrationInSec = static_cast(elapsed.count()/1000); + + crow::json::wvalue res; + if(durrationInSec > 7) { + res["status"] = "offline"; + res["playerCount"] = "0"; + } else { + std::lock_guard lock(mtx_serverData); + + res["status"] = serverData.status; + res["playerCount"] = std::to_string(serverData.playerCount); + } + return res; + }); + + // PUT /status + CROW_ROUTE(app, "/status").methods("PUT"_method)([&lastResponse](const crow::request& req) { + auto body = crow::json::load(req.body); + if (!body || !body.has("status")) { + return crow::response(400, "Missing 'status' field"); + } + lastResponse = std::chrono::high_resolution_clock::now(); + std::lock_guard lock(mtx_serverData); + serverData.status = body["status"].s(); + serverData.playerCount = body["playerCount"].i(); + + return crow::response(200, "Updated"); + }); + + app.port(18080).multithreaded().run(); +} + +Ini getConfigData() { + Ini ret; + // #### LOADIN INI #### + IniManager manager; + if(!IniData::CreateConfigIfMissing(IniData::CONFIG_FILE)) + return ret; + else + std::cout << "-- Config loaded --" << "\n"; + + ret.serverIp = manager.GetItem(IniData::CONFIG_FILE, IniData::Item::GENERAL_SERVER_IP); + ret.serverPort = std::stoi(manager.GetItem(IniData::CONFIG_FILE, IniData::Item::GENERAL_SERVER_PORT)); + return ret; } \ No newline at end of file diff --git a/common/lib/cpp-httplib/README.txt b/common/lib/cpp-httplib/README.txt new file mode 100644 index 0000000..b777ae8 --- /dev/null +++ b/common/lib/cpp-httplib/README.txt @@ -0,0 +1 @@ +https://github.com/yhirose/cpp-httplib \ No newline at end of file diff --git a/common/lib/cpp-httplib/httplib.h b/common/lib/cpp-httplib/httplib.h new file mode 100644 index 0000000..d9aa8f1 --- /dev/null +++ b/common/lib/cpp-httplib/httplib.h @@ -0,0 +1,10562 @@ +// +// httplib.h +// +// Copyright (c) 2025 Yuji Hirose. All rights reserved. +// MIT License +// + +#ifndef CPPHTTPLIB_HTTPLIB_H +#define CPPHTTPLIB_HTTPLIB_H + +#define CPPHTTPLIB_VERSION "0.21.0" + +/* + * Configuration + */ + +#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND +#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND +#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND 10000 +#endif + +#ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT +#define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 100 +#endif + +#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND +#define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300 +#endif + +#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND +#define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND +#define CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND +#define CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND +#define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND +#define CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND +#define CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND 300 +#endif + +#ifndef CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND +#define CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND +#define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND 5 +#endif + +#ifndef CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND +#define CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND 0 +#endif + +#ifndef CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND +#define CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND 0 +#endif + +#ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND +#define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0 +#endif + +#ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND +#ifdef _WIN32 +#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000 +#else +#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0 +#endif +#endif + +#ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH +#define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192 +#endif + +#ifndef CPPHTTPLIB_HEADER_MAX_LENGTH +#define CPPHTTPLIB_HEADER_MAX_LENGTH 8192 +#endif + +#ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT +#define CPPHTTPLIB_REDIRECT_MAX_COUNT 20 +#endif + +#ifndef CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT +#define CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT 1024 +#endif + +#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH +#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits::max)()) +#endif + +#ifndef CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH +#define CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH 8192 +#endif + +#ifndef CPPHTTPLIB_RANGE_MAX_COUNT +#define CPPHTTPLIB_RANGE_MAX_COUNT 1024 +#endif + +#ifndef CPPHTTPLIB_TCP_NODELAY +#define CPPHTTPLIB_TCP_NODELAY false +#endif + +#ifndef CPPHTTPLIB_IPV6_V6ONLY +#define CPPHTTPLIB_IPV6_V6ONLY false +#endif + +#ifndef CPPHTTPLIB_RECV_BUFSIZ +#define CPPHTTPLIB_RECV_BUFSIZ size_t(16384u) +#endif + +#ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ +#define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u) +#endif + +#ifndef CPPHTTPLIB_THREAD_POOL_COUNT +#define CPPHTTPLIB_THREAD_POOL_COUNT \ + ((std::max)(8u, std::thread::hardware_concurrency() > 0 \ + ? std::thread::hardware_concurrency() - 1 \ + : 0)) +#endif + +#ifndef CPPHTTPLIB_RECV_FLAGS +#define CPPHTTPLIB_RECV_FLAGS 0 +#endif + +#ifndef CPPHTTPLIB_SEND_FLAGS +#define CPPHTTPLIB_SEND_FLAGS 0 +#endif + +#ifndef CPPHTTPLIB_LISTEN_BACKLOG +#define CPPHTTPLIB_LISTEN_BACKLOG 5 +#endif + +#ifndef CPPHTTPLIB_MAX_LINE_LENGTH +#define CPPHTTPLIB_MAX_LINE_LENGTH 32768 +#endif + +/* + * Headers + */ + +#ifdef _WIN32 +#ifndef _CRT_SECURE_NO_WARNINGS +#define _CRT_SECURE_NO_WARNINGS +#endif //_CRT_SECURE_NO_WARNINGS + +#ifndef _CRT_NONSTDC_NO_DEPRECATE +#define _CRT_NONSTDC_NO_DEPRECATE +#endif //_CRT_NONSTDC_NO_DEPRECATE + +#if defined(_MSC_VER) +#if _MSC_VER < 1900 +#error Sorry, Visual Studio versions prior to 2015 are not supported +#endif + +#pragma comment(lib, "ws2_32.lib") + +#ifdef _WIN64 +using ssize_t = __int64; +#else +using ssize_t = long; +#endif +#endif // _MSC_VER + +#ifndef S_ISREG +#define S_ISREG(m) (((m) & S_IFREG) == S_IFREG) +#endif // S_ISREG + +#ifndef S_ISDIR +#define S_ISDIR(m) (((m) & S_IFDIR) == S_IFDIR) +#endif // S_ISDIR + +#ifndef NOMINMAX +#define NOMINMAX +#endif // NOMINMAX + +#include +#include +#include + +#if defined(__has_include) +#if __has_include() +// afunix.h uses types declared in winsock2.h, so has to be included after it. +#include +#define CPPHTTPLIB_HAVE_AFUNIX_H 1 +#endif +#endif + +#ifndef WSA_FLAG_NO_HANDLE_INHERIT +#define WSA_FLAG_NO_HANDLE_INHERIT 0x80 +#endif + +using nfds_t = unsigned long; +using socket_t = SOCKET; +using socklen_t = int; + +#else // not _WIN32 + +#include +#if !defined(_AIX) && !defined(__MVS__) +#include +#endif +#ifdef __MVS__ +#include +#ifndef NI_MAXHOST +#define NI_MAXHOST 1025 +#endif +#endif +#include +#include +#include +#ifdef __linux__ +#include +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +using socket_t = int; +#ifndef INVALID_SOCKET +#define INVALID_SOCKET (-1) +#endif +#endif //_WIN32 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +#ifdef _WIN32 +#include + +// these are defined in wincrypt.h and it breaks compilation if BoringSSL is +// used +#undef X509_NAME +#undef X509_CERT_PAIR +#undef X509_EXTENSIONS +#undef PKCS7_SIGNER_INFO + +#ifdef _MSC_VER +#pragma comment(lib, "crypt32.lib") +#endif +#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__) +#include +#if TARGET_OS_OSX +#include +#include +#endif // TARGET_OS_OSX +#endif // _WIN32 + +#include +#include +#include +#include + +#if defined(_WIN32) && defined(OPENSSL_USE_APPLINK) +#include +#endif + +#include +#include + +#if defined(OPENSSL_IS_BORINGSSL) || defined(LIBRESSL_VERSION_NUMBER) +#if OPENSSL_VERSION_NUMBER < 0x1010107f +#error Please use OpenSSL or a current version of BoringSSL +#endif +#define SSL_get1_peer_certificate SSL_get_peer_certificate +#elif OPENSSL_VERSION_NUMBER < 0x30000000L +#error Sorry, OpenSSL versions prior to 3.0.0 are not supported +#endif + +#endif + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT +#include +#endif + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT +#include +#include +#endif + +#ifdef CPPHTTPLIB_ZSTD_SUPPORT +#include +#endif + +/* + * Declaration + */ +namespace httplib { + +namespace detail { + +/* + * Backport std::make_unique from C++14. + * + * NOTE: This code came up with the following stackoverflow post: + * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique + * + */ + +template +typename std::enable_if::value, std::unique_ptr>::type +make_unique(Args &&...args) { + return std::unique_ptr(new T(std::forward(args)...)); +} + +template +typename std::enable_if::value, std::unique_ptr>::type +make_unique(std::size_t n) { + typedef typename std::remove_extent::type RT; + return std::unique_ptr(new RT[n]); +} + +namespace case_ignore { + +inline unsigned char to_lower(int c) { + const static unsigned char table[256] = { + 0, 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, 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, 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, 224, 225, 226, + 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, + 242, 243, 244, 245, 246, 215, 248, 249, 250, 251, 252, 253, 254, 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, + }; + return table[(unsigned char)(char)c]; +} + +inline bool equal(const std::string &a, const std::string &b) { + return a.size() == b.size() && + std::equal(a.begin(), a.end(), b.begin(), [](char ca, char cb) { + return to_lower(ca) == to_lower(cb); + }); +} + +struct equal_to { + bool operator()(const std::string &a, const std::string &b) const { + return equal(a, b); + } +}; + +struct hash { + size_t operator()(const std::string &key) const { + return hash_core(key.data(), key.size(), 0); + } + + size_t hash_core(const char *s, size_t l, size_t h) const { + return (l == 0) ? h + : hash_core(s + 1, l - 1, + // Unsets the 6 high bits of h, therefore no + // overflow happens + (((std::numeric_limits::max)() >> 6) & + h * 33) ^ + static_cast(to_lower(*s))); + } +}; + +} // namespace case_ignore + +// This is based on +// "http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4189". + +struct scope_exit { + explicit scope_exit(std::function &&f) + : exit_function(std::move(f)), execute_on_destruction{true} {} + + scope_exit(scope_exit &&rhs) noexcept + : exit_function(std::move(rhs.exit_function)), + execute_on_destruction{rhs.execute_on_destruction} { + rhs.release(); + } + + ~scope_exit() { + if (execute_on_destruction) { this->exit_function(); } + } + + void release() { this->execute_on_destruction = false; } + +private: + scope_exit(const scope_exit &) = delete; + void operator=(const scope_exit &) = delete; + scope_exit &operator=(scope_exit &&) = delete; + + std::function exit_function; + bool execute_on_destruction; +}; + +} // namespace detail + +enum SSLVerifierResponse { + // no decision has been made, use the built-in certificate verifier + NoDecisionMade, + // connection certificate is verified and accepted + CertificateAccepted, + // connection certificate was processed but is rejected + CertificateRejected +}; + +enum StatusCode { + // Information responses + Continue_100 = 100, + SwitchingProtocol_101 = 101, + Processing_102 = 102, + EarlyHints_103 = 103, + + // Successful responses + OK_200 = 200, + Created_201 = 201, + Accepted_202 = 202, + NonAuthoritativeInformation_203 = 203, + NoContent_204 = 204, + ResetContent_205 = 205, + PartialContent_206 = 206, + MultiStatus_207 = 207, + AlreadyReported_208 = 208, + IMUsed_226 = 226, + + // Redirection messages + MultipleChoices_300 = 300, + MovedPermanently_301 = 301, + Found_302 = 302, + SeeOther_303 = 303, + NotModified_304 = 304, + UseProxy_305 = 305, + unused_306 = 306, + TemporaryRedirect_307 = 307, + PermanentRedirect_308 = 308, + + // Client error responses + BadRequest_400 = 400, + Unauthorized_401 = 401, + PaymentRequired_402 = 402, + Forbidden_403 = 403, + NotFound_404 = 404, + MethodNotAllowed_405 = 405, + NotAcceptable_406 = 406, + ProxyAuthenticationRequired_407 = 407, + RequestTimeout_408 = 408, + Conflict_409 = 409, + Gone_410 = 410, + LengthRequired_411 = 411, + PreconditionFailed_412 = 412, + PayloadTooLarge_413 = 413, + UriTooLong_414 = 414, + UnsupportedMediaType_415 = 415, + RangeNotSatisfiable_416 = 416, + ExpectationFailed_417 = 417, + ImATeapot_418 = 418, + MisdirectedRequest_421 = 421, + UnprocessableContent_422 = 422, + Locked_423 = 423, + FailedDependency_424 = 424, + TooEarly_425 = 425, + UpgradeRequired_426 = 426, + PreconditionRequired_428 = 428, + TooManyRequests_429 = 429, + RequestHeaderFieldsTooLarge_431 = 431, + UnavailableForLegalReasons_451 = 451, + + // Server error responses + InternalServerError_500 = 500, + NotImplemented_501 = 501, + BadGateway_502 = 502, + ServiceUnavailable_503 = 503, + GatewayTimeout_504 = 504, + HttpVersionNotSupported_505 = 505, + VariantAlsoNegotiates_506 = 506, + InsufficientStorage_507 = 507, + LoopDetected_508 = 508, + NotExtended_510 = 510, + NetworkAuthenticationRequired_511 = 511, +}; + +using Headers = + std::unordered_multimap; + +using Params = std::multimap; +using Match = std::smatch; + +using Progress = std::function; + +struct Response; +using ResponseHandler = std::function; + +struct MultipartFormData { + std::string name; + std::string content; + std::string filename; + std::string content_type; + Headers headers; +}; +using MultipartFormDataItems = std::vector; +using MultipartFormDataMap = std::multimap; + +class DataSink { +public: + DataSink() : os(&sb_), sb_(*this) {} + + DataSink(const DataSink &) = delete; + DataSink &operator=(const DataSink &) = delete; + DataSink(DataSink &&) = delete; + DataSink &operator=(DataSink &&) = delete; + + std::function write; + std::function is_writable; + std::function done; + std::function done_with_trailer; + std::ostream os; + +private: + class data_sink_streambuf final : public std::streambuf { + public: + explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {} + + protected: + std::streamsize xsputn(const char *s, std::streamsize n) override { + sink_.write(s, static_cast(n)); + return n; + } + + private: + DataSink &sink_; + }; + + data_sink_streambuf sb_; +}; + +using ContentProvider = + std::function; + +using ContentProviderWithoutLength = + std::function; + +using ContentProviderResourceReleaser = std::function; + +struct MultipartFormDataProvider { + std::string name; + ContentProviderWithoutLength provider; + std::string filename; + std::string content_type; +}; +using MultipartFormDataProviderItems = std::vector; + +using ContentReceiverWithProgress = + std::function; + +using ContentReceiver = + std::function; + +using MultipartContentHeader = + std::function; + +class ContentReader { +public: + using Reader = std::function; + using MultipartReader = std::function; + + ContentReader(Reader reader, MultipartReader multipart_reader) + : reader_(std::move(reader)), + multipart_reader_(std::move(multipart_reader)) {} + + bool operator()(MultipartContentHeader header, + ContentReceiver receiver) const { + return multipart_reader_(std::move(header), std::move(receiver)); + } + + bool operator()(ContentReceiver receiver) const { + return reader_(std::move(receiver)); + } + + Reader reader_; + MultipartReader multipart_reader_; +}; + +using Range = std::pair; +using Ranges = std::vector; + +struct Request { + std::string method; + std::string path; + std::string matched_route; + Params params; + Headers headers; + std::string body; + + std::string remote_addr; + int remote_port = -1; + std::string local_addr; + int local_port = -1; + + // for server + std::string version; + std::string target; + MultipartFormDataMap files; + Ranges ranges; + Match matches; + std::unordered_map path_params; + std::function is_connection_closed = []() { return true; }; + + // for client + ResponseHandler response_handler; + ContentReceiverWithProgress content_receiver; + Progress progress; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + const SSL *ssl = nullptr; +#endif + + bool has_header(const std::string &key) const; + std::string get_header_value(const std::string &key, const char *def = "", + size_t id = 0) const; + uint64_t get_header_value_u64(const std::string &key, uint64_t def = 0, + size_t id = 0) const; + size_t get_header_value_count(const std::string &key) const; + void set_header(const std::string &key, const std::string &val); + + bool has_param(const std::string &key) const; + std::string get_param_value(const std::string &key, size_t id = 0) const; + size_t get_param_value_count(const std::string &key) const; + + bool is_multipart_form_data() const; + + bool has_file(const std::string &key) const; + MultipartFormData get_file_value(const std::string &key) const; + std::vector get_file_values(const std::string &key) const; + + // private members... + size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT; + size_t content_length_ = 0; + ContentProvider content_provider_; + bool is_chunked_content_provider_ = false; + size_t authorization_count_ = 0; + std::chrono::time_point start_time_ = + (std::chrono::steady_clock::time_point::min)(); +}; + +struct Response { + std::string version; + int status = -1; + std::string reason; + Headers headers; + std::string body; + std::string location; // Redirect location + + bool has_header(const std::string &key) const; + std::string get_header_value(const std::string &key, const char *def = "", + size_t id = 0) const; + uint64_t get_header_value_u64(const std::string &key, uint64_t def = 0, + size_t id = 0) const; + size_t get_header_value_count(const std::string &key) const; + void set_header(const std::string &key, const std::string &val); + + void set_redirect(const std::string &url, int status = StatusCode::Found_302); + void set_content(const char *s, size_t n, const std::string &content_type); + void set_content(const std::string &s, const std::string &content_type); + void set_content(std::string &&s, const std::string &content_type); + + void set_content_provider( + size_t length, const std::string &content_type, ContentProvider provider, + ContentProviderResourceReleaser resource_releaser = nullptr); + + void set_content_provider( + const std::string &content_type, ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser = nullptr); + + void set_chunked_content_provider( + const std::string &content_type, ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser = nullptr); + + void set_file_content(const std::string &path, + const std::string &content_type); + void set_file_content(const std::string &path); + + Response() = default; + Response(const Response &) = default; + Response &operator=(const Response &) = default; + Response(Response &&) = default; + Response &operator=(Response &&) = default; + ~Response() { + if (content_provider_resource_releaser_) { + content_provider_resource_releaser_(content_provider_success_); + } + } + + // private members... + size_t content_length_ = 0; + ContentProvider content_provider_; + ContentProviderResourceReleaser content_provider_resource_releaser_; + bool is_chunked_content_provider_ = false; + bool content_provider_success_ = false; + std::string file_content_path_; + std::string file_content_content_type_; +}; + +class Stream { +public: + virtual ~Stream() = default; + + virtual bool is_readable() const = 0; + virtual bool wait_readable() const = 0; + virtual bool wait_writable() const = 0; + + virtual ssize_t read(char *ptr, size_t size) = 0; + virtual ssize_t write(const char *ptr, size_t size) = 0; + virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0; + virtual void get_local_ip_and_port(std::string &ip, int &port) const = 0; + virtual socket_t socket() const = 0; + + virtual time_t duration() const = 0; + + ssize_t write(const char *ptr); + ssize_t write(const std::string &s); +}; + +class TaskQueue { +public: + TaskQueue() = default; + virtual ~TaskQueue() = default; + + virtual bool enqueue(std::function fn) = 0; + virtual void shutdown() = 0; + + virtual void on_idle() {} +}; + +class ThreadPool final : public TaskQueue { +public: + explicit ThreadPool(size_t n, size_t mqr = 0) + : shutdown_(false), max_queued_requests_(mqr) { + while (n) { + threads_.emplace_back(worker(*this)); + n--; + } + } + + ThreadPool(const ThreadPool &) = delete; + ~ThreadPool() override = default; + + bool enqueue(std::function fn) override { + { + std::unique_lock lock(mutex_); + if (max_queued_requests_ > 0 && jobs_.size() >= max_queued_requests_) { + return false; + } + jobs_.push_back(std::move(fn)); + } + + cond_.notify_one(); + return true; + } + + void shutdown() override { + // Stop all worker threads... + { + std::unique_lock lock(mutex_); + shutdown_ = true; + } + + cond_.notify_all(); + + // Join... + for (auto &t : threads_) { + t.join(); + } + } + +private: + struct worker { + explicit worker(ThreadPool &pool) : pool_(pool) {} + + void operator()() { + for (;;) { + std::function fn; + { + std::unique_lock lock(pool_.mutex_); + + pool_.cond_.wait( + lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; }); + + if (pool_.shutdown_ && pool_.jobs_.empty()) { break; } + + fn = pool_.jobs_.front(); + pool_.jobs_.pop_front(); + } + + assert(true == static_cast(fn)); + fn(); + } + +#if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(OPENSSL_IS_BORINGSSL) && \ + !defined(LIBRESSL_VERSION_NUMBER) + OPENSSL_thread_stop(); +#endif + } + + ThreadPool &pool_; + }; + friend struct worker; + + std::vector threads_; + std::list> jobs_; + + bool shutdown_; + size_t max_queued_requests_ = 0; + + std::condition_variable cond_; + std::mutex mutex_; +}; + +using Logger = std::function; + +using SocketOptions = std::function; + +namespace detail { + +bool set_socket_opt_impl(socket_t sock, int level, int optname, + const void *optval, socklen_t optlen); +bool set_socket_opt(socket_t sock, int level, int optname, int opt); +bool set_socket_opt_time(socket_t sock, int level, int optname, time_t sec, + time_t usec); + +} // namespace detail + +void default_socket_options(socket_t sock); + +const char *status_message(int status); + +std::string get_bearer_token_auth(const Request &req); + +namespace detail { + +class MatcherBase { +public: + MatcherBase(std::string pattern) : pattern_(pattern) {} + virtual ~MatcherBase() = default; + + const std::string &pattern() const { return pattern_; } + + // Match request path and populate its matches and + virtual bool match(Request &request) const = 0; + +private: + std::string pattern_; +}; + +/** + * Captures parameters in request path and stores them in Request::path_params + * + * Capture name is a substring of a pattern from : to /. + * The rest of the pattern is matched against the request path directly + * Parameters are captured starting from the next character after + * the end of the last matched static pattern fragment until the next /. + * + * Example pattern: + * "/path/fragments/:capture/more/fragments/:second_capture" + * Static fragments: + * "/path/fragments/", "more/fragments/" + * + * Given the following request path: + * "/path/fragments/:1/more/fragments/:2" + * the resulting capture will be + * {{"capture", "1"}, {"second_capture", "2"}} + */ +class PathParamsMatcher final : public MatcherBase { +public: + PathParamsMatcher(const std::string &pattern); + + bool match(Request &request) const override; + +private: + // Treat segment separators as the end of path parameter capture + // Does not need to handle query parameters as they are parsed before path + // matching + static constexpr char separator = '/'; + + // Contains static path fragments to match against, excluding the '/' after + // path params + // Fragments are separated by path params + std::vector static_fragments_; + // Stores the names of the path parameters to be used as keys in the + // Request::path_params map + std::vector param_names_; +}; + +/** + * Performs std::regex_match on request path + * and stores the result in Request::matches + * + * Note that regex match is performed directly on the whole request. + * This means that wildcard patterns may match multiple path segments with /: + * "/begin/(.*)/end" will match both "/begin/middle/end" and "/begin/1/2/end". + */ +class RegexMatcher final : public MatcherBase { +public: + RegexMatcher(const std::string &pattern) + : MatcherBase(pattern), regex_(pattern) {} + + bool match(Request &request) const override; + +private: + std::regex regex_; +}; + +ssize_t write_headers(Stream &strm, const Headers &headers); + +} // namespace detail + +class Server { +public: + using Handler = std::function; + + using ExceptionHandler = + std::function; + + enum class HandlerResponse { + Handled, + Unhandled, + }; + using HandlerWithResponse = + std::function; + + using HandlerWithContentReader = std::function; + + using Expect100ContinueHandler = + std::function; + + Server(); + + virtual ~Server(); + + virtual bool is_valid() const; + + Server &Get(const std::string &pattern, Handler handler); + Server &Post(const std::string &pattern, Handler handler); + Server &Post(const std::string &pattern, HandlerWithContentReader handler); + Server &Put(const std::string &pattern, Handler handler); + Server &Put(const std::string &pattern, HandlerWithContentReader handler); + Server &Patch(const std::string &pattern, Handler handler); + Server &Patch(const std::string &pattern, HandlerWithContentReader handler); + Server &Delete(const std::string &pattern, Handler handler); + Server &Delete(const std::string &pattern, HandlerWithContentReader handler); + Server &Options(const std::string &pattern, Handler handler); + + bool set_base_dir(const std::string &dir, + const std::string &mount_point = std::string()); + bool set_mount_point(const std::string &mount_point, const std::string &dir, + Headers headers = Headers()); + bool remove_mount_point(const std::string &mount_point); + Server &set_file_extension_and_mimetype_mapping(const std::string &ext, + const std::string &mime); + Server &set_default_file_mimetype(const std::string &mime); + Server &set_file_request_handler(Handler handler); + + template + Server &set_error_handler(ErrorHandlerFunc &&handler) { + return set_error_handler_core( + std::forward(handler), + std::is_convertible{}); + } + + Server &set_exception_handler(ExceptionHandler handler); + + Server &set_pre_routing_handler(HandlerWithResponse handler); + Server &set_post_routing_handler(Handler handler); + + Server &set_pre_request_handler(HandlerWithResponse handler); + + Server &set_expect_100_continue_handler(Expect100ContinueHandler handler); + Server &set_logger(Logger logger); + + Server &set_address_family(int family); + Server &set_tcp_nodelay(bool on); + Server &set_ipv6_v6only(bool on); + Server &set_socket_options(SocketOptions socket_options); + + Server &set_default_headers(Headers headers); + Server & + set_header_writer(std::function const &writer); + + Server &set_keep_alive_max_count(size_t count); + Server &set_keep_alive_timeout(time_t sec); + + Server &set_read_timeout(time_t sec, time_t usec = 0); + template + Server &set_read_timeout(const std::chrono::duration &duration); + + Server &set_write_timeout(time_t sec, time_t usec = 0); + template + Server &set_write_timeout(const std::chrono::duration &duration); + + Server &set_idle_interval(time_t sec, time_t usec = 0); + template + Server &set_idle_interval(const std::chrono::duration &duration); + + Server &set_payload_max_length(size_t length); + + bool bind_to_port(const std::string &host, int port, int socket_flags = 0); + int bind_to_any_port(const std::string &host, int socket_flags = 0); + bool listen_after_bind(); + + bool listen(const std::string &host, int port, int socket_flags = 0); + + bool is_running() const; + void wait_until_ready() const; + void stop(); + void decommission(); + + std::function new_task_queue; + +protected: + bool process_request(Stream &strm, const std::string &remote_addr, + int remote_port, const std::string &local_addr, + int local_port, bool close_connection, + bool &connection_closed, + const std::function &setup_request); + + std::atomic svr_sock_{INVALID_SOCKET}; + size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT; + time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND; + time_t read_timeout_sec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_SECOND; + time_t read_timeout_usec_ = CPPHTTPLIB_SERVER_READ_TIMEOUT_USECOND; + time_t write_timeout_sec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_SECOND; + time_t write_timeout_usec_ = CPPHTTPLIB_SERVER_WRITE_TIMEOUT_USECOND; + time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND; + time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND; + size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH; + +private: + using Handlers = + std::vector, Handler>>; + using HandlersForContentReader = + std::vector, + HandlerWithContentReader>>; + + static std::unique_ptr + make_matcher(const std::string &pattern); + + Server &set_error_handler_core(HandlerWithResponse handler, std::true_type); + Server &set_error_handler_core(Handler handler, std::false_type); + + socket_t create_server_socket(const std::string &host, int port, + int socket_flags, + SocketOptions socket_options) const; + int bind_internal(const std::string &host, int port, int socket_flags); + bool listen_internal(); + + bool routing(Request &req, Response &res, Stream &strm); + bool handle_file_request(const Request &req, Response &res); + bool dispatch_request(Request &req, Response &res, + const Handlers &handlers) const; + bool dispatch_request_for_content_reader( + Request &req, Response &res, ContentReader content_reader, + const HandlersForContentReader &handlers) const; + + bool parse_request_line(const char *s, Request &req) const; + void apply_ranges(const Request &req, Response &res, + std::string &content_type, std::string &boundary) const; + bool write_response(Stream &strm, bool close_connection, Request &req, + Response &res); + bool write_response_with_content(Stream &strm, bool close_connection, + const Request &req, Response &res); + bool write_response_core(Stream &strm, bool close_connection, + const Request &req, Response &res, + bool need_apply_ranges); + bool write_content_with_provider(Stream &strm, const Request &req, + Response &res, const std::string &boundary, + const std::string &content_type); + bool read_content(Stream &strm, Request &req, Response &res); + bool + read_content_with_content_receiver(Stream &strm, Request &req, Response &res, + ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver); + bool read_content_core(Stream &strm, Request &req, Response &res, + ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver) const; + + virtual bool process_and_close_socket(socket_t sock); + + std::atomic is_running_{false}; + std::atomic is_decommissioned{false}; + + struct MountPointEntry { + std::string mount_point; + std::string base_dir; + Headers headers; + }; + std::vector base_dirs_; + std::map file_extension_and_mimetype_map_; + std::string default_file_mimetype_ = "application/octet-stream"; + Handler file_request_handler_; + + Handlers get_handlers_; + Handlers post_handlers_; + HandlersForContentReader post_handlers_for_content_reader_; + Handlers put_handlers_; + HandlersForContentReader put_handlers_for_content_reader_; + Handlers patch_handlers_; + HandlersForContentReader patch_handlers_for_content_reader_; + Handlers delete_handlers_; + HandlersForContentReader delete_handlers_for_content_reader_; + Handlers options_handlers_; + + HandlerWithResponse error_handler_; + ExceptionHandler exception_handler_; + HandlerWithResponse pre_routing_handler_; + Handler post_routing_handler_; + HandlerWithResponse pre_request_handler_; + Expect100ContinueHandler expect_100_continue_handler_; + + Logger logger_; + + int address_family_ = AF_UNSPEC; + bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; + bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY; + SocketOptions socket_options_ = default_socket_options; + + Headers default_headers_; + std::function header_writer_ = + detail::write_headers; +}; + +enum class Error { + Success = 0, + Unknown, + Connection, + BindIPAddress, + Read, + Write, + ExceedRedirectCount, + Canceled, + SSLConnection, + SSLLoadingCerts, + SSLServerVerification, + SSLServerHostnameVerification, + UnsupportedMultipartBoundaryChars, + Compression, + ConnectionTimeout, + ProxyConnection, + + // For internal use only + SSLPeerCouldBeClosed_, +}; + +std::string to_string(Error error); + +std::ostream &operator<<(std::ostream &os, const Error &obj); + +class Result { +public: + Result() = default; + Result(std::unique_ptr &&res, Error err, + Headers &&request_headers = Headers{}) + : res_(std::move(res)), err_(err), + request_headers_(std::move(request_headers)) {} + // Response + operator bool() const { return res_ != nullptr; } + bool operator==(std::nullptr_t) const { return res_ == nullptr; } + bool operator!=(std::nullptr_t) const { return res_ != nullptr; } + const Response &value() const { return *res_; } + Response &value() { return *res_; } + const Response &operator*() const { return *res_; } + Response &operator*() { return *res_; } + const Response *operator->() const { return res_.get(); } + Response *operator->() { return res_.get(); } + + // Error + Error error() const { return err_; } + + // Request Headers + bool has_request_header(const std::string &key) const; + std::string get_request_header_value(const std::string &key, + const char *def = "", + size_t id = 0) const; + uint64_t get_request_header_value_u64(const std::string &key, + uint64_t def = 0, size_t id = 0) const; + size_t get_request_header_value_count(const std::string &key) const; + +private: + std::unique_ptr res_; + Error err_ = Error::Unknown; + Headers request_headers_; +}; + +class ClientImpl { +public: + explicit ClientImpl(const std::string &host); + + explicit ClientImpl(const std::string &host, int port); + + explicit ClientImpl(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path); + + virtual ~ClientImpl(); + + virtual bool is_valid() const; + + Result Get(const std::string &path); + Result Get(const std::string &path, const Headers &headers); + Result Get(const std::string &path, Progress progress); + Result Get(const std::string &path, const Headers &headers, + Progress progress); + Result Get(const std::string &path, ContentReceiver content_receiver); + Result Get(const std::string &path, const Headers &headers, + ContentReceiver content_receiver); + Result Get(const std::string &path, ContentReceiver content_receiver, + Progress progress); + Result Get(const std::string &path, const Headers &headers, + ContentReceiver content_receiver, Progress progress); + Result Get(const std::string &path, ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const std::string &path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const std::string &path, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress); + Result Get(const std::string &path, const Headers &headers, + ResponseHandler response_handler, ContentReceiver content_receiver, + Progress progress); + + Result Get(const std::string &path, const Params ¶ms, + const Headers &headers, Progress progress = nullptr); + Result Get(const std::string &path, const Params ¶ms, + const Headers &headers, ContentReceiver content_receiver, + Progress progress = nullptr); + Result Get(const std::string &path, const Params ¶ms, + const Headers &headers, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress = nullptr); + + Result Head(const std::string &path); + Result Head(const std::string &path, const Headers &headers); + + Result Post(const std::string &path); + Result Post(const std::string &path, const Headers &headers); + Result Post(const std::string &path, const char *body, size_t content_length, + const std::string &content_type); + Result Post(const std::string &path, const Headers &headers, const char *body, + size_t content_length, const std::string &content_type); + Result Post(const std::string &path, const Headers &headers, const char *body, + size_t content_length, const std::string &content_type, + Progress progress); + Result Post(const std::string &path, const std::string &body, + const std::string &content_type); + Result Post(const std::string &path, const std::string &body, + const std::string &content_type, Progress progress); + Result Post(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type); + Result Post(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type, + Progress progress); + Result Post(const std::string &path, size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Post(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Post(const std::string &path, const Headers &headers, + size_t content_length, ContentProvider content_provider, + const std::string &content_type); + Result Post(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Post(const std::string &path, const Params ¶ms); + Result Post(const std::string &path, const Headers &headers, + const Params ¶ms); + Result Post(const std::string &path, const Headers &headers, + const Params ¶ms, Progress progress); + Result Post(const std::string &path, const MultipartFormDataItems &items); + Result Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items); + Result Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, const std::string &boundary); + Result Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items); + + Result Put(const std::string &path); + Result Put(const std::string &path, const char *body, size_t content_length, + const std::string &content_type); + Result Put(const std::string &path, const Headers &headers, const char *body, + size_t content_length, const std::string &content_type); + Result Put(const std::string &path, const Headers &headers, const char *body, + size_t content_length, const std::string &content_type, + Progress progress); + Result Put(const std::string &path, const std::string &body, + const std::string &content_type); + Result Put(const std::string &path, const std::string &body, + const std::string &content_type, Progress progress); + Result Put(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type); + Result Put(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type, + Progress progress); + Result Put(const std::string &path, size_t content_length, + ContentProvider content_provider, const std::string &content_type); + Result Put(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Put(const std::string &path, const Headers &headers, + size_t content_length, ContentProvider content_provider, + const std::string &content_type); + Result Put(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Put(const std::string &path, const Params ¶ms); + Result Put(const std::string &path, const Headers &headers, + const Params ¶ms); + Result Put(const std::string &path, const Headers &headers, + const Params ¶ms, Progress progress); + Result Put(const std::string &path, const MultipartFormDataItems &items); + Result Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items); + Result Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, const std::string &boundary); + Result Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items); + + Result Patch(const std::string &path); + Result Patch(const std::string &path, const char *body, size_t content_length, + const std::string &content_type); + Result Patch(const std::string &path, const char *body, size_t content_length, + const std::string &content_type, Progress progress); + Result Patch(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type); + Result Patch(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, Progress progress); + Result Patch(const std::string &path, const std::string &body, + const std::string &content_type); + Result Patch(const std::string &path, const std::string &body, + const std::string &content_type, Progress progress); + Result Patch(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type); + Result Patch(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type, + Progress progress); + Result Patch(const std::string &path, size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Patch(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Patch(const std::string &path, const Headers &headers, + size_t content_length, ContentProvider content_provider, + const std::string &content_type); + Result Patch(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + + Result Delete(const std::string &path); + Result Delete(const std::string &path, const Headers &headers); + Result Delete(const std::string &path, const char *body, + size_t content_length, const std::string &content_type); + Result Delete(const std::string &path, const char *body, + size_t content_length, const std::string &content_type, + Progress progress); + Result Delete(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type); + Result Delete(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, Progress progress); + Result Delete(const std::string &path, const std::string &body, + const std::string &content_type); + Result Delete(const std::string &path, const std::string &body, + const std::string &content_type, Progress progress); + Result Delete(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type); + Result Delete(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type, + Progress progress); + + Result Options(const std::string &path); + Result Options(const std::string &path, const Headers &headers); + + bool send(Request &req, Response &res, Error &error); + Result send(const Request &req); + + void stop(); + + std::string host() const; + int port() const; + + size_t is_socket_open() const; + socket_t socket() const; + + void set_hostname_addr_map(std::map addr_map); + + void set_default_headers(Headers headers); + + void + set_header_writer(std::function const &writer); + + void set_address_family(int family); + void set_tcp_nodelay(bool on); + void set_ipv6_v6only(bool on); + void set_socket_options(SocketOptions socket_options); + + void set_connection_timeout(time_t sec, time_t usec = 0); + template + void + set_connection_timeout(const std::chrono::duration &duration); + + void set_read_timeout(time_t sec, time_t usec = 0); + template + void set_read_timeout(const std::chrono::duration &duration); + + void set_write_timeout(time_t sec, time_t usec = 0); + template + void set_write_timeout(const std::chrono::duration &duration); + + void set_max_timeout(time_t msec); + template + void set_max_timeout(const std::chrono::duration &duration); + + void set_basic_auth(const std::string &username, const std::string &password); + void set_bearer_token_auth(const std::string &token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_digest_auth(const std::string &username, + const std::string &password); +#endif + + void set_keep_alive(bool on); + void set_follow_location(bool on); + + void set_url_encode(bool on); + + void set_compress(bool on); + + void set_decompress(bool on); + + void set_interface(const std::string &intf); + + void set_proxy(const std::string &host, int port); + void set_proxy_basic_auth(const std::string &username, + const std::string &password); + void set_proxy_bearer_token_auth(const std::string &token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_proxy_digest_auth(const std::string &username, + const std::string &password); +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_ca_cert_path(const std::string &ca_cert_file_path, + const std::string &ca_cert_dir_path = std::string()); + void set_ca_cert_store(X509_STORE *ca_cert_store); + X509_STORE *create_ca_cert_store(const char *ca_cert, std::size_t size) const; +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void enable_server_certificate_verification(bool enabled); + void enable_server_hostname_verification(bool enabled); + void set_server_certificate_verifier( + std::function verifier); +#endif + + void set_logger(Logger logger); + +protected: + struct Socket { + socket_t sock = INVALID_SOCKET; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + SSL *ssl = nullptr; +#endif + + bool is_open() const { return sock != INVALID_SOCKET; } + }; + + virtual bool create_and_connect_socket(Socket &socket, Error &error); + + // All of: + // shutdown_ssl + // shutdown_socket + // close_socket + // should ONLY be called when socket_mutex_ is locked. + // Also, shutdown_ssl and close_socket should also NOT be called concurrently + // with a DIFFERENT thread sending requests using that socket. + virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully); + void shutdown_socket(Socket &socket) const; + void close_socket(Socket &socket); + + bool process_request(Stream &strm, Request &req, Response &res, + bool close_connection, Error &error); + + bool write_content_with_provider(Stream &strm, const Request &req, + Error &error) const; + + void copy_settings(const ClientImpl &rhs); + + // Socket endpoint information + const std::string host_; + const int port_; + const std::string host_and_port_; + + // Current open socket + Socket socket_; + mutable std::mutex socket_mutex_; + std::recursive_mutex request_mutex_; + + // These are all protected under socket_mutex + size_t socket_requests_in_flight_ = 0; + std::thread::id socket_requests_are_from_thread_ = std::thread::id(); + bool socket_should_be_closed_when_request_is_done_ = false; + + // Hostname-IP map + std::map addr_map_; + + // Default headers + Headers default_headers_; + + // Header writer + std::function header_writer_ = + detail::write_headers; + + // Settings + std::string client_cert_path_; + std::string client_key_path_; + + time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND; + time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND; + time_t read_timeout_sec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_SECOND; + time_t read_timeout_usec_ = CPPHTTPLIB_CLIENT_READ_TIMEOUT_USECOND; + time_t write_timeout_sec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_SECOND; + time_t write_timeout_usec_ = CPPHTTPLIB_CLIENT_WRITE_TIMEOUT_USECOND; + time_t max_timeout_msec_ = CPPHTTPLIB_CLIENT_MAX_TIMEOUT_MSECOND; + + std::string basic_auth_username_; + std::string basic_auth_password_; + std::string bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + std::string digest_auth_username_; + std::string digest_auth_password_; +#endif + + bool keep_alive_ = false; + bool follow_location_ = false; + + bool url_encode_ = true; + + int address_family_ = AF_UNSPEC; + bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY; + bool ipv6_v6only_ = CPPHTTPLIB_IPV6_V6ONLY; + SocketOptions socket_options_ = nullptr; + + bool compress_ = false; + bool decompress_ = true; + + std::string interface_; + + std::string proxy_host_; + int proxy_port_ = -1; + + std::string proxy_basic_auth_username_; + std::string proxy_basic_auth_password_; + std::string proxy_bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + std::string proxy_digest_auth_username_; + std::string proxy_digest_auth_password_; +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + std::string ca_cert_file_path_; + std::string ca_cert_dir_path_; + + X509_STORE *ca_cert_store_ = nullptr; +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + bool server_certificate_verification_ = true; + bool server_hostname_verification_ = true; + std::function server_certificate_verifier_; +#endif + + Logger logger_; + +private: + bool send_(Request &req, Response &res, Error &error); + Result send_(Request &&req); + + socket_t create_client_socket(Error &error) const; + bool read_response_line(Stream &strm, const Request &req, + Response &res) const; + bool write_request(Stream &strm, Request &req, bool close_connection, + Error &error); + bool redirect(Request &req, Response &res, Error &error); + bool handle_request(Stream &strm, Request &req, Response &res, + bool close_connection, Error &error); + std::unique_ptr send_with_content_provider( + Request &req, const char *body, size_t content_length, + ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string &content_type, Error &error); + Result send_with_content_provider( + const std::string &method, const std::string &path, + const Headers &headers, const char *body, size_t content_length, + ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string &content_type, Progress progress); + ContentProviderWithoutLength get_multipart_content_provider( + const std::string &boundary, const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items) const; + + std::string adjust_host_string(const std::string &host) const; + + virtual bool + process_socket(const Socket &socket, + std::chrono::time_point start_time, + std::function callback); + virtual bool is_ssl() const; +}; + +class Client { +public: + // Universal interface + explicit Client(const std::string &scheme_host_port); + + explicit Client(const std::string &scheme_host_port, + const std::string &client_cert_path, + const std::string &client_key_path); + + // HTTP only interface + explicit Client(const std::string &host, int port); + + explicit Client(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path); + + Client(Client &&) = default; + Client &operator=(Client &&) = default; + + ~Client(); + + bool is_valid() const; + + Result Get(const std::string &path); + Result Get(const std::string &path, const Headers &headers); + Result Get(const std::string &path, Progress progress); + Result Get(const std::string &path, const Headers &headers, + Progress progress); + Result Get(const std::string &path, ContentReceiver content_receiver); + Result Get(const std::string &path, const Headers &headers, + ContentReceiver content_receiver); + Result Get(const std::string &path, ContentReceiver content_receiver, + Progress progress); + Result Get(const std::string &path, const Headers &headers, + ContentReceiver content_receiver, Progress progress); + Result Get(const std::string &path, ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const std::string &path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver); + Result Get(const std::string &path, const Headers &headers, + ResponseHandler response_handler, ContentReceiver content_receiver, + Progress progress); + Result Get(const std::string &path, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress); + + Result Get(const std::string &path, const Params ¶ms, + const Headers &headers, Progress progress = nullptr); + Result Get(const std::string &path, const Params ¶ms, + const Headers &headers, ContentReceiver content_receiver, + Progress progress = nullptr); + Result Get(const std::string &path, const Params ¶ms, + const Headers &headers, ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress = nullptr); + + Result Head(const std::string &path); + Result Head(const std::string &path, const Headers &headers); + + Result Post(const std::string &path); + Result Post(const std::string &path, const Headers &headers); + Result Post(const std::string &path, const char *body, size_t content_length, + const std::string &content_type); + Result Post(const std::string &path, const Headers &headers, const char *body, + size_t content_length, const std::string &content_type); + Result Post(const std::string &path, const Headers &headers, const char *body, + size_t content_length, const std::string &content_type, + Progress progress); + Result Post(const std::string &path, const std::string &body, + const std::string &content_type); + Result Post(const std::string &path, const std::string &body, + const std::string &content_type, Progress progress); + Result Post(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type); + Result Post(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type, + Progress progress); + Result Post(const std::string &path, size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Post(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Post(const std::string &path, const Headers &headers, + size_t content_length, ContentProvider content_provider, + const std::string &content_type); + Result Post(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Post(const std::string &path, const Params ¶ms); + Result Post(const std::string &path, const Headers &headers, + const Params ¶ms); + Result Post(const std::string &path, const Headers &headers, + const Params ¶ms, Progress progress); + Result Post(const std::string &path, const MultipartFormDataItems &items); + Result Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items); + Result Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, const std::string &boundary); + Result Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items); + + Result Put(const std::string &path); + Result Put(const std::string &path, const char *body, size_t content_length, + const std::string &content_type); + Result Put(const std::string &path, const Headers &headers, const char *body, + size_t content_length, const std::string &content_type); + Result Put(const std::string &path, const Headers &headers, const char *body, + size_t content_length, const std::string &content_type, + Progress progress); + Result Put(const std::string &path, const std::string &body, + const std::string &content_type); + Result Put(const std::string &path, const std::string &body, + const std::string &content_type, Progress progress); + Result Put(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type); + Result Put(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type, + Progress progress); + Result Put(const std::string &path, size_t content_length, + ContentProvider content_provider, const std::string &content_type); + Result Put(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Put(const std::string &path, const Headers &headers, + size_t content_length, ContentProvider content_provider, + const std::string &content_type); + Result Put(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Put(const std::string &path, const Params ¶ms); + Result Put(const std::string &path, const Headers &headers, + const Params ¶ms); + Result Put(const std::string &path, const Headers &headers, + const Params ¶ms, Progress progress); + Result Put(const std::string &path, const MultipartFormDataItems &items); + Result Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items); + Result Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, const std::string &boundary); + Result Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items); + + Result Patch(const std::string &path); + Result Patch(const std::string &path, const char *body, size_t content_length, + const std::string &content_type); + Result Patch(const std::string &path, const char *body, size_t content_length, + const std::string &content_type, Progress progress); + Result Patch(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type); + Result Patch(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, Progress progress); + Result Patch(const std::string &path, const std::string &body, + const std::string &content_type); + Result Patch(const std::string &path, const std::string &body, + const std::string &content_type, Progress progress); + Result Patch(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type); + Result Patch(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type, + Progress progress); + Result Patch(const std::string &path, size_t content_length, + ContentProvider content_provider, + const std::string &content_type); + Result Patch(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + Result Patch(const std::string &path, const Headers &headers, + size_t content_length, ContentProvider content_provider, + const std::string &content_type); + Result Patch(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type); + + Result Delete(const std::string &path); + Result Delete(const std::string &path, const Headers &headers); + Result Delete(const std::string &path, const char *body, + size_t content_length, const std::string &content_type); + Result Delete(const std::string &path, const char *body, + size_t content_length, const std::string &content_type, + Progress progress); + Result Delete(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type); + Result Delete(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, Progress progress); + Result Delete(const std::string &path, const std::string &body, + const std::string &content_type); + Result Delete(const std::string &path, const std::string &body, + const std::string &content_type, Progress progress); + Result Delete(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type); + Result Delete(const std::string &path, const Headers &headers, + const std::string &body, const std::string &content_type, + Progress progress); + + Result Options(const std::string &path); + Result Options(const std::string &path, const Headers &headers); + + bool send(Request &req, Response &res, Error &error); + Result send(const Request &req); + + void stop(); + + std::string host() const; + int port() const; + + size_t is_socket_open() const; + socket_t socket() const; + + void set_hostname_addr_map(std::map addr_map); + + void set_default_headers(Headers headers); + + void + set_header_writer(std::function const &writer); + + void set_address_family(int family); + void set_tcp_nodelay(bool on); + void set_socket_options(SocketOptions socket_options); + + void set_connection_timeout(time_t sec, time_t usec = 0); + template + void + set_connection_timeout(const std::chrono::duration &duration); + + void set_read_timeout(time_t sec, time_t usec = 0); + template + void set_read_timeout(const std::chrono::duration &duration); + + void set_write_timeout(time_t sec, time_t usec = 0); + template + void set_write_timeout(const std::chrono::duration &duration); + + void set_max_timeout(time_t msec); + template + void set_max_timeout(const std::chrono::duration &duration); + + void set_basic_auth(const std::string &username, const std::string &password); + void set_bearer_token_auth(const std::string &token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_digest_auth(const std::string &username, + const std::string &password); +#endif + + void set_keep_alive(bool on); + void set_follow_location(bool on); + + void set_url_encode(bool on); + + void set_compress(bool on); + + void set_decompress(bool on); + + void set_interface(const std::string &intf); + + void set_proxy(const std::string &host, int port); + void set_proxy_basic_auth(const std::string &username, + const std::string &password); + void set_proxy_bearer_token_auth(const std::string &token); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_proxy_digest_auth(const std::string &username, + const std::string &password); +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void enable_server_certificate_verification(bool enabled); + void enable_server_hostname_verification(bool enabled); + void set_server_certificate_verifier( + std::function verifier); +#endif + + void set_logger(Logger logger); + + // SSL +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + void set_ca_cert_path(const std::string &ca_cert_file_path, + const std::string &ca_cert_dir_path = std::string()); + + void set_ca_cert_store(X509_STORE *ca_cert_store); + void load_ca_cert_store(const char *ca_cert, std::size_t size); + + long get_openssl_verify_result() const; + + SSL_CTX *ssl_context() const; +#endif + +private: + std::unique_ptr cli_; + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + bool is_ssl_ = false; +#endif +}; + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +class SSLServer : public Server { +public: + SSLServer(const char *cert_path, const char *private_key_path, + const char *client_ca_cert_file_path = nullptr, + const char *client_ca_cert_dir_path = nullptr, + const char *private_key_password = nullptr); + + SSLServer(X509 *cert, EVP_PKEY *private_key, + X509_STORE *client_ca_cert_store = nullptr); + + SSLServer( + const std::function &setup_ssl_ctx_callback); + + ~SSLServer() override; + + bool is_valid() const override; + + SSL_CTX *ssl_context() const; + + void update_certs(X509 *cert, EVP_PKEY *private_key, + X509_STORE *client_ca_cert_store = nullptr); + +private: + bool process_and_close_socket(socket_t sock) override; + + SSL_CTX *ctx_; + std::mutex ctx_mutex_; +}; + +class SSLClient final : public ClientImpl { +public: + explicit SSLClient(const std::string &host); + + explicit SSLClient(const std::string &host, int port); + + explicit SSLClient(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path, + const std::string &private_key_password = std::string()); + + explicit SSLClient(const std::string &host, int port, X509 *client_cert, + EVP_PKEY *client_key, + const std::string &private_key_password = std::string()); + + ~SSLClient() override; + + bool is_valid() const override; + + void set_ca_cert_store(X509_STORE *ca_cert_store); + void load_ca_cert_store(const char *ca_cert, std::size_t size); + + long get_openssl_verify_result() const; + + SSL_CTX *ssl_context() const; + +private: + bool create_and_connect_socket(Socket &socket, Error &error) override; + void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override; + void shutdown_ssl_impl(Socket &socket, bool shutdown_gracefully); + + bool + process_socket(const Socket &socket, + std::chrono::time_point start_time, + std::function callback) override; + bool is_ssl() const override; + + bool connect_with_proxy( + Socket &sock, + std::chrono::time_point start_time, + Response &res, bool &success, Error &error); + bool initialize_ssl(Socket &socket, Error &error); + + bool load_certs(); + + bool verify_host(X509 *server_cert) const; + bool verify_host_with_subject_alt_name(X509 *server_cert) const; + bool verify_host_with_common_name(X509 *server_cert) const; + bool check_host_name(const char *pattern, size_t pattern_len) const; + + SSL_CTX *ctx_; + std::mutex ctx_mutex_; + std::once_flag initialize_cert_; + + std::vector host_components_; + + long verify_result_ = 0; + + friend class ClientImpl; +}; +#endif + +/* + * Implementation of template methods. + */ + +namespace detail { + +template +inline void duration_to_sec_and_usec(const T &duration, U callback) { + auto sec = std::chrono::duration_cast(duration).count(); + auto usec = std::chrono::duration_cast( + duration - std::chrono::seconds(sec)) + .count(); + callback(static_cast(sec), static_cast(usec)); +} + +template inline constexpr size_t str_len(const char (&)[N]) { + return N - 1; +} + +inline bool is_numeric(const std::string &str) { + return !str.empty() && + std::all_of(str.cbegin(), str.cend(), + [](unsigned char c) { return std::isdigit(c); }); +} + +inline uint64_t get_header_value_u64(const Headers &headers, + const std::string &key, uint64_t def, + size_t id, bool &is_invalid_value) { + is_invalid_value = false; + auto rng = headers.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { + if (is_numeric(it->second)) { + return std::strtoull(it->second.data(), nullptr, 10); + } else { + is_invalid_value = true; + } + } + return def; +} + +inline uint64_t get_header_value_u64(const Headers &headers, + const std::string &key, uint64_t def, + size_t id) { + bool dummy = false; + return get_header_value_u64(headers, key, def, id, dummy); +} + +} // namespace detail + +inline uint64_t Request::get_header_value_u64(const std::string &key, + uint64_t def, size_t id) const { + return detail::get_header_value_u64(headers, key, def, id); +} + +inline uint64_t Response::get_header_value_u64(const std::string &key, + uint64_t def, size_t id) const { + return detail::get_header_value_u64(headers, key, def, id); +} + +namespace detail { + +inline bool set_socket_opt_impl(socket_t sock, int level, int optname, + const void *optval, socklen_t optlen) { + return setsockopt(sock, level, optname, +#ifdef _WIN32 + reinterpret_cast(optval), +#else + optval, +#endif + optlen) == 0; +} + +inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) { + return set_socket_opt_impl(sock, level, optname, &optval, sizeof(optval)); +} + +inline bool set_socket_opt_time(socket_t sock, int level, int optname, + time_t sec, time_t usec) { +#ifdef _WIN32 + auto timeout = static_cast(sec * 1000 + usec / 1000); +#else + timeval timeout; + timeout.tv_sec = static_cast(sec); + timeout.tv_usec = static_cast(usec); +#endif + return set_socket_opt_impl(sock, level, optname, &timeout, sizeof(timeout)); +} + +} // namespace detail + +inline void default_socket_options(socket_t sock) { + detail::set_socket_opt(sock, SOL_SOCKET, +#ifdef SO_REUSEPORT + SO_REUSEPORT, +#else + SO_REUSEADDR, +#endif + 1); +} + +inline const char *status_message(int status) { + switch (status) { + case StatusCode::Continue_100: return "Continue"; + case StatusCode::SwitchingProtocol_101: return "Switching Protocol"; + case StatusCode::Processing_102: return "Processing"; + case StatusCode::EarlyHints_103: return "Early Hints"; + case StatusCode::OK_200: return "OK"; + case StatusCode::Created_201: return "Created"; + case StatusCode::Accepted_202: return "Accepted"; + case StatusCode::NonAuthoritativeInformation_203: + return "Non-Authoritative Information"; + case StatusCode::NoContent_204: return "No Content"; + case StatusCode::ResetContent_205: return "Reset Content"; + case StatusCode::PartialContent_206: return "Partial Content"; + case StatusCode::MultiStatus_207: return "Multi-Status"; + case StatusCode::AlreadyReported_208: return "Already Reported"; + case StatusCode::IMUsed_226: return "IM Used"; + case StatusCode::MultipleChoices_300: return "Multiple Choices"; + case StatusCode::MovedPermanently_301: return "Moved Permanently"; + case StatusCode::Found_302: return "Found"; + case StatusCode::SeeOther_303: return "See Other"; + case StatusCode::NotModified_304: return "Not Modified"; + case StatusCode::UseProxy_305: return "Use Proxy"; + case StatusCode::unused_306: return "unused"; + case StatusCode::TemporaryRedirect_307: return "Temporary Redirect"; + case StatusCode::PermanentRedirect_308: return "Permanent Redirect"; + case StatusCode::BadRequest_400: return "Bad Request"; + case StatusCode::Unauthorized_401: return "Unauthorized"; + case StatusCode::PaymentRequired_402: return "Payment Required"; + case StatusCode::Forbidden_403: return "Forbidden"; + case StatusCode::NotFound_404: return "Not Found"; + case StatusCode::MethodNotAllowed_405: return "Method Not Allowed"; + case StatusCode::NotAcceptable_406: return "Not Acceptable"; + case StatusCode::ProxyAuthenticationRequired_407: + return "Proxy Authentication Required"; + case StatusCode::RequestTimeout_408: return "Request Timeout"; + case StatusCode::Conflict_409: return "Conflict"; + case StatusCode::Gone_410: return "Gone"; + case StatusCode::LengthRequired_411: return "Length Required"; + case StatusCode::PreconditionFailed_412: return "Precondition Failed"; + case StatusCode::PayloadTooLarge_413: return "Payload Too Large"; + case StatusCode::UriTooLong_414: return "URI Too Long"; + case StatusCode::UnsupportedMediaType_415: return "Unsupported Media Type"; + case StatusCode::RangeNotSatisfiable_416: return "Range Not Satisfiable"; + case StatusCode::ExpectationFailed_417: return "Expectation Failed"; + case StatusCode::ImATeapot_418: return "I'm a teapot"; + case StatusCode::MisdirectedRequest_421: return "Misdirected Request"; + case StatusCode::UnprocessableContent_422: return "Unprocessable Content"; + case StatusCode::Locked_423: return "Locked"; + case StatusCode::FailedDependency_424: return "Failed Dependency"; + case StatusCode::TooEarly_425: return "Too Early"; + case StatusCode::UpgradeRequired_426: return "Upgrade Required"; + case StatusCode::PreconditionRequired_428: return "Precondition Required"; + case StatusCode::TooManyRequests_429: return "Too Many Requests"; + case StatusCode::RequestHeaderFieldsTooLarge_431: + return "Request Header Fields Too Large"; + case StatusCode::UnavailableForLegalReasons_451: + return "Unavailable For Legal Reasons"; + case StatusCode::NotImplemented_501: return "Not Implemented"; + case StatusCode::BadGateway_502: return "Bad Gateway"; + case StatusCode::ServiceUnavailable_503: return "Service Unavailable"; + case StatusCode::GatewayTimeout_504: return "Gateway Timeout"; + case StatusCode::HttpVersionNotSupported_505: + return "HTTP Version Not Supported"; + case StatusCode::VariantAlsoNegotiates_506: return "Variant Also Negotiates"; + case StatusCode::InsufficientStorage_507: return "Insufficient Storage"; + case StatusCode::LoopDetected_508: return "Loop Detected"; + case StatusCode::NotExtended_510: return "Not Extended"; + case StatusCode::NetworkAuthenticationRequired_511: + return "Network Authentication Required"; + + default: + case StatusCode::InternalServerError_500: return "Internal Server Error"; + } +} + +inline std::string get_bearer_token_auth(const Request &req) { + if (req.has_header("Authorization")) { + constexpr auto bearer_header_prefix_len = detail::str_len("Bearer "); + return req.get_header_value("Authorization") + .substr(bearer_header_prefix_len); + } + return ""; +} + +template +inline Server & +Server::set_read_timeout(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); + return *this; +} + +template +inline Server & +Server::set_write_timeout(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); + return *this; +} + +template +inline Server & +Server::set_idle_interval(const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); }); + return *this; +} + +inline std::string to_string(const Error error) { + switch (error) { + case Error::Success: return "Success (no error)"; + case Error::Connection: return "Could not establish connection"; + case Error::BindIPAddress: return "Failed to bind IP address"; + case Error::Read: return "Failed to read connection"; + case Error::Write: return "Failed to write connection"; + case Error::ExceedRedirectCount: return "Maximum redirect count exceeded"; + case Error::Canceled: return "Connection handling canceled"; + case Error::SSLConnection: return "SSL connection failed"; + case Error::SSLLoadingCerts: return "SSL certificate loading failed"; + case Error::SSLServerVerification: return "SSL server verification failed"; + case Error::SSLServerHostnameVerification: + return "SSL server hostname verification failed"; + case Error::UnsupportedMultipartBoundaryChars: + return "Unsupported HTTP multipart boundary characters"; + case Error::Compression: return "Compression failed"; + case Error::ConnectionTimeout: return "Connection timed out"; + case Error::ProxyConnection: return "Proxy connection failed"; + case Error::Unknown: return "Unknown"; + default: break; + } + + return "Invalid"; +} + +inline std::ostream &operator<<(std::ostream &os, const Error &obj) { + os << to_string(obj); + os << " (" << static_cast::type>(obj) << ')'; + return os; +} + +inline uint64_t Result::get_request_header_value_u64(const std::string &key, + uint64_t def, + size_t id) const { + return detail::get_header_value_u64(request_headers_, key, def, id); +} + +template +inline void ClientImpl::set_connection_timeout( + const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) { + set_connection_timeout(sec, usec); + }); +} + +template +inline void ClientImpl::set_read_timeout( + const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); }); +} + +template +inline void ClientImpl::set_write_timeout( + const std::chrono::duration &duration) { + detail::duration_to_sec_and_usec( + duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); }); +} + +template +inline void ClientImpl::set_max_timeout( + const std::chrono::duration &duration) { + auto msec = + std::chrono::duration_cast(duration).count(); + set_max_timeout(msec); +} + +template +inline void Client::set_connection_timeout( + const std::chrono::duration &duration) { + cli_->set_connection_timeout(duration); +} + +template +inline void +Client::set_read_timeout(const std::chrono::duration &duration) { + cli_->set_read_timeout(duration); +} + +template +inline void +Client::set_write_timeout(const std::chrono::duration &duration) { + cli_->set_write_timeout(duration); +} + +template +inline void +Client::set_max_timeout(const std::chrono::duration &duration) { + cli_->set_max_timeout(duration); +} + +/* + * Forward declarations and types that will be part of the .h file if split into + * .h + .cc. + */ + +std::string hosted_at(const std::string &hostname); + +void hosted_at(const std::string &hostname, std::vector &addrs); + +std::string append_query_params(const std::string &path, const Params ¶ms); + +std::pair make_range_header(const Ranges &ranges); + +std::pair +make_basic_authentication_header(const std::string &username, + const std::string &password, + bool is_proxy = false); + +namespace detail { + +#if defined(_WIN32) +inline std::wstring u8string_to_wstring(const char *s) { + std::wstring ws; + auto len = static_cast(strlen(s)); + auto wlen = ::MultiByteToWideChar(CP_UTF8, 0, s, len, nullptr, 0); + if (wlen > 0) { + ws.resize(wlen); + wlen = ::MultiByteToWideChar( + CP_UTF8, 0, s, len, + const_cast(reinterpret_cast(ws.data())), wlen); + if (wlen != static_cast(ws.size())) { ws.clear(); } + } + return ws; +} +#endif + +struct FileStat { + FileStat(const std::string &path); + bool is_file() const; + bool is_dir() const; + +private: +#if defined(_WIN32) + struct _stat st_; +#else + struct stat st_; +#endif + int ret_ = -1; +}; + +std::string encode_query_param(const std::string &value); + +std::string decode_url(const std::string &s, bool convert_plus_to_space); + +std::string trim_copy(const std::string &s); + +void divide( + const char *data, std::size_t size, char d, + std::function + fn); + +void divide( + const std::string &str, char d, + std::function + fn); + +void split(const char *b, const char *e, char d, + std::function fn); + +void split(const char *b, const char *e, char d, size_t m, + std::function fn); + +bool process_client_socket( + socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, time_t write_timeout_usec, + time_t max_timeout_msec, + std::chrono::time_point start_time, + std::function callback); + +socket_t create_client_socket(const std::string &host, const std::string &ip, + int port, int address_family, bool tcp_nodelay, + bool ipv6_v6only, SocketOptions socket_options, + time_t connection_timeout_sec, + time_t connection_timeout_usec, + time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, + time_t write_timeout_usec, + const std::string &intf, Error &error); + +const char *get_header_value(const Headers &headers, const std::string &key, + const char *def, size_t id); + +std::string params_to_query_str(const Params ¶ms); + +void parse_query_text(const char *data, std::size_t size, Params ¶ms); + +void parse_query_text(const std::string &s, Params ¶ms); + +bool parse_multipart_boundary(const std::string &content_type, + std::string &boundary); + +bool parse_range_header(const std::string &s, Ranges &ranges); + +int close_socket(socket_t sock); + +ssize_t send_socket(socket_t sock, const void *ptr, size_t size, int flags); + +ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags); + +enum class EncodingType { None = 0, Gzip, Brotli, Zstd }; + +EncodingType encoding_type(const Request &req, const Response &res); + +class BufferStream final : public Stream { +public: + BufferStream() = default; + ~BufferStream() override = default; + + bool is_readable() const override; + bool wait_readable() const override; + bool wait_writable() const override; + ssize_t read(char *ptr, size_t size) override; + ssize_t write(const char *ptr, size_t size) override; + void get_remote_ip_and_port(std::string &ip, int &port) const override; + void get_local_ip_and_port(std::string &ip, int &port) const override; + socket_t socket() const override; + time_t duration() const override; + + const std::string &get_buffer() const; + +private: + std::string buffer; + size_t position = 0; +}; + +class compressor { +public: + virtual ~compressor() = default; + + typedef std::function Callback; + virtual bool compress(const char *data, size_t data_length, bool last, + Callback callback) = 0; +}; + +class decompressor { +public: + virtual ~decompressor() = default; + + virtual bool is_valid() const = 0; + + typedef std::function Callback; + virtual bool decompress(const char *data, size_t data_length, + Callback callback) = 0; +}; + +class nocompressor final : public compressor { +public: + ~nocompressor() override = default; + + bool compress(const char *data, size_t data_length, bool /*last*/, + Callback callback) override; +}; + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT +class gzip_compressor final : public compressor { +public: + gzip_compressor(); + ~gzip_compressor() override; + + bool compress(const char *data, size_t data_length, bool last, + Callback callback) override; + +private: + bool is_valid_ = false; + z_stream strm_; +}; + +class gzip_decompressor final : public decompressor { +public: + gzip_decompressor(); + ~gzip_decompressor() override; + + bool is_valid() const override; + + bool decompress(const char *data, size_t data_length, + Callback callback) override; + +private: + bool is_valid_ = false; + z_stream strm_; +}; +#endif + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT +class brotli_compressor final : public compressor { +public: + brotli_compressor(); + ~brotli_compressor(); + + bool compress(const char *data, size_t data_length, bool last, + Callback callback) override; + +private: + BrotliEncoderState *state_ = nullptr; +}; + +class brotli_decompressor final : public decompressor { +public: + brotli_decompressor(); + ~brotli_decompressor(); + + bool is_valid() const override; + + bool decompress(const char *data, size_t data_length, + Callback callback) override; + +private: + BrotliDecoderResult decoder_r; + BrotliDecoderState *decoder_s = nullptr; +}; +#endif + +#ifdef CPPHTTPLIB_ZSTD_SUPPORT +class zstd_compressor : public compressor { +public: + zstd_compressor(); + ~zstd_compressor(); + + bool compress(const char *data, size_t data_length, bool last, + Callback callback) override; + +private: + ZSTD_CCtx *ctx_ = nullptr; +}; + +class zstd_decompressor : public decompressor { +public: + zstd_decompressor(); + ~zstd_decompressor(); + + bool is_valid() const override; + + bool decompress(const char *data, size_t data_length, + Callback callback) override; + +private: + ZSTD_DCtx *ctx_ = nullptr; +}; +#endif + +// NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer` +// to store data. The call can set memory on stack for performance. +class stream_line_reader { +public: + stream_line_reader(Stream &strm, char *fixed_buffer, + size_t fixed_buffer_size); + const char *ptr() const; + size_t size() const; + bool end_with_crlf() const; + bool getline(); + +private: + void append(char c); + + Stream &strm_; + char *fixed_buffer_; + const size_t fixed_buffer_size_; + size_t fixed_buffer_used_size_ = 0; + std::string growable_buffer_; +}; + +class mmap { +public: + mmap(const char *path); + ~mmap(); + + bool open(const char *path); + void close(); + + bool is_open() const; + size_t size() const; + const char *data() const; + +private: +#if defined(_WIN32) + HANDLE hFile_ = NULL; + HANDLE hMapping_ = NULL; +#else + int fd_ = -1; +#endif + size_t size_ = 0; + void *addr_ = nullptr; + bool is_open_empty_file = false; +}; + +// NOTE: https://www.rfc-editor.org/rfc/rfc9110#section-5 +namespace fields { + +inline bool is_token_char(char c) { + return std::isalnum(c) || c == '!' || c == '#' || c == '$' || c == '%' || + c == '&' || c == '\'' || c == '*' || c == '+' || c == '-' || + c == '.' || c == '^' || c == '_' || c == '`' || c == '|' || c == '~'; +} + +inline bool is_token(const std::string &s) { + if (s.empty()) { return false; } + for (auto c : s) { + if (!is_token_char(c)) { return false; } + } + return true; +} + +inline bool is_field_name(const std::string &s) { return is_token(s); } + +inline bool is_vchar(char c) { return c >= 33 && c <= 126; } + +inline bool is_obs_text(char c) { return 128 <= static_cast(c); } + +inline bool is_field_vchar(char c) { return is_vchar(c) || is_obs_text(c); } + +inline bool is_field_content(const std::string &s) { + if (s.empty()) { return true; } + + if (s.size() == 1) { + return is_field_vchar(s[0]); + } else if (s.size() == 2) { + return is_field_vchar(s[0]) && is_field_vchar(s[1]); + } else { + size_t i = 0; + + if (!is_field_vchar(s[i])) { return false; } + i++; + + while (i < s.size() - 1) { + auto c = s[i++]; + if (c == ' ' || c == '\t' || is_field_vchar(c)) { + } else { + return false; + } + } + + return is_field_vchar(s[i]); + } +} + +inline bool is_field_value(const std::string &s) { return is_field_content(s); } + +} // namespace fields + +} // namespace detail + +// ---------------------------------------------------------------------------- + +/* + * Implementation that will be part of the .cc file if split into .h + .cc. + */ + +namespace detail { + +inline bool is_hex(char c, int &v) { + if (0x20 <= c && isdigit(c)) { + v = c - '0'; + return true; + } else if ('A' <= c && c <= 'F') { + v = c - 'A' + 10; + return true; + } else if ('a' <= c && c <= 'f') { + v = c - 'a' + 10; + return true; + } + return false; +} + +inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt, + int &val) { + if (i >= s.size()) { return false; } + + val = 0; + for (; cnt; i++, cnt--) { + if (!s[i]) { return false; } + auto v = 0; + if (is_hex(s[i], v)) { + val = val * 16 + v; + } else { + return false; + } + } + return true; +} + +inline std::string from_i_to_hex(size_t n) { + static const auto charset = "0123456789abcdef"; + std::string ret; + do { + ret = charset[n & 15] + ret; + n >>= 4; + } while (n > 0); + return ret; +} + +inline size_t to_utf8(int code, char *buff) { + if (code < 0x0080) { + buff[0] = static_cast(code & 0x7F); + return 1; + } else if (code < 0x0800) { + buff[0] = static_cast(0xC0 | ((code >> 6) & 0x1F)); + buff[1] = static_cast(0x80 | (code & 0x3F)); + return 2; + } else if (code < 0xD800) { + buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); + buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[2] = static_cast(0x80 | (code & 0x3F)); + return 3; + } else if (code < 0xE000) { // D800 - DFFF is invalid... + return 0; + } else if (code < 0x10000) { + buff[0] = static_cast(0xE0 | ((code >> 12) & 0xF)); + buff[1] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[2] = static_cast(0x80 | (code & 0x3F)); + return 3; + } else if (code < 0x110000) { + buff[0] = static_cast(0xF0 | ((code >> 18) & 0x7)); + buff[1] = static_cast(0x80 | ((code >> 12) & 0x3F)); + buff[2] = static_cast(0x80 | ((code >> 6) & 0x3F)); + buff[3] = static_cast(0x80 | (code & 0x3F)); + return 4; + } + + // NOTREACHED + return 0; +} + +// NOTE: This code came up with the following stackoverflow post: +// https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c +inline std::string base64_encode(const std::string &in) { + static const auto lookup = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + std::string out; + out.reserve(in.size()); + + auto val = 0; + auto valb = -6; + + for (auto c : in) { + val = (val << 8) + static_cast(c); + valb += 8; + while (valb >= 0) { + out.push_back(lookup[(val >> valb) & 0x3F]); + valb -= 6; + } + } + + if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); } + + while (out.size() % 4) { + out.push_back('='); + } + + return out; +} + +inline bool is_valid_path(const std::string &path) { + size_t level = 0; + size_t i = 0; + + // Skip slash + while (i < path.size() && path[i] == '/') { + i++; + } + + while (i < path.size()) { + // Read component + auto beg = i; + while (i < path.size() && path[i] != '/') { + if (path[i] == '\0') { + return false; + } else if (path[i] == '\\') { + return false; + } + i++; + } + + auto len = i - beg; + assert(len > 0); + + if (!path.compare(beg, len, ".")) { + ; + } else if (!path.compare(beg, len, "..")) { + if (level == 0) { return false; } + level--; + } else { + level++; + } + + // Skip slash + while (i < path.size() && path[i] == '/') { + i++; + } + } + + return true; +} + +inline FileStat::FileStat(const std::string &path) { +#if defined(_WIN32) + auto wpath = u8string_to_wstring(path.c_str()); + ret_ = _wstat(wpath.c_str(), &st_); +#else + ret_ = stat(path.c_str(), &st_); +#endif +} +inline bool FileStat::is_file() const { + return ret_ >= 0 && S_ISREG(st_.st_mode); +} +inline bool FileStat::is_dir() const { + return ret_ >= 0 && S_ISDIR(st_.st_mode); +} + +inline std::string encode_query_param(const std::string &value) { + std::ostringstream escaped; + escaped.fill('0'); + escaped << std::hex; + + for (auto c : value) { + if (std::isalnum(static_cast(c)) || c == '-' || c == '_' || + c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || + c == ')') { + escaped << c; + } else { + escaped << std::uppercase; + escaped << '%' << std::setw(2) + << static_cast(static_cast(c)); + escaped << std::nouppercase; + } + } + + return escaped.str(); +} + +inline std::string encode_url(const std::string &s) { + std::string result; + result.reserve(s.size()); + + for (size_t i = 0; s[i]; i++) { + switch (s[i]) { + case ' ': result += "%20"; break; + case '+': result += "%2B"; break; + case '\r': result += "%0D"; break; + case '\n': result += "%0A"; break; + case '\'': result += "%27"; break; + case ',': result += "%2C"; break; + // case ':': result += "%3A"; break; // ok? probably... + case ';': result += "%3B"; break; + default: + auto c = static_cast(s[i]); + if (c >= 0x80) { + result += '%'; + char hex[4]; + auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c); + assert(len == 2); + result.append(hex, static_cast(len)); + } else { + result += s[i]; + } + break; + } + } + + return result; +} + +inline std::string decode_url(const std::string &s, + bool convert_plus_to_space) { + std::string result; + + for (size_t i = 0; i < s.size(); i++) { + if (s[i] == '%' && i + 1 < s.size()) { + if (s[i + 1] == 'u') { + auto val = 0; + if (from_hex_to_i(s, i + 2, 4, val)) { + // 4 digits Unicode codes + char buff[4]; + size_t len = to_utf8(val, buff); + if (len > 0) { result.append(buff, len); } + i += 5; // 'u0000' + } else { + result += s[i]; + } + } else { + auto val = 0; + if (from_hex_to_i(s, i + 1, 2, val)) { + // 2 digits hex codes + result += static_cast(val); + i += 2; // '00' + } else { + result += s[i]; + } + } + } else if (convert_plus_to_space && s[i] == '+') { + result += ' '; + } else { + result += s[i]; + } + } + + return result; +} + +inline std::string file_extension(const std::string &path) { + std::smatch m; + thread_local auto re = std::regex("\\.([a-zA-Z0-9]+)$"); + if (std::regex_search(path, m, re)) { return m[1].str(); } + return std::string(); +} + +inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; } + +inline std::pair trim(const char *b, const char *e, size_t left, + size_t right) { + while (b + left < e && is_space_or_tab(b[left])) { + left++; + } + while (right > 0 && is_space_or_tab(b[right - 1])) { + right--; + } + return std::make_pair(left, right); +} + +inline std::string trim_copy(const std::string &s) { + auto r = trim(s.data(), s.data() + s.size(), 0, s.size()); + return s.substr(r.first, r.second - r.first); +} + +inline std::string trim_double_quotes_copy(const std::string &s) { + if (s.length() >= 2 && s.front() == '"' && s.back() == '"') { + return s.substr(1, s.size() - 2); + } + return s; +} + +inline void +divide(const char *data, std::size_t size, char d, + std::function + fn) { + const auto it = std::find(data, data + size, d); + const auto found = static_cast(it != data + size); + const auto lhs_data = data; + const auto lhs_size = static_cast(it - data); + const auto rhs_data = it + found; + const auto rhs_size = size - lhs_size - found; + + fn(lhs_data, lhs_size, rhs_data, rhs_size); +} + +inline void +divide(const std::string &str, char d, + std::function + fn) { + divide(str.data(), str.size(), d, std::move(fn)); +} + +inline void split(const char *b, const char *e, char d, + std::function fn) { + return split(b, e, d, (std::numeric_limits::max)(), std::move(fn)); +} + +inline void split(const char *b, const char *e, char d, size_t m, + std::function fn) { + size_t i = 0; + size_t beg = 0; + size_t count = 1; + + while (e ? (b + i < e) : (b[i] != '\0')) { + if (b[i] == d && count < m) { + auto r = trim(b, e, beg, i); + if (r.first < r.second) { fn(&b[r.first], &b[r.second]); } + beg = i + 1; + count++; + } + i++; + } + + if (i) { + auto r = trim(b, e, beg, i); + if (r.first < r.second) { fn(&b[r.first], &b[r.second]); } + } +} + +inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer, + size_t fixed_buffer_size) + : strm_(strm), fixed_buffer_(fixed_buffer), + fixed_buffer_size_(fixed_buffer_size) {} + +inline const char *stream_line_reader::ptr() const { + if (growable_buffer_.empty()) { + return fixed_buffer_; + } else { + return growable_buffer_.data(); + } +} + +inline size_t stream_line_reader::size() const { + if (growable_buffer_.empty()) { + return fixed_buffer_used_size_; + } else { + return growable_buffer_.size(); + } +} + +inline bool stream_line_reader::end_with_crlf() const { + auto end = ptr() + size(); + return size() >= 2 && end[-2] == '\r' && end[-1] == '\n'; +} + +inline bool stream_line_reader::getline() { + fixed_buffer_used_size_ = 0; + growable_buffer_.clear(); + +#ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR + char prev_byte = 0; +#endif + + for (size_t i = 0;; i++) { + if (size() >= CPPHTTPLIB_MAX_LINE_LENGTH) { + // Treat exceptionally long lines as an error to + // prevent infinite loops/memory exhaustion + return false; + } + char byte; + auto n = strm_.read(&byte, 1); + + if (n < 0) { + return false; + } else if (n == 0) { + if (i == 0) { + return false; + } else { + break; + } + } + + append(byte); + +#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR + if (byte == '\n') { break; } +#else + if (prev_byte == '\r' && byte == '\n') { break; } + prev_byte = byte; +#endif + } + + return true; +} + +inline void stream_line_reader::append(char c) { + if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) { + fixed_buffer_[fixed_buffer_used_size_++] = c; + fixed_buffer_[fixed_buffer_used_size_] = '\0'; + } else { + if (growable_buffer_.empty()) { + assert(fixed_buffer_[fixed_buffer_used_size_] == '\0'); + growable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_); + } + growable_buffer_ += c; + } +} + +inline mmap::mmap(const char *path) { open(path); } + +inline mmap::~mmap() { close(); } + +inline bool mmap::open(const char *path) { + close(); + +#if defined(_WIN32) + auto wpath = u8string_to_wstring(path); + if (wpath.empty()) { return false; } + +#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + hFile_ = ::CreateFile2(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, + OPEN_EXISTING, NULL); +#else + hFile_ = ::CreateFileW(wpath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, + OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); +#endif + + if (hFile_ == INVALID_HANDLE_VALUE) { return false; } + + LARGE_INTEGER size{}; + if (!::GetFileSizeEx(hFile_, &size)) { return false; } + // If the following line doesn't compile due to QuadPart, update Windows SDK. + // See: + // https://github.com/yhirose/cpp-httplib/issues/1903#issuecomment-2316520721 + if (static_cast(size.QuadPart) > + (std::numeric_limits::max)()) { + // `size_t` might be 32-bits, on 32-bits Windows. + return false; + } + size_ = static_cast(size.QuadPart); + +#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + hMapping_ = + ::CreateFileMappingFromApp(hFile_, NULL, PAGE_READONLY, size_, NULL); +#else + hMapping_ = ::CreateFileMappingW(hFile_, NULL, PAGE_READONLY, 0, 0, NULL); +#endif + + // Special treatment for an empty file... + if (hMapping_ == NULL && size_ == 0) { + close(); + is_open_empty_file = true; + return true; + } + + if (hMapping_ == NULL) { + close(); + return false; + } + +#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + addr_ = ::MapViewOfFileFromApp(hMapping_, FILE_MAP_READ, 0, 0); +#else + addr_ = ::MapViewOfFile(hMapping_, FILE_MAP_READ, 0, 0, 0); +#endif + + if (addr_ == nullptr) { + close(); + return false; + } +#else + fd_ = ::open(path, O_RDONLY); + if (fd_ == -1) { return false; } + + struct stat sb; + if (fstat(fd_, &sb) == -1) { + close(); + return false; + } + size_ = static_cast(sb.st_size); + + addr_ = ::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0); + + // Special treatment for an empty file... + if (addr_ == MAP_FAILED && size_ == 0) { + close(); + is_open_empty_file = true; + return false; + } +#endif + + return true; +} + +inline bool mmap::is_open() const { + return is_open_empty_file ? true : addr_ != nullptr; +} + +inline size_t mmap::size() const { return size_; } + +inline const char *mmap::data() const { + return is_open_empty_file ? "" : static_cast(addr_); +} + +inline void mmap::close() { +#if defined(_WIN32) + if (addr_) { + ::UnmapViewOfFile(addr_); + addr_ = nullptr; + } + + if (hMapping_) { + ::CloseHandle(hMapping_); + hMapping_ = NULL; + } + + if (hFile_ != INVALID_HANDLE_VALUE) { + ::CloseHandle(hFile_); + hFile_ = INVALID_HANDLE_VALUE; + } + + is_open_empty_file = false; +#else + if (addr_ != nullptr) { + munmap(addr_, size_); + addr_ = nullptr; + } + + if (fd_ != -1) { + ::close(fd_); + fd_ = -1; + } +#endif + size_ = 0; +} +inline int close_socket(socket_t sock) { +#ifdef _WIN32 + return closesocket(sock); +#else + return close(sock); +#endif +} + +template inline ssize_t handle_EINTR(T fn) { + ssize_t res = 0; + while (true) { + res = fn(); + if (res < 0 && errno == EINTR) { + std::this_thread::sleep_for(std::chrono::microseconds{1}); + continue; + } + break; + } + return res; +} + +inline ssize_t read_socket(socket_t sock, void *ptr, size_t size, int flags) { + return handle_EINTR([&]() { + return recv(sock, +#ifdef _WIN32 + static_cast(ptr), static_cast(size), +#else + ptr, size, +#endif + flags); + }); +} + +inline ssize_t send_socket(socket_t sock, const void *ptr, size_t size, + int flags) { + return handle_EINTR([&]() { + return send(sock, +#ifdef _WIN32 + static_cast(ptr), static_cast(size), +#else + ptr, size, +#endif + flags); + }); +} + +inline int poll_wrapper(struct pollfd *fds, nfds_t nfds, int timeout) { +#ifdef _WIN32 + return ::WSAPoll(fds, nfds, timeout); +#else + return ::poll(fds, nfds, timeout); +#endif +} + +template +inline ssize_t select_impl(socket_t sock, time_t sec, time_t usec) { + struct pollfd pfd; + pfd.fd = sock; + pfd.events = (Read ? POLLIN : POLLOUT); + + auto timeout = static_cast(sec * 1000 + usec / 1000); + + return handle_EINTR([&]() { return poll_wrapper(&pfd, 1, timeout); }); +} + +inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) { + return select_impl(sock, sec, usec); +} + +inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) { + return select_impl(sock, sec, usec); +} + +inline Error wait_until_socket_is_ready(socket_t sock, time_t sec, + time_t usec) { + struct pollfd pfd_read; + pfd_read.fd = sock; + pfd_read.events = POLLIN | POLLOUT; + + auto timeout = static_cast(sec * 1000 + usec / 1000); + + auto poll_res = + handle_EINTR([&]() { return poll_wrapper(&pfd_read, 1, timeout); }); + + if (poll_res == 0) { return Error::ConnectionTimeout; } + + if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) { + auto error = 0; + socklen_t len = sizeof(error); + auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR, + reinterpret_cast(&error), &len); + auto successful = res >= 0 && !error; + return successful ? Error::Success : Error::Connection; + } + + return Error::Connection; +} + +inline bool is_socket_alive(socket_t sock) { + const auto val = detail::select_read(sock, 0, 0); + if (val == 0) { + return true; + } else if (val < 0 && errno == EBADF) { + return false; + } + char buf[1]; + return detail::read_socket(sock, &buf[0], sizeof(buf), MSG_PEEK) > 0; +} + +class SocketStream final : public Stream { +public: + SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, time_t write_timeout_usec, + time_t max_timeout_msec = 0, + std::chrono::time_point start_time = + (std::chrono::steady_clock::time_point::min)()); + ~SocketStream() override; + + bool is_readable() const override; + bool wait_readable() const override; + bool wait_writable() const override; + ssize_t read(char *ptr, size_t size) override; + ssize_t write(const char *ptr, size_t size) override; + void get_remote_ip_and_port(std::string &ip, int &port) const override; + void get_local_ip_and_port(std::string &ip, int &port) const override; + socket_t socket() const override; + time_t duration() const override; + +private: + socket_t sock_; + time_t read_timeout_sec_; + time_t read_timeout_usec_; + time_t write_timeout_sec_; + time_t write_timeout_usec_; + time_t max_timeout_msec_; + const std::chrono::time_point start_time_; + + std::vector read_buff_; + size_t read_buff_off_ = 0; + size_t read_buff_content_size_ = 0; + + static const size_t read_buff_size_ = 1024l * 4; +}; + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +class SSLSocketStream final : public Stream { +public: + SSLSocketStream( + socket_t sock, SSL *ssl, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, time_t max_timeout_msec = 0, + std::chrono::time_point start_time = + (std::chrono::steady_clock::time_point::min)()); + ~SSLSocketStream() override; + + bool is_readable() const override; + bool wait_readable() const override; + bool wait_writable() const override; + ssize_t read(char *ptr, size_t size) override; + ssize_t write(const char *ptr, size_t size) override; + void get_remote_ip_and_port(std::string &ip, int &port) const override; + void get_local_ip_and_port(std::string &ip, int &port) const override; + socket_t socket() const override; + time_t duration() const override; + +private: + socket_t sock_; + SSL *ssl_; + time_t read_timeout_sec_; + time_t read_timeout_usec_; + time_t write_timeout_sec_; + time_t write_timeout_usec_; + time_t max_timeout_msec_; + const std::chrono::time_point start_time_; +}; +#endif + +inline bool keep_alive(const std::atomic &svr_sock, socket_t sock, + time_t keep_alive_timeout_sec) { + using namespace std::chrono; + + const auto interval_usec = + CPPHTTPLIB_KEEPALIVE_TIMEOUT_CHECK_INTERVAL_USECOND; + + // Avoid expensive `steady_clock::now()` call for the first time + if (select_read(sock, 0, interval_usec) > 0) { return true; } + + const auto start = steady_clock::now() - microseconds{interval_usec}; + const auto timeout = seconds{keep_alive_timeout_sec}; + + while (true) { + if (svr_sock == INVALID_SOCKET) { + break; // Server socket is closed + } + + auto val = select_read(sock, 0, interval_usec); + if (val < 0) { + break; // Ssocket error + } else if (val == 0) { + if (steady_clock::now() - start > timeout) { + break; // Timeout + } + } else { + return true; // Ready for read + } + } + + return false; +} + +template +inline bool +process_server_socket_core(const std::atomic &svr_sock, socket_t sock, + size_t keep_alive_max_count, + time_t keep_alive_timeout_sec, T callback) { + assert(keep_alive_max_count > 0); + auto ret = false; + auto count = keep_alive_max_count; + while (count > 0 && keep_alive(svr_sock, sock, keep_alive_timeout_sec)) { + auto close_connection = count == 1; + auto connection_closed = false; + ret = callback(close_connection, connection_closed); + if (!ret || connection_closed) { break; } + count--; + } + return ret; +} + +template +inline bool +process_server_socket(const std::atomic &svr_sock, socket_t sock, + size_t keep_alive_max_count, + time_t keep_alive_timeout_sec, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, T callback) { + return process_server_socket_core( + svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec, + [&](bool close_connection, bool &connection_closed) { + SocketStream strm(sock, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec); + return callback(strm, close_connection, connection_closed); + }); +} + +inline bool process_client_socket( + socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, time_t write_timeout_usec, + time_t max_timeout_msec, + std::chrono::time_point start_time, + std::function callback) { + SocketStream strm(sock, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec, max_timeout_msec, + start_time); + return callback(strm); +} + +inline int shutdown_socket(socket_t sock) { +#ifdef _WIN32 + return shutdown(sock, SD_BOTH); +#else + return shutdown(sock, SHUT_RDWR); +#endif +} + +inline std::string escape_abstract_namespace_unix_domain(const std::string &s) { + if (s.size() > 1 && s[0] == '\0') { + auto ret = s; + ret[0] = '@'; + return ret; + } + return s; +} + +inline std::string +unescape_abstract_namespace_unix_domain(const std::string &s) { + if (s.size() > 1 && s[0] == '@') { + auto ret = s; + ret[0] = '\0'; + return ret; + } + return s; +} + +template +socket_t create_socket(const std::string &host, const std::string &ip, int port, + int address_family, int socket_flags, bool tcp_nodelay, + bool ipv6_v6only, SocketOptions socket_options, + BindOrConnect bind_or_connect) { + // Get address info + const char *node = nullptr; + struct addrinfo hints; + struct addrinfo *result; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_IP; + + if (!ip.empty()) { + node = ip.c_str(); + // Ask getaddrinfo to convert IP in c-string to address + hints.ai_family = AF_UNSPEC; + hints.ai_flags = AI_NUMERICHOST; + } else { + if (!host.empty()) { node = host.c_str(); } + hints.ai_family = address_family; + hints.ai_flags = socket_flags; + } + +#if !defined(_WIN32) || defined(CPPHTTPLIB_HAVE_AFUNIX_H) + if (hints.ai_family == AF_UNIX) { + const auto addrlen = host.length(); + if (addrlen > sizeof(sockaddr_un::sun_path)) { return INVALID_SOCKET; } + +#ifdef SOCK_CLOEXEC + auto sock = socket(hints.ai_family, hints.ai_socktype | SOCK_CLOEXEC, + hints.ai_protocol); +#else + auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol); +#endif + + if (sock != INVALID_SOCKET) { + sockaddr_un addr{}; + addr.sun_family = AF_UNIX; + + auto unescaped_host = unescape_abstract_namespace_unix_domain(host); + std::copy(unescaped_host.begin(), unescaped_host.end(), addr.sun_path); + + hints.ai_addr = reinterpret_cast(&addr); + hints.ai_addrlen = static_cast( + sizeof(addr) - sizeof(addr.sun_path) + addrlen); + +#ifndef SOCK_CLOEXEC +#ifndef _WIN32 + fcntl(sock, F_SETFD, FD_CLOEXEC); +#endif +#endif + + if (socket_options) { socket_options(sock); } + +#ifdef _WIN32 + // Setting SO_REUSEADDR seems not to work well with AF_UNIX on windows, so + // remove the option. + detail::set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 0); +#endif + + bool dummy; + if (!bind_or_connect(sock, hints, dummy)) { + close_socket(sock); + sock = INVALID_SOCKET; + } + } + return sock; + } +#endif + + auto service = std::to_string(port); + + if (getaddrinfo(node, service.c_str(), &hints, &result)) { +#if defined __linux__ && !defined __ANDROID__ + res_init(); +#endif + return INVALID_SOCKET; + } + auto se = detail::scope_exit([&] { freeaddrinfo(result); }); + + for (auto rp = result; rp; rp = rp->ai_next) { + // Create a socket +#ifdef _WIN32 + auto sock = + WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0, + WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED); + /** + * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1 + * and above the socket creation fails on older Windows Systems. + * + * Let's try to create a socket the old way in this case. + * + * Reference: + * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa + * + * WSA_FLAG_NO_HANDLE_INHERIT: + * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with + * SP1, and later + * + */ + if (sock == INVALID_SOCKET) { + sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); + } +#else + +#ifdef SOCK_CLOEXEC + auto sock = + socket(rp->ai_family, rp->ai_socktype | SOCK_CLOEXEC, rp->ai_protocol); +#else + auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); +#endif + +#endif + if (sock == INVALID_SOCKET) { continue; } + +#if !defined _WIN32 && !defined SOCK_CLOEXEC + if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { + close_socket(sock); + continue; + } +#endif + + if (tcp_nodelay) { set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1); } + + if (rp->ai_family == AF_INET6) { + set_socket_opt(sock, IPPROTO_IPV6, IPV6_V6ONLY, ipv6_v6only ? 1 : 0); + } + + if (socket_options) { socket_options(sock); } + + // bind or connect + auto quit = false; + if (bind_or_connect(sock, *rp, quit)) { return sock; } + + close_socket(sock); + + if (quit) { break; } + } + + return INVALID_SOCKET; +} + +inline void set_nonblocking(socket_t sock, bool nonblocking) { +#ifdef _WIN32 + auto flags = nonblocking ? 1UL : 0UL; + ioctlsocket(sock, FIONBIO, &flags); +#else + auto flags = fcntl(sock, F_GETFL, 0); + fcntl(sock, F_SETFL, + nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK))); +#endif +} + +inline bool is_connection_error() { +#ifdef _WIN32 + return WSAGetLastError() != WSAEWOULDBLOCK; +#else + return errno != EINPROGRESS; +#endif +} + +inline bool bind_ip_address(socket_t sock, const std::string &host) { + struct addrinfo hints; + struct addrinfo *result; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = 0; + + if (getaddrinfo(host.c_str(), "0", &hints, &result)) { return false; } + auto se = detail::scope_exit([&] { freeaddrinfo(result); }); + + auto ret = false; + for (auto rp = result; rp; rp = rp->ai_next) { + const auto &ai = *rp; + if (!::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { + ret = true; + break; + } + } + + return ret; +} + +#if !defined _WIN32 && !defined ANDROID && !defined _AIX && !defined __MVS__ +#define USE_IF2IP +#endif + +#ifdef USE_IF2IP +inline std::string if2ip(int address_family, const std::string &ifn) { + struct ifaddrs *ifap; + getifaddrs(&ifap); + auto se = detail::scope_exit([&] { freeifaddrs(ifap); }); + + std::string addr_candidate; + for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) { + if (ifa->ifa_addr && ifn == ifa->ifa_name && + (AF_UNSPEC == address_family || + ifa->ifa_addr->sa_family == address_family)) { + if (ifa->ifa_addr->sa_family == AF_INET) { + auto sa = reinterpret_cast(ifa->ifa_addr); + char buf[INET_ADDRSTRLEN]; + if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) { + return std::string(buf, INET_ADDRSTRLEN); + } + } else if (ifa->ifa_addr->sa_family == AF_INET6) { + auto sa = reinterpret_cast(ifa->ifa_addr); + if (!IN6_IS_ADDR_LINKLOCAL(&sa->sin6_addr)) { + char buf[INET6_ADDRSTRLEN] = {}; + if (inet_ntop(AF_INET6, &sa->sin6_addr, buf, INET6_ADDRSTRLEN)) { + // equivalent to mac's IN6_IS_ADDR_UNIQUE_LOCAL + auto s6_addr_head = sa->sin6_addr.s6_addr[0]; + if (s6_addr_head == 0xfc || s6_addr_head == 0xfd) { + addr_candidate = std::string(buf, INET6_ADDRSTRLEN); + } else { + return std::string(buf, INET6_ADDRSTRLEN); + } + } + } + } + } + } + return addr_candidate; +} +#endif + +inline socket_t create_client_socket( + const std::string &host, const std::string &ip, int port, + int address_family, bool tcp_nodelay, bool ipv6_v6only, + SocketOptions socket_options, time_t connection_timeout_sec, + time_t connection_timeout_usec, time_t read_timeout_sec, + time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, const std::string &intf, Error &error) { + auto sock = create_socket( + host, ip, port, address_family, 0, tcp_nodelay, ipv6_v6only, + std::move(socket_options), + [&](socket_t sock2, struct addrinfo &ai, bool &quit) -> bool { + if (!intf.empty()) { +#ifdef USE_IF2IP + auto ip_from_if = if2ip(address_family, intf); + if (ip_from_if.empty()) { ip_from_if = intf; } + if (!bind_ip_address(sock2, ip_from_if)) { + error = Error::BindIPAddress; + return false; + } +#endif + } + + set_nonblocking(sock2, true); + + auto ret = + ::connect(sock2, ai.ai_addr, static_cast(ai.ai_addrlen)); + + if (ret < 0) { + if (is_connection_error()) { + error = Error::Connection; + return false; + } + error = wait_until_socket_is_ready(sock2, connection_timeout_sec, + connection_timeout_usec); + if (error != Error::Success) { + if (error == Error::ConnectionTimeout) { quit = true; } + return false; + } + } + + set_nonblocking(sock2, false); + set_socket_opt_time(sock2, SOL_SOCKET, SO_RCVTIMEO, read_timeout_sec, + read_timeout_usec); + set_socket_opt_time(sock2, SOL_SOCKET, SO_SNDTIMEO, write_timeout_sec, + write_timeout_usec); + + error = Error::Success; + return true; + }); + + if (sock != INVALID_SOCKET) { + error = Error::Success; + } else { + if (error == Error::Success) { error = Error::Connection; } + } + + return sock; +} + +inline bool get_ip_and_port(const struct sockaddr_storage &addr, + socklen_t addr_len, std::string &ip, int &port) { + if (addr.ss_family == AF_INET) { + port = ntohs(reinterpret_cast(&addr)->sin_port); + } else if (addr.ss_family == AF_INET6) { + port = + ntohs(reinterpret_cast(&addr)->sin6_port); + } else { + return false; + } + + std::array ipstr{}; + if (getnameinfo(reinterpret_cast(&addr), addr_len, + ipstr.data(), static_cast(ipstr.size()), nullptr, + 0, NI_NUMERICHOST)) { + return false; + } + + ip = ipstr.data(); + return true; +} + +inline void get_local_ip_and_port(socket_t sock, std::string &ip, int &port) { + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + if (!getsockname(sock, reinterpret_cast(&addr), + &addr_len)) { + get_ip_and_port(addr, addr_len, ip, port); + } +} + +inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) { + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + + if (!getpeername(sock, reinterpret_cast(&addr), + &addr_len)) { +#ifndef _WIN32 + if (addr.ss_family == AF_UNIX) { +#if defined(__linux__) + struct ucred ucred; + socklen_t len = sizeof(ucred); + if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &ucred, &len) == 0) { + port = ucred.pid; + } +#elif defined(SOL_LOCAL) && defined(SO_PEERPID) // __APPLE__ + pid_t pid; + socklen_t len = sizeof(pid); + if (getsockopt(sock, SOL_LOCAL, SO_PEERPID, &pid, &len) == 0) { + port = pid; + } +#endif + return; + } +#endif + get_ip_and_port(addr, addr_len, ip, port); + } +} + +inline constexpr unsigned int str2tag_core(const char *s, size_t l, + unsigned int h) { + return (l == 0) + ? h + : str2tag_core( + s + 1, l - 1, + // Unsets the 6 high bits of h, therefore no overflow happens + (((std::numeric_limits::max)() >> 6) & + h * 33) ^ + static_cast(*s)); +} + +inline unsigned int str2tag(const std::string &s) { + return str2tag_core(s.data(), s.size(), 0); +} + +namespace udl { + +inline constexpr unsigned int operator""_t(const char *s, size_t l) { + return str2tag_core(s, l, 0); +} + +} // namespace udl + +inline std::string +find_content_type(const std::string &path, + const std::map &user_data, + const std::string &default_content_type) { + auto ext = file_extension(path); + + auto it = user_data.find(ext); + if (it != user_data.end()) { return it->second; } + + using udl::operator""_t; + + switch (str2tag(ext)) { + default: return default_content_type; + + case "css"_t: return "text/css"; + case "csv"_t: return "text/csv"; + case "htm"_t: + case "html"_t: return "text/html"; + case "js"_t: + case "mjs"_t: return "text/javascript"; + case "txt"_t: return "text/plain"; + case "vtt"_t: return "text/vtt"; + + case "apng"_t: return "image/apng"; + case "avif"_t: return "image/avif"; + case "bmp"_t: return "image/bmp"; + case "gif"_t: return "image/gif"; + case "png"_t: return "image/png"; + case "svg"_t: return "image/svg+xml"; + case "webp"_t: return "image/webp"; + case "ico"_t: return "image/x-icon"; + case "tif"_t: return "image/tiff"; + case "tiff"_t: return "image/tiff"; + case "jpg"_t: + case "jpeg"_t: return "image/jpeg"; + + case "mp4"_t: return "video/mp4"; + case "mpeg"_t: return "video/mpeg"; + case "webm"_t: return "video/webm"; + + case "mp3"_t: return "audio/mp3"; + case "mpga"_t: return "audio/mpeg"; + case "weba"_t: return "audio/webm"; + case "wav"_t: return "audio/wave"; + + case "otf"_t: return "font/otf"; + case "ttf"_t: return "font/ttf"; + case "woff"_t: return "font/woff"; + case "woff2"_t: return "font/woff2"; + + case "7z"_t: return "application/x-7z-compressed"; + case "atom"_t: return "application/atom+xml"; + case "pdf"_t: return "application/pdf"; + case "json"_t: return "application/json"; + case "rss"_t: return "application/rss+xml"; + case "tar"_t: return "application/x-tar"; + case "xht"_t: + case "xhtml"_t: return "application/xhtml+xml"; + case "xslt"_t: return "application/xslt+xml"; + case "xml"_t: return "application/xml"; + case "gz"_t: return "application/gzip"; + case "zip"_t: return "application/zip"; + case "wasm"_t: return "application/wasm"; + } +} + +inline bool can_compress_content_type(const std::string &content_type) { + using udl::operator""_t; + + auto tag = str2tag(content_type); + + switch (tag) { + case "image/svg+xml"_t: + case "application/javascript"_t: + case "application/json"_t: + case "application/xml"_t: + case "application/protobuf"_t: + case "application/xhtml+xml"_t: return true; + + case "text/event-stream"_t: return false; + + default: return !content_type.rfind("text/", 0); + } +} + +inline EncodingType encoding_type(const Request &req, const Response &res) { + auto ret = + detail::can_compress_content_type(res.get_header_value("Content-Type")); + if (!ret) { return EncodingType::None; } + + const auto &s = req.get_header_value("Accept-Encoding"); + (void)(s); + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + // TODO: 'Accept-Encoding' has br, not br;q=0 + ret = s.find("br") != std::string::npos; + if (ret) { return EncodingType::Brotli; } +#endif + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + // TODO: 'Accept-Encoding' has gzip, not gzip;q=0 + ret = s.find("gzip") != std::string::npos; + if (ret) { return EncodingType::Gzip; } +#endif + +#ifdef CPPHTTPLIB_ZSTD_SUPPORT + // TODO: 'Accept-Encoding' has zstd, not zstd;q=0 + ret = s.find("zstd") != std::string::npos; + if (ret) { return EncodingType::Zstd; } +#endif + + return EncodingType::None; +} + +inline bool nocompressor::compress(const char *data, size_t data_length, + bool /*last*/, Callback callback) { + if (!data_length) { return true; } + return callback(data, data_length); +} + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT +inline gzip_compressor::gzip_compressor() { + std::memset(&strm_, 0, sizeof(strm_)); + strm_.zalloc = Z_NULL; + strm_.zfree = Z_NULL; + strm_.opaque = Z_NULL; + + is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, + Z_DEFAULT_STRATEGY) == Z_OK; +} + +inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); } + +inline bool gzip_compressor::compress(const char *data, size_t data_length, + bool last, Callback callback) { + assert(is_valid_); + + do { + constexpr size_t max_avail_in = + (std::numeric_limits::max)(); + + strm_.avail_in = static_cast( + (std::min)(data_length, max_avail_in)); + strm_.next_in = const_cast(reinterpret_cast(data)); + + data_length -= strm_.avail_in; + data += strm_.avail_in; + + auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH; + auto ret = Z_OK; + + std::array buff{}; + do { + strm_.avail_out = static_cast(buff.size()); + strm_.next_out = reinterpret_cast(buff.data()); + + ret = deflate(&strm_, flush); + if (ret == Z_STREAM_ERROR) { return false; } + + if (!callback(buff.data(), buff.size() - strm_.avail_out)) { + return false; + } + } while (strm_.avail_out == 0); + + assert((flush == Z_FINISH && ret == Z_STREAM_END) || + (flush == Z_NO_FLUSH && ret == Z_OK)); + assert(strm_.avail_in == 0); + } while (data_length > 0); + + return true; +} + +inline gzip_decompressor::gzip_decompressor() { + std::memset(&strm_, 0, sizeof(strm_)); + strm_.zalloc = Z_NULL; + strm_.zfree = Z_NULL; + strm_.opaque = Z_NULL; + + // 15 is the value of wbits, which should be at the maximum possible value + // to ensure that any gzip stream can be decoded. The offset of 32 specifies + // that the stream type should be automatically detected either gzip or + // deflate. + is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK; +} + +inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); } + +inline bool gzip_decompressor::is_valid() const { return is_valid_; } + +inline bool gzip_decompressor::decompress(const char *data, size_t data_length, + Callback callback) { + assert(is_valid_); + + auto ret = Z_OK; + + do { + constexpr size_t max_avail_in = + (std::numeric_limits::max)(); + + strm_.avail_in = static_cast( + (std::min)(data_length, max_avail_in)); + strm_.next_in = const_cast(reinterpret_cast(data)); + + data_length -= strm_.avail_in; + data += strm_.avail_in; + + std::array buff{}; + while (strm_.avail_in > 0 && ret == Z_OK) { + strm_.avail_out = static_cast(buff.size()); + strm_.next_out = reinterpret_cast(buff.data()); + + ret = inflate(&strm_, Z_NO_FLUSH); + + assert(ret != Z_STREAM_ERROR); + switch (ret) { + case Z_NEED_DICT: + case Z_DATA_ERROR: + case Z_MEM_ERROR: inflateEnd(&strm_); return false; + } + + if (!callback(buff.data(), buff.size() - strm_.avail_out)) { + return false; + } + } + + if (ret != Z_OK && ret != Z_STREAM_END) { return false; } + + } while (data_length > 0); + + return true; +} +#endif + +#ifdef CPPHTTPLIB_BROTLI_SUPPORT +inline brotli_compressor::brotli_compressor() { + state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); +} + +inline brotli_compressor::~brotli_compressor() { + BrotliEncoderDestroyInstance(state_); +} + +inline bool brotli_compressor::compress(const char *data, size_t data_length, + bool last, Callback callback) { + std::array buff{}; + + auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS; + auto available_in = data_length; + auto next_in = reinterpret_cast(data); + + for (;;) { + if (last) { + if (BrotliEncoderIsFinished(state_)) { break; } + } else { + if (!available_in) { break; } + } + + auto available_out = buff.size(); + auto next_out = buff.data(); + + if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in, + &available_out, &next_out, nullptr)) { + return false; + } + + auto output_bytes = buff.size() - available_out; + if (output_bytes) { + callback(reinterpret_cast(buff.data()), output_bytes); + } + } + + return true; +} + +inline brotli_decompressor::brotli_decompressor() { + decoder_s = BrotliDecoderCreateInstance(0, 0, 0); + decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT + : BROTLI_DECODER_RESULT_ERROR; +} + +inline brotli_decompressor::~brotli_decompressor() { + if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); } +} + +inline bool brotli_decompressor::is_valid() const { return decoder_s; } + +inline bool brotli_decompressor::decompress(const char *data, + size_t data_length, + Callback callback) { + if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS || + decoder_r == BROTLI_DECODER_RESULT_ERROR) { + return 0; + } + + auto next_in = reinterpret_cast(data); + size_t avail_in = data_length; + size_t total_out; + + decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT; + + std::array buff{}; + while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) { + char *next_out = buff.data(); + size_t avail_out = buff.size(); + + decoder_r = BrotliDecoderDecompressStream( + decoder_s, &avail_in, &next_in, &avail_out, + reinterpret_cast(&next_out), &total_out); + + if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; } + + if (!callback(buff.data(), buff.size() - avail_out)) { return false; } + } + + return decoder_r == BROTLI_DECODER_RESULT_SUCCESS || + decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT; +} +#endif + +#ifdef CPPHTTPLIB_ZSTD_SUPPORT +inline zstd_compressor::zstd_compressor() { + ctx_ = ZSTD_createCCtx(); + ZSTD_CCtx_setParameter(ctx_, ZSTD_c_compressionLevel, ZSTD_fast); +} + +inline zstd_compressor::~zstd_compressor() { ZSTD_freeCCtx(ctx_); } + +inline bool zstd_compressor::compress(const char *data, size_t data_length, + bool last, Callback callback) { + std::array buff{}; + + ZSTD_EndDirective mode = last ? ZSTD_e_end : ZSTD_e_continue; + ZSTD_inBuffer input = {data, data_length, 0}; + + bool finished; + do { + ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0}; + size_t const remaining = ZSTD_compressStream2(ctx_, &output, &input, mode); + + if (ZSTD_isError(remaining)) { return false; } + + if (!callback(buff.data(), output.pos)) { return false; } + + finished = last ? (remaining == 0) : (input.pos == input.size); + + } while (!finished); + + return true; +} + +inline zstd_decompressor::zstd_decompressor() { ctx_ = ZSTD_createDCtx(); } + +inline zstd_decompressor::~zstd_decompressor() { ZSTD_freeDCtx(ctx_); } + +inline bool zstd_decompressor::is_valid() const { return ctx_ != nullptr; } + +inline bool zstd_decompressor::decompress(const char *data, size_t data_length, + Callback callback) { + std::array buff{}; + ZSTD_inBuffer input = {data, data_length, 0}; + + while (input.pos < input.size) { + ZSTD_outBuffer output = {buff.data(), CPPHTTPLIB_COMPRESSION_BUFSIZ, 0}; + size_t const remaining = ZSTD_decompressStream(ctx_, &output, &input); + + if (ZSTD_isError(remaining)) { return false; } + + if (!callback(buff.data(), output.pos)) { return false; } + } + + return true; +} +#endif + +inline bool has_header(const Headers &headers, const std::string &key) { + return headers.find(key) != headers.end(); +} + +inline const char *get_header_value(const Headers &headers, + const std::string &key, const char *def, + size_t id) { + auto rng = headers.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { return it->second.c_str(); } + return def; +} + +template +inline bool parse_header(const char *beg, const char *end, T fn) { + // Skip trailing spaces and tabs. + while (beg < end && is_space_or_tab(end[-1])) { + end--; + } + + auto p = beg; + while (p < end && *p != ':') { + p++; + } + + auto name = std::string(beg, p); + if (!detail::fields::is_field_name(name)) { return false; } + + if (p == end) { return false; } + + auto key_end = p; + + if (*p++ != ':') { return false; } + + while (p < end && is_space_or_tab(*p)) { + p++; + } + + if (p <= end) { + auto key_len = key_end - beg; + if (!key_len) { return false; } + + auto key = std::string(beg, key_end); + auto val = std::string(p, end); + + if (!detail::fields::is_field_value(val)) { return false; } + + if (case_ignore::equal(key, "Location") || + case_ignore::equal(key, "Referer")) { + fn(key, val); + } else { + fn(key, decode_url(val, false)); + } + + return true; + } + + return false; +} + +inline bool read_headers(Stream &strm, Headers &headers) { + const auto bufsiz = 2048; + char buf[bufsiz]; + stream_line_reader line_reader(strm, buf, bufsiz); + + for (;;) { + if (!line_reader.getline()) { return false; } + + // Check if the line ends with CRLF. + auto line_terminator_len = 2; + if (line_reader.end_with_crlf()) { + // Blank line indicates end of headers. + if (line_reader.size() == 2) { break; } + } else { +#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR + // Blank line indicates end of headers. + if (line_reader.size() == 1) { break; } + line_terminator_len = 1; +#else + continue; // Skip invalid line. +#endif + } + + if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + + // Exclude line terminator + auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; + + if (!parse_header(line_reader.ptr(), end, + [&](const std::string &key, const std::string &val) { + headers.emplace(key, val); + })) { + return false; + } + } + + return true; +} + +inline bool read_content_with_length(Stream &strm, uint64_t len, + Progress progress, + ContentReceiverWithProgress out) { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + + uint64_t r = 0; + while (r < len) { + auto read_len = static_cast(len - r); + auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); + if (n <= 0) { return false; } + + if (!out(buf, static_cast(n), r, len)) { return false; } + r += static_cast(n); + + if (progress) { + if (!progress(r, len)) { return false; } + } + } + + return true; +} + +inline void skip_content_with_length(Stream &strm, uint64_t len) { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + uint64_t r = 0; + while (r < len) { + auto read_len = static_cast(len - r); + auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); + if (n <= 0) { return; } + r += static_cast(n); + } +} + +inline bool read_content_without_length(Stream &strm, + ContentReceiverWithProgress out) { + char buf[CPPHTTPLIB_RECV_BUFSIZ]; + uint64_t r = 0; + for (;;) { + auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ); + if (n == 0) { return true; } + if (n < 0) { return false; } + + if (!out(buf, static_cast(n), r, 0)) { return false; } + r += static_cast(n); + } + + return true; +} + +template +inline bool read_content_chunked(Stream &strm, T &x, + ContentReceiverWithProgress out) { + const auto bufsiz = 16; + char buf[bufsiz]; + + stream_line_reader line_reader(strm, buf, bufsiz); + + if (!line_reader.getline()) { return false; } + + unsigned long chunk_len; + while (true) { + char *end_ptr; + + chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16); + + if (end_ptr == line_reader.ptr()) { return false; } + if (chunk_len == ULONG_MAX) { return false; } + + if (chunk_len == 0) { break; } + + if (!read_content_with_length(strm, chunk_len, nullptr, out)) { + return false; + } + + if (!line_reader.getline()) { return false; } + + if (strcmp(line_reader.ptr(), "\r\n") != 0) { return false; } + + if (!line_reader.getline()) { return false; } + } + + assert(chunk_len == 0); + + // NOTE: In RFC 9112, '7.1 Chunked Transfer Coding' mentions "The chunked + // transfer coding is complete when a chunk with a chunk-size of zero is + // received, possibly followed by a trailer section, and finally terminated by + // an empty line". https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1 + // + // In '7.1.3. Decoding Chunked', however, the pseudo-code in the section + // does't care for the existence of the final CRLF. In other words, it seems + // to be ok whether the final CRLF exists or not in the chunked data. + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.1.3 + // + // According to the reference code in RFC 9112, cpp-httplib now allows + // chunked transfer coding data without the final CRLF. + if (!line_reader.getline()) { return true; } + + while (strcmp(line_reader.ptr(), "\r\n") != 0) { + if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + + // Exclude line terminator + constexpr auto line_terminator_len = 2; + auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; + + parse_header(line_reader.ptr(), end, + [&](const std::string &key, const std::string &val) { + x.headers.emplace(key, val); + }); + + if (!line_reader.getline()) { return false; } + } + + return true; +} + +inline bool is_chunked_transfer_encoding(const Headers &headers) { + return case_ignore::equal( + get_header_value(headers, "Transfer-Encoding", "", 0), "chunked"); +} + +template +bool prepare_content_receiver(T &x, int &status, + ContentReceiverWithProgress receiver, + bool decompress, U callback) { + if (decompress) { + std::string encoding = x.get_header_value("Content-Encoding"); + std::unique_ptr decompressor; + + if (encoding == "gzip" || encoding == "deflate") { +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + decompressor = detail::make_unique(); +#else + status = StatusCode::UnsupportedMediaType_415; + return false; +#endif + } else if (encoding.find("br") != std::string::npos) { +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + decompressor = detail::make_unique(); +#else + status = StatusCode::UnsupportedMediaType_415; + return false; +#endif + } else if (encoding == "zstd") { +#ifdef CPPHTTPLIB_ZSTD_SUPPORT + decompressor = detail::make_unique(); +#else + status = StatusCode::UnsupportedMediaType_415; + return false; +#endif + } + + if (decompressor) { + if (decompressor->is_valid()) { + ContentReceiverWithProgress out = [&](const char *buf, size_t n, + uint64_t off, uint64_t len) { + return decompressor->decompress(buf, n, + [&](const char *buf2, size_t n2) { + return receiver(buf2, n2, off, len); + }); + }; + return callback(std::move(out)); + } else { + status = StatusCode::InternalServerError_500; + return false; + } + } + } + + ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off, + uint64_t len) { + return receiver(buf, n, off, len); + }; + return callback(std::move(out)); +} + +template +bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status, + Progress progress, ContentReceiverWithProgress receiver, + bool decompress) { + return prepare_content_receiver( + x, status, std::move(receiver), decompress, + [&](const ContentReceiverWithProgress &out) { + auto ret = true; + auto exceed_payload_max_length = false; + + if (is_chunked_transfer_encoding(x.headers)) { + ret = read_content_chunked(strm, x, out); + } else if (!has_header(x.headers, "Content-Length")) { + ret = read_content_without_length(strm, out); + } else { + auto is_invalid_value = false; + auto len = get_header_value_u64( + x.headers, "Content-Length", + (std::numeric_limits::max)(), 0, is_invalid_value); + + if (is_invalid_value) { + ret = false; + } else if (len > payload_max_length) { + exceed_payload_max_length = true; + skip_content_with_length(strm, len); + ret = false; + } else if (len > 0) { + ret = read_content_with_length(strm, len, std::move(progress), out); + } + } + + if (!ret) { + status = exceed_payload_max_length ? StatusCode::PayloadTooLarge_413 + : StatusCode::BadRequest_400; + } + return ret; + }); +} + +inline ssize_t write_request_line(Stream &strm, const std::string &method, + const std::string &path) { + std::string s = method; + s += " "; + s += path; + s += " HTTP/1.1\r\n"; + return strm.write(s.data(), s.size()); +} + +inline ssize_t write_response_line(Stream &strm, int status) { + std::string s = "HTTP/1.1 "; + s += std::to_string(status); + s += " "; + s += httplib::status_message(status); + s += "\r\n"; + return strm.write(s.data(), s.size()); +} + +inline ssize_t write_headers(Stream &strm, const Headers &headers) { + ssize_t write_len = 0; + for (const auto &x : headers) { + std::string s; + s = x.first; + s += ": "; + s += x.second; + s += "\r\n"; + + auto len = strm.write(s.data(), s.size()); + if (len < 0) { return len; } + write_len += len; + } + auto len = strm.write("\r\n"); + if (len < 0) { return len; } + write_len += len; + return write_len; +} + +inline bool write_data(Stream &strm, const char *d, size_t l) { + size_t offset = 0; + while (offset < l) { + auto length = strm.write(d + offset, l - offset); + if (length < 0) { return false; } + offset += static_cast(length); + } + return true; +} + +template +inline bool write_content(Stream &strm, const ContentProvider &content_provider, + size_t offset, size_t length, T is_shutting_down, + Error &error) { + size_t end_offset = offset + length; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char *d, size_t l) -> bool { + if (ok) { + if (write_data(strm, d, l)) { + offset += l; + } else { + ok = false; + } + } + return ok; + }; + + data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); }; + + while (offset < end_offset && !is_shutting_down()) { + if (!strm.wait_writable()) { + error = Error::Write; + return false; + } else if (!content_provider(offset, end_offset - offset, data_sink)) { + error = Error::Canceled; + return false; + } else if (!ok) { + error = Error::Write; + return false; + } + } + + error = Error::Success; + return true; +} + +template +inline bool write_content(Stream &strm, const ContentProvider &content_provider, + size_t offset, size_t length, + const T &is_shutting_down) { + auto error = Error::Success; + return write_content(strm, content_provider, offset, length, is_shutting_down, + error); +} + +template +inline bool +write_content_without_length(Stream &strm, + const ContentProvider &content_provider, + const T &is_shutting_down) { + size_t offset = 0; + auto data_available = true; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char *d, size_t l) -> bool { + if (ok) { + offset += l; + if (!write_data(strm, d, l)) { ok = false; } + } + return ok; + }; + + data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); }; + + data_sink.done = [&](void) { data_available = false; }; + + while (data_available && !is_shutting_down()) { + if (!strm.wait_writable()) { + return false; + } else if (!content_provider(offset, 0, data_sink)) { + return false; + } else if (!ok) { + return false; + } + } + return true; +} + +template +inline bool +write_content_chunked(Stream &strm, const ContentProvider &content_provider, + const T &is_shutting_down, U &compressor, Error &error) { + size_t offset = 0; + auto data_available = true; + auto ok = true; + DataSink data_sink; + + data_sink.write = [&](const char *d, size_t l) -> bool { + if (ok) { + data_available = l > 0; + offset += l; + + std::string payload; + if (compressor.compress(d, l, false, + [&](const char *data, size_t data_len) { + payload.append(data, data_len); + return true; + })) { + if (!payload.empty()) { + // Emit chunked response header and footer for each chunk + auto chunk = + from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; + if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; } + } + } else { + ok = false; + } + } + return ok; + }; + + data_sink.is_writable = [&]() -> bool { return strm.wait_writable(); }; + + auto done_with_trailer = [&](const Headers *trailer) { + if (!ok) { return; } + + data_available = false; + + std::string payload; + if (!compressor.compress(nullptr, 0, true, + [&](const char *data, size_t data_len) { + payload.append(data, data_len); + return true; + })) { + ok = false; + return; + } + + if (!payload.empty()) { + // Emit chunked response header and footer for each chunk + auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n"; + if (!write_data(strm, chunk.data(), chunk.size())) { + ok = false; + return; + } + } + + constexpr const char done_marker[] = "0\r\n"; + if (!write_data(strm, done_marker, str_len(done_marker))) { ok = false; } + + // Trailer + if (trailer) { + for (const auto &kv : *trailer) { + std::string field_line = kv.first + ": " + kv.second + "\r\n"; + if (!write_data(strm, field_line.data(), field_line.size())) { + ok = false; + } + } + } + + constexpr const char crlf[] = "\r\n"; + if (!write_data(strm, crlf, str_len(crlf))) { ok = false; } + }; + + data_sink.done = [&](void) { done_with_trailer(nullptr); }; + + data_sink.done_with_trailer = [&](const Headers &trailer) { + done_with_trailer(&trailer); + }; + + while (data_available && !is_shutting_down()) { + if (!strm.wait_writable()) { + error = Error::Write; + return false; + } else if (!content_provider(offset, 0, data_sink)) { + error = Error::Canceled; + return false; + } else if (!ok) { + error = Error::Write; + return false; + } + } + + error = Error::Success; + return true; +} + +template +inline bool write_content_chunked(Stream &strm, + const ContentProvider &content_provider, + const T &is_shutting_down, U &compressor) { + auto error = Error::Success; + return write_content_chunked(strm, content_provider, is_shutting_down, + compressor, error); +} + +template +inline bool redirect(T &cli, Request &req, Response &res, + const std::string &path, const std::string &location, + Error &error) { + Request new_req = req; + new_req.path = path; + new_req.redirect_count_ -= 1; + + if (res.status == StatusCode::SeeOther_303 && + (req.method != "GET" && req.method != "HEAD")) { + new_req.method = "GET"; + new_req.body.clear(); + new_req.headers.clear(); + } + + Response new_res; + + auto ret = cli.send(new_req, new_res, error); + if (ret) { + req = new_req; + res = new_res; + + if (res.location.empty()) { res.location = location; } + } + return ret; +} + +inline std::string params_to_query_str(const Params ¶ms) { + std::string query; + + for (auto it = params.begin(); it != params.end(); ++it) { + if (it != params.begin()) { query += "&"; } + query += it->first; + query += "="; + query += encode_query_param(it->second); + } + return query; +} + +inline void parse_query_text(const char *data, std::size_t size, + Params ¶ms) { + std::set cache; + split(data, data + size, '&', [&](const char *b, const char *e) { + std::string kv(b, e); + if (cache.find(kv) != cache.end()) { return; } + cache.insert(std::move(kv)); + + std::string key; + std::string val; + divide(b, static_cast(e - b), '=', + [&](const char *lhs_data, std::size_t lhs_size, const char *rhs_data, + std::size_t rhs_size) { + key.assign(lhs_data, lhs_size); + val.assign(rhs_data, rhs_size); + }); + + if (!key.empty()) { + params.emplace(decode_url(key, true), decode_url(val, true)); + } + }); +} + +inline void parse_query_text(const std::string &s, Params ¶ms) { + parse_query_text(s.data(), s.size(), params); +} + +inline bool parse_multipart_boundary(const std::string &content_type, + std::string &boundary) { + auto boundary_keyword = "boundary="; + auto pos = content_type.find(boundary_keyword); + if (pos == std::string::npos) { return false; } + auto end = content_type.find(';', pos); + auto beg = pos + strlen(boundary_keyword); + boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg)); + return !boundary.empty(); +} + +inline void parse_disposition_params(const std::string &s, Params ¶ms) { + std::set cache; + split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) { + std::string kv(b, e); + if (cache.find(kv) != cache.end()) { return; } + cache.insert(kv); + + std::string key; + std::string val; + split(b, e, '=', [&](const char *b2, const char *e2) { + if (key.empty()) { + key.assign(b2, e2); + } else { + val.assign(b2, e2); + } + }); + + if (!key.empty()) { + params.emplace(trim_double_quotes_copy((key)), + trim_double_quotes_copy((val))); + } + }); +} + +#ifdef CPPHTTPLIB_NO_EXCEPTIONS +inline bool parse_range_header(const std::string &s, Ranges &ranges) { +#else +inline bool parse_range_header(const std::string &s, Ranges &ranges) try { +#endif + auto is_valid = [](const std::string &str) { + return std::all_of(str.cbegin(), str.cend(), + [](unsigned char c) { return std::isdigit(c); }); + }; + + if (s.size() > 7 && s.compare(0, 6, "bytes=") == 0) { + const auto pos = static_cast(6); + const auto len = static_cast(s.size() - 6); + auto all_valid_ranges = true; + split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) { + if (!all_valid_ranges) { return; } + + const auto it = std::find(b, e, '-'); + if (it == e) { + all_valid_ranges = false; + return; + } + + const auto lhs = std::string(b, it); + const auto rhs = std::string(it + 1, e); + if (!is_valid(lhs) || !is_valid(rhs)) { + all_valid_ranges = false; + return; + } + + const auto first = + static_cast(lhs.empty() ? -1 : std::stoll(lhs)); + const auto last = + static_cast(rhs.empty() ? -1 : std::stoll(rhs)); + if ((first == -1 && last == -1) || + (first != -1 && last != -1 && first > last)) { + all_valid_ranges = false; + return; + } + + ranges.emplace_back(first, last); + }); + return all_valid_ranges && !ranges.empty(); + } + return false; +#ifdef CPPHTTPLIB_NO_EXCEPTIONS +} +#else +} catch (...) { return false; } +#endif + +class MultipartFormDataParser { +public: + MultipartFormDataParser() = default; + + void set_boundary(std::string &&boundary) { + boundary_ = boundary; + dash_boundary_crlf_ = dash_ + boundary_ + crlf_; + crlf_dash_boundary_ = crlf_ + dash_ + boundary_; + } + + bool is_valid() const { return is_valid_; } + + bool parse(const char *buf, size_t n, const ContentReceiver &content_callback, + const MultipartContentHeader &header_callback) { + + buf_append(buf, n); + + while (buf_size() > 0) { + switch (state_) { + case 0: { // Initial boundary + buf_erase(buf_find(dash_boundary_crlf_)); + if (dash_boundary_crlf_.size() > buf_size()) { return true; } + if (!buf_start_with(dash_boundary_crlf_)) { return false; } + buf_erase(dash_boundary_crlf_.size()); + state_ = 1; + break; + } + case 1: { // New entry + clear_file_info(); + state_ = 2; + break; + } + case 2: { // Headers + auto pos = buf_find(crlf_); + if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + while (pos < buf_size()) { + // Empty line + if (pos == 0) { + if (!header_callback(file_)) { + is_valid_ = false; + return false; + } + buf_erase(crlf_.size()); + state_ = 3; + break; + } + + const auto header = buf_head(pos); + + if (!parse_header(header.data(), header.data() + header.size(), + [&](const std::string &, const std::string &) {})) { + is_valid_ = false; + return false; + } + + // parse and emplace space trimmed headers into a map + if (!parse_header( + header.data(), header.data() + header.size(), + [&](const std::string &key, const std::string &val) { + file_.headers.emplace(key, val); + })) { + is_valid_ = false; + return false; + } + + constexpr const char header_content_type[] = "Content-Type:"; + + if (start_with_case_ignore(header, header_content_type)) { + file_.content_type = + trim_copy(header.substr(str_len(header_content_type))); + } else { + thread_local const std::regex re_content_disposition( + R"~(^Content-Disposition:\s*form-data;\s*(.*)$)~", + std::regex_constants::icase); + + std::smatch m; + if (std::regex_match(header, m, re_content_disposition)) { + Params params; + parse_disposition_params(m[1], params); + + auto it = params.find("name"); + if (it != params.end()) { + file_.name = it->second; + } else { + is_valid_ = false; + return false; + } + + it = params.find("filename"); + if (it != params.end()) { file_.filename = it->second; } + + it = params.find("filename*"); + if (it != params.end()) { + // Only allow UTF-8 encoding... + thread_local const std::regex re_rfc5987_encoding( + R"~(^UTF-8''(.+?)$)~", std::regex_constants::icase); + + std::smatch m2; + if (std::regex_match(it->second, m2, re_rfc5987_encoding)) { + file_.filename = decode_url(m2[1], false); // override... + } else { + is_valid_ = false; + return false; + } + } + } + } + buf_erase(pos + crlf_.size()); + pos = buf_find(crlf_); + } + if (state_ != 3) { return true; } + break; + } + case 3: { // Body + if (crlf_dash_boundary_.size() > buf_size()) { return true; } + auto pos = buf_find(crlf_dash_boundary_); + if (pos < buf_size()) { + if (!content_callback(buf_data(), pos)) { + is_valid_ = false; + return false; + } + buf_erase(pos + crlf_dash_boundary_.size()); + state_ = 4; + } else { + auto len = buf_size() - crlf_dash_boundary_.size(); + if (len > 0) { + if (!content_callback(buf_data(), len)) { + is_valid_ = false; + return false; + } + buf_erase(len); + } + return true; + } + break; + } + case 4: { // Boundary + if (crlf_.size() > buf_size()) { return true; } + if (buf_start_with(crlf_)) { + buf_erase(crlf_.size()); + state_ = 1; + } else { + if (dash_.size() > buf_size()) { return true; } + if (buf_start_with(dash_)) { + buf_erase(dash_.size()); + is_valid_ = true; + buf_erase(buf_size()); // Remove epilogue + } else { + return true; + } + } + break; + } + } + } + + return true; + } + +private: + void clear_file_info() { + file_.name.clear(); + file_.filename.clear(); + file_.content_type.clear(); + file_.headers.clear(); + } + + bool start_with_case_ignore(const std::string &a, const char *b) const { + const auto b_len = strlen(b); + if (a.size() < b_len) { return false; } + for (size_t i = 0; i < b_len; i++) { + if (case_ignore::to_lower(a[i]) != case_ignore::to_lower(b[i])) { + return false; + } + } + return true; + } + + const std::string dash_ = "--"; + const std::string crlf_ = "\r\n"; + std::string boundary_; + std::string dash_boundary_crlf_; + std::string crlf_dash_boundary_; + + size_t state_ = 0; + bool is_valid_ = false; + MultipartFormData file_; + + // Buffer + bool start_with(const std::string &a, size_t spos, size_t epos, + const std::string &b) const { + if (epos - spos < b.size()) { return false; } + for (size_t i = 0; i < b.size(); i++) { + if (a[i + spos] != b[i]) { return false; } + } + return true; + } + + size_t buf_size() const { return buf_epos_ - buf_spos_; } + + const char *buf_data() const { return &buf_[buf_spos_]; } + + std::string buf_head(size_t l) const { return buf_.substr(buf_spos_, l); } + + bool buf_start_with(const std::string &s) const { + return start_with(buf_, buf_spos_, buf_epos_, s); + } + + size_t buf_find(const std::string &s) const { + auto c = s.front(); + + size_t off = buf_spos_; + while (off < buf_epos_) { + auto pos = off; + while (true) { + if (pos == buf_epos_) { return buf_size(); } + if (buf_[pos] == c) { break; } + pos++; + } + + auto remaining_size = buf_epos_ - pos; + if (s.size() > remaining_size) { return buf_size(); } + + if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; } + + off = pos + 1; + } + + return buf_size(); + } + + void buf_append(const char *data, size_t n) { + auto remaining_size = buf_size(); + if (remaining_size > 0 && buf_spos_ > 0) { + for (size_t i = 0; i < remaining_size; i++) { + buf_[i] = buf_[buf_spos_ + i]; + } + } + buf_spos_ = 0; + buf_epos_ = remaining_size; + + if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); } + + for (size_t i = 0; i < n; i++) { + buf_[buf_epos_ + i] = data[i]; + } + buf_epos_ += n; + } + + void buf_erase(size_t size) { buf_spos_ += size; } + + std::string buf_; + size_t buf_spos_ = 0; + size_t buf_epos_ = 0; +}; + +inline std::string random_string(size_t length) { + constexpr const char data[] = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; + + thread_local auto engine([]() { + // std::random_device might actually be deterministic on some + // platforms, but due to lack of support in the c++ standard library, + // doing better requires either some ugly hacks or breaking portability. + std::random_device seed_gen; + // Request 128 bits of entropy for initialization + std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()}; + return std::mt19937(seed_sequence); + }()); + + std::string result; + for (size_t i = 0; i < length; i++) { + result += data[engine() % (sizeof(data) - 1)]; + } + return result; +} + +inline std::string make_multipart_data_boundary() { + return "--cpp-httplib-multipart-data-" + detail::random_string(16); +} + +inline bool is_multipart_boundary_chars_valid(const std::string &boundary) { + auto valid = true; + for (size_t i = 0; i < boundary.size(); i++) { + auto c = boundary[i]; + if (!std::isalnum(c) && c != '-' && c != '_') { + valid = false; + break; + } + } + return valid; +} + +template +inline std::string +serialize_multipart_formdata_item_begin(const T &item, + const std::string &boundary) { + std::string body = "--" + boundary + "\r\n"; + body += "Content-Disposition: form-data; name=\"" + item.name + "\""; + if (!item.filename.empty()) { + body += "; filename=\"" + item.filename + "\""; + } + body += "\r\n"; + if (!item.content_type.empty()) { + body += "Content-Type: " + item.content_type + "\r\n"; + } + body += "\r\n"; + + return body; +} + +inline std::string serialize_multipart_formdata_item_end() { return "\r\n"; } + +inline std::string +serialize_multipart_formdata_finish(const std::string &boundary) { + return "--" + boundary + "--\r\n"; +} + +inline std::string +serialize_multipart_formdata_get_content_type(const std::string &boundary) { + return "multipart/form-data; boundary=" + boundary; +} + +inline std::string +serialize_multipart_formdata(const MultipartFormDataItems &items, + const std::string &boundary, bool finish = true) { + std::string body; + + for (const auto &item : items) { + body += serialize_multipart_formdata_item_begin(item, boundary); + body += item.content + serialize_multipart_formdata_item_end(); + } + + if (finish) { body += serialize_multipart_formdata_finish(boundary); } + + return body; +} + +inline bool range_error(Request &req, Response &res) { + if (!req.ranges.empty() && 200 <= res.status && res.status < 300) { + ssize_t content_len = static_cast( + res.content_length_ ? res.content_length_ : res.body.size()); + + ssize_t prev_first_pos = -1; + ssize_t prev_last_pos = -1; + size_t overwrapping_count = 0; + + // NOTE: The following Range check is based on '14.2. Range' in RFC 9110 + // 'HTTP Semantics' to avoid potential denial-of-service attacks. + // https://www.rfc-editor.org/rfc/rfc9110#section-14.2 + + // Too many ranges + if (req.ranges.size() > CPPHTTPLIB_RANGE_MAX_COUNT) { return true; } + + for (auto &r : req.ranges) { + auto &first_pos = r.first; + auto &last_pos = r.second; + + if (first_pos == -1 && last_pos == -1) { + first_pos = 0; + last_pos = content_len; + } + + if (first_pos == -1) { + first_pos = content_len - last_pos; + last_pos = content_len - 1; + } + + // NOTE: RFC-9110 '14.1.2. Byte Ranges': + // A client can limit the number of bytes requested without knowing the + // size of the selected representation. If the last-pos value is absent, + // or if the value is greater than or equal to the current length of the + // representation data, the byte range is interpreted as the remainder of + // the representation (i.e., the server replaces the value of last-pos + // with a value that is one less than the current length of the selected + // representation). + // https://www.rfc-editor.org/rfc/rfc9110.html#section-14.1.2-6 + if (last_pos == -1 || last_pos >= content_len) { + last_pos = content_len - 1; + } + + // Range must be within content length + if (!(0 <= first_pos && first_pos <= last_pos && + last_pos <= content_len - 1)) { + return true; + } + + // Ranges must be in ascending order + if (first_pos <= prev_first_pos) { return true; } + + // Request must not have more than two overlapping ranges + if (first_pos <= prev_last_pos) { + overwrapping_count++; + if (overwrapping_count > 2) { return true; } + } + + prev_first_pos = (std::max)(prev_first_pos, first_pos); + prev_last_pos = (std::max)(prev_last_pos, last_pos); + } + } + + return false; +} + +inline std::pair +get_range_offset_and_length(Range r, size_t content_length) { + assert(r.first != -1 && r.second != -1); + assert(0 <= r.first && r.first < static_cast(content_length)); + assert(r.first <= r.second && + r.second < static_cast(content_length)); + (void)(content_length); + return std::make_pair(r.first, static_cast(r.second - r.first) + 1); +} + +inline std::string make_content_range_header_field( + const std::pair &offset_and_length, size_t content_length) { + auto st = offset_and_length.first; + auto ed = st + offset_and_length.second - 1; + + std::string field = "bytes "; + field += std::to_string(st); + field += "-"; + field += std::to_string(ed); + field += "/"; + field += std::to_string(content_length); + return field; +} + +template +bool process_multipart_ranges_data(const Request &req, + const std::string &boundary, + const std::string &content_type, + size_t content_length, SToken stoken, + CToken ctoken, Content content) { + for (size_t i = 0; i < req.ranges.size(); i++) { + ctoken("--"); + stoken(boundary); + ctoken("\r\n"); + if (!content_type.empty()) { + ctoken("Content-Type: "); + stoken(content_type); + ctoken("\r\n"); + } + + auto offset_and_length = + get_range_offset_and_length(req.ranges[i], content_length); + + ctoken("Content-Range: "); + stoken(make_content_range_header_field(offset_and_length, content_length)); + ctoken("\r\n"); + ctoken("\r\n"); + + if (!content(offset_and_length.first, offset_and_length.second)) { + return false; + } + ctoken("\r\n"); + } + + ctoken("--"); + stoken(boundary); + ctoken("--"); + + return true; +} + +inline void make_multipart_ranges_data(const Request &req, Response &res, + const std::string &boundary, + const std::string &content_type, + size_t content_length, + std::string &data) { + process_multipart_ranges_data( + req, boundary, content_type, content_length, + [&](const std::string &token) { data += token; }, + [&](const std::string &token) { data += token; }, + [&](size_t offset, size_t length) { + assert(offset + length <= content_length); + data += res.body.substr(offset, length); + return true; + }); +} + +inline size_t get_multipart_ranges_data_length(const Request &req, + const std::string &boundary, + const std::string &content_type, + size_t content_length) { + size_t data_length = 0; + + process_multipart_ranges_data( + req, boundary, content_type, content_length, + [&](const std::string &token) { data_length += token.size(); }, + [&](const std::string &token) { data_length += token.size(); }, + [&](size_t /*offset*/, size_t length) { + data_length += length; + return true; + }); + + return data_length; +} + +template +inline bool +write_multipart_ranges_data(Stream &strm, const Request &req, Response &res, + const std::string &boundary, + const std::string &content_type, + size_t content_length, const T &is_shutting_down) { + return process_multipart_ranges_data( + req, boundary, content_type, content_length, + [&](const std::string &token) { strm.write(token); }, + [&](const std::string &token) { strm.write(token); }, + [&](size_t offset, size_t length) { + return write_content(strm, res.content_provider_, offset, length, + is_shutting_down); + }); +} + +inline bool expect_content(const Request &req) { + if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" || + req.method == "DELETE") { + return true; + } + if (req.has_header("Content-Length") && + req.get_header_value_u64("Content-Length") > 0) { + return true; + } + if (is_chunked_transfer_encoding(req.headers)) { return true; } + return false; +} + +inline bool has_crlf(const std::string &s) { + auto p = s.c_str(); + while (*p) { + if (*p == '\r' || *p == '\n') { return true; } + p++; + } + return false; +} + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline std::string message_digest(const std::string &s, const EVP_MD *algo) { + auto context = std::unique_ptr( + EVP_MD_CTX_new(), EVP_MD_CTX_free); + + unsigned int hash_length = 0; + unsigned char hash[EVP_MAX_MD_SIZE]; + + EVP_DigestInit_ex(context.get(), algo, nullptr); + EVP_DigestUpdate(context.get(), s.c_str(), s.size()); + EVP_DigestFinal_ex(context.get(), hash, &hash_length); + + std::stringstream ss; + for (auto i = 0u; i < hash_length; ++i) { + ss << std::hex << std::setw(2) << std::setfill('0') + << static_cast(hash[i]); + } + + return ss.str(); +} + +inline std::string MD5(const std::string &s) { + return message_digest(s, EVP_md5()); +} + +inline std::string SHA_256(const std::string &s) { + return message_digest(s, EVP_sha256()); +} + +inline std::string SHA_512(const std::string &s) { + return message_digest(s, EVP_sha512()); +} + +inline std::pair make_digest_authentication_header( + const Request &req, const std::map &auth, + size_t cnonce_count, const std::string &cnonce, const std::string &username, + const std::string &password, bool is_proxy = false) { + std::string nc; + { + std::stringstream ss; + ss << std::setfill('0') << std::setw(8) << std::hex << cnonce_count; + nc = ss.str(); + } + + std::string qop; + if (auth.find("qop") != auth.end()) { + qop = auth.at("qop"); + if (qop.find("auth-int") != std::string::npos) { + qop = "auth-int"; + } else if (qop.find("auth") != std::string::npos) { + qop = "auth"; + } else { + qop.clear(); + } + } + + std::string algo = "MD5"; + if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); } + + std::string response; + { + auto H = algo == "SHA-256" ? detail::SHA_256 + : algo == "SHA-512" ? detail::SHA_512 + : detail::MD5; + + auto A1 = username + ":" + auth.at("realm") + ":" + password; + + auto A2 = req.method + ":" + req.path; + if (qop == "auth-int") { A2 += ":" + H(req.body); } + + if (qop.empty()) { + response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2)); + } else { + response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce + + ":" + qop + ":" + H(A2)); + } + } + + auto opaque = (auth.find("opaque") != auth.end()) ? auth.at("opaque") : ""; + + auto field = "Digest username=\"" + username + "\", realm=\"" + + auth.at("realm") + "\", nonce=\"" + auth.at("nonce") + + "\", uri=\"" + req.path + "\", algorithm=" + algo + + (qop.empty() ? ", response=\"" + : ", qop=" + qop + ", nc=" + nc + ", cnonce=\"" + + cnonce + "\", response=\"") + + response + "\"" + + (opaque.empty() ? "" : ", opaque=\"" + opaque + "\""); + + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, field); +} + +inline bool is_ssl_peer_could_be_closed(SSL *ssl, socket_t sock) { + detail::set_nonblocking(sock, true); + auto se = detail::scope_exit([&]() { detail::set_nonblocking(sock, false); }); + + char buf[1]; + return !SSL_peek(ssl, buf, 1) && + SSL_get_error(ssl, 0) == SSL_ERROR_ZERO_RETURN; +} + +#ifdef _WIN32 +// NOTE: This code came up with the following stackoverflow post: +// https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store +inline bool load_system_certs_on_windows(X509_STORE *store) { + auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT"); + if (!hStore) { return false; } + + auto result = false; + PCCERT_CONTEXT pContext = NULL; + while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) != + nullptr) { + auto encoded_cert = + static_cast(pContext->pbCertEncoded); + + auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded); + if (x509) { + X509_STORE_add_cert(store, x509); + X509_free(x509); + result = true; + } + } + + CertFreeCertificateContext(pContext); + CertCloseStore(hStore, 0); + + return result; +} +#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__) +#if TARGET_OS_OSX +template +using CFObjectPtr = + std::unique_ptr::type, void (*)(CFTypeRef)>; + +inline void cf_object_ptr_deleter(CFTypeRef obj) { + if (obj) { CFRelease(obj); } +} + +inline bool retrieve_certs_from_keychain(CFObjectPtr &certs) { + CFStringRef keys[] = {kSecClass, kSecMatchLimit, kSecReturnRef}; + CFTypeRef values[] = {kSecClassCertificate, kSecMatchLimitAll, + kCFBooleanTrue}; + + CFObjectPtr query( + CFDictionaryCreate(nullptr, reinterpret_cast(keys), values, + sizeof(keys) / sizeof(keys[0]), + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks), + cf_object_ptr_deleter); + + if (!query) { return false; } + + CFTypeRef security_items = nullptr; + if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess || + CFArrayGetTypeID() != CFGetTypeID(security_items)) { + return false; + } + + certs.reset(reinterpret_cast(security_items)); + return true; +} + +inline bool retrieve_root_certs_from_keychain(CFObjectPtr &certs) { + CFArrayRef root_security_items = nullptr; + if (SecTrustCopyAnchorCertificates(&root_security_items) != errSecSuccess) { + return false; + } + + certs.reset(root_security_items); + return true; +} + +inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) { + auto result = false; + for (auto i = 0; i < CFArrayGetCount(certs); ++i) { + const auto cert = reinterpret_cast( + CFArrayGetValueAtIndex(certs, i)); + + if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; } + + CFDataRef cert_data = nullptr; + if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) != + errSecSuccess) { + continue; + } + + CFObjectPtr cert_data_ptr(cert_data, cf_object_ptr_deleter); + + auto encoded_cert = static_cast( + CFDataGetBytePtr(cert_data_ptr.get())); + + auto x509 = + d2i_X509(NULL, &encoded_cert, CFDataGetLength(cert_data_ptr.get())); + + if (x509) { + X509_STORE_add_cert(store, x509); + X509_free(x509); + result = true; + } + } + + return result; +} + +inline bool load_system_certs_on_macos(X509_STORE *store) { + auto result = false; + CFObjectPtr certs(nullptr, cf_object_ptr_deleter); + if (retrieve_certs_from_keychain(certs) && certs) { + result = add_certs_to_x509_store(certs.get(), store); + } + + if (retrieve_root_certs_from_keychain(certs) && certs) { + result = add_certs_to_x509_store(certs.get(), store) || result; + } + + return result; +} +#endif // TARGET_OS_OSX +#endif // _WIN32 +#endif // CPPHTTPLIB_OPENSSL_SUPPORT + +#ifdef _WIN32 +class WSInit { +public: + WSInit() { + WSADATA wsaData; + if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true; + } + + ~WSInit() { + if (is_valid_) WSACleanup(); + } + + bool is_valid_ = false; +}; + +static WSInit wsinit_; +#endif + +inline bool parse_www_authenticate(const Response &res, + std::map &auth, + bool is_proxy) { + auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate"; + if (res.has_header(auth_key)) { + thread_local auto re = + std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~"); + auto s = res.get_header_value(auth_key); + auto pos = s.find(' '); + if (pos != std::string::npos) { + auto type = s.substr(0, pos); + if (type == "Basic") { + return false; + } else if (type == "Digest") { + s = s.substr(pos + 1); + auto beg = std::sregex_iterator(s.begin(), s.end(), re); + for (auto i = beg; i != std::sregex_iterator(); ++i) { + const auto &m = *i; + auto key = s.substr(static_cast(m.position(1)), + static_cast(m.length(1))); + auto val = m.length(2) > 0 + ? s.substr(static_cast(m.position(2)), + static_cast(m.length(2))) + : s.substr(static_cast(m.position(3)), + static_cast(m.length(3))); + auth[key] = val; + } + return true; + } + } + } + return false; +} + +class ContentProviderAdapter { +public: + explicit ContentProviderAdapter( + ContentProviderWithoutLength &&content_provider) + : content_provider_(content_provider) {} + + bool operator()(size_t offset, size_t, DataSink &sink) { + return content_provider_(offset, sink); + } + +private: + ContentProviderWithoutLength content_provider_; +}; + +} // namespace detail + +inline std::string hosted_at(const std::string &hostname) { + std::vector addrs; + hosted_at(hostname, addrs); + if (addrs.empty()) { return std::string(); } + return addrs[0]; +} + +inline void hosted_at(const std::string &hostname, + std::vector &addrs) { + struct addrinfo hints; + struct addrinfo *result; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = 0; + + if (getaddrinfo(hostname.c_str(), nullptr, &hints, &result)) { +#if defined __linux__ && !defined __ANDROID__ + res_init(); +#endif + return; + } + auto se = detail::scope_exit([&] { freeaddrinfo(result); }); + + for (auto rp = result; rp; rp = rp->ai_next) { + const auto &addr = + *reinterpret_cast(rp->ai_addr); + std::string ip; + auto dummy = -1; + if (detail::get_ip_and_port(addr, sizeof(struct sockaddr_storage), ip, + dummy)) { + addrs.push_back(ip); + } + } +} + +inline std::string append_query_params(const std::string &path, + const Params ¶ms) { + std::string path_with_query = path; + thread_local const std::regex re("[^?]+\\?.*"); + auto delm = std::regex_match(path, re) ? '&' : '?'; + path_with_query += delm + detail::params_to_query_str(params); + return path_with_query; +} + +// Header utilities +inline std::pair +make_range_header(const Ranges &ranges) { + std::string field = "bytes="; + auto i = 0; + for (const auto &r : ranges) { + if (i != 0) { field += ", "; } + if (r.first != -1) { field += std::to_string(r.first); } + field += '-'; + if (r.second != -1) { field += std::to_string(r.second); } + i++; + } + return std::make_pair("Range", std::move(field)); +} + +inline std::pair +make_basic_authentication_header(const std::string &username, + const std::string &password, bool is_proxy) { + auto field = "Basic " + detail::base64_encode(username + ":" + password); + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, std::move(field)); +} + +inline std::pair +make_bearer_token_authentication_header(const std::string &token, + bool is_proxy = false) { + auto field = "Bearer " + token; + auto key = is_proxy ? "Proxy-Authorization" : "Authorization"; + return std::make_pair(key, std::move(field)); +} + +// Request implementation +inline bool Request::has_header(const std::string &key) const { + return detail::has_header(headers, key); +} + +inline std::string Request::get_header_value(const std::string &key, + const char *def, size_t id) const { + return detail::get_header_value(headers, key, def, id); +} + +inline size_t Request::get_header_value_count(const std::string &key) const { + auto r = headers.equal_range(key); + return static_cast(std::distance(r.first, r.second)); +} + +inline void Request::set_header(const std::string &key, + const std::string &val) { + if (detail::fields::is_field_name(key) && + detail::fields::is_field_value(val)) { + headers.emplace(key, val); + } +} + +inline bool Request::has_param(const std::string &key) const { + return params.find(key) != params.end(); +} + +inline std::string Request::get_param_value(const std::string &key, + size_t id) const { + auto rng = params.equal_range(key); + auto it = rng.first; + std::advance(it, static_cast(id)); + if (it != rng.second) { return it->second; } + return std::string(); +} + +inline size_t Request::get_param_value_count(const std::string &key) const { + auto r = params.equal_range(key); + return static_cast(std::distance(r.first, r.second)); +} + +inline bool Request::is_multipart_form_data() const { + const auto &content_type = get_header_value("Content-Type"); + return !content_type.rfind("multipart/form-data", 0); +} + +inline bool Request::has_file(const std::string &key) const { + return files.find(key) != files.end(); +} + +inline MultipartFormData Request::get_file_value(const std::string &key) const { + auto it = files.find(key); + if (it != files.end()) { return it->second; } + return MultipartFormData(); +} + +inline std::vector +Request::get_file_values(const std::string &key) const { + std::vector values; + auto rng = files.equal_range(key); + for (auto it = rng.first; it != rng.second; it++) { + values.push_back(it->second); + } + return values; +} + +// Response implementation +inline bool Response::has_header(const std::string &key) const { + return headers.find(key) != headers.end(); +} + +inline std::string Response::get_header_value(const std::string &key, + const char *def, + size_t id) const { + return detail::get_header_value(headers, key, def, id); +} + +inline size_t Response::get_header_value_count(const std::string &key) const { + auto r = headers.equal_range(key); + return static_cast(std::distance(r.first, r.second)); +} + +inline void Response::set_header(const std::string &key, + const std::string &val) { + if (detail::fields::is_field_name(key) && + detail::fields::is_field_value(val)) { + headers.emplace(key, val); + } +} + +inline void Response::set_redirect(const std::string &url, int stat) { + if (detail::fields::is_field_value(url)) { + set_header("Location", url); + if (300 <= stat && stat < 400) { + this->status = stat; + } else { + this->status = StatusCode::Found_302; + } + } +} + +inline void Response::set_content(const char *s, size_t n, + const std::string &content_type) { + body.assign(s, n); + + auto rng = headers.equal_range("Content-Type"); + headers.erase(rng.first, rng.second); + set_header("Content-Type", content_type); +} + +inline void Response::set_content(const std::string &s, + const std::string &content_type) { + set_content(s.data(), s.size(), content_type); +} + +inline void Response::set_content(std::string &&s, + const std::string &content_type) { + body = std::move(s); + + auto rng = headers.equal_range("Content-Type"); + headers.erase(rng.first, rng.second); + set_header("Content-Type", content_type); +} + +inline void Response::set_content_provider( + size_t in_length, const std::string &content_type, ContentProvider provider, + ContentProviderResourceReleaser resource_releaser) { + set_header("Content-Type", content_type); + content_length_ = in_length; + if (in_length > 0) { content_provider_ = std::move(provider); } + content_provider_resource_releaser_ = std::move(resource_releaser); + is_chunked_content_provider_ = false; +} + +inline void Response::set_content_provider( + const std::string &content_type, ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser) { + set_header("Content-Type", content_type); + content_length_ = 0; + content_provider_ = detail::ContentProviderAdapter(std::move(provider)); + content_provider_resource_releaser_ = std::move(resource_releaser); + is_chunked_content_provider_ = false; +} + +inline void Response::set_chunked_content_provider( + const std::string &content_type, ContentProviderWithoutLength provider, + ContentProviderResourceReleaser resource_releaser) { + set_header("Content-Type", content_type); + content_length_ = 0; + content_provider_ = detail::ContentProviderAdapter(std::move(provider)); + content_provider_resource_releaser_ = std::move(resource_releaser); + is_chunked_content_provider_ = true; +} + +inline void Response::set_file_content(const std::string &path, + const std::string &content_type) { + file_content_path_ = path; + file_content_content_type_ = content_type; +} + +inline void Response::set_file_content(const std::string &path) { + file_content_path_ = path; +} + +// Result implementation +inline bool Result::has_request_header(const std::string &key) const { + return request_headers_.find(key) != request_headers_.end(); +} + +inline std::string Result::get_request_header_value(const std::string &key, + const char *def, + size_t id) const { + return detail::get_header_value(request_headers_, key, def, id); +} + +inline size_t +Result::get_request_header_value_count(const std::string &key) const { + auto r = request_headers_.equal_range(key); + return static_cast(std::distance(r.first, r.second)); +} + +// Stream implementation +inline ssize_t Stream::write(const char *ptr) { + return write(ptr, strlen(ptr)); +} + +inline ssize_t Stream::write(const std::string &s) { + return write(s.data(), s.size()); +} + +namespace detail { + +inline void calc_actual_timeout(time_t max_timeout_msec, time_t duration_msec, + time_t timeout_sec, time_t timeout_usec, + time_t &actual_timeout_sec, + time_t &actual_timeout_usec) { + auto timeout_msec = (timeout_sec * 1000) + (timeout_usec / 1000); + + auto actual_timeout_msec = + (std::min)(max_timeout_msec - duration_msec, timeout_msec); + + if (actual_timeout_msec < 0) { actual_timeout_msec = 0; } + + actual_timeout_sec = actual_timeout_msec / 1000; + actual_timeout_usec = (actual_timeout_msec % 1000) * 1000; +} + +// Socket stream implementation +inline SocketStream::SocketStream( + socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, time_t write_timeout_usec, + time_t max_timeout_msec, + std::chrono::time_point start_time) + : sock_(sock), read_timeout_sec_(read_timeout_sec), + read_timeout_usec_(read_timeout_usec), + write_timeout_sec_(write_timeout_sec), + write_timeout_usec_(write_timeout_usec), + max_timeout_msec_(max_timeout_msec), start_time_(start_time), + read_buff_(read_buff_size_, 0) {} + +inline SocketStream::~SocketStream() = default; + +inline bool SocketStream::is_readable() const { + return read_buff_off_ < read_buff_content_size_; +} + +inline bool SocketStream::wait_readable() const { + if (max_timeout_msec_ <= 0) { + return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; + } + + time_t read_timeout_sec; + time_t read_timeout_usec; + calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_, + read_timeout_usec_, read_timeout_sec, read_timeout_usec); + + return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0; +} + +inline bool SocketStream::wait_writable() const { + return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && + is_socket_alive(sock_); +} + +inline ssize_t SocketStream::read(char *ptr, size_t size) { +#ifdef _WIN32 + size = + (std::min)(size, static_cast((std::numeric_limits::max)())); +#else + size = (std::min)(size, + static_cast((std::numeric_limits::max)())); +#endif + + if (read_buff_off_ < read_buff_content_size_) { + auto remaining_size = read_buff_content_size_ - read_buff_off_; + if (size <= remaining_size) { + memcpy(ptr, read_buff_.data() + read_buff_off_, size); + read_buff_off_ += size; + return static_cast(size); + } else { + memcpy(ptr, read_buff_.data() + read_buff_off_, remaining_size); + read_buff_off_ += remaining_size; + return static_cast(remaining_size); + } + } + + if (!wait_readable()) { return -1; } + + read_buff_off_ = 0; + read_buff_content_size_ = 0; + + if (size < read_buff_size_) { + auto n = read_socket(sock_, read_buff_.data(), read_buff_size_, + CPPHTTPLIB_RECV_FLAGS); + if (n <= 0) { + return n; + } else if (n <= static_cast(size)) { + memcpy(ptr, read_buff_.data(), static_cast(n)); + return n; + } else { + memcpy(ptr, read_buff_.data(), size); + read_buff_off_ = size; + read_buff_content_size_ = static_cast(n); + return static_cast(size); + } + } else { + return read_socket(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS); + } +} + +inline ssize_t SocketStream::write(const char *ptr, size_t size) { + if (!wait_writable()) { return -1; } + +#if defined(_WIN32) && !defined(_WIN64) + size = + (std::min)(size, static_cast((std::numeric_limits::max)())); +#endif + + return send_socket(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS); +} + +inline void SocketStream::get_remote_ip_and_port(std::string &ip, + int &port) const { + return detail::get_remote_ip_and_port(sock_, ip, port); +} + +inline void SocketStream::get_local_ip_and_port(std::string &ip, + int &port) const { + return detail::get_local_ip_and_port(sock_, ip, port); +} + +inline socket_t SocketStream::socket() const { return sock_; } + +inline time_t SocketStream::duration() const { + return std::chrono::duration_cast( + std::chrono::steady_clock::now() - start_time_) + .count(); +} + +// Buffer stream implementation +inline bool BufferStream::is_readable() const { return true; } + +inline bool BufferStream::wait_readable() const { return true; } + +inline bool BufferStream::wait_writable() const { return true; } + +inline ssize_t BufferStream::read(char *ptr, size_t size) { +#if defined(_MSC_VER) && _MSC_VER < 1910 + auto len_read = buffer._Copy_s(ptr, size, size, position); +#else + auto len_read = buffer.copy(ptr, size, position); +#endif + position += static_cast(len_read); + return static_cast(len_read); +} + +inline ssize_t BufferStream::write(const char *ptr, size_t size) { + buffer.append(ptr, size); + return static_cast(size); +} + +inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/, + int & /*port*/) const {} + +inline void BufferStream::get_local_ip_and_port(std::string & /*ip*/, + int & /*port*/) const {} + +inline socket_t BufferStream::socket() const { return 0; } + +inline time_t BufferStream::duration() const { return 0; } + +inline const std::string &BufferStream::get_buffer() const { return buffer; } + +inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern) + : MatcherBase(pattern) { + constexpr const char marker[] = "/:"; + + // One past the last ending position of a path param substring + std::size_t last_param_end = 0; + +#ifndef CPPHTTPLIB_NO_EXCEPTIONS + // Needed to ensure that parameter names are unique during matcher + // construction + // If exceptions are disabled, only last duplicate path + // parameter will be set + std::unordered_set param_name_set; +#endif + + while (true) { + const auto marker_pos = pattern.find( + marker, last_param_end == 0 ? last_param_end : last_param_end - 1); + if (marker_pos == std::string::npos) { break; } + + static_fragments_.push_back( + pattern.substr(last_param_end, marker_pos - last_param_end + 1)); + + const auto param_name_start = marker_pos + str_len(marker); + + auto sep_pos = pattern.find(separator, param_name_start); + if (sep_pos == std::string::npos) { sep_pos = pattern.length(); } + + auto param_name = + pattern.substr(param_name_start, sep_pos - param_name_start); + +#ifndef CPPHTTPLIB_NO_EXCEPTIONS + if (param_name_set.find(param_name) != param_name_set.cend()) { + std::string msg = "Encountered path parameter '" + param_name + + "' multiple times in route pattern '" + pattern + "'."; + throw std::invalid_argument(msg); + } +#endif + + param_names_.push_back(std::move(param_name)); + + last_param_end = sep_pos + 1; + } + + if (last_param_end < pattern.length()) { + static_fragments_.push_back(pattern.substr(last_param_end)); + } +} + +inline bool PathParamsMatcher::match(Request &request) const { + request.matches = std::smatch(); + request.path_params.clear(); + request.path_params.reserve(param_names_.size()); + + // One past the position at which the path matched the pattern last time + std::size_t starting_pos = 0; + for (size_t i = 0; i < static_fragments_.size(); ++i) { + const auto &fragment = static_fragments_[i]; + + if (starting_pos + fragment.length() > request.path.length()) { + return false; + } + + // Avoid unnecessary allocation by using strncmp instead of substr + + // comparison + if (std::strncmp(request.path.c_str() + starting_pos, fragment.c_str(), + fragment.length()) != 0) { + return false; + } + + starting_pos += fragment.length(); + + // Should only happen when we have a static fragment after a param + // Example: '/users/:id/subscriptions' + // The 'subscriptions' fragment here does not have a corresponding param + if (i >= param_names_.size()) { continue; } + + auto sep_pos = request.path.find(separator, starting_pos); + if (sep_pos == std::string::npos) { sep_pos = request.path.length(); } + + const auto ¶m_name = param_names_[i]; + + request.path_params.emplace( + param_name, request.path.substr(starting_pos, sep_pos - starting_pos)); + + // Mark everything up to '/' as matched + starting_pos = sep_pos + 1; + } + // Returns false if the path is longer than the pattern + return starting_pos >= request.path.length(); +} + +inline bool RegexMatcher::match(Request &request) const { + request.path_params.clear(); + return std::regex_match(request.path, request.matches, regex_); +} + +} // namespace detail + +// HTTP server implementation +inline Server::Server() + : new_task_queue( + [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }) { +#ifndef _WIN32 + signal(SIGPIPE, SIG_IGN); +#endif +} + +inline Server::~Server() = default; + +inline std::unique_ptr +Server::make_matcher(const std::string &pattern) { + if (pattern.find("/:") != std::string::npos) { + return detail::make_unique(pattern); + } else { + return detail::make_unique(pattern); + } +} + +inline Server &Server::Get(const std::string &pattern, Handler handler) { + get_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; +} + +inline Server &Server::Post(const std::string &pattern, Handler handler) { + post_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; +} + +inline Server &Server::Post(const std::string &pattern, + HandlerWithContentReader handler) { + post_handlers_for_content_reader_.emplace_back(make_matcher(pattern), + std::move(handler)); + return *this; +} + +inline Server &Server::Put(const std::string &pattern, Handler handler) { + put_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; +} + +inline Server &Server::Put(const std::string &pattern, + HandlerWithContentReader handler) { + put_handlers_for_content_reader_.emplace_back(make_matcher(pattern), + std::move(handler)); + return *this; +} + +inline Server &Server::Patch(const std::string &pattern, Handler handler) { + patch_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; +} + +inline Server &Server::Patch(const std::string &pattern, + HandlerWithContentReader handler) { + patch_handlers_for_content_reader_.emplace_back(make_matcher(pattern), + std::move(handler)); + return *this; +} + +inline Server &Server::Delete(const std::string &pattern, Handler handler) { + delete_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; +} + +inline Server &Server::Delete(const std::string &pattern, + HandlerWithContentReader handler) { + delete_handlers_for_content_reader_.emplace_back(make_matcher(pattern), + std::move(handler)); + return *this; +} + +inline Server &Server::Options(const std::string &pattern, Handler handler) { + options_handlers_.emplace_back(make_matcher(pattern), std::move(handler)); + return *this; +} + +inline bool Server::set_base_dir(const std::string &dir, + const std::string &mount_point) { + return set_mount_point(mount_point, dir); +} + +inline bool Server::set_mount_point(const std::string &mount_point, + const std::string &dir, Headers headers) { + detail::FileStat stat(dir); + if (stat.is_dir()) { + std::string mnt = !mount_point.empty() ? mount_point : "/"; + if (!mnt.empty() && mnt[0] == '/') { + base_dirs_.push_back({mnt, dir, std::move(headers)}); + return true; + } + } + return false; +} + +inline bool Server::remove_mount_point(const std::string &mount_point) { + for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) { + if (it->mount_point == mount_point) { + base_dirs_.erase(it); + return true; + } + } + return false; +} + +inline Server & +Server::set_file_extension_and_mimetype_mapping(const std::string &ext, + const std::string &mime) { + file_extension_and_mimetype_map_[ext] = mime; + return *this; +} + +inline Server &Server::set_default_file_mimetype(const std::string &mime) { + default_file_mimetype_ = mime; + return *this; +} + +inline Server &Server::set_file_request_handler(Handler handler) { + file_request_handler_ = std::move(handler); + return *this; +} + +inline Server &Server::set_error_handler_core(HandlerWithResponse handler, + std::true_type) { + error_handler_ = std::move(handler); + return *this; +} + +inline Server &Server::set_error_handler_core(Handler handler, + std::false_type) { + error_handler_ = [handler](const Request &req, Response &res) { + handler(req, res); + return HandlerResponse::Handled; + }; + return *this; +} + +inline Server &Server::set_exception_handler(ExceptionHandler handler) { + exception_handler_ = std::move(handler); + return *this; +} + +inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) { + pre_routing_handler_ = std::move(handler); + return *this; +} + +inline Server &Server::set_post_routing_handler(Handler handler) { + post_routing_handler_ = std::move(handler); + return *this; +} + +inline Server &Server::set_pre_request_handler(HandlerWithResponse handler) { + pre_request_handler_ = std::move(handler); + return *this; +} + +inline Server &Server::set_logger(Logger logger) { + logger_ = std::move(logger); + return *this; +} + +inline Server & +Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) { + expect_100_continue_handler_ = std::move(handler); + return *this; +} + +inline Server &Server::set_address_family(int family) { + address_family_ = family; + return *this; +} + +inline Server &Server::set_tcp_nodelay(bool on) { + tcp_nodelay_ = on; + return *this; +} + +inline Server &Server::set_ipv6_v6only(bool on) { + ipv6_v6only_ = on; + return *this; +} + +inline Server &Server::set_socket_options(SocketOptions socket_options) { + socket_options_ = std::move(socket_options); + return *this; +} + +inline Server &Server::set_default_headers(Headers headers) { + default_headers_ = std::move(headers); + return *this; +} + +inline Server &Server::set_header_writer( + std::function const &writer) { + header_writer_ = writer; + return *this; +} + +inline Server &Server::set_keep_alive_max_count(size_t count) { + keep_alive_max_count_ = count; + return *this; +} + +inline Server &Server::set_keep_alive_timeout(time_t sec) { + keep_alive_timeout_sec_ = sec; + return *this; +} + +inline Server &Server::set_read_timeout(time_t sec, time_t usec) { + read_timeout_sec_ = sec; + read_timeout_usec_ = usec; + return *this; +} + +inline Server &Server::set_write_timeout(time_t sec, time_t usec) { + write_timeout_sec_ = sec; + write_timeout_usec_ = usec; + return *this; +} + +inline Server &Server::set_idle_interval(time_t sec, time_t usec) { + idle_interval_sec_ = sec; + idle_interval_usec_ = usec; + return *this; +} + +inline Server &Server::set_payload_max_length(size_t length) { + payload_max_length_ = length; + return *this; +} + +inline bool Server::bind_to_port(const std::string &host, int port, + int socket_flags) { + auto ret = bind_internal(host, port, socket_flags); + if (ret == -1) { is_decommissioned = true; } + return ret >= 0; +} +inline int Server::bind_to_any_port(const std::string &host, int socket_flags) { + auto ret = bind_internal(host, 0, socket_flags); + if (ret == -1) { is_decommissioned = true; } + return ret; +} + +inline bool Server::listen_after_bind() { return listen_internal(); } + +inline bool Server::listen(const std::string &host, int port, + int socket_flags) { + return bind_to_port(host, port, socket_flags) && listen_internal(); +} + +inline bool Server::is_running() const { return is_running_; } + +inline void Server::wait_until_ready() const { + while (!is_running_ && !is_decommissioned) { + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } +} + +inline void Server::stop() { + if (is_running_) { + assert(svr_sock_ != INVALID_SOCKET); + std::atomic sock(svr_sock_.exchange(INVALID_SOCKET)); + detail::shutdown_socket(sock); + detail::close_socket(sock); + } + is_decommissioned = false; +} + +inline void Server::decommission() { is_decommissioned = true; } + +inline bool Server::parse_request_line(const char *s, Request &req) const { + auto len = strlen(s); + if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; } + len -= 2; + + { + size_t count = 0; + + detail::split(s, s + len, ' ', [&](const char *b, const char *e) { + switch (count) { + case 0: req.method = std::string(b, e); break; + case 1: req.target = std::string(b, e); break; + case 2: req.version = std::string(b, e); break; + default: break; + } + count++; + }); + + if (count != 3) { return false; } + } + + thread_local const std::set methods{ + "GET", "HEAD", "POST", "PUT", "DELETE", + "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"}; + + if (methods.find(req.method) == methods.end()) { return false; } + + if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { return false; } + + { + // Skip URL fragment + for (size_t i = 0; i < req.target.size(); i++) { + if (req.target[i] == '#') { + req.target.erase(i); + break; + } + } + + detail::divide(req.target, '?', + [&](const char *lhs_data, std::size_t lhs_size, + const char *rhs_data, std::size_t rhs_size) { + req.path = detail::decode_url( + std::string(lhs_data, lhs_size), false); + detail::parse_query_text(rhs_data, rhs_size, req.params); + }); + } + + return true; +} + +inline bool Server::write_response(Stream &strm, bool close_connection, + Request &req, Response &res) { + // NOTE: `req.ranges` should be empty, otherwise it will be applied + // incorrectly to the error content. + req.ranges.clear(); + return write_response_core(strm, close_connection, req, res, false); +} + +inline bool Server::write_response_with_content(Stream &strm, + bool close_connection, + const Request &req, + Response &res) { + return write_response_core(strm, close_connection, req, res, true); +} + +inline bool Server::write_response_core(Stream &strm, bool close_connection, + const Request &req, Response &res, + bool need_apply_ranges) { + assert(res.status != -1); + + if (400 <= res.status && error_handler_ && + error_handler_(req, res) == HandlerResponse::Handled) { + need_apply_ranges = true; + } + + std::string content_type; + std::string boundary; + if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); } + + // Prepare additional headers + if (close_connection || req.get_header_value("Connection") == "close") { + res.set_header("Connection", "close"); + } else { + std::string s = "timeout="; + s += std::to_string(keep_alive_timeout_sec_); + s += ", max="; + s += std::to_string(keep_alive_max_count_); + res.set_header("Keep-Alive", s); + } + + if ((!res.body.empty() || res.content_length_ > 0 || res.content_provider_) && + !res.has_header("Content-Type")) { + res.set_header("Content-Type", "text/plain"); + } + + if (res.body.empty() && !res.content_length_ && !res.content_provider_ && + !res.has_header("Content-Length")) { + res.set_header("Content-Length", "0"); + } + + if (req.method == "HEAD" && !res.has_header("Accept-Ranges")) { + res.set_header("Accept-Ranges", "bytes"); + } + + if (post_routing_handler_) { post_routing_handler_(req, res); } + + // Response line and headers + { + detail::BufferStream bstrm; + if (!detail::write_response_line(bstrm, res.status)) { return false; } + if (!header_writer_(bstrm, res.headers)) { return false; } + + // Flush buffer + auto &data = bstrm.get_buffer(); + detail::write_data(strm, data.data(), data.size()); + } + + // Body + auto ret = true; + if (req.method != "HEAD") { + if (!res.body.empty()) { + if (!detail::write_data(strm, res.body.data(), res.body.size())) { + ret = false; + } + } else if (res.content_provider_) { + if (write_content_with_provider(strm, req, res, boundary, content_type)) { + res.content_provider_success_ = true; + } else { + ret = false; + } + } + } + + // Log + if (logger_) { logger_(req, res); } + + return ret; +} + +inline bool +Server::write_content_with_provider(Stream &strm, const Request &req, + Response &res, const std::string &boundary, + const std::string &content_type) { + auto is_shutting_down = [this]() { + return this->svr_sock_ == INVALID_SOCKET; + }; + + if (res.content_length_ > 0) { + if (req.ranges.empty()) { + return detail::write_content(strm, res.content_provider_, 0, + res.content_length_, is_shutting_down); + } else if (req.ranges.size() == 1) { + auto offset_and_length = detail::get_range_offset_and_length( + req.ranges[0], res.content_length_); + + return detail::write_content(strm, res.content_provider_, + offset_and_length.first, + offset_and_length.second, is_shutting_down); + } else { + return detail::write_multipart_ranges_data( + strm, req, res, boundary, content_type, res.content_length_, + is_shutting_down); + } + } else { + if (res.is_chunked_content_provider_) { + auto type = detail::encoding_type(req, res); + + std::unique_ptr compressor; + if (type == detail::EncodingType::Gzip) { +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + compressor = detail::make_unique(); +#endif + } else if (type == detail::EncodingType::Brotli) { +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + compressor = detail::make_unique(); +#endif + } else if (type == detail::EncodingType::Zstd) { +#ifdef CPPHTTPLIB_ZSTD_SUPPORT + compressor = detail::make_unique(); +#endif + } else { + compressor = detail::make_unique(); + } + assert(compressor != nullptr); + + return detail::write_content_chunked(strm, res.content_provider_, + is_shutting_down, *compressor); + } else { + return detail::write_content_without_length(strm, res.content_provider_, + is_shutting_down); + } + } +} + +inline bool Server::read_content(Stream &strm, Request &req, Response &res) { + MultipartFormDataMap::iterator cur; + auto file_count = 0; + if (read_content_core( + strm, req, res, + // Regular + [&](const char *buf, size_t n) { + if (req.body.size() + n > req.body.max_size()) { return false; } + req.body.append(buf, n); + return true; + }, + // Multipart + [&](const MultipartFormData &file) { + if (file_count++ == CPPHTTPLIB_MULTIPART_FORM_DATA_FILE_MAX_COUNT) { + return false; + } + cur = req.files.emplace(file.name, file); + return true; + }, + [&](const char *buf, size_t n) { + auto &content = cur->second.content; + if (content.size() + n > content.max_size()) { return false; } + content.append(buf, n); + return true; + })) { + const auto &content_type = req.get_header_value("Content-Type"); + if (!content_type.find("application/x-www-form-urlencoded")) { + if (req.body.size() > CPPHTTPLIB_FORM_URL_ENCODED_PAYLOAD_MAX_LENGTH) { + res.status = StatusCode::PayloadTooLarge_413; // NOTE: should be 414? + return false; + } + detail::parse_query_text(req.body, req.params); + } + return true; + } + return false; +} + +inline bool Server::read_content_with_content_receiver( + Stream &strm, Request &req, Response &res, ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver) { + return read_content_core(strm, req, res, std::move(receiver), + std::move(multipart_header), + std::move(multipart_receiver)); +} + +inline bool +Server::read_content_core(Stream &strm, Request &req, Response &res, + ContentReceiver receiver, + MultipartContentHeader multipart_header, + ContentReceiver multipart_receiver) const { + detail::MultipartFormDataParser multipart_form_data_parser; + ContentReceiverWithProgress out; + + if (req.is_multipart_form_data()) { + const auto &content_type = req.get_header_value("Content-Type"); + std::string boundary; + if (!detail::parse_multipart_boundary(content_type, boundary)) { + res.status = StatusCode::BadRequest_400; + return false; + } + + multipart_form_data_parser.set_boundary(std::move(boundary)); + out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) { + /* For debug + size_t pos = 0; + while (pos < n) { + auto read_size = (std::min)(1, n - pos); + auto ret = multipart_form_data_parser.parse( + buf + pos, read_size, multipart_receiver, multipart_header); + if (!ret) { return false; } + pos += read_size; + } + return true; + */ + return multipart_form_data_parser.parse(buf, n, multipart_receiver, + multipart_header); + }; + } else { + out = [receiver](const char *buf, size_t n, uint64_t /*off*/, + uint64_t /*len*/) { return receiver(buf, n); }; + } + + if (req.method == "DELETE" && !req.has_header("Content-Length")) { + return true; + } + + if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr, + out, true)) { + return false; + } + + if (req.is_multipart_form_data()) { + if (!multipart_form_data_parser.is_valid()) { + res.status = StatusCode::BadRequest_400; + return false; + } + } + + return true; +} + +inline bool Server::handle_file_request(const Request &req, Response &res) { + for (const auto &entry : base_dirs_) { + // Prefix match + if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) { + std::string sub_path = "/" + req.path.substr(entry.mount_point.size()); + if (detail::is_valid_path(sub_path)) { + auto path = entry.base_dir + sub_path; + if (path.back() == '/') { path += "index.html"; } + + detail::FileStat stat(path); + + if (stat.is_dir()) { + res.set_redirect(sub_path + "/", StatusCode::MovedPermanently_301); + return true; + } + + if (stat.is_file()) { + for (const auto &kv : entry.headers) { + res.set_header(kv.first, kv.second); + } + + auto mm = std::make_shared(path.c_str()); + if (!mm->is_open()) { return false; } + + res.set_content_provider( + mm->size(), + detail::find_content_type(path, file_extension_and_mimetype_map_, + default_file_mimetype_), + [mm](size_t offset, size_t length, DataSink &sink) -> bool { + sink.write(mm->data() + offset, length); + return true; + }); + + if (req.method != "HEAD" && file_request_handler_) { + file_request_handler_(req, res); + } + + return true; + } + } + } + } + return false; +} + +inline socket_t +Server::create_server_socket(const std::string &host, int port, + int socket_flags, + SocketOptions socket_options) const { + return detail::create_socket( + host, std::string(), port, address_family_, socket_flags, tcp_nodelay_, + ipv6_v6only_, std::move(socket_options), + [](socket_t sock, struct addrinfo &ai, bool & /*quit*/) -> bool { + if (::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { + return false; + } + if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { return false; } + return true; + }); +} + +inline int Server::bind_internal(const std::string &host, int port, + int socket_flags) { + if (is_decommissioned) { return -1; } + + if (!is_valid()) { return -1; } + + svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_); + if (svr_sock_ == INVALID_SOCKET) { return -1; } + + if (port == 0) { + struct sockaddr_storage addr; + socklen_t addr_len = sizeof(addr); + if (getsockname(svr_sock_, reinterpret_cast(&addr), + &addr_len) == -1) { + return -1; + } + if (addr.ss_family == AF_INET) { + return ntohs(reinterpret_cast(&addr)->sin_port); + } else if (addr.ss_family == AF_INET6) { + return ntohs(reinterpret_cast(&addr)->sin6_port); + } else { + return -1; + } + } else { + return port; + } +} + +inline bool Server::listen_internal() { + if (is_decommissioned) { return false; } + + auto ret = true; + is_running_ = true; + auto se = detail::scope_exit([&]() { is_running_ = false; }); + + { + std::unique_ptr task_queue(new_task_queue()); + + while (svr_sock_ != INVALID_SOCKET) { +#ifndef _WIN32 + if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) { +#endif + auto val = detail::select_read(svr_sock_, idle_interval_sec_, + idle_interval_usec_); + if (val == 0) { // Timeout + task_queue->on_idle(); + continue; + } +#ifndef _WIN32 + } +#endif + +#if defined _WIN32 + // sockets connected via WASAccept inherit flags NO_HANDLE_INHERIT, + // OVERLAPPED + socket_t sock = WSAAccept(svr_sock_, nullptr, nullptr, nullptr, 0); +#elif defined SOCK_CLOEXEC + socket_t sock = accept4(svr_sock_, nullptr, nullptr, SOCK_CLOEXEC); +#else + socket_t sock = accept(svr_sock_, nullptr, nullptr); +#endif + + if (sock == INVALID_SOCKET) { + if (errno == EMFILE) { + // The per-process limit of open file descriptors has been reached. + // Try to accept new connections after a short sleep. + std::this_thread::sleep_for(std::chrono::microseconds{1}); + continue; + } else if (errno == EINTR || errno == EAGAIN) { + continue; + } + if (svr_sock_ != INVALID_SOCKET) { + detail::close_socket(svr_sock_); + ret = false; + } else { + ; // The server socket was closed by user. + } + break; + } + + detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, + read_timeout_sec_, read_timeout_usec_); + detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, + write_timeout_sec_, write_timeout_usec_); + + if (!task_queue->enqueue( + [this, sock]() { process_and_close_socket(sock); })) { + detail::shutdown_socket(sock); + detail::close_socket(sock); + } + } + + task_queue->shutdown(); + } + + is_decommissioned = !ret; + return ret; +} + +inline bool Server::routing(Request &req, Response &res, Stream &strm) { + if (pre_routing_handler_ && + pre_routing_handler_(req, res) == HandlerResponse::Handled) { + return true; + } + + // File handler + if ((req.method == "GET" || req.method == "HEAD") && + handle_file_request(req, res)) { + return true; + } + + if (detail::expect_content(req)) { + // Content reader handler + { + ContentReader reader( + [&](ContentReceiver receiver) { + return read_content_with_content_receiver( + strm, req, res, std::move(receiver), nullptr, nullptr); + }, + [&](MultipartContentHeader header, ContentReceiver receiver) { + return read_content_with_content_receiver(strm, req, res, nullptr, + std::move(header), + std::move(receiver)); + }); + + if (req.method == "POST") { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + post_handlers_for_content_reader_)) { + return true; + } + } else if (req.method == "PUT") { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + put_handlers_for_content_reader_)) { + return true; + } + } else if (req.method == "PATCH") { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + patch_handlers_for_content_reader_)) { + return true; + } + } else if (req.method == "DELETE") { + if (dispatch_request_for_content_reader( + req, res, std::move(reader), + delete_handlers_for_content_reader_)) { + return true; + } + } + } + + // Read content into `req.body` + if (!read_content(strm, req, res)) { return false; } + } + + // Regular handler + if (req.method == "GET" || req.method == "HEAD") { + return dispatch_request(req, res, get_handlers_); + } else if (req.method == "POST") { + return dispatch_request(req, res, post_handlers_); + } else if (req.method == "PUT") { + return dispatch_request(req, res, put_handlers_); + } else if (req.method == "DELETE") { + return dispatch_request(req, res, delete_handlers_); + } else if (req.method == "OPTIONS") { + return dispatch_request(req, res, options_handlers_); + } else if (req.method == "PATCH") { + return dispatch_request(req, res, patch_handlers_); + } + + res.status = StatusCode::BadRequest_400; + return false; +} + +inline bool Server::dispatch_request(Request &req, Response &res, + const Handlers &handlers) const { + for (const auto &x : handlers) { + const auto &matcher = x.first; + const auto &handler = x.second; + + if (matcher->match(req)) { + req.matched_route = matcher->pattern(); + if (!pre_request_handler_ || + pre_request_handler_(req, res) != HandlerResponse::Handled) { + handler(req, res); + } + return true; + } + } + return false; +} + +inline void Server::apply_ranges(const Request &req, Response &res, + std::string &content_type, + std::string &boundary) const { + if (req.ranges.size() > 1 && res.status == StatusCode::PartialContent_206) { + auto it = res.headers.find("Content-Type"); + if (it != res.headers.end()) { + content_type = it->second; + res.headers.erase(it); + } + + boundary = detail::make_multipart_data_boundary(); + + res.set_header("Content-Type", + "multipart/byteranges; boundary=" + boundary); + } + + auto type = detail::encoding_type(req, res); + + if (res.body.empty()) { + if (res.content_length_ > 0) { + size_t length = 0; + if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) { + length = res.content_length_; + } else if (req.ranges.size() == 1) { + auto offset_and_length = detail::get_range_offset_and_length( + req.ranges[0], res.content_length_); + + length = offset_and_length.second; + + auto content_range = detail::make_content_range_header_field( + offset_and_length, res.content_length_); + res.set_header("Content-Range", content_range); + } else { + length = detail::get_multipart_ranges_data_length( + req, boundary, content_type, res.content_length_); + } + res.set_header("Content-Length", std::to_string(length)); + } else { + if (res.content_provider_) { + if (res.is_chunked_content_provider_) { + res.set_header("Transfer-Encoding", "chunked"); + if (type == detail::EncodingType::Gzip) { + res.set_header("Content-Encoding", "gzip"); + } else if (type == detail::EncodingType::Brotli) { + res.set_header("Content-Encoding", "br"); + } else if (type == detail::EncodingType::Zstd) { + res.set_header("Content-Encoding", "zstd"); + } + } + } + } + } else { + if (req.ranges.empty() || res.status != StatusCode::PartialContent_206) { + ; + } else if (req.ranges.size() == 1) { + auto offset_and_length = + detail::get_range_offset_and_length(req.ranges[0], res.body.size()); + auto offset = offset_and_length.first; + auto length = offset_and_length.second; + + auto content_range = detail::make_content_range_header_field( + offset_and_length, res.body.size()); + res.set_header("Content-Range", content_range); + + assert(offset + length <= res.body.size()); + res.body = res.body.substr(offset, length); + } else { + std::string data; + detail::make_multipart_ranges_data(req, res, boundary, content_type, + res.body.size(), data); + res.body.swap(data); + } + + if (type != detail::EncodingType::None) { + std::unique_ptr compressor; + std::string content_encoding; + + if (type == detail::EncodingType::Gzip) { +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + compressor = detail::make_unique(); + content_encoding = "gzip"; +#endif + } else if (type == detail::EncodingType::Brotli) { +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + compressor = detail::make_unique(); + content_encoding = "br"; +#endif + } else if (type == detail::EncodingType::Zstd) { +#ifdef CPPHTTPLIB_ZSTD_SUPPORT + compressor = detail::make_unique(); + content_encoding = "zstd"; +#endif + } + + if (compressor) { + std::string compressed; + if (compressor->compress(res.body.data(), res.body.size(), true, + [&](const char *data, size_t data_len) { + compressed.append(data, data_len); + return true; + })) { + res.body.swap(compressed); + res.set_header("Content-Encoding", content_encoding); + } + } + } + + auto length = std::to_string(res.body.size()); + res.set_header("Content-Length", length); + } +} + +inline bool Server::dispatch_request_for_content_reader( + Request &req, Response &res, ContentReader content_reader, + const HandlersForContentReader &handlers) const { + for (const auto &x : handlers) { + const auto &matcher = x.first; + const auto &handler = x.second; + + if (matcher->match(req)) { + req.matched_route = matcher->pattern(); + if (!pre_request_handler_ || + pre_request_handler_(req, res) != HandlerResponse::Handled) { + handler(req, res, content_reader); + } + return true; + } + } + return false; +} + +inline bool +Server::process_request(Stream &strm, const std::string &remote_addr, + int remote_port, const std::string &local_addr, + int local_port, bool close_connection, + bool &connection_closed, + const std::function &setup_request) { + std::array buf{}; + + detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); + + // Connection has been closed on client + if (!line_reader.getline()) { return false; } + + Request req; + + Response res; + res.version = "HTTP/1.1"; + res.headers = default_headers_; + + // Request line and headers + if (!parse_request_line(line_reader.ptr(), req) || + !detail::read_headers(strm, req.headers)) { + res.status = StatusCode::BadRequest_400; + return write_response(strm, close_connection, req, res); + } + + // Check if the request URI doesn't exceed the limit + if (req.target.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) { + Headers dummy; + detail::read_headers(strm, dummy); + res.status = StatusCode::UriTooLong_414; + return write_response(strm, close_connection, req, res); + } + + if (req.get_header_value("Connection") == "close") { + connection_closed = true; + } + + if (req.version == "HTTP/1.0" && + req.get_header_value("Connection") != "Keep-Alive") { + connection_closed = true; + } + + req.remote_addr = remote_addr; + req.remote_port = remote_port; + req.set_header("REMOTE_ADDR", req.remote_addr); + req.set_header("REMOTE_PORT", std::to_string(req.remote_port)); + + req.local_addr = local_addr; + req.local_port = local_port; + req.set_header("LOCAL_ADDR", req.local_addr); + req.set_header("LOCAL_PORT", std::to_string(req.local_port)); + + if (req.has_header("Range")) { + const auto &range_header_value = req.get_header_value("Range"); + if (!detail::parse_range_header(range_header_value, req.ranges)) { + res.status = StatusCode::RangeNotSatisfiable_416; + return write_response(strm, close_connection, req, res); + } + } + + if (setup_request) { setup_request(req); } + + if (req.get_header_value("Expect") == "100-continue") { + int status = StatusCode::Continue_100; + if (expect_100_continue_handler_) { + status = expect_100_continue_handler_(req, res); + } + switch (status) { + case StatusCode::Continue_100: + case StatusCode::ExpectationFailed_417: + detail::write_response_line(strm, status); + strm.write("\r\n"); + break; + default: + connection_closed = true; + return write_response(strm, true, req, res); + } + } + + // Setup `is_connection_closed` method + auto sock = strm.socket(); + req.is_connection_closed = [sock]() { + return !detail::is_socket_alive(sock); + }; + + // Routing + auto routed = false; +#ifdef CPPHTTPLIB_NO_EXCEPTIONS + routed = routing(req, res, strm); +#else + try { + routed = routing(req, res, strm); + } catch (std::exception &e) { + if (exception_handler_) { + auto ep = std::current_exception(); + exception_handler_(req, res, ep); + routed = true; + } else { + res.status = StatusCode::InternalServerError_500; + std::string val; + auto s = e.what(); + for (size_t i = 0; s[i]; i++) { + switch (s[i]) { + case '\r': val += "\\r"; break; + case '\n': val += "\\n"; break; + default: val += s[i]; break; + } + } + res.set_header("EXCEPTION_WHAT", val); + } + } catch (...) { + if (exception_handler_) { + auto ep = std::current_exception(); + exception_handler_(req, res, ep); + routed = true; + } else { + res.status = StatusCode::InternalServerError_500; + res.set_header("EXCEPTION_WHAT", "UNKNOWN"); + } + } +#endif + if (routed) { + if (res.status == -1) { + res.status = req.ranges.empty() ? StatusCode::OK_200 + : StatusCode::PartialContent_206; + } + + // Serve file content by using a content provider + if (!res.file_content_path_.empty()) { + const auto &path = res.file_content_path_; + auto mm = std::make_shared(path.c_str()); + if (!mm->is_open()) { + res.body.clear(); + res.content_length_ = 0; + res.content_provider_ = nullptr; + res.status = StatusCode::NotFound_404; + return write_response(strm, close_connection, req, res); + } + + auto content_type = res.file_content_content_type_; + if (content_type.empty()) { + content_type = detail::find_content_type( + path, file_extension_and_mimetype_map_, default_file_mimetype_); + } + + res.set_content_provider( + mm->size(), content_type, + [mm](size_t offset, size_t length, DataSink &sink) -> bool { + sink.write(mm->data() + offset, length); + return true; + }); + } + + if (detail::range_error(req, res)) { + res.body.clear(); + res.content_length_ = 0; + res.content_provider_ = nullptr; + res.status = StatusCode::RangeNotSatisfiable_416; + return write_response(strm, close_connection, req, res); + } + + return write_response_with_content(strm, close_connection, req, res); + } else { + if (res.status == -1) { res.status = StatusCode::NotFound_404; } + + return write_response(strm, close_connection, req, res); + } +} + +inline bool Server::is_valid() const { return true; } + +inline bool Server::process_and_close_socket(socket_t sock) { + std::string remote_addr; + int remote_port = 0; + detail::get_remote_ip_and_port(sock, remote_addr, remote_port); + + std::string local_addr; + int local_port = 0; + detail::get_local_ip_and_port(sock, local_addr, local_port); + + auto ret = detail::process_server_socket( + svr_sock_, sock, keep_alive_max_count_, keep_alive_timeout_sec_, + read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, + [&](Stream &strm, bool close_connection, bool &connection_closed) { + return process_request(strm, remote_addr, remote_port, local_addr, + local_port, close_connection, connection_closed, + nullptr); + }); + + detail::shutdown_socket(sock); + detail::close_socket(sock); + return ret; +} + +// HTTP client implementation +inline ClientImpl::ClientImpl(const std::string &host) + : ClientImpl(host, 80, std::string(), std::string()) {} + +inline ClientImpl::ClientImpl(const std::string &host, int port) + : ClientImpl(host, port, std::string(), std::string()) {} + +inline ClientImpl::ClientImpl(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path) + : host_(detail::escape_abstract_namespace_unix_domain(host)), port_(port), + host_and_port_(adjust_host_string(host_) + ":" + std::to_string(port)), + client_cert_path_(client_cert_path), client_key_path_(client_key_path) {} + +inline ClientImpl::~ClientImpl() { + // Wait until all the requests in flight are handled. + size_t retry_count = 10; + while (retry_count-- > 0) { + { + std::lock_guard guard(socket_mutex_); + if (socket_requests_in_flight_ == 0) { break; } + } + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + + std::lock_guard guard(socket_mutex_); + shutdown_socket(socket_); + close_socket(socket_); +} + +inline bool ClientImpl::is_valid() const { return true; } + +inline void ClientImpl::copy_settings(const ClientImpl &rhs) { + client_cert_path_ = rhs.client_cert_path_; + client_key_path_ = rhs.client_key_path_; + connection_timeout_sec_ = rhs.connection_timeout_sec_; + read_timeout_sec_ = rhs.read_timeout_sec_; + read_timeout_usec_ = rhs.read_timeout_usec_; + write_timeout_sec_ = rhs.write_timeout_sec_; + write_timeout_usec_ = rhs.write_timeout_usec_; + max_timeout_msec_ = rhs.max_timeout_msec_; + basic_auth_username_ = rhs.basic_auth_username_; + basic_auth_password_ = rhs.basic_auth_password_; + bearer_token_auth_token_ = rhs.bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + digest_auth_username_ = rhs.digest_auth_username_; + digest_auth_password_ = rhs.digest_auth_password_; +#endif + keep_alive_ = rhs.keep_alive_; + follow_location_ = rhs.follow_location_; + url_encode_ = rhs.url_encode_; + address_family_ = rhs.address_family_; + tcp_nodelay_ = rhs.tcp_nodelay_; + ipv6_v6only_ = rhs.ipv6_v6only_; + socket_options_ = rhs.socket_options_; + compress_ = rhs.compress_; + decompress_ = rhs.decompress_; + interface_ = rhs.interface_; + proxy_host_ = rhs.proxy_host_; + proxy_port_ = rhs.proxy_port_; + proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_; + proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_; + proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_; +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_; + proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_; +#endif +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + ca_cert_file_path_ = rhs.ca_cert_file_path_; + ca_cert_dir_path_ = rhs.ca_cert_dir_path_; + ca_cert_store_ = rhs.ca_cert_store_; +#endif +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + server_certificate_verification_ = rhs.server_certificate_verification_; + server_hostname_verification_ = rhs.server_hostname_verification_; + server_certificate_verifier_ = rhs.server_certificate_verifier_; +#endif + logger_ = rhs.logger_; +} + +inline socket_t ClientImpl::create_client_socket(Error &error) const { + if (!proxy_host_.empty() && proxy_port_ != -1) { + return detail::create_client_socket( + proxy_host_, std::string(), proxy_port_, address_family_, tcp_nodelay_, + ipv6_v6only_, socket_options_, connection_timeout_sec_, + connection_timeout_usec_, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, interface_, error); + } + + // Check is custom IP specified for host_ + std::string ip; + auto it = addr_map_.find(host_); + if (it != addr_map_.end()) { ip = it->second; } + + return detail::create_client_socket( + host_, ip, port_, address_family_, tcp_nodelay_, ipv6_v6only_, + socket_options_, connection_timeout_sec_, connection_timeout_usec_, + read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, interface_, error); +} + +inline bool ClientImpl::create_and_connect_socket(Socket &socket, + Error &error) { + auto sock = create_client_socket(error); + if (sock == INVALID_SOCKET) { return false; } + socket.sock = sock; + return true; +} + +inline void ClientImpl::shutdown_ssl(Socket & /*socket*/, + bool /*shutdown_gracefully*/) { + // If there are any requests in flight from threads other than us, then it's + // a thread-unsafe race because individual ssl* objects are not thread-safe. + assert(socket_requests_in_flight_ == 0 || + socket_requests_are_from_thread_ == std::this_thread::get_id()); +} + +inline void ClientImpl::shutdown_socket(Socket &socket) const { + if (socket.sock == INVALID_SOCKET) { return; } + detail::shutdown_socket(socket.sock); +} + +inline void ClientImpl::close_socket(Socket &socket) { + // If there are requests in flight in another thread, usually closing + // the socket will be fine and they will simply receive an error when + // using the closed socket, but it is still a bug since rarely the OS + // may reassign the socket id to be used for a new socket, and then + // suddenly they will be operating on a live socket that is different + // than the one they intended! + assert(socket_requests_in_flight_ == 0 || + socket_requests_are_from_thread_ == std::this_thread::get_id()); + + // It is also a bug if this happens while SSL is still active +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + assert(socket.ssl == nullptr); +#endif + if (socket.sock == INVALID_SOCKET) { return; } + detail::close_socket(socket.sock); + socket.sock = INVALID_SOCKET; +} + +inline bool ClientImpl::read_response_line(Stream &strm, const Request &req, + Response &res) const { + std::array buf{}; + + detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); + + if (!line_reader.getline()) { return false; } + +#ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR + thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n"); +#else + thread_local const std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n"); +#endif + + std::cmatch m; + if (!std::regex_match(line_reader.ptr(), m, re)) { + return req.method == "CONNECT"; + } + res.version = std::string(m[1]); + res.status = std::stoi(std::string(m[2])); + res.reason = std::string(m[3]); + + // Ignore '100 Continue' + while (res.status == StatusCode::Continue_100) { + if (!line_reader.getline()) { return false; } // CRLF + if (!line_reader.getline()) { return false; } // next response line + + if (!std::regex_match(line_reader.ptr(), m, re)) { return false; } + res.version = std::string(m[1]); + res.status = std::stoi(std::string(m[2])); + res.reason = std::string(m[3]); + } + + return true; +} + +inline bool ClientImpl::send(Request &req, Response &res, Error &error) { + std::lock_guard request_mutex_guard(request_mutex_); + auto ret = send_(req, res, error); + if (error == Error::SSLPeerCouldBeClosed_) { + assert(!ret); + ret = send_(req, res, error); + } + return ret; +} + +inline bool ClientImpl::send_(Request &req, Response &res, Error &error) { + { + std::lock_guard guard(socket_mutex_); + + // Set this to false immediately - if it ever gets set to true by the end of + // the request, we know another thread instructed us to close the socket. + socket_should_be_closed_when_request_is_done_ = false; + + auto is_alive = false; + if (socket_.is_open()) { + is_alive = detail::is_socket_alive(socket_.sock); + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if (is_alive && is_ssl()) { + if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) { + is_alive = false; + } + } +#endif + + if (!is_alive) { + // Attempt to avoid sigpipe by shutting down non-gracefully if it seems + // like the other side has already closed the connection Also, there + // cannot be any requests in flight from other threads since we locked + // request_mutex_, so safe to close everything immediately + const bool shutdown_gracefully = false; + shutdown_ssl(socket_, shutdown_gracefully); + shutdown_socket(socket_); + close_socket(socket_); + } + } + + if (!is_alive) { + if (!create_and_connect_socket(socket_, error)) { return false; } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + // TODO: refactoring + if (is_ssl()) { + auto &scli = static_cast(*this); + if (!proxy_host_.empty() && proxy_port_ != -1) { + auto success = false; + if (!scli.connect_with_proxy(socket_, req.start_time_, res, success, + error)) { + return success; + } + } + + if (!scli.initialize_ssl(socket_, error)) { return false; } + } +#endif + } + + // Mark the current socket as being in use so that it cannot be closed by + // anyone else while this request is ongoing, even though we will be + // releasing the mutex. + if (socket_requests_in_flight_ > 1) { + assert(socket_requests_are_from_thread_ == std::this_thread::get_id()); + } + socket_requests_in_flight_ += 1; + socket_requests_are_from_thread_ = std::this_thread::get_id(); + } + + for (const auto &header : default_headers_) { + if (req.headers.find(header.first) == req.headers.end()) { + req.headers.insert(header); + } + } + + auto ret = false; + auto close_connection = !keep_alive_; + + auto se = detail::scope_exit([&]() { + // Briefly lock mutex in order to mark that a request is no longer ongoing + std::lock_guard guard(socket_mutex_); + socket_requests_in_flight_ -= 1; + if (socket_requests_in_flight_ <= 0) { + assert(socket_requests_in_flight_ == 0); + socket_requests_are_from_thread_ = std::thread::id(); + } + + if (socket_should_be_closed_when_request_is_done_ || close_connection || + !ret) { + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); + } + }); + + ret = process_socket(socket_, req.start_time_, [&](Stream &strm) { + return handle_request(strm, req, res, close_connection, error); + }); + + if (!ret) { + if (error == Error::Success) { error = Error::Unknown; } + } + + return ret; +} + +inline Result ClientImpl::send(const Request &req) { + auto req2 = req; + return send_(std::move(req2)); +} + +inline Result ClientImpl::send_(Request &&req) { + auto res = detail::make_unique(); + auto error = Error::Success; + auto ret = send(req, *res, error); + return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)}; +} + +inline bool ClientImpl::handle_request(Stream &strm, Request &req, + Response &res, bool close_connection, + Error &error) { + if (req.path.empty()) { + error = Error::Connection; + return false; + } + + auto req_save = req; + + bool ret; + + if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) { + auto req2 = req; + req2.path = "http://" + host_and_port_ + req.path; + ret = process_request(strm, req2, res, close_connection, error); + req = req2; + req.path = req_save.path; + } else { + ret = process_request(strm, req, res, close_connection, error); + } + + if (!ret) { return false; } + + if (res.get_header_value("Connection") == "close" || + (res.version == "HTTP/1.0" && res.reason != "Connection established")) { + // TODO this requires a not-entirely-obvious chain of calls to be correct + // for this to be safe. + + // This is safe to call because handle_request is only called by send_ + // which locks the request mutex during the process. It would be a bug + // to call it from a different thread since it's a thread-safety issue + // to do these things to the socket if another thread is using the socket. + std::lock_guard guard(socket_mutex_); + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); + } + + if (300 < res.status && res.status < 400 && follow_location_) { + req = req_save; + ret = redirect(req, res, error); + } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if ((res.status == StatusCode::Unauthorized_401 || + res.status == StatusCode::ProxyAuthenticationRequired_407) && + req.authorization_count_ < 5) { + auto is_proxy = res.status == StatusCode::ProxyAuthenticationRequired_407; + const auto &username = + is_proxy ? proxy_digest_auth_username_ : digest_auth_username_; + const auto &password = + is_proxy ? proxy_digest_auth_password_ : digest_auth_password_; + + if (!username.empty() && !password.empty()) { + std::map auth; + if (detail::parse_www_authenticate(res, auth, is_proxy)) { + Request new_req = req; + new_req.authorization_count_ += 1; + new_req.headers.erase(is_proxy ? "Proxy-Authorization" + : "Authorization"); + new_req.headers.insert(detail::make_digest_authentication_header( + req, auth, new_req.authorization_count_, detail::random_string(10), + username, password, is_proxy)); + + Response new_res; + + ret = send(new_req, new_res, error); + if (ret) { res = new_res; } + } + } + } +#endif + + return ret; +} + +inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) { + if (req.redirect_count_ == 0) { + error = Error::ExceedRedirectCount; + return false; + } + + auto location = res.get_header_value("location"); + if (location.empty()) { return false; } + + thread_local const std::regex re( + R"((?:(https?):)?(?://(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)"); + + std::smatch m; + if (!std::regex_match(location, m, re)) { return false; } + + auto scheme = is_ssl() ? "https" : "http"; + + auto next_scheme = m[1].str(); + auto next_host = m[2].str(); + if (next_host.empty()) { next_host = m[3].str(); } + auto port_str = m[4].str(); + auto next_path = m[5].str(); + auto next_query = m[6].str(); + + auto next_port = port_; + if (!port_str.empty()) { + next_port = std::stoi(port_str); + } else if (!next_scheme.empty()) { + next_port = next_scheme == "https" ? 443 : 80; + } + + if (next_scheme.empty()) { next_scheme = scheme; } + if (next_host.empty()) { next_host = host_; } + if (next_path.empty()) { next_path = "/"; } + + auto path = detail::decode_url(next_path, true) + next_query; + + if (next_scheme == scheme && next_host == host_ && next_port == port_) { + return detail::redirect(*this, req, res, path, location, error); + } else { + if (next_scheme == "https") { +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + SSLClient cli(next_host, next_port); + cli.copy_settings(*this); + if (ca_cert_store_) { cli.set_ca_cert_store(ca_cert_store_); } + return detail::redirect(cli, req, res, path, location, error); +#else + return false; +#endif + } else { + ClientImpl cli(next_host, next_port); + cli.copy_settings(*this); + return detail::redirect(cli, req, res, path, location, error); + } + } +} + +inline bool ClientImpl::write_content_with_provider(Stream &strm, + const Request &req, + Error &error) const { + auto is_shutting_down = []() { return false; }; + + if (req.is_chunked_content_provider_) { + // TODO: Brotli support + std::unique_ptr compressor; +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (compress_) { + compressor = detail::make_unique(); + } else +#endif + { + compressor = detail::make_unique(); + } + + return detail::write_content_chunked(strm, req.content_provider_, + is_shutting_down, *compressor, error); + } else { + return detail::write_content(strm, req.content_provider_, 0, + req.content_length_, is_shutting_down, error); + } +} + +inline bool ClientImpl::write_request(Stream &strm, Request &req, + bool close_connection, Error &error) { + // Prepare additional headers + if (close_connection) { + if (!req.has_header("Connection")) { + req.set_header("Connection", "close"); + } + } + + if (!req.has_header("Host")) { + if (is_ssl()) { + if (port_ == 443) { + req.set_header("Host", host_); + } else { + req.set_header("Host", host_and_port_); + } + } else { + if (port_ == 80) { + req.set_header("Host", host_); + } else { + req.set_header("Host", host_and_port_); + } + } + } + + if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); } + + if (!req.content_receiver) { + if (!req.has_header("Accept-Encoding")) { + std::string accept_encoding; +#ifdef CPPHTTPLIB_BROTLI_SUPPORT + accept_encoding = "br"; +#endif +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (!accept_encoding.empty()) { accept_encoding += ", "; } + accept_encoding += "gzip, deflate"; +#endif +#ifdef CPPHTTPLIB_ZSTD_SUPPORT + if (!accept_encoding.empty()) { accept_encoding += ", "; } + accept_encoding += "zstd"; +#endif + req.set_header("Accept-Encoding", accept_encoding); + } + +#ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT + if (!req.has_header("User-Agent")) { + auto agent = std::string("cpp-httplib/") + CPPHTTPLIB_VERSION; + req.set_header("User-Agent", agent); + } +#endif + }; + + if (req.body.empty()) { + if (req.content_provider_) { + if (!req.is_chunked_content_provider_) { + if (!req.has_header("Content-Length")) { + auto length = std::to_string(req.content_length_); + req.set_header("Content-Length", length); + } + } + } else { + if (req.method == "POST" || req.method == "PUT" || + req.method == "PATCH") { + req.set_header("Content-Length", "0"); + } + } + } else { + if (!req.has_header("Content-Type")) { + req.set_header("Content-Type", "text/plain"); + } + + if (!req.has_header("Content-Length")) { + auto length = std::to_string(req.body.size()); + req.set_header("Content-Length", length); + } + } + + if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) { + if (!req.has_header("Authorization")) { + req.headers.insert(make_basic_authentication_header( + basic_auth_username_, basic_auth_password_, false)); + } + } + + if (!proxy_basic_auth_username_.empty() && + !proxy_basic_auth_password_.empty()) { + if (!req.has_header("Proxy-Authorization")) { + req.headers.insert(make_basic_authentication_header( + proxy_basic_auth_username_, proxy_basic_auth_password_, true)); + } + } + + if (!bearer_token_auth_token_.empty()) { + if (!req.has_header("Authorization")) { + req.headers.insert(make_bearer_token_authentication_header( + bearer_token_auth_token_, false)); + } + } + + if (!proxy_bearer_token_auth_token_.empty()) { + if (!req.has_header("Proxy-Authorization")) { + req.headers.insert(make_bearer_token_authentication_header( + proxy_bearer_token_auth_token_, true)); + } + } + + // Request line and headers + { + detail::BufferStream bstrm; + + const auto &path_with_query = + req.params.empty() ? req.path + : append_query_params(req.path, req.params); + + const auto &path = + url_encode_ ? detail::encode_url(path_with_query) : path_with_query; + + detail::write_request_line(bstrm, req.method, path); + + header_writer_(bstrm, req.headers); + + // Flush buffer + auto &data = bstrm.get_buffer(); + if (!detail::write_data(strm, data.data(), data.size())) { + error = Error::Write; + return false; + } + } + + // Body + if (req.body.empty()) { + return write_content_with_provider(strm, req, error); + } + + if (!detail::write_data(strm, req.body.data(), req.body.size())) { + error = Error::Write; + return false; + } + + return true; +} + +inline std::unique_ptr ClientImpl::send_with_content_provider( + Request &req, const char *body, size_t content_length, + ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string &content_type, Error &error) { + if (!content_type.empty()) { req.set_header("Content-Type", content_type); } + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (compress_) { req.set_header("Content-Encoding", "gzip"); } +#endif + +#ifdef CPPHTTPLIB_ZLIB_SUPPORT + if (compress_ && !content_provider_without_length) { + // TODO: Brotli support + detail::gzip_compressor compressor; + + if (content_provider) { + auto ok = true; + size_t offset = 0; + DataSink data_sink; + + data_sink.write = [&](const char *data, size_t data_len) -> bool { + if (ok) { + auto last = offset + data_len == content_length; + + auto ret = compressor.compress( + data, data_len, last, + [&](const char *compressed_data, size_t compressed_data_len) { + req.body.append(compressed_data, compressed_data_len); + return true; + }); + + if (ret) { + offset += data_len; + } else { + ok = false; + } + } + return ok; + }; + + while (ok && offset < content_length) { + if (!content_provider(offset, content_length - offset, data_sink)) { + error = Error::Canceled; + return nullptr; + } + } + } else { + if (!compressor.compress(body, content_length, true, + [&](const char *data, size_t data_len) { + req.body.append(data, data_len); + return true; + })) { + error = Error::Compression; + return nullptr; + } + } + } else +#endif + { + if (content_provider) { + req.content_length_ = content_length; + req.content_provider_ = std::move(content_provider); + req.is_chunked_content_provider_ = false; + } else if (content_provider_without_length) { + req.content_length_ = 0; + req.content_provider_ = detail::ContentProviderAdapter( + std::move(content_provider_without_length)); + req.is_chunked_content_provider_ = true; + req.set_header("Transfer-Encoding", "chunked"); + } else { + req.body.assign(body, content_length); + } + } + + auto res = detail::make_unique(); + return send(req, *res, error) ? std::move(res) : nullptr; +} + +inline Result ClientImpl::send_with_content_provider( + const std::string &method, const std::string &path, const Headers &headers, + const char *body, size_t content_length, ContentProvider content_provider, + ContentProviderWithoutLength content_provider_without_length, + const std::string &content_type, Progress progress) { + Request req; + req.method = method; + req.headers = headers; + req.path = path; + req.progress = progress; + if (max_timeout_msec_ > 0) { + req.start_time_ = std::chrono::steady_clock::now(); + } + + auto error = Error::Success; + + auto res = send_with_content_provider( + req, body, content_length, std::move(content_provider), + std::move(content_provider_without_length), content_type, error); + + return Result{std::move(res), error, std::move(req.headers)}; +} + +inline std::string +ClientImpl::adjust_host_string(const std::string &host) const { + if (host.find(':') != std::string::npos) { return "[" + host + "]"; } + return host; +} + +inline bool ClientImpl::process_request(Stream &strm, Request &req, + Response &res, bool close_connection, + Error &error) { + // Send request + if (!write_request(strm, req, close_connection, error)) { return false; } + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if (is_ssl()) { + auto is_proxy_enabled = !proxy_host_.empty() && proxy_port_ != -1; + if (!is_proxy_enabled) { + if (detail::is_ssl_peer_could_be_closed(socket_.ssl, socket_.sock)) { + error = Error::SSLPeerCouldBeClosed_; + return false; + } + } + } +#endif + + // Receive response and headers + if (!read_response_line(strm, req, res) || + !detail::read_headers(strm, res.headers)) { + error = Error::Read; + return false; + } + + // Body + if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" && + req.method != "CONNECT") { + auto redirect = 300 < res.status && res.status < 400 && + res.status != StatusCode::NotModified_304 && + follow_location_; + + if (req.response_handler && !redirect) { + if (!req.response_handler(res)) { + error = Error::Canceled; + return false; + } + } + + auto out = + req.content_receiver + ? static_cast( + [&](const char *buf, size_t n, uint64_t off, uint64_t len) { + if (redirect) { return true; } + auto ret = req.content_receiver(buf, n, off, len); + if (!ret) { error = Error::Canceled; } + return ret; + }) + : static_cast( + [&](const char *buf, size_t n, uint64_t /*off*/, + uint64_t /*len*/) { + assert(res.body.size() + n <= res.body.max_size()); + res.body.append(buf, n); + return true; + }); + + auto progress = [&](uint64_t current, uint64_t total) { + if (!req.progress || redirect) { return true; } + auto ret = req.progress(current, total); + if (!ret) { error = Error::Canceled; } + return ret; + }; + + if (res.has_header("Content-Length")) { + if (!req.content_receiver) { + auto len = res.get_header_value_u64("Content-Length"); + if (len > res.body.max_size()) { + error = Error::Read; + return false; + } + res.body.reserve(static_cast(len)); + } + } + + if (res.status != StatusCode::NotModified_304) { + int dummy_status; + if (!detail::read_content(strm, res, (std::numeric_limits::max)(), + dummy_status, std::move(progress), + std::move(out), decompress_)) { + if (error != Error::Canceled) { error = Error::Read; } + return false; + } + } + } + + // Log + if (logger_) { logger_(req, res); } + + return true; +} + +inline ContentProviderWithoutLength ClientImpl::get_multipart_content_provider( + const std::string &boundary, const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items) const { + size_t cur_item = 0; + size_t cur_start = 0; + // cur_item and cur_start are copied to within the std::function and maintain + // state between successive calls + return [&, cur_item, cur_start](size_t offset, + DataSink &sink) mutable -> bool { + if (!offset && !items.empty()) { + sink.os << detail::serialize_multipart_formdata(items, boundary, false); + return true; + } else if (cur_item < provider_items.size()) { + if (!cur_start) { + const auto &begin = detail::serialize_multipart_formdata_item_begin( + provider_items[cur_item], boundary); + offset += begin.size(); + cur_start = offset; + sink.os << begin; + } + + DataSink cur_sink; + auto has_data = true; + cur_sink.write = sink.write; + cur_sink.done = [&]() { has_data = false; }; + + if (!provider_items[cur_item].provider(offset - cur_start, cur_sink)) { + return false; + } + + if (!has_data) { + sink.os << detail::serialize_multipart_formdata_item_end(); + cur_item++; + cur_start = 0; + } + return true; + } else { + sink.os << detail::serialize_multipart_formdata_finish(boundary); + sink.done(); + return true; + } + }; +} + +inline bool ClientImpl::process_socket( + const Socket &socket, + std::chrono::time_point start_time, + std::function callback) { + return detail::process_client_socket( + socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, max_timeout_msec_, start_time, std::move(callback)); +} + +inline bool ClientImpl::is_ssl() const { return false; } + +inline Result ClientImpl::Get(const std::string &path) { + return Get(path, Headers(), Progress()); +} + +inline Result ClientImpl::Get(const std::string &path, Progress progress) { + return Get(path, Headers(), std::move(progress)); +} + +inline Result ClientImpl::Get(const std::string &path, const Headers &headers) { + return Get(path, headers, Progress()); +} + +inline Result ClientImpl::Get(const std::string &path, const Headers &headers, + Progress progress) { + Request req; + req.method = "GET"; + req.path = path; + req.headers = headers; + req.progress = std::move(progress); + if (max_timeout_msec_ > 0) { + req.start_time_ = std::chrono::steady_clock::now(); + } + + return send_(std::move(req)); +} + +inline Result ClientImpl::Get(const std::string &path, + ContentReceiver content_receiver) { + return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr); +} + +inline Result ClientImpl::Get(const std::string &path, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, Headers(), nullptr, std::move(content_receiver), + std::move(progress)); +} + +inline Result ClientImpl::Get(const std::string &path, const Headers &headers, + ContentReceiver content_receiver) { + return Get(path, headers, nullptr, std::move(content_receiver), nullptr); +} + +inline Result ClientImpl::Get(const std::string &path, const Headers &headers, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, headers, nullptr, std::move(content_receiver), + std::move(progress)); +} + +inline Result ClientImpl::Get(const std::string &path, + ResponseHandler response_handler, + ContentReceiver content_receiver) { + return Get(path, Headers(), std::move(response_handler), + std::move(content_receiver), nullptr); +} + +inline Result ClientImpl::Get(const std::string &path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver) { + return Get(path, headers, std::move(response_handler), + std::move(content_receiver), nullptr); +} + +inline Result ClientImpl::Get(const std::string &path, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, Headers(), std::move(response_handler), + std::move(content_receiver), std::move(progress)); +} + +inline Result ClientImpl::Get(const std::string &path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + Request req; + req.method = "GET"; + req.path = path; + req.headers = headers; + req.response_handler = std::move(response_handler); + req.content_receiver = + [content_receiver](const char *data, size_t data_length, + uint64_t /*offset*/, uint64_t /*total_length*/) { + return content_receiver(data, data_length); + }; + req.progress = std::move(progress); + if (max_timeout_msec_ > 0) { + req.start_time_ = std::chrono::steady_clock::now(); + } + + return send_(std::move(req)); +} + +inline Result ClientImpl::Get(const std::string &path, const Params ¶ms, + const Headers &headers, Progress progress) { + if (params.empty()) { return Get(path, headers); } + + std::string path_with_query = append_query_params(path, params); + return Get(path_with_query, headers, std::move(progress)); +} + +inline Result ClientImpl::Get(const std::string &path, const Params ¶ms, + const Headers &headers, + ContentReceiver content_receiver, + Progress progress) { + return Get(path, params, headers, nullptr, std::move(content_receiver), + std::move(progress)); +} + +inline Result ClientImpl::Get(const std::string &path, const Params ¶ms, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, + Progress progress) { + if (params.empty()) { + return Get(path, headers, std::move(response_handler), + std::move(content_receiver), std::move(progress)); + } + + std::string path_with_query = append_query_params(path, params); + return Get(path_with_query, headers, std::move(response_handler), + std::move(content_receiver), std::move(progress)); +} + +inline Result ClientImpl::Head(const std::string &path) { + return Head(path, Headers()); +} + +inline Result ClientImpl::Head(const std::string &path, + const Headers &headers) { + Request req; + req.method = "HEAD"; + req.headers = headers; + req.path = path; + if (max_timeout_msec_ > 0) { + req.start_time_ = std::chrono::steady_clock::now(); + } + + return send_(std::move(req)); +} + +inline Result ClientImpl::Post(const std::string &path) { + return Post(path, std::string(), std::string()); +} + +inline Result ClientImpl::Post(const std::string &path, + const Headers &headers) { + return Post(path, headers, nullptr, 0, std::string()); +} + +inline Result ClientImpl::Post(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type) { + return Post(path, Headers(), body, content_length, content_type, nullptr); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type) { + return send_with_content_provider("POST", path, headers, body, content_length, + nullptr, nullptr, content_type, nullptr); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, + Progress progress) { + return send_with_content_provider("POST", path, headers, body, content_length, + nullptr, nullptr, content_type, progress); +} + +inline Result ClientImpl::Post(const std::string &path, const std::string &body, + const std::string &content_type) { + return Post(path, Headers(), body, content_type); +} + +inline Result ClientImpl::Post(const std::string &path, const std::string &body, + const std::string &content_type, + Progress progress) { + return Post(path, Headers(), body, content_type, progress); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type) { + return send_with_content_provider("POST", path, headers, body.data(), + body.size(), nullptr, nullptr, content_type, + nullptr); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type, + Progress progress) { + return send_with_content_provider("POST", path, headers, body.data(), + body.size(), nullptr, nullptr, content_type, + progress); +} + +inline Result ClientImpl::Post(const std::string &path, const Params ¶ms) { + return Post(path, Headers(), params); +} + +inline Result ClientImpl::Post(const std::string &path, size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return Post(path, Headers(), content_length, std::move(content_provider), + content_type); +} + +inline Result ClientImpl::Post(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return Post(path, Headers(), std::move(content_provider), content_type); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return send_with_content_provider("POST", path, headers, nullptr, + content_length, std::move(content_provider), + nullptr, content_type, nullptr); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr, + std::move(content_provider), content_type, + nullptr); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, + const Params ¶ms) { + auto query = detail::params_to_query_str(params); + return Post(path, headers, query, "application/x-www-form-urlencoded"); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, + const Params ¶ms, Progress progress) { + auto query = detail::params_to_query_str(params); + return Post(path, headers, query, "application/x-www-form-urlencoded", + progress); +} + +inline Result ClientImpl::Post(const std::string &path, + const MultipartFormDataItems &items) { + return Post(path, Headers(), items); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items) { + const auto &boundary = detail::make_multipart_data_boundary(); + const auto &content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + const auto &body = detail::serialize_multipart_formdata(items, boundary); + return Post(path, headers, body, content_type); +} + +inline Result ClientImpl::Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const std::string &boundary) { + if (!detail::is_multipart_boundary_chars_valid(boundary)) { + return Result{nullptr, Error::UnsupportedMultipartBoundaryChars}; + } + + const auto &content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + const auto &body = detail::serialize_multipart_formdata(items, boundary); + return Post(path, headers, body, content_type); +} + +inline Result +ClientImpl::Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items) { + const auto &boundary = detail::make_multipart_data_boundary(); + const auto &content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + return send_with_content_provider( + "POST", path, headers, nullptr, 0, nullptr, + get_multipart_content_provider(boundary, items, provider_items), + content_type, nullptr); +} + +inline Result ClientImpl::Put(const std::string &path) { + return Put(path, std::string(), std::string()); +} + +inline Result ClientImpl::Put(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type) { + return Put(path, Headers(), body, content_length, content_type); +} + +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type) { + return send_with_content_provider("PUT", path, headers, body, content_length, + nullptr, nullptr, content_type, nullptr); +} + +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, + Progress progress) { + return send_with_content_provider("PUT", path, headers, body, content_length, + nullptr, nullptr, content_type, progress); +} + +inline Result ClientImpl::Put(const std::string &path, const std::string &body, + const std::string &content_type) { + return Put(path, Headers(), body, content_type); +} + +inline Result ClientImpl::Put(const std::string &path, const std::string &body, + const std::string &content_type, + Progress progress) { + return Put(path, Headers(), body, content_type, progress); +} + +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type) { + return send_with_content_provider("PUT", path, headers, body.data(), + body.size(), nullptr, nullptr, content_type, + nullptr); +} + +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type, + Progress progress) { + return send_with_content_provider("PUT", path, headers, body.data(), + body.size(), nullptr, nullptr, content_type, + progress); +} + +inline Result ClientImpl::Put(const std::string &path, size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return Put(path, Headers(), content_length, std::move(content_provider), + content_type); +} + +inline Result ClientImpl::Put(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return Put(path, Headers(), std::move(content_provider), content_type); +} + +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return send_with_content_provider("PUT", path, headers, nullptr, + content_length, std::move(content_provider), + nullptr, content_type, nullptr); +} + +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr, + std::move(content_provider), content_type, + nullptr); +} + +inline Result ClientImpl::Put(const std::string &path, const Params ¶ms) { + return Put(path, Headers(), params); +} + +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, + const Params ¶ms) { + auto query = detail::params_to_query_str(params); + return Put(path, headers, query, "application/x-www-form-urlencoded"); +} + +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, + const Params ¶ms, Progress progress) { + auto query = detail::params_to_query_str(params); + return Put(path, headers, query, "application/x-www-form-urlencoded", + progress); +} + +inline Result ClientImpl::Put(const std::string &path, + const MultipartFormDataItems &items) { + return Put(path, Headers(), items); +} + +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items) { + const auto &boundary = detail::make_multipart_data_boundary(); + const auto &content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + const auto &body = detail::serialize_multipart_formdata(items, boundary); + return Put(path, headers, body, content_type); +} + +inline Result ClientImpl::Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const std::string &boundary) { + if (!detail::is_multipart_boundary_chars_valid(boundary)) { + return Result{nullptr, Error::UnsupportedMultipartBoundaryChars}; + } + + const auto &content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + const auto &body = detail::serialize_multipart_formdata(items, boundary); + return Put(path, headers, body, content_type); +} + +inline Result +ClientImpl::Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items) { + const auto &boundary = detail::make_multipart_data_boundary(); + const auto &content_type = + detail::serialize_multipart_formdata_get_content_type(boundary); + return send_with_content_provider( + "PUT", path, headers, nullptr, 0, nullptr, + get_multipart_content_provider(boundary, items, provider_items), + content_type, nullptr); +} +inline Result ClientImpl::Patch(const std::string &path) { + return Patch(path, std::string(), std::string()); +} + +inline Result ClientImpl::Patch(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type) { + return Patch(path, Headers(), body, content_length, content_type); +} + +inline Result ClientImpl::Patch(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type, + Progress progress) { + return Patch(path, Headers(), body, content_length, content_type, progress); +} + +inline Result ClientImpl::Patch(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type) { + return Patch(path, headers, body, content_length, content_type, nullptr); +} + +inline Result ClientImpl::Patch(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, + Progress progress) { + return send_with_content_provider("PATCH", path, headers, body, + content_length, nullptr, nullptr, + content_type, progress); +} + +inline Result ClientImpl::Patch(const std::string &path, + const std::string &body, + const std::string &content_type) { + return Patch(path, Headers(), body, content_type); +} + +inline Result ClientImpl::Patch(const std::string &path, + const std::string &body, + const std::string &content_type, + Progress progress) { + return Patch(path, Headers(), body, content_type, progress); +} + +inline Result ClientImpl::Patch(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type) { + return Patch(path, headers, body, content_type, nullptr); +} + +inline Result ClientImpl::Patch(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type, + Progress progress) { + return send_with_content_provider("PATCH", path, headers, body.data(), + body.size(), nullptr, nullptr, content_type, + progress); +} + +inline Result ClientImpl::Patch(const std::string &path, size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return Patch(path, Headers(), content_length, std::move(content_provider), + content_type); +} + +inline Result ClientImpl::Patch(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return Patch(path, Headers(), std::move(content_provider), content_type); +} + +inline Result ClientImpl::Patch(const std::string &path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return send_with_content_provider("PATCH", path, headers, nullptr, + content_length, std::move(content_provider), + nullptr, content_type, nullptr); +} + +inline Result ClientImpl::Patch(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr, + std::move(content_provider), content_type, + nullptr); +} + +inline Result ClientImpl::Delete(const std::string &path) { + return Delete(path, Headers(), std::string(), std::string()); +} + +inline Result ClientImpl::Delete(const std::string &path, + const Headers &headers) { + return Delete(path, headers, std::string(), std::string()); +} + +inline Result ClientImpl::Delete(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type) { + return Delete(path, Headers(), body, content_length, content_type); +} + +inline Result ClientImpl::Delete(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type, + Progress progress) { + return Delete(path, Headers(), body, content_length, content_type, progress); +} + +inline Result ClientImpl::Delete(const std::string &path, + const Headers &headers, const char *body, + size_t content_length, + const std::string &content_type) { + return Delete(path, headers, body, content_length, content_type, nullptr); +} + +inline Result ClientImpl::Delete(const std::string &path, + const Headers &headers, const char *body, + size_t content_length, + const std::string &content_type, + Progress progress) { + Request req; + req.method = "DELETE"; + req.headers = headers; + req.path = path; + req.progress = progress; + if (max_timeout_msec_ > 0) { + req.start_time_ = std::chrono::steady_clock::now(); + } + + if (!content_type.empty()) { req.set_header("Content-Type", content_type); } + req.body.assign(body, content_length); + + return send_(std::move(req)); +} + +inline Result ClientImpl::Delete(const std::string &path, + const std::string &body, + const std::string &content_type) { + return Delete(path, Headers(), body.data(), body.size(), content_type); +} + +inline Result ClientImpl::Delete(const std::string &path, + const std::string &body, + const std::string &content_type, + Progress progress) { + return Delete(path, Headers(), body.data(), body.size(), content_type, + progress); +} + +inline Result ClientImpl::Delete(const std::string &path, + const Headers &headers, + const std::string &body, + const std::string &content_type) { + return Delete(path, headers, body.data(), body.size(), content_type); +} + +inline Result ClientImpl::Delete(const std::string &path, + const Headers &headers, + const std::string &body, + const std::string &content_type, + Progress progress) { + return Delete(path, headers, body.data(), body.size(), content_type, + progress); +} + +inline Result ClientImpl::Options(const std::string &path) { + return Options(path, Headers()); +} + +inline Result ClientImpl::Options(const std::string &path, + const Headers &headers) { + Request req; + req.method = "OPTIONS"; + req.headers = headers; + req.path = path; + if (max_timeout_msec_ > 0) { + req.start_time_ = std::chrono::steady_clock::now(); + } + + return send_(std::move(req)); +} + +inline void ClientImpl::stop() { + std::lock_guard guard(socket_mutex_); + + // If there is anything ongoing right now, the ONLY thread-safe thing we can + // do is to shutdown_socket, so that threads using this socket suddenly + // discover they can't read/write any more and error out. Everything else + // (closing the socket, shutting ssl down) is unsafe because these actions are + // not thread-safe. + if (socket_requests_in_flight_ > 0) { + shutdown_socket(socket_); + + // Aside from that, we set a flag for the socket to be closed when we're + // done. + socket_should_be_closed_when_request_is_done_ = true; + return; + } + + // Otherwise, still holding the mutex, we can shut everything down ourselves + shutdown_ssl(socket_, true); + shutdown_socket(socket_); + close_socket(socket_); +} + +inline std::string ClientImpl::host() const { return host_; } + +inline int ClientImpl::port() const { return port_; } + +inline size_t ClientImpl::is_socket_open() const { + std::lock_guard guard(socket_mutex_); + return socket_.is_open(); +} + +inline socket_t ClientImpl::socket() const { return socket_.sock; } + +inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) { + connection_timeout_sec_ = sec; + connection_timeout_usec_ = usec; +} + +inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) { + read_timeout_sec_ = sec; + read_timeout_usec_ = usec; +} + +inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) { + write_timeout_sec_ = sec; + write_timeout_usec_ = usec; +} + +inline void ClientImpl::set_max_timeout(time_t msec) { + max_timeout_msec_ = msec; +} + +inline void ClientImpl::set_basic_auth(const std::string &username, + const std::string &password) { + basic_auth_username_ = username; + basic_auth_password_ = password; +} + +inline void ClientImpl::set_bearer_token_auth(const std::string &token) { + bearer_token_auth_token_ = token; +} + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void ClientImpl::set_digest_auth(const std::string &username, + const std::string &password) { + digest_auth_username_ = username; + digest_auth_password_ = password; +} +#endif + +inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; } + +inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; } + +inline void ClientImpl::set_url_encode(bool on) { url_encode_ = on; } + +inline void +ClientImpl::set_hostname_addr_map(std::map addr_map) { + addr_map_ = std::move(addr_map); +} + +inline void ClientImpl::set_default_headers(Headers headers) { + default_headers_ = std::move(headers); +} + +inline void ClientImpl::set_header_writer( + std::function const &writer) { + header_writer_ = writer; +} + +inline void ClientImpl::set_address_family(int family) { + address_family_ = family; +} + +inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; } + +inline void ClientImpl::set_ipv6_v6only(bool on) { ipv6_v6only_ = on; } + +inline void ClientImpl::set_socket_options(SocketOptions socket_options) { + socket_options_ = std::move(socket_options); +} + +inline void ClientImpl::set_compress(bool on) { compress_ = on; } + +inline void ClientImpl::set_decompress(bool on) { decompress_ = on; } + +inline void ClientImpl::set_interface(const std::string &intf) { + interface_ = intf; +} + +inline void ClientImpl::set_proxy(const std::string &host, int port) { + proxy_host_ = host; + proxy_port_ = port; +} + +inline void ClientImpl::set_proxy_basic_auth(const std::string &username, + const std::string &password) { + proxy_basic_auth_username_ = username; + proxy_basic_auth_password_ = password; +} + +inline void ClientImpl::set_proxy_bearer_token_auth(const std::string &token) { + proxy_bearer_token_auth_token_ = token; +} + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void ClientImpl::set_proxy_digest_auth(const std::string &username, + const std::string &password) { + proxy_digest_auth_username_ = username; + proxy_digest_auth_password_ = password; +} + +inline void ClientImpl::set_ca_cert_path(const std::string &ca_cert_file_path, + const std::string &ca_cert_dir_path) { + ca_cert_file_path_ = ca_cert_file_path; + ca_cert_dir_path_ = ca_cert_dir_path; +} + +inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) { + if (ca_cert_store && ca_cert_store != ca_cert_store_) { + ca_cert_store_ = ca_cert_store; + } +} + +inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert, + std::size_t size) const { + auto mem = BIO_new_mem_buf(ca_cert, static_cast(size)); + auto se = detail::scope_exit([&] { BIO_free_all(mem); }); + if (!mem) { return nullptr; } + + auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr); + if (!inf) { return nullptr; } + + auto cts = X509_STORE_new(); + if (cts) { + for (auto i = 0; i < static_cast(sk_X509_INFO_num(inf)); i++) { + auto itmp = sk_X509_INFO_value(inf, i); + if (!itmp) { continue; } + + if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); } + if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); } + } + } + + sk_X509_INFO_pop_free(inf, X509_INFO_free); + return cts; +} + +inline void ClientImpl::enable_server_certificate_verification(bool enabled) { + server_certificate_verification_ = enabled; +} + +inline void ClientImpl::enable_server_hostname_verification(bool enabled) { + server_hostname_verification_ = enabled; +} + +inline void ClientImpl::set_server_certificate_verifier( + std::function verifier) { + server_certificate_verifier_ = verifier; +} +#endif + +inline void ClientImpl::set_logger(Logger logger) { + logger_ = std::move(logger); +} + +/* + * SSL Implementation + */ +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +namespace detail { + +template +inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex, + U SSL_connect_or_accept, V setup) { + SSL *ssl = nullptr; + { + std::lock_guard guard(ctx_mutex); + ssl = SSL_new(ctx); + } + + if (ssl) { + set_nonblocking(sock, true); + auto bio = BIO_new_socket(static_cast(sock), BIO_NOCLOSE); + BIO_set_nbio(bio, 1); + SSL_set_bio(ssl, bio, bio); + + if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) { + SSL_shutdown(ssl); + { + std::lock_guard guard(ctx_mutex); + SSL_free(ssl); + } + set_nonblocking(sock, false); + return nullptr; + } + BIO_set_nbio(bio, 0); + set_nonblocking(sock, false); + } + + return ssl; +} + +inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, socket_t sock, + bool shutdown_gracefully) { + // sometimes we may want to skip this to try to avoid SIGPIPE if we know + // the remote has closed the network connection + // Note that it is not always possible to avoid SIGPIPE, this is merely a + // best-efforts. + if (shutdown_gracefully) { + (void)(sock); + // SSL_shutdown() returns 0 on first call (indicating close_notify alert + // sent) and 1 on subsequent call (indicating close_notify alert received) + if (SSL_shutdown(ssl) == 0) { + // Expected to return 1, but even if it doesn't, we free ssl + SSL_shutdown(ssl); + } + } + + std::lock_guard guard(ctx_mutex); + SSL_free(ssl); +} + +template +bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl, + U ssl_connect_or_accept, + time_t timeout_sec, + time_t timeout_usec) { + auto res = 0; + while ((res = ssl_connect_or_accept(ssl)) != 1) { + auto err = SSL_get_error(ssl, res); + switch (err) { + case SSL_ERROR_WANT_READ: + if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; } + break; + case SSL_ERROR_WANT_WRITE: + if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; } + break; + default: break; + } + return false; + } + return true; +} + +template +inline bool process_server_socket_ssl( + const std::atomic &svr_sock, SSL *ssl, socket_t sock, + size_t keep_alive_max_count, time_t keep_alive_timeout_sec, + time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec, + time_t write_timeout_usec, T callback) { + return process_server_socket_core( + svr_sock, sock, keep_alive_max_count, keep_alive_timeout_sec, + [&](bool close_connection, bool &connection_closed) { + SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec); + return callback(strm, close_connection, connection_closed); + }); +} + +template +inline bool process_client_socket_ssl( + SSL *ssl, socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, time_t write_timeout_usec, + time_t max_timeout_msec, + std::chrono::time_point start_time, T callback) { + SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec, + write_timeout_sec, write_timeout_usec, max_timeout_msec, + start_time); + return callback(strm); +} + +// SSL socket stream implementation +inline SSLSocketStream::SSLSocketStream( + socket_t sock, SSL *ssl, time_t read_timeout_sec, time_t read_timeout_usec, + time_t write_timeout_sec, time_t write_timeout_usec, + time_t max_timeout_msec, + std::chrono::time_point start_time) + : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec), + read_timeout_usec_(read_timeout_usec), + write_timeout_sec_(write_timeout_sec), + write_timeout_usec_(write_timeout_usec), + max_timeout_msec_(max_timeout_msec), start_time_(start_time) { + SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY); +} + +inline SSLSocketStream::~SSLSocketStream() = default; + +inline bool SSLSocketStream::is_readable() const { + return SSL_pending(ssl_) > 0; +} + +inline bool SSLSocketStream::wait_readable() const { + if (max_timeout_msec_ <= 0) { + return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0; + } + + time_t read_timeout_sec; + time_t read_timeout_usec; + calc_actual_timeout(max_timeout_msec_, duration(), read_timeout_sec_, + read_timeout_usec_, read_timeout_sec, read_timeout_usec); + + return select_read(sock_, read_timeout_sec, read_timeout_usec) > 0; +} + +inline bool SSLSocketStream::wait_writable() const { + return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0 && + is_socket_alive(sock_) && !is_ssl_peer_could_be_closed(ssl_, sock_); +} + +inline ssize_t SSLSocketStream::read(char *ptr, size_t size) { + if (SSL_pending(ssl_) > 0) { + return SSL_read(ssl_, ptr, static_cast(size)); + } else if (wait_readable()) { + auto ret = SSL_read(ssl_, ptr, static_cast(size)); + if (ret < 0) { + auto err = SSL_get_error(ssl_, ret); + auto n = 1000; +#ifdef _WIN32 + while (--n >= 0 && (err == SSL_ERROR_WANT_READ || + (err == SSL_ERROR_SYSCALL && + WSAGetLastError() == WSAETIMEDOUT))) { +#else + while (--n >= 0 && err == SSL_ERROR_WANT_READ) { +#endif + if (SSL_pending(ssl_) > 0) { + return SSL_read(ssl_, ptr, static_cast(size)); + } else if (wait_readable()) { + std::this_thread::sleep_for(std::chrono::microseconds{10}); + ret = SSL_read(ssl_, ptr, static_cast(size)); + if (ret >= 0) { return ret; } + err = SSL_get_error(ssl_, ret); + } else { + return -1; + } + } + } + return ret; + } else { + return -1; + } +} + +inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) { + if (wait_writable()) { + auto handle_size = static_cast( + std::min(size, (std::numeric_limits::max)())); + + auto ret = SSL_write(ssl_, ptr, static_cast(handle_size)); + if (ret < 0) { + auto err = SSL_get_error(ssl_, ret); + auto n = 1000; +#ifdef _WIN32 + while (--n >= 0 && (err == SSL_ERROR_WANT_WRITE || + (err == SSL_ERROR_SYSCALL && + WSAGetLastError() == WSAETIMEDOUT))) { +#else + while (--n >= 0 && err == SSL_ERROR_WANT_WRITE) { +#endif + if (wait_writable()) { + std::this_thread::sleep_for(std::chrono::microseconds{10}); + ret = SSL_write(ssl_, ptr, static_cast(handle_size)); + if (ret >= 0) { return ret; } + err = SSL_get_error(ssl_, ret); + } else { + return -1; + } + } + } + return ret; + } + return -1; +} + +inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip, + int &port) const { + detail::get_remote_ip_and_port(sock_, ip, port); +} + +inline void SSLSocketStream::get_local_ip_and_port(std::string &ip, + int &port) const { + detail::get_local_ip_and_port(sock_, ip, port); +} + +inline socket_t SSLSocketStream::socket() const { return sock_; } + +inline time_t SSLSocketStream::duration() const { + return std::chrono::duration_cast( + std::chrono::steady_clock::now() - start_time_) + .count(); +} + +} // namespace detail + +// SSL HTTP server implementation +inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path, + const char *client_ca_cert_file_path, + const char *client_ca_cert_dir_path, + const char *private_key_password) { + ctx_ = SSL_CTX_new(TLS_server_method()); + + if (ctx_) { + SSL_CTX_set_options(ctx_, + SSL_OP_NO_COMPRESSION | + SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); + + SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); + + if (private_key_password != nullptr && (private_key_password[0] != '\0')) { + SSL_CTX_set_default_passwd_cb_userdata( + ctx_, + reinterpret_cast(const_cast(private_key_password))); + } + + if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 || + SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) != + 1 || + SSL_CTX_check_private_key(ctx_) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } else if (client_ca_cert_file_path || client_ca_cert_dir_path) { + SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path, + client_ca_cert_dir_path); + + SSL_CTX_set_verify( + ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); + } + } +} + +inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key, + X509_STORE *client_ca_cert_store) { + ctx_ = SSL_CTX_new(TLS_server_method()); + + if (ctx_) { + SSL_CTX_set_options(ctx_, + SSL_OP_NO_COMPRESSION | + SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); + + SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); + + if (SSL_CTX_use_certificate(ctx_, cert) != 1 || + SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } else if (client_ca_cert_store) { + SSL_CTX_set_cert_store(ctx_, client_ca_cert_store); + + SSL_CTX_set_verify( + ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr); + } + } +} + +inline SSLServer::SSLServer( + const std::function &setup_ssl_ctx_callback) { + ctx_ = SSL_CTX_new(TLS_method()); + if (ctx_) { + if (!setup_ssl_ctx_callback(*ctx_)) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + } +} + +inline SSLServer::~SSLServer() { + if (ctx_) { SSL_CTX_free(ctx_); } +} + +inline bool SSLServer::is_valid() const { return ctx_; } + +inline SSL_CTX *SSLServer::ssl_context() const { return ctx_; } + +inline void SSLServer::update_certs(X509 *cert, EVP_PKEY *private_key, + X509_STORE *client_ca_cert_store) { + + std::lock_guard guard(ctx_mutex_); + + SSL_CTX_use_certificate(ctx_, cert); + SSL_CTX_use_PrivateKey(ctx_, private_key); + + if (client_ca_cert_store != nullptr) { + SSL_CTX_set_cert_store(ctx_, client_ca_cert_store); + } +} + +inline bool SSLServer::process_and_close_socket(socket_t sock) { + auto ssl = detail::ssl_new( + sock, ctx_, ctx_mutex_, + [&](SSL *ssl2) { + return detail::ssl_connect_or_accept_nonblocking( + sock, ssl2, SSL_accept, read_timeout_sec_, read_timeout_usec_); + }, + [](SSL * /*ssl2*/) { return true; }); + + auto ret = false; + if (ssl) { + std::string remote_addr; + int remote_port = 0; + detail::get_remote_ip_and_port(sock, remote_addr, remote_port); + + std::string local_addr; + int local_port = 0; + detail::get_local_ip_and_port(sock, local_addr, local_port); + + ret = detail::process_server_socket_ssl( + svr_sock_, ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_, + read_timeout_sec_, read_timeout_usec_, write_timeout_sec_, + write_timeout_usec_, + [&](Stream &strm, bool close_connection, bool &connection_closed) { + return process_request(strm, remote_addr, remote_port, local_addr, + local_port, close_connection, + connection_closed, + [&](Request &req) { req.ssl = ssl; }); + }); + + // Shutdown gracefully if the result seemed successful, non-gracefully if + // the connection appeared to be closed. + const bool shutdown_gracefully = ret; + detail::ssl_delete(ctx_mutex_, ssl, sock, shutdown_gracefully); + } + + detail::shutdown_socket(sock); + detail::close_socket(sock); + return ret; +} + +// SSL HTTP client implementation +inline SSLClient::SSLClient(const std::string &host) + : SSLClient(host, 443, std::string(), std::string()) {} + +inline SSLClient::SSLClient(const std::string &host, int port) + : SSLClient(host, port, std::string(), std::string()) {} + +inline SSLClient::SSLClient(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path, + const std::string &private_key_password) + : ClientImpl(host, port, client_cert_path, client_key_path) { + ctx_ = SSL_CTX_new(TLS_client_method()); + + SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); + + detail::split(&host_[0], &host_[host_.size()], '.', + [&](const char *b, const char *e) { + host_components_.emplace_back(b, e); + }); + + if (!client_cert_path.empty() && !client_key_path.empty()) { + if (!private_key_password.empty()) { + SSL_CTX_set_default_passwd_cb_userdata( + ctx_, reinterpret_cast( + const_cast(private_key_password.c_str()))); + } + + if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(), + SSL_FILETYPE_PEM) != 1 || + SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(), + SSL_FILETYPE_PEM) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + } +} + +inline SSLClient::SSLClient(const std::string &host, int port, + X509 *client_cert, EVP_PKEY *client_key, + const std::string &private_key_password) + : ClientImpl(host, port) { + ctx_ = SSL_CTX_new(TLS_client_method()); + + detail::split(&host_[0], &host_[host_.size()], '.', + [&](const char *b, const char *e) { + host_components_.emplace_back(b, e); + }); + + if (client_cert != nullptr && client_key != nullptr) { + if (!private_key_password.empty()) { + SSL_CTX_set_default_passwd_cb_userdata( + ctx_, reinterpret_cast( + const_cast(private_key_password.c_str()))); + } + + if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 || + SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + } +} + +inline SSLClient::~SSLClient() { + if (ctx_) { SSL_CTX_free(ctx_); } + // Make sure to shut down SSL since shutdown_ssl will resolve to the + // base function rather than the derived function once we get to the + // base class destructor, and won't free the SSL (causing a leak). + shutdown_ssl_impl(socket_, true); +} + +inline bool SSLClient::is_valid() const { return ctx_; } + +inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) { + if (ca_cert_store) { + if (ctx_) { + if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) { + // Free memory allocated for old cert and use new store `ca_cert_store` + SSL_CTX_set_cert_store(ctx_, ca_cert_store); + } + } else { + X509_STORE_free(ca_cert_store); + } + } +} + +inline void SSLClient::load_ca_cert_store(const char *ca_cert, + std::size_t size) { + set_ca_cert_store(ClientImpl::create_ca_cert_store(ca_cert, size)); +} + +inline long SSLClient::get_openssl_verify_result() const { + return verify_result_; +} + +inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; } + +inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) { + return is_valid() && ClientImpl::create_and_connect_socket(socket, error); +} + +// Assumes that socket_mutex_ is locked and that there are no requests in flight +inline bool SSLClient::connect_with_proxy( + Socket &socket, + std::chrono::time_point start_time, + Response &res, bool &success, Error &error) { + success = true; + Response proxy_res; + if (!detail::process_client_socket( + socket.sock, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, + start_time, [&](Stream &strm) { + Request req2; + req2.method = "CONNECT"; + req2.path = host_and_port_; + if (max_timeout_msec_ > 0) { + req2.start_time_ = std::chrono::steady_clock::now(); + } + return process_request(strm, req2, proxy_res, false, error); + })) { + // Thread-safe to close everything because we are assuming there are no + // requests in flight + shutdown_ssl(socket, true); + shutdown_socket(socket); + close_socket(socket); + success = false; + return false; + } + + if (proxy_res.status == StatusCode::ProxyAuthenticationRequired_407) { + if (!proxy_digest_auth_username_.empty() && + !proxy_digest_auth_password_.empty()) { + std::map auth; + if (detail::parse_www_authenticate(proxy_res, auth, true)) { + proxy_res = Response(); + if (!detail::process_client_socket( + socket.sock, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, + start_time, [&](Stream &strm) { + Request req3; + req3.method = "CONNECT"; + req3.path = host_and_port_; + req3.headers.insert(detail::make_digest_authentication_header( + req3, auth, 1, detail::random_string(10), + proxy_digest_auth_username_, proxy_digest_auth_password_, + true)); + if (max_timeout_msec_ > 0) { + req3.start_time_ = std::chrono::steady_clock::now(); + } + return process_request(strm, req3, proxy_res, false, error); + })) { + // Thread-safe to close everything because we are assuming there are + // no requests in flight + shutdown_ssl(socket, true); + shutdown_socket(socket); + close_socket(socket); + success = false; + return false; + } + } + } + } + + // If status code is not 200, proxy request is failed. + // Set error to ProxyConnection and return proxy response + // as the response of the request + if (proxy_res.status != StatusCode::OK_200) { + error = Error::ProxyConnection; + res = std::move(proxy_res); + // Thread-safe to close everything because we are assuming there are + // no requests in flight + shutdown_ssl(socket, true); + shutdown_socket(socket); + close_socket(socket); + return false; + } + + return true; +} + +inline bool SSLClient::load_certs() { + auto ret = true; + + std::call_once(initialize_cert_, [&]() { + std::lock_guard guard(ctx_mutex_); + if (!ca_cert_file_path_.empty()) { + if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(), + nullptr)) { + ret = false; + } + } else if (!ca_cert_dir_path_.empty()) { + if (!SSL_CTX_load_verify_locations(ctx_, nullptr, + ca_cert_dir_path_.c_str())) { + ret = false; + } + } else { + auto loaded = false; +#ifdef _WIN32 + loaded = + detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_)); +#elif defined(CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN) && defined(__APPLE__) +#if TARGET_OS_OSX + loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_)); +#endif // TARGET_OS_OSX +#endif // _WIN32 + if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); } + } + }); + + return ret; +} + +inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) { + auto ssl = detail::ssl_new( + socket.sock, ctx_, ctx_mutex_, + [&](SSL *ssl2) { + if (server_certificate_verification_) { + if (!load_certs()) { + error = Error::SSLLoadingCerts; + return false; + } + SSL_set_verify(ssl2, SSL_VERIFY_NONE, nullptr); + } + + if (!detail::ssl_connect_or_accept_nonblocking( + socket.sock, ssl2, SSL_connect, connection_timeout_sec_, + connection_timeout_usec_)) { + error = Error::SSLConnection; + return false; + } + + if (server_certificate_verification_) { + auto verification_status = SSLVerifierResponse::NoDecisionMade; + + if (server_certificate_verifier_) { + verification_status = server_certificate_verifier_(ssl2); + } + + if (verification_status == SSLVerifierResponse::CertificateRejected) { + error = Error::SSLServerVerification; + return false; + } + + if (verification_status == SSLVerifierResponse::NoDecisionMade) { + verify_result_ = SSL_get_verify_result(ssl2); + + if (verify_result_ != X509_V_OK) { + error = Error::SSLServerVerification; + return false; + } + + auto server_cert = SSL_get1_peer_certificate(ssl2); + auto se = detail::scope_exit([&] { X509_free(server_cert); }); + + if (server_cert == nullptr) { + error = Error::SSLServerVerification; + return false; + } + + if (server_hostname_verification_) { + if (!verify_host(server_cert)) { + error = Error::SSLServerHostnameVerification; + return false; + } + } + } + } + + return true; + }, + [&](SSL *ssl2) { +#if defined(OPENSSL_IS_BORINGSSL) + SSL_set_tlsext_host_name(ssl2, host_.c_str()); +#else + // NOTE: Direct call instead of using the OpenSSL macro to suppress + // -Wold-style-cast warning + SSL_ctrl(ssl2, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, + static_cast(const_cast(host_.c_str()))); +#endif + return true; + }); + + if (ssl) { + socket.ssl = ssl; + return true; + } + + shutdown_socket(socket); + close_socket(socket); + return false; +} + +inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) { + shutdown_ssl_impl(socket, shutdown_gracefully); +} + +inline void SSLClient::shutdown_ssl_impl(Socket &socket, + bool shutdown_gracefully) { + if (socket.sock == INVALID_SOCKET) { + assert(socket.ssl == nullptr); + return; + } + if (socket.ssl) { + detail::ssl_delete(ctx_mutex_, socket.ssl, socket.sock, + shutdown_gracefully); + socket.ssl = nullptr; + } + assert(socket.ssl == nullptr); +} + +inline bool SSLClient::process_socket( + const Socket &socket, + std::chrono::time_point start_time, + std::function callback) { + assert(socket.ssl); + return detail::process_client_socket_ssl( + socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_, + write_timeout_sec_, write_timeout_usec_, max_timeout_msec_, start_time, + std::move(callback)); +} + +inline bool SSLClient::is_ssl() const { return true; } + +inline bool SSLClient::verify_host(X509 *server_cert) const { + /* Quote from RFC2818 section 3.1 "Server Identity" + + If a subjectAltName extension of type dNSName is present, that MUST + be used as the identity. Otherwise, the (most specific) Common Name + field in the Subject field of the certificate MUST be used. Although + the use of the Common Name is existing practice, it is deprecated and + Certification Authorities are encouraged to use the dNSName instead. + + Matching is performed using the matching rules specified by + [RFC2459]. If more than one identity of a given type is present in + the certificate (e.g., more than one dNSName name, a match in any one + of the set is considered acceptable.) Names may contain the wildcard + character * which is considered to match any single domain name + component or component fragment. E.g., *.a.com matches foo.a.com but + not bar.foo.a.com. f*.com matches foo.com but not bar.com. + + In some cases, the URI is specified as an IP address rather than a + hostname. In this case, the iPAddress subjectAltName must be present + in the certificate and must exactly match the IP in the URI. + + */ + return verify_host_with_subject_alt_name(server_cert) || + verify_host_with_common_name(server_cert); +} + +inline bool +SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const { + auto ret = false; + + auto type = GEN_DNS; + + struct in6_addr addr6 = {}; + struct in_addr addr = {}; + size_t addr_len = 0; + +#ifndef __MINGW32__ + if (inet_pton(AF_INET6, host_.c_str(), &addr6)) { + type = GEN_IPADD; + addr_len = sizeof(struct in6_addr); + } else if (inet_pton(AF_INET, host_.c_str(), &addr)) { + type = GEN_IPADD; + addr_len = sizeof(struct in_addr); + } +#endif + + auto alt_names = static_cast( + X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr)); + + if (alt_names) { + auto dsn_matched = false; + auto ip_matched = false; + + auto count = sk_GENERAL_NAME_num(alt_names); + + for (decltype(count) i = 0; i < count && !dsn_matched; i++) { + auto val = sk_GENERAL_NAME_value(alt_names, i); + if (val->type == type) { + auto name = + reinterpret_cast(ASN1_STRING_get0_data(val->d.ia5)); + auto name_len = static_cast(ASN1_STRING_length(val->d.ia5)); + + switch (type) { + case GEN_DNS: dsn_matched = check_host_name(name, name_len); break; + + case GEN_IPADD: + if (!memcmp(&addr6, name, addr_len) || + !memcmp(&addr, name, addr_len)) { + ip_matched = true; + } + break; + } + } + } + + if (dsn_matched || ip_matched) { ret = true; } + } + + GENERAL_NAMES_free(const_cast( + reinterpret_cast(alt_names))); + return ret; +} + +inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const { + const auto subject_name = X509_get_subject_name(server_cert); + + if (subject_name != nullptr) { + char name[BUFSIZ]; + auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName, + name, sizeof(name)); + + if (name_len != -1) { + return check_host_name(name, static_cast(name_len)); + } + } + + return false; +} + +inline bool SSLClient::check_host_name(const char *pattern, + size_t pattern_len) const { + if (host_.size() == pattern_len && host_ == pattern) { return true; } + + // Wildcard match + // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484 + std::vector pattern_components; + detail::split(&pattern[0], &pattern[pattern_len], '.', + [&](const char *b, const char *e) { + pattern_components.emplace_back(b, e); + }); + + if (host_components_.size() != pattern_components.size()) { return false; } + + auto itr = pattern_components.begin(); + for (const auto &h : host_components_) { + auto &p = *itr; + if (p != h && p != "*") { + auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' && + !p.compare(0, p.size() - 1, h)); + if (!partial_match) { return false; } + } + ++itr; + } + + return true; +} +#endif + +// Universal client implementation +inline Client::Client(const std::string &scheme_host_port) + : Client(scheme_host_port, std::string(), std::string()) {} + +inline Client::Client(const std::string &scheme_host_port, + const std::string &client_cert_path, + const std::string &client_key_path) { + const static std::regex re( + R"((?:([a-z]+):\/\/)?(?:\[([a-fA-F\d:]+)\]|([^:/?#]+))(?::(\d+))?)"); + + std::smatch m; + if (std::regex_match(scheme_host_port, m, re)) { + auto scheme = m[1].str(); + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if (!scheme.empty() && (scheme != "http" && scheme != "https")) { +#else + if (!scheme.empty() && scheme != "http") { +#endif +#ifndef CPPHTTPLIB_NO_EXCEPTIONS + std::string msg = "'" + scheme + "' scheme is not supported."; + throw std::invalid_argument(msg); +#endif + return; + } + + auto is_ssl = scheme == "https"; + + auto host = m[2].str(); + if (host.empty()) { host = m[3].str(); } + + auto port_str = m[4].str(); + auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80); + + if (is_ssl) { +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + cli_ = detail::make_unique(host, port, client_cert_path, + client_key_path); + is_ssl_ = is_ssl; +#endif + } else { + cli_ = detail::make_unique(host, port, client_cert_path, + client_key_path); + } + } else { + // NOTE: Update TEST(UniversalClientImplTest, Ipv6LiteralAddress) + // if port param below changes. + cli_ = detail::make_unique(scheme_host_port, 80, + client_cert_path, client_key_path); + } +} // namespace detail + +inline Client::Client(const std::string &host, int port) + : cli_(detail::make_unique(host, port)) {} + +inline Client::Client(const std::string &host, int port, + const std::string &client_cert_path, + const std::string &client_key_path) + : cli_(detail::make_unique(host, port, client_cert_path, + client_key_path)) {} + +inline Client::~Client() = default; + +inline bool Client::is_valid() const { + return cli_ != nullptr && cli_->is_valid(); +} + +inline Result Client::Get(const std::string &path) { return cli_->Get(path); } +inline Result Client::Get(const std::string &path, const Headers &headers) { + return cli_->Get(path, headers); +} +inline Result Client::Get(const std::string &path, Progress progress) { + return cli_->Get(path, std::move(progress)); +} +inline Result Client::Get(const std::string &path, const Headers &headers, + Progress progress) { + return cli_->Get(path, headers, std::move(progress)); +} +inline Result Client::Get(const std::string &path, + ContentReceiver content_receiver) { + return cli_->Get(path, std::move(content_receiver)); +} +inline Result Client::Get(const std::string &path, const Headers &headers, + ContentReceiver content_receiver) { + return cli_->Get(path, headers, std::move(content_receiver)); +} +inline Result Client::Get(const std::string &path, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, std::move(content_receiver), std::move(progress)); +} +inline Result Client::Get(const std::string &path, const Headers &headers, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, headers, std::move(content_receiver), + std::move(progress)); +} +inline Result Client::Get(const std::string &path, + ResponseHandler response_handler, + ContentReceiver content_receiver) { + return cli_->Get(path, std::move(response_handler), + std::move(content_receiver)); +} +inline Result Client::Get(const std::string &path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver) { + return cli_->Get(path, headers, std::move(response_handler), + std::move(content_receiver)); +} +inline Result Client::Get(const std::string &path, + ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, std::move(response_handler), + std::move(content_receiver), std::move(progress)); +} +inline Result Client::Get(const std::string &path, const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, headers, std::move(response_handler), + std::move(content_receiver), std::move(progress)); +} +inline Result Client::Get(const std::string &path, const Params ¶ms, + const Headers &headers, Progress progress) { + return cli_->Get(path, params, headers, std::move(progress)); +} +inline Result Client::Get(const std::string &path, const Params ¶ms, + const Headers &headers, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, params, headers, std::move(content_receiver), + std::move(progress)); +} +inline Result Client::Get(const std::string &path, const Params ¶ms, + const Headers &headers, + ResponseHandler response_handler, + ContentReceiver content_receiver, Progress progress) { + return cli_->Get(path, params, headers, std::move(response_handler), + std::move(content_receiver), std::move(progress)); +} + +inline Result Client::Head(const std::string &path) { return cli_->Head(path); } +inline Result Client::Head(const std::string &path, const Headers &headers) { + return cli_->Head(path, headers); +} + +inline Result Client::Post(const std::string &path) { return cli_->Post(path); } +inline Result Client::Post(const std::string &path, const Headers &headers) { + return cli_->Post(path, headers); +} +inline Result Client::Post(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type) { + return cli_->Post(path, body, content_length, content_type); +} +inline Result Client::Post(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type) { + return cli_->Post(path, headers, body, content_length, content_type); +} +inline Result Client::Post(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, Progress progress) { + return cli_->Post(path, headers, body, content_length, content_type, + progress); +} +inline Result Client::Post(const std::string &path, const std::string &body, + const std::string &content_type) { + return cli_->Post(path, body, content_type); +} +inline Result Client::Post(const std::string &path, const std::string &body, + const std::string &content_type, Progress progress) { + return cli_->Post(path, body, content_type, progress); +} +inline Result Client::Post(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type) { + return cli_->Post(path, headers, body, content_type); +} +inline Result Client::Post(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type, Progress progress) { + return cli_->Post(path, headers, body, content_type, progress); +} +inline Result Client::Post(const std::string &path, size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return cli_->Post(path, content_length, std::move(content_provider), + content_type); +} +inline Result Client::Post(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return cli_->Post(path, std::move(content_provider), content_type); +} +inline Result Client::Post(const std::string &path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return cli_->Post(path, headers, content_length, std::move(content_provider), + content_type); +} +inline Result Client::Post(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return cli_->Post(path, headers, std::move(content_provider), content_type); +} +inline Result Client::Post(const std::string &path, const Params ¶ms) { + return cli_->Post(path, params); +} +inline Result Client::Post(const std::string &path, const Headers &headers, + const Params ¶ms) { + return cli_->Post(path, headers, params); +} +inline Result Client::Post(const std::string &path, const Headers &headers, + const Params ¶ms, Progress progress) { + return cli_->Post(path, headers, params, progress); +} +inline Result Client::Post(const std::string &path, + const MultipartFormDataItems &items) { + return cli_->Post(path, items); +} +inline Result Client::Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items) { + return cli_->Post(path, headers, items); +} +inline Result Client::Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const std::string &boundary) { + return cli_->Post(path, headers, items, boundary); +} +inline Result +Client::Post(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items) { + return cli_->Post(path, headers, items, provider_items); +} +inline Result Client::Put(const std::string &path) { return cli_->Put(path); } +inline Result Client::Put(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type) { + return cli_->Put(path, body, content_length, content_type); +} +inline Result Client::Put(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type) { + return cli_->Put(path, headers, body, content_length, content_type); +} +inline Result Client::Put(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, Progress progress) { + return cli_->Put(path, headers, body, content_length, content_type, progress); +} +inline Result Client::Put(const std::string &path, const std::string &body, + const std::string &content_type) { + return cli_->Put(path, body, content_type); +} +inline Result Client::Put(const std::string &path, const std::string &body, + const std::string &content_type, Progress progress) { + return cli_->Put(path, body, content_type, progress); +} +inline Result Client::Put(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type) { + return cli_->Put(path, headers, body, content_type); +} +inline Result Client::Put(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type, Progress progress) { + return cli_->Put(path, headers, body, content_type, progress); +} +inline Result Client::Put(const std::string &path, size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return cli_->Put(path, content_length, std::move(content_provider), + content_type); +} +inline Result Client::Put(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return cli_->Put(path, std::move(content_provider), content_type); +} +inline Result Client::Put(const std::string &path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return cli_->Put(path, headers, content_length, std::move(content_provider), + content_type); +} +inline Result Client::Put(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return cli_->Put(path, headers, std::move(content_provider), content_type); +} +inline Result Client::Put(const std::string &path, const Params ¶ms) { + return cli_->Put(path, params); +} +inline Result Client::Put(const std::string &path, const Headers &headers, + const Params ¶ms) { + return cli_->Put(path, headers, params); +} +inline Result Client::Put(const std::string &path, const Headers &headers, + const Params ¶ms, Progress progress) { + return cli_->Put(path, headers, params, progress); +} +inline Result Client::Put(const std::string &path, + const MultipartFormDataItems &items) { + return cli_->Put(path, items); +} +inline Result Client::Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items) { + return cli_->Put(path, headers, items); +} +inline Result Client::Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const std::string &boundary) { + return cli_->Put(path, headers, items, boundary); +} +inline Result +Client::Put(const std::string &path, const Headers &headers, + const MultipartFormDataItems &items, + const MultipartFormDataProviderItems &provider_items) { + return cli_->Put(path, headers, items, provider_items); +} +inline Result Client::Patch(const std::string &path) { + return cli_->Patch(path); +} +inline Result Client::Patch(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type) { + return cli_->Patch(path, body, content_length, content_type); +} +inline Result Client::Patch(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type, + Progress progress) { + return cli_->Patch(path, body, content_length, content_type, progress); +} +inline Result Client::Patch(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type) { + return cli_->Patch(path, headers, body, content_length, content_type); +} +inline Result Client::Patch(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, + Progress progress) { + return cli_->Patch(path, headers, body, content_length, content_type, + progress); +} +inline Result Client::Patch(const std::string &path, const std::string &body, + const std::string &content_type) { + return cli_->Patch(path, body, content_type); +} +inline Result Client::Patch(const std::string &path, const std::string &body, + const std::string &content_type, + Progress progress) { + return cli_->Patch(path, body, content_type, progress); +} +inline Result Client::Patch(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type) { + return cli_->Patch(path, headers, body, content_type); +} +inline Result Client::Patch(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type, + Progress progress) { + return cli_->Patch(path, headers, body, content_type, progress); +} +inline Result Client::Patch(const std::string &path, size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return cli_->Patch(path, content_length, std::move(content_provider), + content_type); +} +inline Result Client::Patch(const std::string &path, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return cli_->Patch(path, std::move(content_provider), content_type); +} +inline Result Client::Patch(const std::string &path, const Headers &headers, + size_t content_length, + ContentProvider content_provider, + const std::string &content_type) { + return cli_->Patch(path, headers, content_length, std::move(content_provider), + content_type); +} +inline Result Client::Patch(const std::string &path, const Headers &headers, + ContentProviderWithoutLength content_provider, + const std::string &content_type) { + return cli_->Patch(path, headers, std::move(content_provider), content_type); +} +inline Result Client::Delete(const std::string &path) { + return cli_->Delete(path); +} +inline Result Client::Delete(const std::string &path, const Headers &headers) { + return cli_->Delete(path, headers); +} +inline Result Client::Delete(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type) { + return cli_->Delete(path, body, content_length, content_type); +} +inline Result Client::Delete(const std::string &path, const char *body, + size_t content_length, + const std::string &content_type, + Progress progress) { + return cli_->Delete(path, body, content_length, content_type, progress); +} +inline Result Client::Delete(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type) { + return cli_->Delete(path, headers, body, content_length, content_type); +} +inline Result Client::Delete(const std::string &path, const Headers &headers, + const char *body, size_t content_length, + const std::string &content_type, + Progress progress) { + return cli_->Delete(path, headers, body, content_length, content_type, + progress); +} +inline Result Client::Delete(const std::string &path, const std::string &body, + const std::string &content_type) { + return cli_->Delete(path, body, content_type); +} +inline Result Client::Delete(const std::string &path, const std::string &body, + const std::string &content_type, + Progress progress) { + return cli_->Delete(path, body, content_type, progress); +} +inline Result Client::Delete(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type) { + return cli_->Delete(path, headers, body, content_type); +} +inline Result Client::Delete(const std::string &path, const Headers &headers, + const std::string &body, + const std::string &content_type, + Progress progress) { + return cli_->Delete(path, headers, body, content_type, progress); +} +inline Result Client::Options(const std::string &path) { + return cli_->Options(path); +} +inline Result Client::Options(const std::string &path, const Headers &headers) { + return cli_->Options(path, headers); +} + +inline bool Client::send(Request &req, Response &res, Error &error) { + return cli_->send(req, res, error); +} + +inline Result Client::send(const Request &req) { return cli_->send(req); } + +inline void Client::stop() { cli_->stop(); } + +inline std::string Client::host() const { return cli_->host(); } + +inline int Client::port() const { return cli_->port(); } + +inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); } + +inline socket_t Client::socket() const { return cli_->socket(); } + +inline void +Client::set_hostname_addr_map(std::map addr_map) { + cli_->set_hostname_addr_map(std::move(addr_map)); +} + +inline void Client::set_default_headers(Headers headers) { + cli_->set_default_headers(std::move(headers)); +} + +inline void Client::set_header_writer( + std::function const &writer) { + cli_->set_header_writer(writer); +} + +inline void Client::set_address_family(int family) { + cli_->set_address_family(family); +} + +inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); } + +inline void Client::set_socket_options(SocketOptions socket_options) { + cli_->set_socket_options(std::move(socket_options)); +} + +inline void Client::set_connection_timeout(time_t sec, time_t usec) { + cli_->set_connection_timeout(sec, usec); +} + +inline void Client::set_read_timeout(time_t sec, time_t usec) { + cli_->set_read_timeout(sec, usec); +} + +inline void Client::set_write_timeout(time_t sec, time_t usec) { + cli_->set_write_timeout(sec, usec); +} + +inline void Client::set_basic_auth(const std::string &username, + const std::string &password) { + cli_->set_basic_auth(username, password); +} +inline void Client::set_bearer_token_auth(const std::string &token) { + cli_->set_bearer_token_auth(token); +} +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void Client::set_digest_auth(const std::string &username, + const std::string &password) { + cli_->set_digest_auth(username, password); +} +#endif + +inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); } +inline void Client::set_follow_location(bool on) { + cli_->set_follow_location(on); +} + +inline void Client::set_url_encode(bool on) { cli_->set_url_encode(on); } + +inline void Client::set_compress(bool on) { cli_->set_compress(on); } + +inline void Client::set_decompress(bool on) { cli_->set_decompress(on); } + +inline void Client::set_interface(const std::string &intf) { + cli_->set_interface(intf); +} + +inline void Client::set_proxy(const std::string &host, int port) { + cli_->set_proxy(host, port); +} +inline void Client::set_proxy_basic_auth(const std::string &username, + const std::string &password) { + cli_->set_proxy_basic_auth(username, password); +} +inline void Client::set_proxy_bearer_token_auth(const std::string &token) { + cli_->set_proxy_bearer_token_auth(token); +} +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void Client::set_proxy_digest_auth(const std::string &username, + const std::string &password) { + cli_->set_proxy_digest_auth(username, password); +} +#endif + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void Client::enable_server_certificate_verification(bool enabled) { + cli_->enable_server_certificate_verification(enabled); +} + +inline void Client::enable_server_hostname_verification(bool enabled) { + cli_->enable_server_hostname_verification(enabled); +} + +inline void Client::set_server_certificate_verifier( + std::function verifier) { + cli_->set_server_certificate_verifier(verifier); +} +#endif + +inline void Client::set_logger(Logger logger) { + cli_->set_logger(std::move(logger)); +} + +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT +inline void Client::set_ca_cert_path(const std::string &ca_cert_file_path, + const std::string &ca_cert_dir_path) { + cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path); +} + +inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) { + if (is_ssl_) { + static_cast(*cli_).set_ca_cert_store(ca_cert_store); + } else { + cli_->set_ca_cert_store(ca_cert_store); + } +} + +inline void Client::load_ca_cert_store(const char *ca_cert, std::size_t size) { + set_ca_cert_store(cli_->create_ca_cert_store(ca_cert, size)); +} + +inline long Client::get_openssl_verify_result() const { + if (is_ssl_) { + return static_cast(*cli_).get_openssl_verify_result(); + } + return -1; // NOTE: -1 doesn't match any of X509_V_ERR_??? +} + +inline SSL_CTX *Client::ssl_context() const { + if (is_ssl_) { return static_cast(*cli_).ssl_context(); } + return nullptr; +} +#endif + +// ---------------------------------------------------------------------------- + +} // namespace httplib + +#endif // CPPHTTPLIB_HTTPLIB_H diff --git a/common/src/IniManager.cpp b/common/src/IniManager.cpp index fdda510..da6774d 100644 --- a/common/src/IniManager.cpp +++ b/common/src/IniManager.cpp @@ -19,26 +19,4 @@ int IniManager::handler(void *user, const char *section, const char *name, const std::string key = std::string(section) + "." + name; (*config)[key] = value; return 1; -} - -bool IniManager::CreateConfigIfMissing(const std::string& path) // STATIC -{ - writeConfig(path); - - if (std::filesystem::exists(path)) - return true; - - return false; -} - -void IniManager::writeConfig(const std::string& path) // STATIC -{ - if (std::filesystem::exists(path)) - return; - - std::ofstream out(path); - out << "[General]\n"; - out << "username = Player1\n"; - out << "server_ip = 127.0.0.1\n"; - out << "server_port = 12345\n"; } \ No newline at end of file diff --git a/common/src/IniManager.h b/common/src/IniManager.h index 936b6be..f4208e4 100644 --- a/common/src/IniManager.h +++ b/common/src/IniManager.h @@ -14,11 +14,6 @@ */ class IniManager { public: - /** - * @brief Default filename for the client configuration file. - */ - static constexpr char * CLIENT_CONFIG_FILE = "gpr_config.ini"; - /** * @brief Retrieves a specific configuration item from an INI file. * @@ -27,25 +22,6 @@ class IniManager { * @return The corresponding value as a string, or an empty string if not found. */ static std::string GetItem(const char * file, std::string item); - - /** - * @brief Creates a default Config if it is missing. - * @return Returns a false if Config could not be created. - */ - static bool CreateConfigIfMissing(const std::string& path); - - /** - * @class Item - * @brief Contains predefined keys for accessing configuration values. - */ - class Item - { - public: - static constexpr char * GENERAL_USERNAME = "General.username"; - static constexpr char * GENERAL_SERVER_IP = "General.server_ip"; - static constexpr char * GENERAL_SERVER_PORT = "General.server_port"; - }; - private: /** * @brief Internal handler used as a callback for the INIH parser. @@ -57,11 +33,4 @@ class IniManager { * @return 1 on success, 0 on failure. */ static int handler(void* user, const char* section, const char* name, const char* value); - - /** - * @brief Writes a default configuration to the specified file if it does not already exist. - * - * @param path Path to the configuration file. - */ - static void writeConfig(const std::string& path); }; \ No newline at end of file diff --git a/server/src/CommonStructures.h b/server/src/CommonStructures.h index 2c0d9dc..87fe757 100644 --- a/server/src/CommonStructures.h +++ b/server/src/CommonStructures.h @@ -4,6 +4,17 @@ using boost::asio::ip::udp; namespace CommonStructures { + + struct Ini { + std::string serverIp = "127.0.0.1"; + int serverPort = 12345; + + bool monitoringActive = false; + std::string monitoringIp = "127.0.0.1"; + int monitoringPort = 18080; + }; + + struct PlayerEquipment { std::string meleeWeaponInstanceName; std::string rangedWeaponInstanceName; diff --git a/server/src/IniData.h b/server/src/IniData.h new file mode 100644 index 0000000..a3015ec --- /dev/null +++ b/server/src/IniData.h @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +#include + +class IniData { + public: + static constexpr char * CONFIG_FILE = "config.ini"; + + class Item + { + public: + static constexpr char * GENERAL_SERVER_IP = "General.server_ip"; + static constexpr char * GENERAL_SERVER_PORT = "General.server_port"; + + static constexpr char * MONITORING_ACTIVE = "Monitoring.active"; + static constexpr char * MONITORING_IP = "Monitoring.server_ip"; + static constexpr char * MONITORING_PORT = "Monitoring.server_port"; + }; + + static bool CreateConfigIfMissing(const std::string& path) // STATIC + { + writeConfig(path); + + if (std::filesystem::exists(path)) + return true; + + return false; + } + + private: + static void writeConfig(const std::string& path) + { + if (std::filesystem::exists(path)) + return; + + std::ofstream out(path); + out << "[General]\n"; + out << "server_ip = 127.0.0.1\n"; + out << "server_port = 12345\n\n"; + + out << "[Monitoring]\n"; + out << "active = false\n"; + out << "server_ip = 127.0.0.1\n"; + out << "server_port = 18080\n"; + } + +}; \ No newline at end of file diff --git a/server/src/Monitoring/MonitoringClient.cpp b/server/src/Monitoring/MonitoringClient.cpp index 6ae5cfe..fcfaba7 100644 --- a/server/src/Monitoring/MonitoringClient.cpp +++ b/server/src/Monitoring/MonitoringClient.cpp @@ -1,10 +1,31 @@ #include "MonitoringClient.h" -MonitoringClient::MonitoringClient(AsyncUnorderedMap *clients) : pClients(clients) +MonitoringClient::MonitoringClient(std::string ip, int port, AsyncUnorderedMap *clients, bool &serverRunning) + : ip(ip), port(port), pClients(clients), pServerRunning(&serverRunning) { - + startingMonitoringClient(); } void MonitoringClient::startingMonitoringClient(){ - + httplib::Client cli(this->ip, this->port); + + while(*pServerRunning){ + std::string status= "online"; + int count = this->pClients->getUnorderedMap()->size(); + + std::string body = + "{" + "\"status\": \"" + status + "\", " + "\"playerCount\": " + std::to_string(count) + + "}"; + + auto put_res = cli.Put("/status", body, "application/json"); + if (put_res && put_res->status == 200) { + //std::cout << "Status updated successfully\n"; + } else { + std::cerr << "PUT failed\n"; + } + + std::this_thread::sleep_for(std::chrono::seconds(5)); + } } \ No newline at end of file diff --git a/server/src/Monitoring/MonitoringClient.h b/server/src/Monitoring/MonitoringClient.h index 0bf08f8..6fda776 100644 --- a/server/src/Monitoring/MonitoringClient.h +++ b/server/src/Monitoring/MonitoringClient.h @@ -2,13 +2,20 @@ #include "../CommonStructures.h" #include "../../../common/src/Async/AsyncUnorderedMap.h" +#include "../../../common/lib/cpp-httplib/httplib.h" + +//TODO: Add .ini file for IP:Port and ask if monitoring is active + class MonitoringClient { public: - MonitoringClient(AsyncUnorderedMap *clients); - + MonitoringClient(std::string ip, int port, AsyncUnorderedMap *clients, bool &serverRunning); + MonitoringClient(); + void startingMonitoringClient(); private: AsyncUnorderedMap *pClients; - - void startingMonitoringClient(); + bool *pServerRunning; + + std::string ip = "127.0.0.1"; + int port = 18080; }; \ No newline at end of file diff --git a/server/src/ServerManager.cpp b/server/src/ServerManager.cpp index 95e25ae..ed89d22 100644 --- a/server/src/ServerManager.cpp +++ b/server/src/ServerManager.cpp @@ -1,17 +1,33 @@ #include "ServerManager.h" #include +#include +#include "IniData.h" -ServerManager::ServerManager(boost::asio::io_context &io_context, boost::asio::io_context &processing_context) : socket(io_context, udp::endpoint(udp::v4(), 12345)){ +#include +using boost::asio::ip::address; + +ServerManager::ServerManager(boost::asio::io_context &io_context, boost::asio::io_context &processing_context, CommonStructures::Ini config) + : configData(config), socket(io_context, udp::endpoint(boost::asio::ip::make_address(config.serverIp), config.serverPort)) { this->processing_context = &processing_context; - std::cout << "UDP-Server started on Port 12345..." << std::endl; + std::cout << "UDP-Server started on "<< configData.serverIp << ":" << std::to_string(configData.serverPort) << "..." << std::endl; serverRunning = true; messageHandler = new MessageHandler(clients, socket); start_receive(); - - monitor = std::make_unique(&clients); + // Task with Heartbeat + boost::asio::post(io_context, [this]() { + watchingHeartbeat(); + }); + + // If activated then sending server status to rest-server + if(configData.monitoringActive) { + boost::asio::post(io_context, [&]() { + std::cout << "Monitoring Client connected to " << configData.monitoringIp << ":" << std::to_string(configData.monitoringPort) <<"..."<< std::endl; + monitor = std::make_unique(configData.monitoringIp, configData.monitoringPort, &clients, serverRunning); + }); + } } void ServerManager::start_receive() diff --git a/server/src/ServerManager.h b/server/src/ServerManager.h index 961f71e..0820e57 100644 --- a/server/src/ServerManager.h +++ b/server/src/ServerManager.h @@ -10,13 +10,13 @@ #include "Monitoring/MonitoringClient.h" #include "../../common/src/Async/AsyncUnorderedMap.h" - +#include "../../common/src/IniManager.h" using boost::asio::ip::udp; class ServerManager { public: - ServerManager(boost::asio::io_context &io_context, boost::asio::io_context &processing_context); + ServerManager(boost::asio::io_context &io_context, boost::asio::io_context &processing_context, CommonStructures::Ini configData); void watchingHeartbeat(); private: udp::socket socket; @@ -28,5 +28,7 @@ class ServerManager { MessageHandler *messageHandler; void start_receive(); + CommonStructures::Ini configData; std::unique_ptr monitor; + }; \ No newline at end of file diff --git a/server/src/main.cpp b/server/src/main.cpp index 8243986..a6a9ba8 100644 --- a/server/src/main.cpp +++ b/server/src/main.cpp @@ -5,21 +5,56 @@ #include #include "ServerManager.h" +#include "IniData.h" #include "MessageHandler.h" //#include "../../common/src/IniManager.h" using boost::asio::ip::udp; + +std::string ascii = R"( + ____ _ _ _ ____ _ + | _ \ __ _ _ __ __ _| | | ___| | | _ \ ___ __ _| |_ __ ___ ___ + | |_) / _` | '__/ _` | | |/ _ \ | | |_) / _ \/ _` | | '_ ` _ \/ __| + | __/ (_| | | | (_| | | | __/ | | _ < __/ (_| | | | | | | \__ \ + |_| \__,_|_| \__,_|_|_|\___|_| |_| \_\___|\__,_|_|_| |_| |_|___/ +)"; + + +CommonStructures::Ini getConfigData() { + CommonStructures::Ini ret; + // #### LOADIN INI #### + IniManager manager; + if(!IniData::CreateConfigIfMissing(IniData::CONFIG_FILE)) + return ret; + else + std::cout << "-- Config loaded --" << "\n"; + + ret.serverIp = manager.GetItem(IniData::CONFIG_FILE, IniData::Item::GENERAL_SERVER_IP); + ret.serverPort = std::stoi(manager.GetItem(IniData::CONFIG_FILE, IniData::Item::GENERAL_SERVER_PORT)); + + std::string active = manager.GetItem(IniData::CONFIG_FILE, IniData::Item::MONITORING_ACTIVE); + if(active == "true") + ret.monitoringActive = true; + ret.monitoringIp = manager.GetItem(IniData::CONFIG_FILE, IniData::Item::MONITORING_IP); + ret.monitoringPort = std::stoi(manager.GetItem(IniData::CONFIG_FILE, IniData::Item::MONITORING_PORT)); + + return ret; +} + int main() { + std::cout << ascii << "\n\n"; try { + CommonStructures::Ini configData = getConfigData(); + boost::asio::io_context io_context; boost::asio::io_context processing_context; boost::asio::executor_work_guard work_guard(processing_context.get_executor()); - ServerManager serverManager(io_context, processing_context); + ServerManager serverManager(io_context, processing_context, configData); const size_t thread_count = std::max(1u, std::thread::hardware_concurrency() / 2); std::cout << "Using " << thread_count << " network threads.\n"; @@ -38,7 +73,7 @@ int main() threads.emplace_back([&processing_context]() { processing_context.run(); }); } - serverManager.watchingHeartbeat(); + //serverManager.watchingHeartbeat(); // waiting for the end of all threads for (auto &thread : threads) diff --git a/src/Models/IniData.h b/src/Models/IniData.h new file mode 100644 index 0000000..cfbc521 --- /dev/null +++ b/src/Models/IniData.h @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +#include + +class IniData { + public: + /** + * @brief Default filename for the client configuration file. + */ + static constexpr char * CLIENT_CONFIG_FILE = "gpr_config.ini"; + + /** + * @class Item + * @brief Contains predefined keys for accessing configuration values. + */ + class Item + { + public: + static constexpr char * GENERAL_USERNAME = "General.username"; + static constexpr char * GENERAL_SERVER_IP = "General.server_ip"; + static constexpr char * GENERAL_SERVER_PORT = "General.server_port"; + }; + + static bool CreateConfigIfMissing(const std::string& path) // STATIC + { + writeConfig(path); + + if (std::filesystem::exists(path)) + return true; + + return false; + } + + private: + static void writeConfig(const std::string& path) + { + if (std::filesystem::exists(path)) + return; + + std::ofstream out(path); + out << "[General]\n"; + out << "username = Player\n"; + out << "server_ip = 127.0.0.1\n"; + out << "server_port = 12345\n"; + } + +}; \ No newline at end of file diff --git a/src/dllmain.cpp b/src/dllmain.cpp index 97b1861..fef4542 100644 --- a/src/dllmain.cpp +++ b/src/dllmain.cpp @@ -13,7 +13,7 @@ #include "Logic/sMain.h" #include "Network/DataChangeNotifier.h" #include "../common/src/IniManager.h" - +#include "Models/IniData.h" // Globals HINSTANCE dll_handle; @@ -156,12 +156,12 @@ DWORD WINAPI MainThread() SetupConsole(); // ######### INI STUFF ######### - if(!IniManager::CreateConfigIfMissing(IniManager::CLIENT_CONFIG_FILE)) + if(!IniData::CreateConfigIfMissing(IniData::CLIENT_CONFIG_FILE)) return -1; - std::string username = IniManager::GetItem(IniManager::CLIENT_CONFIG_FILE, IniManager::Item::GENERAL_USERNAME); - std::string serverIp = IniManager::GetItem(IniManager::CLIENT_CONFIG_FILE, IniManager::Item::GENERAL_SERVER_IP); - std::string serverPort = IniManager::GetItem(IniManager::CLIENT_CONFIG_FILE, IniManager::Item::GENERAL_SERVER_PORT); + std::string username = IniManager::GetItem(IniData::CLIENT_CONFIG_FILE, IniData::Item::GENERAL_USERNAME); + std::string serverIp = IniManager::GetItem(IniData::CLIENT_CONFIG_FILE, IniData::Item::GENERAL_SERVER_IP); + std::string serverPort = IniManager::GetItem(IniData::CLIENT_CONFIG_FILE, IniData::Item::GENERAL_SERVER_PORT); // ########################### std::cout << "Starting MAIN...\n" From 809e1519ea733f698728fd5cc53632dae830253e Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Sat, 21 Jun 2025 14:06:06 +0200 Subject: [PATCH 06/11] fixed config stuff --- MonitoringServer/src/IniData.h | 29 +++++++++--- MonitoringServer/src/main.cpp | 31 ++++++------- server/src/CommonStructures.h | 10 ----- server/src/IniData.h | 51 +++++++++++++++++----- server/src/Monitoring/MonitoringClient.cpp | 15 +++++-- server/src/Monitoring/MonitoringClient.h | 8 ++-- server/src/ServerManager.cpp | 6 +-- server/src/ServerManager.h | 5 ++- server/src/main.cpp | 19 +++----- src/Logic/ImGuiManager.cpp | 12 ++--- src/Logic/ImGuiManager.h | 2 +- src/Models/IniData.h | 29 +++++++++--- src/Network/MessageHandler.cpp | 2 +- src/Wrapper/OCNpc.cpp | 8 ++-- src/Wrapper/OCNpc.h | 8 ++-- src/dllmain.cpp | 11 +++-- 16 files changed, 146 insertions(+), 100 deletions(-) diff --git a/MonitoringServer/src/IniData.h b/MonitoringServer/src/IniData.h index 1486606..f848bbc 100644 --- a/MonitoringServer/src/IniData.h +++ b/MonitoringServer/src/IniData.h @@ -3,18 +3,35 @@ #include #include #include +#include +#include "../../common/src/IniManager.h" class IniData { public: - static constexpr char * CONFIG_FILE = "config.ini"; + + struct Ini { + std::string serverIp = "127.0.0.1"; + int serverPort = 18080; + std::string secret = "my_secret_key"; + }; + static constexpr const char * CONFIG_FILE = "config.ini"; class Item { public: - static constexpr char * GENERAL_SERVER_IP = "General.server_ip"; - static constexpr char * GENERAL_SERVER_PORT = "General.server_port"; + static constexpr const char * GENERAL_SERVER_IP = "General.server_ip"; + static constexpr const char * GENERAL_SERVER_PORT = "General.server_port"; + static constexpr const char * GENERAL_SERVER_HEADER_SECRET = "General.header_secret"; }; + static Ini LoadIni() + { + Ini retIni; + retIni.serverIp = IniManager::GetItem(CONFIG_FILE, Item::GENERAL_SERVER_IP); + retIni.serverPort = std::stoi(IniManager::GetItem(IniData::CONFIG_FILE, Item::GENERAL_SERVER_PORT)); + retIni.secret = IniManager::GetItem(CONFIG_FILE, Item::GENERAL_SERVER_HEADER_SECRET); + return retIni; + } static bool CreateConfigIfMissing(const std::string& path) // STATIC { writeConfig(path); @@ -31,10 +48,12 @@ class IniData { if (std::filesystem::exists(path)) return; + Ini tempIni; std::ofstream out(path); out << "[General]\n"; - out << "server_ip = 127.0.0.1\n"; - out << "server_port = 18080\n\n"; + out << "server_ip =" << tempIni.serverIp << "\n"; + out << "server_port = " << std::to_string(tempIni.serverPort).c_str() << "\n"; + out << "header_secret = " << tempIni.secret << "\n\n"; } }; \ No newline at end of file diff --git a/MonitoringServer/src/main.cpp b/MonitoringServer/src/main.cpp index 28866b0..842851c 100644 --- a/MonitoringServer/src/main.cpp +++ b/MonitoringServer/src/main.cpp @@ -1,15 +1,11 @@ #include #include -#include "../../common/src/IniManager.h" - #include "IniData.h" #include "crow.h" //#include "crow_all.h" -class IniManager; - std::string ascii = R"( ____ _____ ____ _____ __ __ _ _ | _ \| ____/ ___|_ _| | \/ | ___ _ __ (_) |_ ___ _ __ @@ -20,10 +16,7 @@ std::string ascii = R"( std::mutex mtx_serverData; -struct Ini { - std::string serverIp = "127.0.0.1"; - int serverPort = 18080; -} config; +IniData::Ini config; struct GothicServerData { std::string status = "offline"; @@ -31,7 +24,7 @@ struct GothicServerData { } serverData; -Ini getConfigData(); +IniData::Ini getConfigData(); /*This RestAPI receives every 5 Seconds a Message from the GothicServer, if there is no answer for more than 7 Seconds, @@ -40,7 +33,7 @@ this RestAPI-Sever answers with an Offline-Status. int main() { std::cout << ascii << "\n\n"; - Ini configData = getConfigData(); + config = getConfigData(); crow::SimpleApp app; //define your crow application @@ -67,6 +60,10 @@ int main() // PUT /status CROW_ROUTE(app, "/status").methods("PUT"_method)([&lastResponse](const crow::request& req) { + if (req.get_header_value("X-Auth-Token") != config.secret){ + return crow::response(403, "Forbidden"); + } + auto body = crow::json::load(req.body); if (!body || !body.has("status")) { return crow::response(400, "Missing 'status' field"); @@ -79,19 +76,17 @@ int main() return crow::response(200, "Updated"); }); - app.port(18080).multithreaded().run(); + app.bindaddr(config.serverIp).port(config.serverPort).multithreaded().run(); } -Ini getConfigData() { - Ini ret; +IniData::Ini getConfigData() { + IniData::Ini ret; + // #### LOADIN INI #### - IniManager manager; if(!IniData::CreateConfigIfMissing(IniData::CONFIG_FILE)) return ret; - else - std::cout << "-- Config loaded --" << "\n"; - ret.serverIp = manager.GetItem(IniData::CONFIG_FILE, IniData::Item::GENERAL_SERVER_IP); - ret.serverPort = std::stoi(manager.GetItem(IniData::CONFIG_FILE, IniData::Item::GENERAL_SERVER_PORT)); + ret = IniData::LoadIni(); + std::cout << "-- Config loaded --" << "\n"; return ret; } \ No newline at end of file diff --git a/server/src/CommonStructures.h b/server/src/CommonStructures.h index 87fe757..242cfdb 100644 --- a/server/src/CommonStructures.h +++ b/server/src/CommonStructures.h @@ -5,16 +5,6 @@ using boost::asio::ip::udp; namespace CommonStructures { - struct Ini { - std::string serverIp = "127.0.0.1"; - int serverPort = 12345; - - bool monitoringActive = false; - std::string monitoringIp = "127.0.0.1"; - int monitoringPort = 18080; - }; - - struct PlayerEquipment { std::string meleeWeaponInstanceName; std::string rangedWeaponInstanceName; diff --git a/server/src/IniData.h b/server/src/IniData.h index a3015ec..3bb504d 100644 --- a/server/src/IniData.h +++ b/server/src/IniData.h @@ -3,22 +3,51 @@ #include #include #include +#include +#include "../../common/src/IniManager.h" + class IniData { public: - static constexpr char * CONFIG_FILE = "config.ini"; + struct Ini { + std::string serverIp = "127.0.0.1"; + int serverPort = 12345; + + bool monitoringActive = false; + std::string monitoringIp = "127.0.0.1"; + int monitoringPort = 18080; + std::string monitoringSecret = "my_secret_key"; + }; + + static constexpr const char * CONFIG_FILE = "config.ini"; class Item { public: - static constexpr char * GENERAL_SERVER_IP = "General.server_ip"; - static constexpr char * GENERAL_SERVER_PORT = "General.server_port"; + static constexpr const char * GENERAL_SERVER_IP = "General.server_ip"; + static constexpr const char * GENERAL_SERVER_PORT = "General.server_port"; - static constexpr char * MONITORING_ACTIVE = "Monitoring.active"; - static constexpr char * MONITORING_IP = "Monitoring.server_ip"; - static constexpr char * MONITORING_PORT = "Monitoring.server_port"; + static constexpr const char * MONITORING_ACTIVE = "Monitoring.active"; + static constexpr const char * MONITORING_IP = "Monitoring.server_ip"; + static constexpr const char * MONITORING_PORT = "Monitoring.server_port"; + static constexpr const char * MONITORING_HEADER_SECRET = "Monitoring.header_secret"; }; + static Ini LoadIni() + { + Ini retIni; + retIni.serverIp = IniManager::GetItem(CONFIG_FILE, Item::GENERAL_SERVER_IP); + retIni.serverPort = std::stoi(IniManager::GetItem(CONFIG_FILE, Item::GENERAL_SERVER_PORT)); + + std::string active = IniManager::GetItem(CONFIG_FILE, Item::MONITORING_ACTIVE); + if(active == "true") + retIni.monitoringActive = true; + retIni.monitoringIp = IniManager::GetItem(CONFIG_FILE, Item::MONITORING_IP); + retIni.monitoringPort = std::stoi(IniManager::GetItem(CONFIG_FILE, Item::MONITORING_PORT)); + retIni.monitoringSecret = IniManager::GetItem(CONFIG_FILE, Item::MONITORING_HEADER_SECRET); + return retIni; + } + static bool CreateConfigIfMissing(const std::string& path) // STATIC { writeConfig(path); @@ -35,15 +64,17 @@ class IniData { if (std::filesystem::exists(path)) return; + Ini tempIni; std::ofstream out(path); out << "[General]\n"; - out << "server_ip = 127.0.0.1\n"; - out << "server_port = 12345\n\n"; + out << "server_ip = " << tempIni.serverIp << "\n"; + out << "server_port = " << std::to_string(tempIni.serverPort) << "\n\n"; out << "[Monitoring]\n"; out << "active = false\n"; - out << "server_ip = 127.0.0.1\n"; - out << "server_port = 18080\n"; + out << "server_ip = " << tempIni.monitoringIp << "\n"; + out << "server_port = " << std::to_string(tempIni.monitoringPort) << "\n"; + out << "header_secret = " << tempIni.monitoringSecret << "\n"; } }; \ No newline at end of file diff --git a/server/src/Monitoring/MonitoringClient.cpp b/server/src/Monitoring/MonitoringClient.cpp index fcfaba7..95a8f0e 100644 --- a/server/src/Monitoring/MonitoringClient.cpp +++ b/server/src/Monitoring/MonitoringClient.cpp @@ -1,25 +1,32 @@ #include "MonitoringClient.h" -MonitoringClient::MonitoringClient(std::string ip, int port, AsyncUnorderedMap *clients, bool &serverRunning) - : ip(ip), port(port), pClients(clients), pServerRunning(&serverRunning) +MonitoringClient::MonitoringClient(IniData::Ini config, AsyncUnorderedMap *clients, bool &serverRunning) + : configData(config), pClients(clients), pServerRunning(&serverRunning) { startingMonitoringClient(); } void MonitoringClient::startingMonitoringClient(){ - httplib::Client cli(this->ip, this->port); + httplib::Client cli(this->configData.monitoringIp, this->configData.monitoringPort); while(*pServerRunning){ std::string status= "online"; int count = this->pClients->getUnorderedMap()->size(); + httplib::Headers headers = { + {"X-Auth-Token", this->configData.monitoringSecret} + }; + std::string body = "{" "\"status\": \"" + status + "\", " "\"playerCount\": " + std::to_string(count) + "}"; - auto put_res = cli.Put("/status", body, "application/json"); + + auto put_res = cli.Put("/status", headers, body, "application/json"); + //put_res.value().set_header("/status", "Ma key"); + if (put_res && put_res->status == 200) { //std::cout << "Status updated successfully\n"; } else { diff --git a/server/src/Monitoring/MonitoringClient.h b/server/src/Monitoring/MonitoringClient.h index 6fda776..b3c418f 100644 --- a/server/src/Monitoring/MonitoringClient.h +++ b/server/src/Monitoring/MonitoringClient.h @@ -1,5 +1,7 @@ #pragma once +#include "../IniData.h" + #include "../CommonStructures.h" #include "../../../common/src/Async/AsyncUnorderedMap.h" #include "../../../common/lib/cpp-httplib/httplib.h" @@ -9,13 +11,11 @@ class MonitoringClient { public: - MonitoringClient(std::string ip, int port, AsyncUnorderedMap *clients, bool &serverRunning); - MonitoringClient(); + MonitoringClient(IniData::Ini config, AsyncUnorderedMap *clients, bool &serverRunning); void startingMonitoringClient(); private: AsyncUnorderedMap *pClients; bool *pServerRunning; - std::string ip = "127.0.0.1"; - int port = 18080; + IniData::Ini configData; }; \ No newline at end of file diff --git a/server/src/ServerManager.cpp b/server/src/ServerManager.cpp index ed89d22..4ce2ae4 100644 --- a/server/src/ServerManager.cpp +++ b/server/src/ServerManager.cpp @@ -1,12 +1,10 @@ #include "ServerManager.h" #include #include -#include "IniData.h" -#include using boost::asio::ip::address; -ServerManager::ServerManager(boost::asio::io_context &io_context, boost::asio::io_context &processing_context, CommonStructures::Ini config) +ServerManager::ServerManager(boost::asio::io_context &io_context, boost::asio::io_context &processing_context, IniData::Ini config) : configData(config), socket(io_context, udp::endpoint(boost::asio::ip::make_address(config.serverIp), config.serverPort)) { this->processing_context = &processing_context; @@ -25,7 +23,7 @@ ServerManager::ServerManager(boost::asio::io_context &io_context, boost::asio::i if(configData.monitoringActive) { boost::asio::post(io_context, [&]() { std::cout << "Monitoring Client connected to " << configData.monitoringIp << ":" << std::to_string(configData.monitoringPort) <<"..."<< std::endl; - monitor = std::make_unique(configData.monitoringIp, configData.monitoringPort, &clients, serverRunning); + monitor = std::make_unique(configData, &clients, serverRunning); }); } } diff --git a/server/src/ServerManager.h b/server/src/ServerManager.h index 0820e57..c2adbe6 100644 --- a/server/src/ServerManager.h +++ b/server/src/ServerManager.h @@ -8,6 +8,7 @@ #include "CommonStructures.h" #include "Monitoring/MonitoringClient.h" +#include "IniData.h" #include "../../common/src/Async/AsyncUnorderedMap.h" #include "../../common/src/IniManager.h" @@ -16,7 +17,7 @@ using boost::asio::ip::udp; class ServerManager { public: - ServerManager(boost::asio::io_context &io_context, boost::asio::io_context &processing_context, CommonStructures::Ini configData); + ServerManager(boost::asio::io_context &io_context, boost::asio::io_context &processing_context, IniData::Ini configData); void watchingHeartbeat(); private: udp::socket socket; @@ -28,7 +29,7 @@ class ServerManager { MessageHandler *messageHandler; void start_receive(); - CommonStructures::Ini configData; + IniData::Ini configData; std::unique_ptr monitor; }; \ No newline at end of file diff --git a/server/src/main.cpp b/server/src/main.cpp index a6a9ba8..32b7f28 100644 --- a/server/src/main.cpp +++ b/server/src/main.cpp @@ -22,23 +22,14 @@ std::string ascii = R"( )"; -CommonStructures::Ini getConfigData() { - CommonStructures::Ini ret; +IniData::Ini getConfigData() { + IniData::Ini ret; // #### LOADIN INI #### - IniManager manager; if(!IniData::CreateConfigIfMissing(IniData::CONFIG_FILE)) return ret; - else - std::cout << "-- Config loaded --" << "\n"; - ret.serverIp = manager.GetItem(IniData::CONFIG_FILE, IniData::Item::GENERAL_SERVER_IP); - ret.serverPort = std::stoi(manager.GetItem(IniData::CONFIG_FILE, IniData::Item::GENERAL_SERVER_PORT)); - - std::string active = manager.GetItem(IniData::CONFIG_FILE, IniData::Item::MONITORING_ACTIVE); - if(active == "true") - ret.monitoringActive = true; - ret.monitoringIp = manager.GetItem(IniData::CONFIG_FILE, IniData::Item::MONITORING_IP); - ret.monitoringPort = std::stoi(manager.GetItem(IniData::CONFIG_FILE, IniData::Item::MONITORING_PORT)); + ret = IniData::LoadIni(); + std::cout << "-- Config loaded --" << "\n"; return ret; } @@ -48,7 +39,7 @@ int main() std::cout << ascii << "\n\n"; try { - CommonStructures::Ini configData = getConfigData(); + IniData::Ini configData = getConfigData(); boost::asio::io_context io_context; boost::asio::io_context processing_context; diff --git a/src/Logic/ImGuiManager.cpp b/src/Logic/ImGuiManager.cpp index 78967c1..d8fb817 100644 --- a/src/Logic/ImGuiManager.cpp +++ b/src/Logic/ImGuiManager.cpp @@ -26,8 +26,8 @@ void ImGuiManager::showContent(ImGuiData imGuiData) std::string coords = "Coords.:" + player->getCoordinates(); std::string level = "Level:" + std::to_string(player->getCurrentLevel()); - ImGui::Text(coords.c_str()); - ImGui::Text(level.c_str()); + ImGui::Text("%s", coords.c_str()); + ImGui::Text("%s", level.c_str()); ImGui::Text("\nPlayers"); if (!imGuiData.clients.empty()) @@ -42,10 +42,10 @@ void ImGuiManager::showContent(ImGuiData imGuiData) std::string posZ = std::to_string(valueNpc->getZ()); std::string posY = std::to_string(valueNpc->getY()); - ImGui::Text(valueNpc->getName().c_str()); - ImGui::Text(("\t" + posX).c_str()); - ImGui::Text(("\t" + posZ).c_str()); - ImGui::Text(("\t" + posY).c_str()); + ImGui::Text("%s", valueNpc->getName().c_str()); + ImGui::Text("%s", ("\t" + posX).c_str()); + ImGui::Text("%s", ("\t" + posZ).c_str()); + ImGui::Text("%s", ("\t" + posY).c_str()); } } else diff --git a/src/Logic/ImGuiManager.h b/src/Logic/ImGuiManager.h index 51d3e81..c87deb7 100644 --- a/src/Logic/ImGuiManager.h +++ b/src/Logic/ImGuiManager.h @@ -13,7 +13,7 @@ #include #pragma comment(lib, "d3d11.lib") -#include "../Models/NPC.h" +#include "../Models/Npc.h" #include "../Models/ImGuiData.h" class ImGuiManager { diff --git a/src/Models/IniData.h b/src/Models/IniData.h index cfbc521..6127887 100644 --- a/src/Models/IniData.h +++ b/src/Models/IniData.h @@ -6,10 +6,15 @@ class IniData { public: + struct Ini { + std::string username = "Player"; + std::string serverIp = "127.0.0.1"; + std::string serverPort = "12345"; + }; /** * @brief Default filename for the client configuration file. */ - static constexpr char * CLIENT_CONFIG_FILE = "gpr_config.ini"; + static constexpr const char * CLIENT_CONFIG_FILE = "gpr_config.ini"; /** * @class Item @@ -18,11 +23,20 @@ class IniData { class Item { public: - static constexpr char * GENERAL_USERNAME = "General.username"; - static constexpr char * GENERAL_SERVER_IP = "General.server_ip"; - static constexpr char * GENERAL_SERVER_PORT = "General.server_port"; + static constexpr const char * GENERAL_USERNAME = "General.username"; + static constexpr const char * GENERAL_SERVER_IP = "General.server_ip"; + static constexpr const char * GENERAL_SERVER_PORT = "General.server_port"; }; + static Ini LoadIni() + { + Ini retIni; + retIni.username = IniManager::GetItem(CLIENT_CONFIG_FILE, Item::GENERAL_USERNAME); + retIni.serverIp = IniManager::GetItem(CLIENT_CONFIG_FILE, Item::GENERAL_SERVER_IP); + retIni.serverPort = IniManager::GetItem(CLIENT_CONFIG_FILE, Item::GENERAL_SERVER_PORT); + return retIni; + } + static bool CreateConfigIfMissing(const std::string& path) // STATIC { writeConfig(path); @@ -39,11 +53,12 @@ class IniData { if (std::filesystem::exists(path)) return; + Ini tempIni; std::ofstream out(path); out << "[General]\n"; - out << "username = Player\n"; - out << "server_ip = 127.0.0.1\n"; - out << "server_port = 12345\n"; + out << "username = " << tempIni.username << "\n"; + out << "server_ip = " << tempIni.serverIp << "\n"; + out << "server_port = " << tempIni.serverPort << "\n\n"; } }; \ No newline at end of file diff --git a/src/Network/MessageHandler.cpp b/src/Network/MessageHandler.cpp index 90b3a3e..62cc785 100644 --- a/src/Network/MessageHandler.cpp +++ b/src/Network/MessageHandler.cpp @@ -158,7 +158,7 @@ void MessageHandler::handleServerDistributeAnimations(std::string &buffer) Npc *value = it.value(); DataStructures::LastAnimation npcLastAnim = value->getLastAnimation(); DataStructures::LastAnimation npcNewAnim; - zCModel *npcModel = new zCModel(value->oCNpc->getModel()); + std::unique_ptr npcModel = std::make_unique(value->oCNpc->getModel()); int animCount = PackagingSystem::ReadItem(buffer); npcNewAnim.animationCount = animCount; diff --git a/src/Wrapper/OCNpc.cpp b/src/Wrapper/OCNpc.cpp index 82dbd8d..2daee34 100644 --- a/src/Wrapper/OCNpc.cpp +++ b/src/Wrapper/OCNpc.cpp @@ -25,7 +25,7 @@ OCNpc * OCNpc::CreateFromPointer(void* address) // STATIC return reinterpret_cast(address); } -void OCNpc::setVisualWithString(char *visual) +void OCNpc::setVisualWithString(const char *visual) { using _SetVisualWithString = void(__thiscall *)(void *pThis, zSTRING *visual); _SetVisualWithString setVisualWithStringRef = reinterpret_cast<_SetVisualWithString>(0x5d6fa0); @@ -34,7 +34,7 @@ void OCNpc::setVisualWithString(char *visual) setVisualWithStringRef(this, visualString); } -void OCNpc::setAdditionalVisuals(char *textureBody, int param2, int param3, char *textureHead, int param5, int param6, int param7) +void OCNpc::setAdditionalVisuals(const char *textureBody, int param2, int param3, const char *textureHead, int param5, int param6, int param7) { using _SetAdditionalVisuals = void(__thiscall *)(void *pThis, zSTRING *textureBody, int param2, int param3, zSTRING *textureHead, int param5, int param6, int param7); _SetAdditionalVisuals setAdditionalVisualsRef = reinterpret_cast<_SetAdditionalVisuals>(0x694ef0); @@ -45,7 +45,7 @@ void OCNpc::setAdditionalVisuals(char *textureBody, int param2, int param3, char setAdditionalVisualsRef(this, body, param2, param3, head, param5, param6, param7); } -void OCNpc::setVobName(char *vobName) +void OCNpc::setVobName(const char *vobName) { using _SetVobName = void(__thiscall *)(void *pThis, zSTRING *vobName); _SetVobName setVobNameRef = reinterpret_cast<_SetVobName>(0x5d4970); @@ -54,7 +54,7 @@ void OCNpc::setVobName(char *vobName) setVobNameRef(this, name); } -void OCNpc::setByScriptInstance(char *nameS, int param2) +void OCNpc::setByScriptInstance(const char *nameS, int param2) { using _SetByScriptInstance = int(__thiscall *)(void *pThis, zSTRING *visual, int param2); _SetByScriptInstance setByScriptInstanceRef = reinterpret_cast<_SetByScriptInstance>(0x6a1bf0); diff --git a/src/Wrapper/OCNpc.h b/src/Wrapper/OCNpc.h index 956084a..d6c4364 100644 --- a/src/Wrapper/OCNpc.h +++ b/src/Wrapper/OCNpc.h @@ -92,13 +92,13 @@ class OCNpc return *reinterpret_cast(reinterpret_cast(this) + offset); } - void setVisualWithString(char *visual); + void setVisualWithString(const char *visual); - void setAdditionalVisuals(char *textureBody, int param2, int param3, char *textureHead, int param5, int param6, int param7); + void setAdditionalVisuals(const char *textureBody, int param2, int param3, const char *textureHead, int param5, int param6, int param7); - void setVobName(char *vobName); + void setVobName(const char *vobName); - void setByScriptInstance(char *name, int param2); + void setByScriptInstance(const char *name, int param2); void enable(ZVec3 *pos); diff --git a/src/dllmain.cpp b/src/dllmain.cpp index fef4542..447060d 100644 --- a/src/dllmain.cpp +++ b/src/dllmain.cpp @@ -159,9 +159,8 @@ DWORD WINAPI MainThread() if(!IniData::CreateConfigIfMissing(IniData::CLIENT_CONFIG_FILE)) return -1; - std::string username = IniManager::GetItem(IniData::CLIENT_CONFIG_FILE, IniData::Item::GENERAL_USERNAME); - std::string serverIp = IniManager::GetItem(IniData::CLIENT_CONFIG_FILE, IniData::Item::GENERAL_SERVER_IP); - std::string serverPort = IniManager::GetItem(IniData::CLIENT_CONFIG_FILE, IniData::Item::GENERAL_SERVER_PORT); + IniData::Ini config = IniData::LoadIni(); + // ########################### std::cout << "Starting MAIN...\n" @@ -186,21 +185,21 @@ DWORD WINAPI MainThread() Sleep(200); // ################## START ############################ std::cout << "Press RControl to connect...\n"; - while (!GetAsyncKeyState(VK_RCONTROL) & 1) + while (!(GetAsyncKeyState(VK_RCONTROL) & 1)) { Sleep(100); } boost::asio::io_context io_context; // create Client - Client client(io_context, username, serverIp, serverPort, gameThreadWorker); + Client client(io_context, config.username, config.serverIp, config.serverPort, gameThreadWorker); // mainloop for receiving messages std::thread io_thread([&io_context]() { io_context.run(); }); DataChangeNotifier notifier(&client); - while (!GetAsyncKeyState(VK_END) & 1) + while (!(GetAsyncKeyState(VK_END) & 1)) { /*if (GetAsyncKeyState(VK_DOWN) < 0){ notifier.sendChanges(); From 1ecea59a9cbcdfcd992253602658bd6738c7329c Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Sat, 19 Jul 2025 11:50:14 +0200 Subject: [PATCH 07/11] structure things --- CMakeLists.txt | 4 +- MinHook/libMinHook.x86.lib | Bin 26888 -> 0 bytes MinHook/oldlibMinHook.x86.lib | Bin 413034 -> 0 bytes {MinHook => common/lib/MinHook}/MinHook.h | 0 .../lib/imGui}/backends/imgui_impl_dx10.cpp | 0 .../lib/imGui}/backends/imgui_impl_dx10.h | 0 .../lib/imGui}/backends/imgui_impl_dx11.cpp | 0 .../lib/imGui}/backends/imgui_impl_dx11.h | 0 .../lib/imGui}/backends/imgui_impl_dx9.cpp | 0 .../lib/imGui}/backends/imgui_impl_dx9.h | 0 .../lib/imGui}/backends/imgui_impl_win32.cpp | 0 .../lib/imGui}/backends/imgui_impl_win32.h | 0 {imGui => common/lib/imGui}/imconfig.h | 0 {imGui => common/lib/imGui}/imgui.cpp | 0 {imGui => common/lib/imGui}/imgui.h | 0 {imGui => common/lib/imGui}/imgui_demo.cpp | 0 {imGui => common/lib/imGui}/imgui_draw.cpp | 0 {imGui => common/lib/imGui}/imgui_internal.h | 0 {imGui => common/lib/imGui}/imgui_tables.cpp | 0 {imGui => common/lib/imGui}/imgui_widgets.cpp | 0 {imGui => common/lib/imGui}/imstb_rectpack.h | 0 {imGui => common/lib/imGui}/imstb_textedit.h | 0 {imGui => common/lib/imGui}/imstb_truetype.h | 0 common/src/Network/PackagingSystem.cpp | 9 +- server/src/MessageHandler.cpp | 2 +- src/Logic/ClientGameMapping.cpp | 33 +++ src/Logic/ClientGameMapping.h | 22 ++ src/Logic/GameThreadWorker.cpp | 107 +------ src/Logic/GameThreadWorker.h | 31 ++- src/Logic/Playground.h | 89 ++++++ src/Logic/sMain.cpp | 262 ------------------ src/Logic/sMain.h | 36 --- src/Models/Npc.cpp | 2 +- src/Models/Npc.h | 7 + src/Network/Client.cpp | 11 +- src/Network/Client.h | 8 +- src/Network/MessageHandler.cpp | 10 +- src/Network/MessageHandler.h | 16 +- src/Wrapper/zCModelAniActive.cpp | 2 + src/Wrapper/zCModelAniActive.h | 12 + src/dllmain.cpp | 25 +- 41 files changed, 235 insertions(+), 453 deletions(-) delete mode 100644 MinHook/libMinHook.x86.lib delete mode 100644 MinHook/oldlibMinHook.x86.lib rename {MinHook => common/lib/MinHook}/MinHook.h (100%) rename {imGui => common/lib/imGui}/backends/imgui_impl_dx10.cpp (100%) rename {imGui => common/lib/imGui}/backends/imgui_impl_dx10.h (100%) rename {imGui => common/lib/imGui}/backends/imgui_impl_dx11.cpp (100%) rename {imGui => common/lib/imGui}/backends/imgui_impl_dx11.h (100%) rename {imGui => common/lib/imGui}/backends/imgui_impl_dx9.cpp (100%) rename {imGui => common/lib/imGui}/backends/imgui_impl_dx9.h (100%) rename {imGui => common/lib/imGui}/backends/imgui_impl_win32.cpp (100%) rename {imGui => common/lib/imGui}/backends/imgui_impl_win32.h (100%) rename {imGui => common/lib/imGui}/imconfig.h (100%) rename {imGui => common/lib/imGui}/imgui.cpp (100%) rename {imGui => common/lib/imGui}/imgui.h (100%) rename {imGui => common/lib/imGui}/imgui_demo.cpp (100%) rename {imGui => common/lib/imGui}/imgui_draw.cpp (100%) rename {imGui => common/lib/imGui}/imgui_internal.h (100%) rename {imGui => common/lib/imGui}/imgui_tables.cpp (100%) rename {imGui => common/lib/imGui}/imgui_widgets.cpp (100%) rename {imGui => common/lib/imGui}/imstb_rectpack.h (100%) rename {imGui => common/lib/imGui}/imstb_textedit.h (100%) rename {imGui => common/lib/imGui}/imstb_truetype.h (100%) create mode 100644 src/Logic/ClientGameMapping.cpp create mode 100644 src/Logic/ClientGameMapping.h create mode 100644 src/Logic/Playground.h delete mode 100644 src/Logic/sMain.cpp delete mode 100644 src/Logic/sMain.h create mode 100644 src/Wrapper/zCModelAniActive.cpp create mode 100644 src/Wrapper/zCModelAniActive.h diff --git a/CMakeLists.txt b/CMakeLists.txt index e9b8ba6..28e05c0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -48,7 +48,7 @@ endif() # MinHook Pfad relativ zum CMake-Projektverzeichnis -set(MINHOOK_DIR ${CMAKE_SOURCE_DIR}/MinHook) +set(MINHOOK_DIR ${CMAKE_SOURCE_DIR}/common/lib/MinHook) # Suche alle .cpp-Dateien im aktuellen Verzeichnis file(GLOB_RECURSE SOURCES "src/*.cpp") @@ -59,7 +59,7 @@ include_directories("common/src/") # Dear ImGui Quellen und Header definieren -set(IMGUI_DIR ${CMAKE_SOURCE_DIR}/imgui) +set(IMGUI_DIR ${CMAKE_SOURCE_DIR}/common/lib/imgui) set(IMGUI_BACKENDS_DIR ${IMGUI_DIR}/backends) set(IMGUI_SOURCES diff --git a/MinHook/libMinHook.x86.lib b/MinHook/libMinHook.x86.lib deleted file mode 100644 index 9216b3ae5c403fdb4a35a6ac4e05c9f53ec5f795..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 26888 zcmd^o4SW>Ux%ccxk|i$Ppo^x8nqst65b^;Lj2{Uw7%&S-$e>s>gk&)xAxX2lDqbUr zleF0kX|XRVt-cit?X}cfsUH-2u_hP^0(~3&xTP(vfy>(_E^53DuwW$j|C}>3JF~k% z`*Hofzu$W>Gynac=bSm`IbYA2Ip_G5o68$3s%}l5k!E(8Ia#waGH2$@y3x#Ms6S_A zWvXapvLFblf{<{lAfycc{ePlg5a{pTN8|mK&1>|Q`@N-&t(@b zGC{E}ida}z?XNDct$xU>K9M~>HXx&8LYH{g*57Z8f2qIRAMlmdFZDN8*WH)LA1c*V zo1SuCSyh3zyg?`fK+b#ws(pp^6*b;Up{%OXo1IlwiKP41YQOxHYN0H@wzj?k>YE!_ zz1rI-lr3oV>Nt`S&3BbmT#74yBT0{5+`tzPA+uA_#!!msxY)9Y8Q z5yp_BhI2uGYDE_kSjE~9lSrPSb%$y#9xE4_85ub_IcaHGbFyc1(Ur-CmP8@HeO&n> zhajY(?vtC2##Z6K-^+iY9|W*lv|s8yIR$c*`Shil&vO8)qU7>~l)2OW-Ut2ZYwI+* zd(pm5cx1^o5?gH92aF=OJT7+Q?DVc_|rrOs>={=Y&j3v|L41 zjW1^=3rm*_{9Uff=p@Ds=wilvaY4RRSX#Jn?oE>ef$GZXDALKFi$;)np3?bI!b=M0 zFV6RfODCsMECT!X4=~7I;svUmMvYO!W-6>`~2R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MinHook/oldlibMinHook.x86.lib b/MinHook/oldlibMinHook.x86.lib deleted file mode 100644 index cf24b628132606354243bc509702116bec138535..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 413034 zcmeFad3aOR7B+s;0m>*82cSrkg4H6ywooi}YMQ2PAZ==!7OH40ZGlQ@O9up;A}S*4 zb-Jk6t6qnzUd35Kk6si9M4UxM5uC5H;)EkAzjv*D_Rcv;T1@?(=lkRLm4|cA-g^!2 zT6^vB>?DpO>pL3eA3g9eyY(+;YHogZ&XlQ#XIt}SGACzRz9>0qpr&aDYudne&9+?*8iZpqp7~DDbP{Bu)VFNxwWaJyS1UKxvf<@=9r+nFqoZJ>MyA% zDw|PMSY8(N&nT4n(@HB#UDL}diwln#@Ah`LE@*8#r4^6U6-7}|VOd$pj1vEJH}QI^ zs{BoxeMLyN_UB`(iiFbMwWo4B=;Bg1cwEl{+89uMa6Q(8g zo>?AuO@Oe5X{Q%@%1c}>PpL_+%LkmrbN1sjjzyOTIqKCE6PbjO~s4~|ICU) zEr^7xy}f1WvE5DGO^t=woFn40tgUT9VNPyDj;p=7FlTCXre{fEuHY_i?yR5F(!}gj zn9$Q2k>PD^?rN@YXXj0ppleHe{s0ZH*1$F4Xlg!}`ooNOhCMS>v#-6On z$^#?PIn3WA`yJ%X-K8&=44 z^I8<$h0`@{K%z?WgQ9D0RRtt!b-7Af>6(_Pg6~&r+7&&~buLwOTPA7R`5&sJRbJy9 zRj_-3rX8PZHH7fNrOt-7h3(BPO&tXp?tqg$uhe@-LlT>z*BGYisG8U0#jHoGFuXr%jri zojv*R*>jp(XP32gcFoG4IvWyaH{?!gY-!1`?+bj+uBGiwjm<5ZbFNlWFuS(7v8kAyVP1T%@ZJnBPrZ!n~`sd+4 z68<^4n$uH;r}6;ks_}oR=A^}r*EJbMCCy#_IVaOfKt31Och%#$?N5T4)7{+C2-|a} z&hD}KL^LyJNn`xN(Q0F~;7M@jq;^!av#Fz_t)ruqL>4BJx6Ad{1p2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;QtlVqTNw-+S+3r*LEVyzuwJ-w&S|`A+15$jy`Vj7I`A_WaR0{i;;guUXQ#Rc`NeY$cEB$N{4?9E0d?}9FCNh^{*ZrI<@Hhq6>;H zEV{Dj>Y{gw-YxpDXgGXIczyV^@EPHa;WNW$!}bN?3t|7F@Wn{uhvCb@SA>5QzA}7u z_?qyw;h%c2hj9e7CBywrwvdC4D8Aj^7ls;JcXz3HBTS}iPeXjI{ z(tnh`T>4t+Tcz)n{=4))rJt1kuk@6%Q_D^-JEQE(va`$1EjzF5!m^9YE-kyP?2580 z%dRfFw(R<{o62r3yQS>5vfIn(id); Async::PrintLn( "ID: " + std::to_string(id) ); @@ -101,7 +102,6 @@ void MessageHandler::clientHandshakeRequest(udp::endpoint &clientEndpoint, std:: // ################################### // ###### SEND CLIENT EVERYONE ELSE ###### - // TODO: Continue Here to share the Name of the new Client to the other clients!! PackagingSystem helloInfo(Packets::ServerPacket::serverNewClientConnected); helloInfo.addString(clientPortIp); diff --git a/src/Logic/ClientGameMapping.cpp b/src/Logic/ClientGameMapping.cpp new file mode 100644 index 0000000..5a07b52 --- /dev/null +++ b/src/Logic/ClientGameMapping.cpp @@ -0,0 +1,33 @@ +#include "ClientGameMapping.h" + +ClientGameMapping::ClientGameMapping(AsyncUnorderedMap *pClients) + : pClients(pClients) +{ +} + +void ClientGameMapping::manageClientsInSync() +{ + syncAnimation(); +} + +void ClientGameMapping::syncAnimation() +{ + /*std::lock_guard lock(pClients->getMutex()); + for (auto it = pClients->getUnorderedMap()->begin(); it != pClients->getUnorderedMap()->end(); ++it) + { + std::unique_ptr npcModel = std::make_unique(it->second->oCNpc->getModel()); + //zCModel* npcModel = reinterpret_cast(it->second->oCNpc->getModel()); + + auto networkAnim = it->second->networkState.animation; + auto lastAnim = it->second->getLastAnimation(); + + if (!lastAnim.isSame(networkAnim)) + { + std::cout << "IS NOT SAME ANIM!!!!!!!!!!!! STARTING\n"; + for (auto &newId : networkAnim.animationIds) + { + npcModel->startAniInt(newId, 0); + } + } + }*/ +} \ No newline at end of file diff --git a/src/Logic/ClientGameMapping.h b/src/Logic/ClientGameMapping.h new file mode 100644 index 0000000..bec8d27 --- /dev/null +++ b/src/Logic/ClientGameMapping.h @@ -0,0 +1,22 @@ +#pragma once + +#include +#include + +#include "../Models/DataStructures.h" +#include "../Models/Npc.h" + +#include "../../common/src/Async/AsyncUnorderedMap.h" + +class ClientGameMapping { + + public: + ClientGameMapping(AsyncUnorderedMap *pClients); + + void manageClientsInSync(); + private: + AsyncUnorderedMap *pClients; + + void syncAnimation(); +}; + diff --git a/src/Logic/GameThreadWorker.cpp b/src/Logic/GameThreadWorker.cpp index 03a7d59..3ab6f60 100644 --- a/src/Logic/GameThreadWorker.cpp +++ b/src/Logic/GameThreadWorker.cpp @@ -1,23 +1,12 @@ #include "GameThreadWorker.h" #include -GameThreadWorker::GameThreadWorker() +GameThreadWorker::GameThreadWorker(Client &client) { - clients = new AsyncUnorderedMap(); - messageHandler = new MessageHandler(clients); - pMainPlayer = new Npc(ADDR_PLAYERBASE); -} - -GameThreadWorker::~GameThreadWorker() -{ - delete clients; - delete messageHandler; - delete pMainPlayer; -} + messageHandler = std::make_unique(&clients, client); + pMainPlayer = std::make_unique(ADDR_PLAYERBASE); -void GameThreadWorker::setClientForHandler(Client &client) -{ - messageHandler->setClient(client); + mapping = std::make_unique(&clients); } void GameThreadWorker::addTask(std::string task) @@ -39,13 +28,10 @@ void GameThreadWorker::processMessages() removeTask(); } } -#include "../Wrapper/oCItem.h" -#include "../Wrapper/oCMsgWeapon.h" -Npc *npc; void GameThreadWorker::checkGameState(){ /* ## Checks if player is in range of an other player to render him ## */ - std::unordered_map copyOfClients = *clients->getUnorderedMap(); + std::unordered_map copyOfClients = *clients.getUnorderedMap(); for (const auto& pair : copyOfClients) { if (pMainPlayer->oCNpc->getDistanceToVob(pair.second->oCNpc) < 4500 && pair.second->oCNpc->getHomeWorld() == 0) @@ -55,86 +41,7 @@ void GameThreadWorker::checkGameState(){ } } - /* ################ Custom Shit Here################# */ - if (GetAsyncKeyState(VK_RSHIFT) < 0) - { - std::cout << "--- ITEM STUFF ---- " << "\n"; - oCItem * armor = pMainPlayer->oCNpc->getEquippedArmor(); - oCItem * melee = pMainPlayer->oCNpc->getEquippedMeleeWeapon(); - oCItem * ranged = pMainPlayer->oCNpc->getEquippedRangedWeapon(); - - std::cout << "Armor Address: " << armor << "\n"; - std::cout << "Armor Name: " << armor->getName() << "\n"; - zSTRING * zArmor = armor->getInstanceName(); - zSTRING * zMelee = melee->getInstanceName(); - zSTRING * zRanged = ranged->getInstanceName(); - std::cout << "zArmor Instance Name: " << zArmor->stdString() << "\n"; - std::cout << "zMelee Instance Name: " << zMelee->stdString() << "\n"; - std::cout << "zRanged Instance Name: " << zRanged->stdString() << "\n"; - - oCItem * npcArmor = oCItem::CreateoCItem(); - npcArmor->setByScriptInstance(zArmor->c_str()); - oCItem * npcMelee = oCItem::CreateoCItem(); - npcMelee->setByScriptInstance(zMelee->c_str()); - oCItem * npcRanged = oCItem::CreateoCItem(); - npcRanged->setByScriptInstance(zRanged->c_str()); - //npcRanged->setFlag(4); //0x40000000, 0x800000 - //npcMelee->setFlag(2); - - std::cout << "CUSTOM Address : " << npcArmor << "\n"; - std::cout << "CUSTOM Name: " << npcArmor->getName() << "\n"; - - std::cout << "CUSTOM Address : " << npcMelee << "\n"; - std::cout << "CUSTOM Name: " << npcMelee->getName() << "\n"; - - std::cout << "CUSTOM Address : " << npcRanged << "\n"; - std::cout << "CUSTOM Name: " << npcRanged->getName() << "\n"; - std::cout << "---- -------- ---- " << "\n"; - + /* ## Checks if clients are in sync with there acions ## */ + mapping->manageClientsInSync(); - /*oCItem * current = pMainPlayer->oCNpc->getWeapon(); - if(current) { - std::cout << "current Address : " << current << "\n"; - std::cout << "current Name: " << current->getName() << "\n"; - } else { - std::cout << "current EMPTY!\n"; - }*/ - - if(npc == nullptr) { - npc = new Npc(); - npc->setCurrentHealth(10); - npc->setMaxHealth(10); - npc->oCNpc->setVisualWithString("HUMANS.MDS"); - npc->oCNpc->setAdditionalVisuals("hum_body_Naked0", 9, 0, "Hum_Head_Pony", 2, 0, -1); - //npc->oCNpc->setTalentValue(0, 10); // Strength - //npc->oCNpc->setTalentValue(1, 10); //Dexterity - npc->oCNpc->callVariable(OCNpc::Offset::DEXTERITY) = 10; - npc->oCNpc->callVariable(OCNpc::Offset::STRENGTH) = 10; - npc->oCNpc->enableWithdCoords(pMainPlayer->getX(), pMainPlayer->getZ(), pMainPlayer->getY()); - npc->setName("Steve"); - - - //npc->oCNpc->putInInv(npcRanged); - //npc->oCNpc->putInInv(npcMelee); - - npc->oCNpc->equip(npcArmor); - npc->oCNpc->equipItem(npcMelee); - npc->oCNpc->equip(npcRanged); - - //npc->oCNpc->equipBestWeapon(2); - //npc->oCNpc->equipBestWeapon(4); - - /*oCMsgWeapon * w = oCMsgWeapon::CreateoCMsgWeapon(4, 0, 0); - int ka = npc->oCNpc->EV_DrawWeapon1(w); - std::cout << "KA: " << std::to_string(ka) << "\n"; */ - - - /*nnpc->oCNpc->putInInv(npcArmor); - npc->oCNpc->putInInv(npcRanged); - npc->oCNpc->putInInv(npcMelee);*/ - - - //npc->oCNpc->equipItem(npcRanged); - } - } } \ No newline at end of file diff --git a/src/Logic/GameThreadWorker.h b/src/Logic/GameThreadWorker.h index 920b834..e5c95fd 100644 --- a/src/Logic/GameThreadWorker.h +++ b/src/Logic/GameThreadWorker.h @@ -13,7 +13,9 @@ #include "../Network/Client.h" #include "../Network/MessageHandler.h" -#include "../common/src/Async/AsyncUnorderedMap.h" +#include "ClientGameMapping.h" + +#include "../../common/src/Async/AsyncUnorderedMap.h" class Client; class Npc; @@ -40,14 +42,16 @@ class MessageHandler; class GameThreadWorker { public: - GameThreadWorker(); + /** + * @brief Associates a specific client with the message handler. + * + * @param client Reference to the client instance. + */ + GameThreadWorker(Client &client); /** * @brief Pointer to a map containing active NPC clients, indexed by their IP/Port combination. */ - AsyncUnorderedMap *clients; - - ~GameThreadWorker(); - + AsyncUnorderedMap clients; /** * @brief Processes incoming network messages. @@ -78,13 +82,6 @@ class GameThreadWorker { * This method is called when a task has been completed. */ void removeTask(); - - /** - * @brief Associates a specific client with the message handler. - * - * @param client Reference to the client instance. - */ - void setClientForHandler(Client &client); private: /** * @brief Queue of tasks to be processed by the game thread. @@ -93,7 +90,11 @@ class GameThreadWorker { /** * @brief Pointer to the MessageHandler responsible for processing communication. */ - MessageHandler * messageHandler; + /*MessageHandler * messageHandler; + Npc *pMainPlayer;*/ + + std::unique_ptr messageHandler; + std::unique_ptr pMainPlayer; - Npc *pMainPlayer; + std::unique_ptr mapping; }; \ No newline at end of file diff --git a/src/Logic/Playground.h b/src/Logic/Playground.h new file mode 100644 index 0000000..e6c90a8 --- /dev/null +++ b/src/Logic/Playground.h @@ -0,0 +1,89 @@ +#pragma once + +#include +#include +#include + +#include "../Models/GlobalFunctions.h" + +#include "../Wrapper/OCNpc.h" +#include "../Wrapper/zCModel.h" +#include "../Wrapper/OCWorld.h" + +#include "../Network/Client.h" +#include "../Network/MessageHandler.h" + +#include "ClientGameMapping.h" + +#include "../common/src/Async/AsyncUnorderedMap.h" +#include "../Wrapper/oCItem.h" +#include "../Wrapper/oCMsgWeapon.h" + + +class Client; +class Npc; +class MessageHandler; + +class Playground { + + public: + Playground(){ + pMainPlayer = std::make_unique(ADDR_PLAYERBASE); + } + + void doThing(){ + /* ################ Custom Shit Here################# */ + if (GetAsyncKeyState(VK_RSHIFT) < 0) + { + + if(npc == nullptr) { + npc = new Npc(); + npc->setCurrentHealth(10); + npc->setMaxHealth(10); + npc->oCNpc->setVisualWithString("HUMANS.MDS"); + npc->oCNpc->setAdditionalVisuals("hum_body_Naked0", 9, 0, "Hum_Head_Pony", 2, 0, -1); + //npc->oCNpc->setTalentValue(0, 10); // Strength + //npc->oCNpc->setTalentValue(1, 10); //Dexterity + npc->oCNpc->callVariable(OCNpc::Offset::DEXTERITY) = 10; + npc->oCNpc->callVariable(OCNpc::Offset::STRENGTH) = 10; + npc->oCNpc->enableWithdCoords(pMainPlayer->getX(), pMainPlayer->getZ(), pMainPlayer->getY()); + npc->setName("Steve"); + + } else { + std::cout << "Setting Anims..\n"; + DataStructures::LastAnimation npcLastAnim = npc->getLastAnimation(); + DataStructures::LastAnimation npcNewAnim = pMainPlayer->getLastAnimation(); + std::unique_ptr npcModel = std::make_unique(npc->oCNpc->getModel()); + + + for (auto &newId : npcNewAnim.animationIds) + { + npcModel->startAniInt(newId, 0); + } + + for (auto &lastId : npcLastAnim.animationIds) + { + bool found = false; + for (auto &newId : npcNewAnim.animationIds) + { + if (lastId == newId) + { + found = true; + } + } + if (!found) + { + void *aniActive = npcModel->getActiveAni(lastId); + if (aniActive) + npcModel->stopAnimationInt(lastId); + } + } + + } + } + + } + private: + std::unique_ptr pMainPlayer; + Npc *npc; +}; \ No newline at end of file diff --git a/src/Logic/sMain.cpp b/src/Logic/sMain.cpp deleted file mode 100644 index 5d4b58f..0000000 --- a/src/Logic/sMain.cpp +++ /dev/null @@ -1,262 +0,0 @@ -#include "sMain.h" -#include -sMain::sMain() -{ - InitTrainer(); -} - -void sMain::InitTrainer() -{ -} - -struct OCGameRef -{ - typedef void(__thiscall *_Func)(void *pThis); - _Func pause; - _Func unPause; - _Func init; - - typedef void(__thiscall *_FuncOneParam)(void *pThis, bool param); - _FuncOneParam openSaveScreen; - - typedef int(__thiscall *_RetFunc)(void *pThis); - _RetFunc getShowPlayerStatus; - _RetFunc getDrawWaynet; - - typedef int(__thiscall *_RetFunc2)(void *pThis, int enumNumber); - _RetFunc2 openView; - - typedef void *(__thiscall *_GetSpawnManager)(void *pThis); - _GetSpawnManager getSpawnManager; - - typedef void *(__thiscall *_EnterWorld)(void *pThis, void *npc, int param_2, zSTRING *str); - _EnterWorld enterWorld; - - void *pThis = *(void **)0x8DA6BC; // Adresse von oCGame -} oCGame; - -struct OCWorldRef -{ - - typedef void(__thiscall *_AddVob)(void *pThis, void *vobParam); - _AddVob addVob; - - typedef unsigned long(__thiscall *_GetVobHashIndex)(void *pThis, void *vobParam); - _GetVobHashIndex getVobHashIndex; - - typedef void(__thiscall *_PrintStatus)(void *pThis); - _PrintStatus printStatus; - - void *pThis = *(void **)(((uintptr_t)oCGame.pThis) + 0x8c); // WORKS TOO -} oCWorldRef; - -struct OCSpawnManagerRef -{ - typedef void *(__thiscall *_SummonNpc)(void *pThis, int param1, ZVec3 *coords, float param3); - _SummonNpc summonNpc; - - typedef void(__thiscall *_SpawnImmediately)(void *pThis, int param1); - _SpawnImmediately spawnImmediately; - typedef void(__thiscall *_SpawnNpcVec)(void *pThis, void *npc, ZVec3 *coords, float param3); - _SpawnNpcVec spawnNpcVec; - typedef void(__thiscall *_SpawnNpcString)(void *pThis, void *npc, zSTRING *coords, float param3); - _SpawnNpcString spawnNpcString; - - // Getting the base address of oCGame and adding offset to turn it into oCSpawnManager - void *pThis = *(void **)(((uintptr_t)oCGame.pThis) + 0x134); -} oCSpawnManager; - -struct OCAntiCrtl_HumanRef -{ - typedef void(__thiscall *_SetWalkMode)(void *pThis, int param1); - _SetWalkMode setWalkMode; - - typedef void(__thiscall *_ToggleWalkMode)(void *pThis, int param1); - _ToggleWalkMode toggleWalkMode; - - typedef int(__thiscall *_IsWalking)(void *pThis); - _IsWalking isWalking; - - // Getting the base address of oCGame and adding offset to turn it into oCSpawnManager - - void *pThis = *(void **)((ADDR_PLAYERBASE) + 0x9b4); -} oCAntiCrtl_HumanRef; - -struct ZCViewRef -{ - typedef void(__thiscall *_PrintMessage)(void *pThis, zSTRING *param_1, zSTRING *param_2, float param_3, ZCOLOR *param_4); - _PrintMessage printMessage; - - typedef void(__thiscall *_PrintTimed)(void *pThis, int param_1, int param_2, zSTRING *param_3, float param_4, ZCOLOR *param_5); - _PrintTimed printTimed; - - typedef void(__thiscall *_Printwin)(void *pThis, zSTRING *str); - _Printwin printwin; - - typedef void(__thiscall *_Open)(void *pThis); - _Open open; - - void *pThis = *(void **)0x8de1bc; // Adresse von CView -} zCViewRef; - -void initAddresses() -{ - oCAntiCrtl_HumanRef.setWalkMode = (OCAntiCrtl_HumanRef::_SetWalkMode)(0x6211e0); - oCAntiCrtl_HumanRef.toggleWalkMode = (OCAntiCrtl_HumanRef::_SetWalkMode)(0x624e30); - oCAntiCrtl_HumanRef.isWalking = (OCAntiCrtl_HumanRef::_IsWalking)(0x6257e0); - - oCWorldRef.addVob = (OCWorldRef::_AddVob)(0x5f6340); - oCWorldRef.getVobHashIndex = (OCWorldRef::_GetVobHashIndex)(0x5f9720); - oCWorldRef.printStatus = (OCWorldRef::_PrintStatus)(0x5f6bf0); - - oCSpawnManager.spawnNpcVec = (OCSpawnManagerRef::_SpawnNpcVec)((0x6d0710)); - oCSpawnManager.spawnImmediately = (OCSpawnManagerRef::_SpawnImmediately)((0x6cf800)); - oCSpawnManager.spawnNpcString = (OCSpawnManagerRef::_SpawnNpcString)((0x6d04c0)); - oCSpawnManager.summonNpc = (OCSpawnManagerRef::_SummonNpc)((0x6d0350)); - - zCViewRef.open = (ZCViewRef::_Open)(0x006fd070); // does something... - zCViewRef.printwin = (ZCViewRef::_Printwin)((0x700d20)); - zCViewRef.printTimed = (ZCViewRef::_PrintTimed)((0x6fe1a0)); - zCViewRef.printMessage = (ZCViewRef::_PrintMessage)(0x6fe5c0); - - oCGame.pause = (OCGameRef::_Func)(0x7dcc48); - oCGame.unPause = (OCGameRef::_Func)((*(DWORD *)0x7dcc4c)); - oCGame.openSaveScreen = (OCGameRef::_FuncOneParam)((*(DWORD *)0x7dcc88)); - oCGame.getDrawWaynet = (OCGameRef::_RetFunc)((*(DWORD *)0x7dcc54)); - oCGame.init = (OCGameRef::_Func)((*(DWORD *)0x7dcbf4)); - oCGame.openView = (OCGameRef::_RetFunc2)(0x425d4d); - oCGame.enterWorld = (OCGameRef::_EnterWorld)(0x63ead0); - - globalFunction.printDebug = (GlobalFunctions::_PrintDebug)(0x645280); - globalFunction.stdPrintWin = (GlobalFunctions::_StdPrintwin)(0x6fc420); - globalFunction.print = (GlobalFunctions::_Print)(0x756e00); - globalFunction.openCheatConsole = (GlobalFunctions::_CheatConsole)(0x647129); -} - -void sMain::setPositions() -{ - for (const auto& pair : *clients) { - std::string key = pair.first; // Zeiger auf den Schlüssel - Npc* value = pair.second; // Zeiger auf den Wert - - // Verarbeitung der Schlüssel-Wert-Paare - std::cout << "Key: " << key << ", Value: " << value << std::endl; - } - -} - -void sMain::listenToKeys(ImGuiData &imGuiData) -{ - clients = new std::unordered_map(); - //imGuiData.clients = clients; - - // ----- SERVER SHIT - /*boost::asio::io_context io_context; - - // Erstelle den Client - Client client(io_context, "192.168.0.209", "12345", clients); - - // Hauptschleife, um Nachrichten zu senden - std::thread io_thread([&io_context]() - { io_context.run(); });*/ - - // ----- ----- - - initAddresses(); - - Npc *mainPlayer = new Npc(ADDR_PLAYERBASE); - ZVec3 tempPosition; - - while (true) - { - - // Tp to Old Camp - if (GetAsyncKeyState(VK_RSHIFT) < 0) - { - std::cout << "Pressed Shift! \n"; - - zMAT4 matrix; - - mainPlayer->oCNpc->getTrafoModelNodeToWorld(&matrix, 0); // Zweiter Parameter: Knotenspezifikation (0 = kein spezifischer Knoten) - - // Rotation extrahieren - float yaw = atan2(matrix[0][2], matrix[0][0]); - float pitch = asin(-matrix[0][1]); - float roll = atan2(matrix[1][2], matrix[2][2]); - - std::cout << "Yaw: " << yaw << ", Pitch: " << pitch << ", Roll: " << roll << std::endl; - - //oCAntiCrtl_HumanRef.setWalkMode(oCAntiCrtl_HumanRef.pThis, 0); - //oCAntiCrtl_HumanRef.toggleWalkMode(oCAntiCrtl_HumanRef.pThis, 1); - - - /*int isJumping = oCAntiCrtl_HumanRef.isWalking(oCAntiCrtl_HumanRef.pThis); - std::cout << "Jumping: " << isJumping << "\n";*/ - - Sleep(400); - /*mainPlayer->setPlayerPosition(-10112.5f, 7768, -900); - std::cout << "Teleported to Old Camp" << std::endl;*/ - } - - // Spawn NPC - if (GetAsyncKeyState(VK_DELETE) < 0) - { - mainPlayer->oCNpc->getPositionWorld(&tempPosition); - std::cout << tempPosition.getPos() << std::endl; - - Npc *npc = new Npc(); - npc->setCurrentHealth(10); - npc->setMaxHealth(10); - npc->oCNpc->setVisualWithString("HUMANS.MDS"); - npc->oCNpc->setAdditionalVisuals("hum_body_Naked0", 9, 0, "Hum_Head_Pony", 2, 0, -1); - - npc->oCNpc->enable(&tempPosition); - - // Set same View direction as player - zMAT4 matrix; - mainPlayer->oCNpc->getTrafoModelNodeToWorld(&matrix, 0); - npc->oCNpc->setTrafo(&matrix); - } - - // Hide/Show Menu - if (GetKeyState(VK_HOME) < 0) - { - imGuiData.toggleGuiVisibility(); - std::cout << "Pressed Home" << std::endl; - } - - // Ejects the DLL - if (GetAsyncKeyState(VK_END)) - { - break; - } - - // Sets or refreshes the Position of NPC's - //setPositions(); - - - /*zMAT4 matrix; - mainPlayer->oCNpc->getTrafoModelNodeToWorld(&matrix, 0); // Zweiter Parameter: Knotenspezifikation (0 = kein spezifischer Knoten) - - // Rotation extrahieren - float yaw = atan2(matrix[0][2], matrix[0][0]); - float pitch = asin(-matrix[0][1]); - float roll = atan2(matrix[1][2], matrix[2][2]); - - Data data; - data.id = 101; - data.names.push_back(std::to_string(mainPlayer->getX())); - data.names.push_back(std::to_string(mainPlayer->getZ())); - data.names.push_back(std::to_string(mainPlayer->getY())); - data.names.push_back(std::to_string(yaw)); - data.names.push_back(std::to_string(pitch)); - data.names.push_back(std::to_string(roll)); - - std::string bufferStr = data.serialize(); - client.send_message(bufferStr);*/ - - Sleep(1000); - } - - //io_thread.join(); -} \ No newline at end of file diff --git a/src/Logic/sMain.h b/src/Logic/sMain.h deleted file mode 100644 index 5b87fc0..0000000 --- a/src/Logic/sMain.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#define WIN32_LEAN_AND_MEAN -#include - -#include -#include - -#include "../Network/Client.h" - -#include "../Models/Npc.h" -#include "../Models/GlobalFunctions.h" - -#include "../Models/ImGuiData.h" - -#include "../Wrapper/ZCVob.h" -#include "../Wrapper/ZCOLOR.h" -#include "../Wrapper/ZCView.h" -#include "../Wrapper/zSTRING.h" -#include "../Wrapper/ZVec3.h" -#include "../Wrapper/OCSpawnManager.h" -#include "../Wrapper/OCNpc.h" - -class sMain -{ - private: - //~sMain(); - void InitTrainer(); - - void setPositions(); - public: - sMain(); - void listenToKeys(ImGuiData &imGuiData); - - std::unordered_map *clients; -}; diff --git a/src/Models/Npc.cpp b/src/Models/Npc.cpp index 6b6606f..a7d96c6 100644 --- a/src/Models/Npc.cpp +++ b/src/Models/Npc.cpp @@ -231,7 +231,7 @@ DataStructures::LastPosition Npc::getLastPosition() { return retLastPos; } -DataStructures::LastAnimation Npc::getLastAnimation() { +DataStructures::LastAnimation Npc::getLastAnimation() {// TODO: Improve this shit DataStructures::LastAnimation retLastAnim; zCModel *npcModel = new zCModel(oCNpc->getModel()); diff --git a/src/Models/Npc.h b/src/Models/Npc.h index 40b34d0..c9e67c8 100644 --- a/src/Models/Npc.h +++ b/src/Models/Npc.h @@ -55,6 +55,13 @@ class Npc void setInterpolatePosition(float x, float z, float y); + struct NetworkState { + DataStructures::LastPosition position; + DataStructures::LastAnimation animation; + DataStructures::LastEquip equip; + DataStructures::LastRotation rotation; + } networkState; + DataStructures::LastPosition getLastPosition(); DataStructures::LastAnimation getLastAnimation(); DataStructures::LastEquip getLastEquip(); diff --git a/src/Network/Client.cpp b/src/Network/Client.cpp index b63bd50..ad3a8b4 100644 --- a/src/Network/Client.cpp +++ b/src/Network/Client.cpp @@ -1,19 +1,20 @@ #include "Client.h" -Client::Client(boost::asio::io_context &io_context, const std::string &username, const std::string &host, const std::string &port, GameThreadWorker *gameThreadWorker) +Client::Client(boost::asio::io_context &io_context, const std::string &username, const std::string &host, const std::string &port, GameThreadWorker *& gameThreadWorker) : socket_(io_context), resolver_(io_context), username(username), server_endpoint_(*resolver_.resolve(udp::v4(), host, port).begin()) { - this->gameThreadWorker = gameThreadWorker; + + gameThreadWorker = new GameThreadWorker(*this); + this->pGameThreadWorker = gameThreadWorker; socket_.open(udp::v4()); start_receive(); - gameThreadWorker->setClientForHandler(*this); } Client::~Client() { delete mainPlayer; - delete gameThreadWorker; + delete pGameThreadWorker; } Npc * Client::getMainPlayer(){ @@ -58,7 +59,7 @@ void Client::start_receive() std::fill(recv_buffer_.begin(), recv_buffer_.end(), 0); // Paket verarbeiten - this->gameThreadWorker->addTask(receivedPackage); + this->pGameThreadWorker->addTask(receivedPackage); } else { diff --git a/src/Network/Client.h b/src/Network/Client.h index fe10f98..cc7dd09 100644 --- a/src/Network/Client.h +++ b/src/Network/Client.h @@ -5,8 +5,8 @@ #include #include -#include "../common/src/Network/PackagingSystem.h" -#include "../common/src/Network/Packets.h" +#include "../../common/src/Network/PackagingSystem.h" +#include "../../common/src/Network/Packets.h" #include "../Logic/GameThreadWorker.h" #include "../Models/Npc.h" @@ -31,7 +31,7 @@ class Client * @param port The server port number. * @param gameThreadWorker Pointer to the game thread worker for processing game-related tasks. */ - Client(boost::asio::io_context &io_context, const std::string &username, const std::string &host, const std::string &port, GameThreadWorker *gameThreadWorker); + Client(boost::asio::io_context &io_context, const std::string &username, const std::string &host, const std::string &port, GameThreadWorker *& gameThreadWorker); ~Client(); void send_message(const std::string &message); @@ -49,7 +49,7 @@ class Client const bool isConnected() const; private: - GameThreadWorker *gameThreadWorker; + GameThreadWorker *pGameThreadWorker; Npc *mainPlayer = new Npc(ADDR_PLAYERBASE); std::string username; udp::socket socket_; diff --git a/src/Network/MessageHandler.cpp b/src/Network/MessageHandler.cpp index 62cc785..eb3ecbc 100644 --- a/src/Network/MessageHandler.cpp +++ b/src/Network/MessageHandler.cpp @@ -1,11 +1,8 @@ #include "MessageHandler.h" -MessageHandler::MessageHandler(AsyncUnorderedMap *pClients) : pClients(pClients) +MessageHandler::MessageHandler(AsyncUnorderedMap *pClients, Client &client) : pClients(pClients), pClient(&client) { -} -void MessageHandler::setClient(Client &client) -{ - this->pClient = &client; + } void MessageHandler::managePacket(std::string stringPacket) @@ -189,6 +186,9 @@ void MessageHandler::handleServerDistributeAnimations(std::string &buffer) npcModel->stopAnimationInt(lastId); } } + + // Handy for ClientGameMapping and DataChangeNotifier Class + value->networkState.animation = npcNewAnim; } void MessageHandler::handleServerDistributeEquip(std::string &buffer) diff --git a/src/Network/MessageHandler.h b/src/Network/MessageHandler.h index e55103b..0c69ecf 100644 --- a/src/Network/MessageHandler.h +++ b/src/Network/MessageHandler.h @@ -7,10 +7,10 @@ #include "../Models/Npc.h" #include "../Wrapper/zCModel.h" #include "../Network/Client.h" -#include "../common/src/Network/Packets.h" -#include "../common/src/Network/PackagingSystem.h" -#include "../common/src/Async/AsyncUnorderedMap.h" -#include "../common/src/Async/Async.h" +#include "../../common/src/Network/Packets.h" +#include "../../common/src/Network/PackagingSystem.h" +#include "../../common/src/Async/AsyncUnorderedMap.h" +#include "../../common/src/Async/Async.h" class Client; /** @@ -26,8 +26,9 @@ class MessageHandler /** * @brief Constructs a MessageHandler instance. * @param pClients Pointer to a map storing connected NPCs, indexed by their unique identifier. + * @param client Reference to the Client instance responsible for network communication. */ - MessageHandler(AsyncUnorderedMap *pClients); + MessageHandler(AsyncUnorderedMap *pClients, Client &client); /** * @brief Processes an incoming packet string. * @param stringPacket The raw packet data received from the server. @@ -35,11 +36,6 @@ class MessageHandler * This function determines the type of packet and calls the appropriate handler method. */ void managePacket(std::string stringPacket); - /** - * @brief Associates a Client instance with the message handler. - * @param client Reference to the Client instance responsible for network communication. - */ - void setClient(Client &client); private: AsyncUnorderedMap *pClients; ///< Pointer to the map storing NPCs currently in the game. diff --git a/src/Wrapper/zCModelAniActive.cpp b/src/Wrapper/zCModelAniActive.cpp new file mode 100644 index 0000000..7040703 --- /dev/null +++ b/src/Wrapper/zCModelAniActive.cpp @@ -0,0 +1,2 @@ +#include "zCModelAniActive.h" + diff --git a/src/Wrapper/zCModelAniActive.h b/src/Wrapper/zCModelAniActive.h new file mode 100644 index 0000000..3115bbb --- /dev/null +++ b/src/Wrapper/zCModelAniActive.h @@ -0,0 +1,12 @@ +#pragma once + + +class zCModelAniActive { + public: + + + private: + + + +}; \ No newline at end of file diff --git a/src/dllmain.cpp b/src/dllmain.cpp index 447060d..4ab9769 100644 --- a/src/dllmain.cpp +++ b/src/dllmain.cpp @@ -10,11 +10,12 @@ #include "Logic/GameThreadWorker.h" #include "Models/ImGuiData.h" #include "Logic/ImGuiManager.h" -#include "Logic/sMain.h" #include "Network/DataChangeNotifier.h" #include "../common/src/IniManager.h" #include "Models/IniData.h" +#include "Logic/Playground.h" + // Globals HINSTANCE dll_handle; @@ -76,9 +77,9 @@ LRESULT __stdcall WndProc(const HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lPar ImGuiData imGuiData; ImGuiManager *guiManager; -sMain *mainLoop = new sMain(); -GameThreadWorker *gameThreadWorker = new GameThreadWorker(); +GameThreadWorker *gameThreadWorker = nullptr;//new GameThreadWorker(); +Playground playground; bool visibleGui = true; bool init = false; @@ -112,11 +113,16 @@ HRESULT __stdcall detour_present(IDXGISwapChain *p_swap_chain, UINT sync_interva return p_present(p_swap_chain, sync_interval, flags); } - // Handling Tasks from Server - gameThreadWorker->processMessages(); - - // Handling Game things, like Rendering of NPCs - gameThreadWorker->checkGameState(); + if(gameThreadWorker) { + // Handling Tasks from Server + gameThreadWorker->processMessages(); + + // Handling Game things, like Rendering of NPCs + gameThreadWorker->checkGameState(); + } + + playground.doThing(); + guiManager->startOfMainLoop(); guiManager->showContent(imGuiData); @@ -214,7 +220,8 @@ DWORD WINAPI MainThread() } // give imGui players Information - imGuiData.clients = *gameThreadWorker->clients->getUnorderedMap(); + if(gameThreadWorker) + imGuiData.clients = *gameThreadWorker->clients.getUnorderedMap(); Sleep(80); } io_thread.join(); From ef6a349ee9da2de94e1abdf0895e439d39b90a2b Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Sun, 27 Jul 2025 11:17:17 +0200 Subject: [PATCH 08/11] added lambda access for map --- common/src/Async/AsyncUnorderedMap.h | 11 +++++++-- server/src/MessageHandler.cpp | 37 ++++++++++++++-------------- server/src/ServerManager.cpp | 13 +++------- src/Models/Npc.cpp | 2 +- 4 files changed, 33 insertions(+), 30 deletions(-) diff --git a/common/src/Async/AsyncUnorderedMap.h b/common/src/Async/AsyncUnorderedMap.h index 88bb040..65bcd47 100644 --- a/common/src/Async/AsyncUnorderedMap.h +++ b/common/src/Async/AsyncUnorderedMap.h @@ -2,6 +2,8 @@ #include #include #include +#include + template class AsyncUnorderedMap { @@ -25,6 +27,11 @@ class AsyncUnorderedMap { return false; } + void accessMap (std::function&)> userFunction) { + std::lock_guard lock(this->mtxMap); + userFunction(map); + } + std::optional> find(const T1& key) { auto it = map.find(key); if(it != map.end()) @@ -36,10 +43,10 @@ class AsyncUnorderedMap { std::unordered_map *getUnorderedMap() { return &this->map; } - +/* std::mutex &getMutex() { return mtxMap; - } + }*/ /*T at(); int size();*/ diff --git a/server/src/MessageHandler.cpp b/server/src/MessageHandler.cpp index c7de06e..0e46cf0 100644 --- a/server/src/MessageHandler.cpp +++ b/server/src/MessageHandler.cpp @@ -121,9 +121,8 @@ void MessageHandler::clientHandshakeRequest(udp::endpoint &clientEndpoint, std:: // ################################### // ###### SEND EVERYONE ELSE TO CLIENT ###### - { - std::lock_guard lock(clients->getMutex()); - for (auto it = clients->getUnorderedMap()->begin(); it != clients->getUnorderedMap()->end(); ++it) + clients->accessMap([&](auto &map) { + for (auto it = map.begin(); it != map.end(); ++it) { if(it->first == clientPortIp) continue; @@ -144,7 +143,7 @@ void MessageHandler::clientHandshakeRequest(udp::endpoint &clientEndpoint, std:: sendMessage(clientEndpoint, playerInfo.serializePacket()); } - } + }); // ################################### } @@ -243,12 +242,13 @@ void MessageHandler::sendMessage(udp::endpoint &clientEndpoint, std::string buff /// NEEDS A REWORK void MessageHandler::sendToAllExceptSender(udp::endpoint &senderEndpoint, std::string buffer) { - std::lock_guard lock(clients->getMutex()); - for (auto it = clients->getUnorderedMap()->begin(); it != clients->getUnorderedMap()->end(); ++it) - { - //if (senderEndpoint != it->second.endpoint) // Uncomment for main branch - sendMessage(it->second.endpoint, buffer); - } + clients->accessMap([&](auto &map){ + for (auto it = map.begin(); it != map.end(); ++it) + { + //if (senderEndpoint != it->second.endpoint) // Uncomment for main branch + sendMessage(it->second.endpoint, buffer); + } + }); } void MessageHandler::removeClient(udp::endpoint &clientEndpoint) @@ -258,14 +258,15 @@ void MessageHandler::removeClient(udp::endpoint &clientEndpoint) if(clients->existsItem(clientPortIp)) clients->remove(clientPortIp); - std::lock_guard lock(clients->getMutex()); - // Telling the Clients to remove unreachable client - for (auto &pair : *clients->getUnorderedMap()) - { - PackagingSystem clientToRemove(Packets::ServerPacket::serverRemoveClient); - clientToRemove.addString(clientPortIp); - sendMessage(pair.second.endpoint, clientToRemove.serializePacket()); - } + + clients->accessMap([&](auto &map) { + for (auto &pair : map) + { + PackagingSystem clientToRemove(Packets::ServerPacket::serverRemoveClient); + clientToRemove.addString(clientPortIp); + sendMessage(pair.second.endpoint, clientToRemove.serializePacket()); + } + }); updateConsoleTitle(); } diff --git a/server/src/ServerManager.cpp b/server/src/ServerManager.cpp index 4ce2ae4..3ced7fa 100644 --- a/server/src/ServerManager.cpp +++ b/server/src/ServerManager.cpp @@ -53,7 +53,6 @@ void ServerManager::start_receive() else { Async::PrintLn( "\nError receiving: " + error.message()); - //std::cerr << "\nError receiving: " << error.message() << "\n"; messageHandler->removeClient(*sender_endpoint); // repeat receiving @@ -65,19 +64,16 @@ void ServerManager::start_receive() void ServerManager::watchingHeartbeat() { while(serverRunning) { std::queue endpointsToRemove; - { - std::lock_guard lock(clients.getMutex()); - for (auto it = clients.getUnorderedMap()->begin(); it != clients.getUnorderedMap()->end(); ++it) + clients.accessMap([&](auto &map) { + for (auto it = map.begin(); it != map.end(); ++it) { auto currentTime = std::chrono::high_resolution_clock::now(); std::chrono::duration elapsed = currentTime - it->second.lastResponse; int durrationInSec = static_cast(elapsed.count()/1000); - if(durrationInSec >= 10/*25*/) { + if(durrationInSec >= 10) { endpointsToRemove.push(it->second.endpoint); - //messageHandler->removeClient(it->second.endpoint); } else if( durrationInSec >= 5) { - //std::cout << "Elapsed Time: " << durrationInSec << " seconds" << std::endl; Async::PrintLn( "Elapsed Time: " + std::to_string(durrationInSec) + " seconds"); // Sending every 5 Seconds a Heartbeat request if(durrationInSec % 5 == 0){ @@ -86,8 +82,7 @@ void ServerManager::watchingHeartbeat() { } } } - } - + }); while (!endpointsToRemove.empty()) { udp::endpoint endpoint = endpointsToRemove.front(); endpointsToRemove.pop(); diff --git a/src/Models/Npc.cpp b/src/Models/Npc.cpp index a7d96c6..2711bfb 100644 --- a/src/Models/Npc.cpp +++ b/src/Models/Npc.cpp @@ -239,7 +239,7 @@ DataStructures::LastAnimation Npc::getLastAnimation() {// TODO: Improve this shi retLastAnim.animationCount = animCount; for(int i = 0; i < animCount; i++) { - uintptr_t addr = reinterpret_cast(npcModel->getAddress())+ 0x38 + (i * 4) ; + uintptr_t addr = reinterpret_cast(npcModel->getAddress())+ 0x38 + (i * 4) ; // 0x38 = zCModelAniActive void * pp = reinterpret_cast (addr); uintptr_t addr2 = *reinterpret_cast(pp); From 30fad3a04511da01b7c2bb86d9c5d7ef6ba8b90e Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Sun, 27 Jul 2025 11:23:39 +0200 Subject: [PATCH 09/11] added description --- common/src/Async/AsyncUnorderedMap.h | 51 ++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/common/src/Async/AsyncUnorderedMap.h b/common/src/Async/AsyncUnorderedMap.h index 65bcd47..4a8d479 100644 --- a/common/src/Async/AsyncUnorderedMap.h +++ b/common/src/Async/AsyncUnorderedMap.h @@ -4,20 +4,47 @@ #include #include - +/** + * @brief A thread-safe wrapper around std::unordered_map. + * + * This class provides synchronized access to an unordered_map using a mutex, + * allowing safe concurrent usage in multithreaded environments. + * + * @tparam T1 Key type + * @tparam T2 Value type + */ template class AsyncUnorderedMap { public: + + /** + * @brief Inserts a key-value pair into the map. + * If the key already exists, the value is not updated. + * + * @param key The key to insert + * @param value The value to associate with the key + */ void append(T1 key, T2 value) { std::lock_guard lock(this->mtxMap); map.insert({key, value}); } + /** + * @brief Removes an entry by key. + * + * @param key The key to remove + */ void remove(T1 key) { std::lock_guard lock(this->mtxMap); map.erase(key); } + /** + * @brief Checks whether the map contains the specified key. + * + * @param key The key to look for + * @return true if key exists, false otherwise + */ bool existsItem(T1 key) { std::lock_guard lock(this->mtxMap); auto it = map.find(key); @@ -27,11 +54,23 @@ class AsyncUnorderedMap { return false; } + /** + * @brief Grants access to the internal map via a user-defined function. + * The map is locked during this operation. + * + * @param userFunction A function that takes a reference to the map + */ void accessMap (std::function&)> userFunction) { std::lock_guard lock(this->mtxMap); userFunction(map); } + /** + * @brief Finds a value by key and returns it as a reference. + * + * @param key The key to look for + * @return std::optional containing a reference to the value if found, or std::nullopt otherwise + */ std::optional> find(const T1& key) { auto it = map.find(key); if(it != map.end()) @@ -40,6 +79,12 @@ class AsyncUnorderedMap { return std::nullopt; } + /** + * @brief Returns a raw pointer to the internal unordered_map. + * Use with caution. No synchronization is applied. + * + * @return Pointer to the internal map + */ std::unordered_map *getUnorderedMap() { return &this->map; } @@ -54,6 +99,6 @@ class AsyncUnorderedMap { void unlock();*/ private: - std::unordered_map map; - std::mutex mtxMap; + std::unordered_map map; ///< The internal key-value map + std::mutex mtxMap; ///< Mutex for thread-safe access }; From b6158586f0d97e7d2341a0fdf8c22b8715c2883f Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Sun, 27 Jul 2025 13:00:17 +0200 Subject: [PATCH 10/11] added weaopnmode --- common/src/Network/Packets.h | 4 +++- server/src/MessageHandler.cpp | 15 +++++++++++++++ server/src/MessageHandler.h | 1 + src/Logic/Playground.h | 8 +++++++- src/Models/DataStructures.h | 14 ++++++++++++++ src/Models/Npc.cpp | 9 +++++++++ src/Models/Npc.h | 1 + src/Models/WeaponMode.h | 10 ++++++++++ src/Network/Client.cpp | 15 ++++++++++++++- src/Network/Client.h | 1 + src/Network/DataChangeNotifier.cpp | 7 +++++++ src/Network/DataChangeNotifier.h | 1 + src/Network/MessageHandler.cpp | 24 ++++++++++++++++++++++++ src/Network/MessageHandler.h | 3 +++ src/Wrapper/OCNpc.cpp | 11 +++++++++++ src/Wrapper/OCNpc.h | 5 +++++ src/dllmain.cpp | 9 ++++++--- 17 files changed, 132 insertions(+), 6 deletions(-) create mode 100644 src/Models/WeaponMode.h diff --git a/common/src/Network/Packets.h b/common/src/Network/Packets.h index b32a85e..6f127c6 100644 --- a/common/src/Network/Packets.h +++ b/common/src/Network/Packets.h @@ -7,6 +7,7 @@ namespace Packets { serverRequestHeartbeat, serverDistributePosition, serverDistributeAnimations, + serverDistributeWeaponMode, serverDistributeEquip, serverRemoveClient @@ -17,7 +18,8 @@ namespace Packets { clientResponseHeartbeat, clientSharePosition, clientShareAnimations, - clientShareEquip + clientShareWeaopnMode, + clientShareEquip, }; } \ No newline at end of file diff --git a/server/src/MessageHandler.cpp b/server/src/MessageHandler.cpp index 0e46cf0..0363558 100644 --- a/server/src/MessageHandler.cpp +++ b/server/src/MessageHandler.cpp @@ -41,6 +41,9 @@ void MessageHandler::handleBuffer(udp::endpoint &clientEndpoint, std::string buf case Packets::ClientPacket::clientShareAnimations: clientSharesAnimations(clientEndpoint, buffer); break; + case Packets::ClientPacket::clientShareWeaopnMode: + clientSharesWeaponMode(clientEndpoint, buffer); + break; case Packets::ClientPacket::clientShareEquip: clientSharesEquip(clientEndpoint, buffer); break; @@ -198,6 +201,18 @@ void MessageHandler::clientSharesAnimations(udp::endpoint &clientEndpoint, std:: sendToAllExceptSender(clientEndpoint, animationPacket.serializePacket()); } +void MessageHandler::clientSharesWeaponMode(udp::endpoint &clientEndpoint, std::string &buffer) +{ + auto safeBuffer = std::make_shared(buffer); + std::string clientPortIp = getClientUniqueString(clientEndpoint); + + PackagingSystem weaponModePacket(Packets::ServerPacket::serverDistributeWeaponMode); + weaponModePacket.addString(clientPortIp); + weaponModePacket.addInt(PackagingSystem::ReadItem(buffer)); + + sendToAllExceptSender(clientEndpoint, weaponModePacket.serializePacket()); +} + void MessageHandler::clientSharesEquip(udp::endpoint &clientEndpoint, std::string &buffer) { auto safeBuffer = std::make_shared(buffer); diff --git a/server/src/MessageHandler.h b/server/src/MessageHandler.h index 370c698..5d069a8 100644 --- a/server/src/MessageHandler.h +++ b/server/src/MessageHandler.h @@ -34,6 +34,7 @@ class MessageHandler void clientRepondsHeartbeat(udp::endpoint &clientEndpoint, std::string &buffer); void clientSharesPosition(udp::endpoint &clientEndpoint, std::string &buffer); void clientSharesAnimations(udp::endpoint &clientEndpoint, std::string &buffer); + void clientSharesWeaponMode(udp::endpoint &clientEndpoint, std::string &buffer); void clientSharesEquip(udp::endpoint &clientEndpoint, std::string &buffer); bool isClientRegistered(udp::endpoint &clientEndpoint); diff --git a/src/Logic/Playground.h b/src/Logic/Playground.h index e6c90a8..c380cb6 100644 --- a/src/Logic/Playground.h +++ b/src/Logic/Playground.h @@ -50,7 +50,7 @@ class Playground { npc->setName("Steve"); } else { - std::cout << "Setting Anims..\n"; + //std::cout << "Setting Anims..\n"; DataStructures::LastAnimation npcLastAnim = npc->getLastAnimation(); DataStructures::LastAnimation npcNewAnim = pMainPlayer->getLastAnimation(); std::unique_ptr npcModel = std::make_unique(npc->oCNpc->getModel()); @@ -79,6 +79,12 @@ class Playground { } } + /*if(pMainPlayer->oCNpc->getWeaponMode != nullptr){ + std::cout << "Weapon is drawn.\n"; + npc->oCNpc->setWeaponMode(1); + }*/ + std::cout << "WeaponMode: " << std::to_string(pMainPlayer->oCNpc->getWeaponMode()) << "\n"; + npc->oCNpc->setWeaponMode(pMainPlayer->oCNpc->getWeaponMode()); } } diff --git a/src/Models/DataStructures.h b/src/Models/DataStructures.h index 09de6f3..5d46a14 100644 --- a/src/Models/DataStructures.h +++ b/src/Models/DataStructures.h @@ -1,5 +1,6 @@ #pragma once #include +#include "../Models/WeaponMode.h" namespace DataStructures { struct LastPosition { @@ -52,6 +53,19 @@ namespace DataStructures { } }; + struct LastWeaponMode { + WeaponMode weaponMode; + + bool isSame(const LastWeaponMode& lastWeaponMode) { + if (weaponMode == lastWeaponMode.weaponMode) { + return true; + } + + weaponMode = lastWeaponMode.weaponMode; + return false; + } + }; + struct LastEquip { std::string meleeWeaponInstanceName = ""; std::string rangedWeaponInstanceName = ""; diff --git a/src/Models/Npc.cpp b/src/Models/Npc.cpp index 2711bfb..4646109 100644 --- a/src/Models/Npc.cpp +++ b/src/Models/Npc.cpp @@ -248,12 +248,21 @@ DataStructures::LastAnimation Npc::getLastAnimation() {// TODO: Improve this shi uintptr_t addr3 = *reinterpret_cast(pp2); addr3 += 0x4c; int * pp3 = reinterpret_cast (addr3); + retLastAnim.animationIds.push_back(*pp3); } return retLastAnim; } +DataStructures::LastWeaponMode Npc::getLastWeaponMode() { + DataStructures::LastWeaponMode retLastWeaponMode; + + retLastWeaponMode.weaponMode = oCNpc->getWeaponMode(); + + return retLastWeaponMode; +} + DataStructures::LastEquip Npc::getLastEquip() { DataStructures::LastEquip retLastEquip; diff --git a/src/Models/Npc.h b/src/Models/Npc.h index c9e67c8..58793e3 100644 --- a/src/Models/Npc.h +++ b/src/Models/Npc.h @@ -64,6 +64,7 @@ class Npc DataStructures::LastPosition getLastPosition(); DataStructures::LastAnimation getLastAnimation(); + DataStructures::LastWeaponMode getLastWeaponMode(); DataStructures::LastEquip getLastEquip(); DataStructures::LastRotation getLastRotation(); }; \ No newline at end of file diff --git a/src/Models/WeaponMode.h b/src/Models/WeaponMode.h new file mode 100644 index 0000000..b066232 --- /dev/null +++ b/src/Models/WeaponMode.h @@ -0,0 +1,10 @@ +#pragma once + +enum WeaponMode { + DefaultMode, + FistMode, + KA, + OneHandMode, + KA2, + BowMode, +}; \ No newline at end of file diff --git a/src/Network/Client.cpp b/src/Network/Client.cpp index ad3a8b4..abf450a 100644 --- a/src/Network/Client.cpp +++ b/src/Network/Client.cpp @@ -120,19 +120,32 @@ void Client::sendPlayerPosition() void Client::sendPlayerAnimation() { - DataStructures::LastAnimation lastAnim = mainPlayer->getLastAnimation(); + DataStructures::LastAnimation lastAnim = mainPlayer->getLastAnimation(); PackagingSystem packetAnim(Packets::ClientPacket::clientShareAnimations); packetAnim.addInt(lastAnim.animationCount); for(const auto &id : lastAnim.animationIds) { packetAnim.addInt(id); + //std::cout << "AnimId: " << std::to_string(id) << "\n"; } std::string bufferStr = packetAnim.serializePacket(); this->send_message(bufferStr); } +void Client::sendPlayerWeaponMode() +{ + DataStructures::LastWeaponMode lastWMode = mainPlayer->getLastWeaponMode(); + + PackagingSystem packetWeaponMode(Packets::ClientPacket::clientShareWeaopnMode); + + packetWeaponMode.addInt(lastWMode.weaponMode); + + std::string bufferStr = packetWeaponMode.serializePacket(); + this->send_message(bufferStr); +} + void Client::sendPlayerEquip() { DataStructures::LastEquip lastEquip = mainPlayer->getLastEquip(); diff --git a/src/Network/Client.h b/src/Network/Client.h index cc7dd09..a77c843 100644 --- a/src/Network/Client.h +++ b/src/Network/Client.h @@ -40,6 +40,7 @@ class Client void sendHandshakeRequest(); void sendPlayerPosition(); void sendPlayerAnimation(); + void sendPlayerWeaponMode(); void sendPlayerEquip(); void sendPlayerRotation(); diff --git a/src/Network/DataChangeNotifier.cpp b/src/Network/DataChangeNotifier.cpp index 6fe647d..ba4dc78 100644 --- a/src/Network/DataChangeNotifier.cpp +++ b/src/Network/DataChangeNotifier.cpp @@ -21,6 +21,13 @@ void DataChangeNotifier::initListValues() { } }); + playerState.push_back( [this]() { + DataStructures::LastWeaponMode retLastWeaponMode = pMainPlayer->getLastWeaponMode(); + if(!playerLastWeaponMode.isSame(retLastWeaponMode)) { + pClient->sendPlayerWeaponMode(); + } + }); + playerState.push_back( [this]() { DataStructures::LastEquip retLastEquip = pMainPlayer->getLastEquip(); if(!playerLastEquip.isSame(retLastEquip)) { diff --git a/src/Network/DataChangeNotifier.h b/src/Network/DataChangeNotifier.h index db69bf0..2829adf 100644 --- a/src/Network/DataChangeNotifier.h +++ b/src/Network/DataChangeNotifier.h @@ -47,6 +47,7 @@ class DataChangeNotifier DataStructures::LastPosition playerLastPos; DataStructures::LastAnimation playerLastAnim; + DataStructures::LastWeaponMode playerLastWeaponMode; DataStructures::LastEquip playerLastEquip; DataStructures::LastRotation playerLastRotation; }; \ No newline at end of file diff --git a/src/Network/MessageHandler.cpp b/src/Network/MessageHandler.cpp index eb3ecbc..161ae7c 100644 --- a/src/Network/MessageHandler.cpp +++ b/src/Network/MessageHandler.cpp @@ -26,6 +26,9 @@ void MessageHandler::managePacket(std::string stringPacket) case Packets::ServerPacket::serverDistributeAnimations: handleServerDistributeAnimations(stringPacket); break; + case Packets::ServerPacket::serverDistributeWeaponMode: + handleServerDistributeWeaponMode(stringPacket); + break; case Packets::ServerPacket::serverDistributeEquip: handleServerDistributeEquip(stringPacket); break; @@ -191,6 +194,27 @@ void MessageHandler::handleServerDistributeAnimations(std::string &buffer) value->networkState.animation = npcNewAnim; } +void MessageHandler::handleServerDistributeWeaponMode(std::string &buffer) +{ + std::string receivedKey = PackagingSystem::ReadItem(buffer); + + auto it = pClients->find(receivedKey); + if (!it) + { + return; + } + + Npc *value = it.value(); + DataStructures::LastWeaponMode npcLastWeaponMode = value->getLastWeaponMode(); + DataStructures::LastAnimation npcNewAnim; + std::unique_ptr npcModel = std::make_unique(value->oCNpc->getModel()); + + WeaponMode weaponMode = static_cast(PackagingSystem::ReadItem(buffer)); + + if(weaponMode != npcLastWeaponMode.weaponMode) + value->oCNpc->setWeaponMode(weaponMode); +} + void MessageHandler::handleServerDistributeEquip(std::string &buffer) { std::string receivedKey = PackagingSystem::ReadItem(buffer); diff --git a/src/Network/MessageHandler.h b/src/Network/MessageHandler.h index 0c69ecf..66219b5 100644 --- a/src/Network/MessageHandler.h +++ b/src/Network/MessageHandler.h @@ -12,6 +12,8 @@ #include "../../common/src/Async/AsyncUnorderedMap.h" #include "../../common/src/Async/Async.h" +#include "../Models/WeaponMode.h" + class Client; /** * @class MessageHandler @@ -48,6 +50,7 @@ class MessageHandler void handleServerRequestsHeartbeat(std::string &buffer); void handleServerDistributePosition(std::string &buffer); void handleServerDistributeAnimations(std::string &buffer); + void handleServerDistributeWeaponMode(std::string &buffer); void handleServerDistributeEquip(std::string &buffer); void handleServerDistributeRotations(std::string &buffer); void handleServerRemoveClient(std::string &buffer); diff --git a/src/Wrapper/OCNpc.cpp b/src/Wrapper/OCNpc.cpp index 2daee34..c814198 100644 --- a/src/Wrapper/OCNpc.cpp +++ b/src/Wrapper/OCNpc.cpp @@ -284,6 +284,17 @@ void OCNpc::setTalentValue(int talentIndex, int value) setTalentValueRef(this, talentIndex, value); } +void OCNpc::setWeaponMode(WeaponMode mode){ + using _SetWeaponMode = void(__thiscall *)(void *pThis, int mode); + _SetWeaponMode setWeaponModeRef = reinterpret_cast<_SetWeaponMode>(0x696550); + setWeaponModeRef(this, mode); +} + +WeaponMode OCNpc::getWeaponMode(){ + using _GetWeaponMode = int(__thiscall *)(void *pThis); + _GetWeaponMode GetWeaponModeRef = reinterpret_cast<_GetWeaponMode>(0x695820); + return static_cast(GetWeaponModeRef(this)); +} /*zSTRING *OCNpc::getName2(){ zSTRING * nS = zSTRING::CreateNewzSTRING(""); using _GetName = zSTRING* (__thiscall *)(void* pThis); diff --git a/src/Wrapper/OCNpc.h b/src/Wrapper/OCNpc.h index d6c4364..7aff7aa 100644 --- a/src/Wrapper/OCNpc.h +++ b/src/Wrapper/OCNpc.h @@ -9,6 +9,8 @@ #include "oCItem.h" #include "oCMsgWeapon.h" +#include "../Models/WeaponMode.h" + class oCItem; /** * @brief Base memory address for the main player's NPC instance. @@ -151,6 +153,9 @@ class OCNpc int useItem(oCItem * item); void setTalentValue(int talentIndex, int value); + + void setWeaponMode(WeaponMode mode); + WeaponMode getWeaponMode(); //zSTRING *getName2(); /*int applyOverlay(char * animName); diff --git a/src/dllmain.cpp b/src/dllmain.cpp index 4ab9769..13d7d5e 100644 --- a/src/dllmain.cpp +++ b/src/dllmain.cpp @@ -162,11 +162,14 @@ DWORD WINAPI MainThread() SetupConsole(); // ######### INI STUFF ######### - if(!IniData::CreateConfigIfMissing(IniData::CLIENT_CONFIG_FILE)) + if(!IniData::CreateConfigIfMissing(IniData::CLIENT_CONFIG_FILE)){ + std::cout << "Error: Couldn't read/create config...\n"; + Sleep(1500); return -1; - + } + IniData::Ini config = IniData::LoadIni(); - + // ########################### std::cout << "Starting MAIN...\n" From d1c836a382da45c50a0a2963012a37a90c2d3304 Mon Sep 17 00:00:00 2001 From: Warawa <42498260+Banner244@users.noreply.github.com> Date: Sun, 14 Sep 2025 08:29:34 +0200 Subject: [PATCH 11/11] added weapon to weapon hand after drawing it. --- src/Logic/Playground.h | 8 ++++++++ src/Network/MessageHandler.cpp | 21 ++++++++++++++++++--- src/Network/MessageHandler.h | 1 + src/Wrapper/OCNpc.cpp | 34 ++++++++++++++++++++++++++++++++++ src/Wrapper/OCNpc.h | 10 ++++++++++ src/Wrapper/oCMsgWeapon.h | 5 +++-- src/Wrapper/zCEventManager.cpp | 7 +++++++ src/Wrapper/zCEventManager.h | 11 +++++++++++ src/Wrapper/zCEventMessage.cpp | 7 +++++++ src/Wrapper/zCEventMessage.h | 7 +++++++ 10 files changed, 106 insertions(+), 5 deletions(-) create mode 100644 src/Wrapper/zCEventManager.cpp create mode 100644 src/Wrapper/zCEventManager.h create mode 100644 src/Wrapper/zCEventMessage.cpp create mode 100644 src/Wrapper/zCEventMessage.h diff --git a/src/Logic/Playground.h b/src/Logic/Playground.h index c380cb6..bed33ff 100644 --- a/src/Logic/Playground.h +++ b/src/Logic/Playground.h @@ -85,6 +85,14 @@ class Playground { }*/ std::cout << "WeaponMode: " << std::to_string(pMainPlayer->oCNpc->getWeaponMode()) << "\n"; npc->oCNpc->setWeaponMode(pMainPlayer->oCNpc->getWeaponMode()); + oCMsgWeapon * c = oCMsgWeapon::CreateoCMsgWeapon(1, 0, 0); + npc->oCNpc->EV_DrawWeapon1(c); + + + //zCEventManager* em = OCNpc::GetEM(1); + + // Nachricht ins System schicken + //em->onMessage(c, npc->oCNpc); } } diff --git a/src/Network/MessageHandler.cpp b/src/Network/MessageHandler.cpp index 161ae7c..97c3be1 100644 --- a/src/Network/MessageHandler.cpp +++ b/src/Network/MessageHandler.cpp @@ -209,10 +209,25 @@ void MessageHandler::handleServerDistributeWeaponMode(std::string &buffer) DataStructures::LastAnimation npcNewAnim; std::unique_ptr npcModel = std::make_unique(value->oCNpc->getModel()); - WeaponMode weaponMode = static_cast(PackagingSystem::ReadItem(buffer)); + int mode = PackagingSystem::ReadItem(buffer); + WeaponMode weaponMode = static_cast(mode); - if(weaponMode != npcLastWeaponMode.weaponMode) - value->oCNpc->setWeaponMode(weaponMode); + if(weaponMode != npcLastWeaponMode.weaponMode){ + //zCEventManager* em = OCNpc::GetEM(1); + //em->onMessage(c, value->oCNpc); + oCMsgWeapon * c = oCMsgWeapon::CreateoCMsgWeapon(mode, 0, 0); + + if(weaponMode == WeaponMode::OneHandMode){ + Async::PrintLn("OneHandMode"); + } + if(weaponMode == WeaponMode::DefaultMode){ + Async::PrintLn("WeaponMode::DefaultMode"); + value->oCNpc->EV_ForceRemoveWeapon(c); + //value->oCNpc->setWeaponMode(weaponMode); + } else { + value->oCNpc->EV_DrawWeapon1(c); + } + } } void MessageHandler::handleServerDistributeEquip(std::string &buffer) diff --git a/src/Network/MessageHandler.h b/src/Network/MessageHandler.h index 66219b5..fd6884a 100644 --- a/src/Network/MessageHandler.h +++ b/src/Network/MessageHandler.h @@ -6,6 +6,7 @@ #include "../Models/Npc.h" #include "../Wrapper/zCModel.h" +#include "../Wrapper/zCEventManager.h" #include "../Network/Client.h" #include "../../common/src/Network/Packets.h" #include "../../common/src/Network/PackagingSystem.h" diff --git a/src/Wrapper/OCNpc.cpp b/src/Wrapper/OCNpc.cpp index c814198..678afa2 100644 --- a/src/Wrapper/OCNpc.cpp +++ b/src/Wrapper/OCNpc.cpp @@ -249,7 +249,13 @@ oCItem * OCNpc::putInInv(oCItem * item) _PutInInv putInInvRef = reinterpret_cast<_PutInInv>(0x6a4ff0); return putInInvRef(this, item); +} + +oCItem * OCNpc::removeFromInv(oCItem * item, int param){ + using _RemoveFromInv = oCItem*(__thiscall *)(void *pThis, oCItem * item, int param); + _RemoveFromInv removeFromInvRef = reinterpret_cast<_RemoveFromInv>(0x6a5260); + return removeFromInvRef(this, item, param); } int OCNpc::EV_DrawWeapon1(oCMsgWeapon * msgWeapon) @@ -260,6 +266,27 @@ int OCNpc::EV_DrawWeapon1(oCMsgWeapon * msgWeapon) return EV_DrawWeapon1Ref(this, msgWeapon); } +int OCNpc::EV_ForceRemoveWeapon(oCMsgWeapon * msgWeapon){ + using _EV_RemoveWeapon = int(__thiscall *)(void *pThis, oCMsgWeapon * msgWeapon); + _EV_RemoveWeapon EV_RemoveWeaponRef = reinterpret_cast<_EV_RemoveWeapon>(0x6a9f40); + + return EV_RemoveWeaponRef(this, msgWeapon); +} + +int OCNpc::EV_RemoveWeapon(oCMsgWeapon * msgWeapon){ + using _EV_RemoveWeapon = int(__thiscall *)(void *pThis, oCMsgWeapon * msgWeapon); + _EV_RemoveWeapon EV_RemoveWeaponRef = reinterpret_cast<_EV_RemoveWeapon>(0x6a93c0); + + return EV_RemoveWeaponRef(this, msgWeapon); +} + +int OCNpc::EV_RemoveWeapon1(oCMsgWeapon * msgWeapon){ + using _EV_RemoveWeapon1 = int(__thiscall *)(void *pThis, oCMsgWeapon * msgWeapon); + _EV_RemoveWeapon1 EV_RemoveWeapon1Ref = reinterpret_cast<_EV_RemoveWeapon1>(0x6a9790); + + return EV_RemoveWeapon1Ref(this, msgWeapon); +} + // returns the weapon in the fighting slot oCItem * OCNpc::getWeapon() { @@ -295,6 +322,13 @@ WeaponMode OCNpc::getWeaponMode(){ _GetWeaponMode GetWeaponModeRef = reinterpret_cast<_GetWeaponMode>(0x695820); return static_cast(GetWeaponModeRef(this)); } + +zCEventManager * OCNpc::GetEM(int createOrNot){ // STATIC + using _GetEM = zCEventManager*(__fastcall *)(int createOrNot); + _GetEM _getEMRef = reinterpret_cast<_GetEM>(0x5d49b0); + return _getEMRef(createOrNot); +} + /*zSTRING *OCNpc::getName2(){ zSTRING * nS = zSTRING::CreateNewzSTRING(""); using _GetName = zSTRING* (__thiscall *)(void* pThis); diff --git a/src/Wrapper/OCNpc.h b/src/Wrapper/OCNpc.h index 7aff7aa..0a92317 100644 --- a/src/Wrapper/OCNpc.h +++ b/src/Wrapper/OCNpc.h @@ -8,10 +8,12 @@ #include "oCObjectFactory.h" #include "oCItem.h" #include "oCMsgWeapon.h" +#include "zCEventManager.h" #include "../Models/WeaponMode.h" class oCItem; +class zCEventManager; /** * @brief Base memory address for the main player's NPC instance. * @@ -145,8 +147,12 @@ class OCNpc void unequipItem(oCItem * item); oCItem * putInInv(oCItem * item); + oCItem * removeFromInv(oCItem * item, int param); int EV_DrawWeapon1(oCMsgWeapon * msgWeapon); + int EV_RemoveWeapon1(oCMsgWeapon * msgWeapon); + int EV_RemoveWeapon(oCMsgWeapon * msgWeapon); + int EV_ForceRemoveWeapon(oCMsgWeapon * msgWeapon); oCItem * getWeapon(); @@ -156,6 +162,10 @@ class OCNpc void setWeaponMode(WeaponMode mode); WeaponMode getWeaponMode(); + + // eventmanager* + // 1 = creates if it's not created. 0 return nullptr if it is not created + static zCEventManager * GetEM(int createOrNot); //zSTRING *getName2(); /*int applyOverlay(char * animName); diff --git a/src/Wrapper/oCMsgWeapon.h b/src/Wrapper/oCMsgWeapon.h index c537e34..36de4b1 100644 --- a/src/Wrapper/oCMsgWeapon.h +++ b/src/Wrapper/oCMsgWeapon.h @@ -1,9 +1,10 @@ #pragma once +#include "zCEventMessage.h" -class oCMsgWeapon { +class oCMsgWeapon : public zCEventMessage { public: - static oCMsgWeapon * CreateoCMsgWeapon(int tWeaponSubType, int param2, int param3); + static oCMsgWeapon * CreateoCMsgWeapon(int tWeaponSubType, int param2, int param3); }; diff --git a/src/Wrapper/zCEventManager.cpp b/src/Wrapper/zCEventManager.cpp new file mode 100644 index 0000000..8759bc1 --- /dev/null +++ b/src/Wrapper/zCEventManager.cpp @@ -0,0 +1,7 @@ +#include "zCEventManager.h" + +void zCEventManager::onMessage(zCEventMessage* event, OCNpc * npc){ + using _OnMessage = void(__thiscall *)(void *pThis, zCEventMessage* event, OCNpc * npc); + _OnMessage onMessageRef = reinterpret_cast<_OnMessage>(0x6dd090); + onMessageRef(this, event, npc); +} \ No newline at end of file diff --git a/src/Wrapper/zCEventManager.h b/src/Wrapper/zCEventManager.h new file mode 100644 index 0000000..55bb934 --- /dev/null +++ b/src/Wrapper/zCEventManager.h @@ -0,0 +1,11 @@ +#pragma once + +#include "OCNpc.h" +#include "zCEventMessage.h" + +class OCNpc; +class zCEventManager { + +public: + void onMessage(zCEventMessage* event, OCNpc * npc); +}; \ No newline at end of file diff --git a/src/Wrapper/zCEventMessage.cpp b/src/Wrapper/zCEventMessage.cpp new file mode 100644 index 0000000..7ada143 --- /dev/null +++ b/src/Wrapper/zCEventMessage.cpp @@ -0,0 +1,7 @@ +#include "zCEventMessage.h" + +/*void zCEventMessage::onMessage(zCEventMessage* event, OCNpc * npc){ + using _OnMessage = void(__thiscall *)(void *pThis, zCEventMessage* event, OCNpc * npc); + _OnMessage onMessageRef = reinterpret_cast<_OnMessage>(0x6dd090); + onMessageRef(this, event, npc); +}*/ \ No newline at end of file diff --git a/src/Wrapper/zCEventMessage.h b/src/Wrapper/zCEventMessage.h new file mode 100644 index 0000000..fd4404c --- /dev/null +++ b/src/Wrapper/zCEventMessage.h @@ -0,0 +1,7 @@ +#pragma once + +class zCEventMessage { + +public: + //void onMessage(zCEventMessage* event, OCNpc * npc); +}; \ No newline at end of file