diff --git a/src/daemon-utils/socket-manager.cpp b/src/daemon-utils/socket-manager.cpp index 5a6a068..026997a 100644 --- a/src/daemon-utils/socket-manager.cpp +++ b/src/daemon-utils/socket-manager.cpp @@ -50,11 +50,35 @@ void handle_client(int client_socket){ void start_http_server(std::uint16_t port){ spdlog::info("Starting HTTP server on {}", port); httplib::Server server = httplib::Server{}; + std::vector pixel = other_general_utils::read_file_bytes("1x1.png"); server.Get("/test", [](const httplib::Request& req, httplib::Response &res) { res.set_content("Hello World!", "text/plain"); spdlog::info("/test endpoint hit by: {}", req.remote_addr); }); - + server.Get("/img", [&pixel](const httplib::Request& req, httplib::Response& res) { + std::string client_ip; + + if (req.has_header("X-Forwarded-For")) { + client_ip = req.get_header_value("X-Forwarded-For"); + // if multiple IPs (comma separated), take first + size_t comma_pos = client_ip.find(','); + if (comma_pos != std::string::npos) + client_ip = client_ip.substr(0, comma_pos); + } else { + client_ip = req.remote_addr; // fallback if not behind proxy + } + + spdlog::info("Received /img hit from client IP: {}", client_ip); + + if (!req.has_param("id")) { + res.status = 405; + return; + } + std::string id = req.get_param_value("id"); + spdlog::info("Received /img hit with param id: {}", id); + res.set_content(pixel.data(), pixel.size(), "image/png"); + }); + server.listen("0.0.0.0", port); } } diff --git a/src/shared-utils/socket-utils.cpp b/src/shared-utils/socket-utils.cpp index f0e42e1..9aa3ecd 100644 --- a/src/shared-utils/socket-utils.cpp +++ b/src/shared-utils/socket-utils.cpp @@ -1,3 +1,6 @@ +#include +#include +#include #include #include #include @@ -54,4 +57,22 @@ ssize_t read_from_socket(int sock_fd, std::vector& read_buffer) { } } // namespace socket_utils +namespace other_general_utils { + +std::vector read_file_bytes(const std::string& filename) { + std::ifstream file = std::ifstream{filename, std::ios::binary | std::ios::ate}; + if (!file) { + throw std::runtime_error("Failed to open file"); + } + std::streamsize size = file.tellg(); // get file size + file.seekg(0, std::ios::beg); + + std::vector buffer(size); + if (!file.read(buffer.data(), size)) { + throw std::runtime_error("Failed to read file"); + } + + return buffer; +} +} diff --git a/src/shared-utils/socket-utils.hpp b/src/shared-utils/socket-utils.hpp index 15c3cb6..92bf0a2 100644 --- a/src/shared-utils/socket-utils.hpp +++ b/src/shared-utils/socket-utils.hpp @@ -1,4 +1,5 @@ #pragma once +#include #include #include @@ -7,5 +8,8 @@ namespace socket_utils{ ssize_t write_to_socket(int sock_fd, std::vector& write_buffer); ssize_t read_from_socket(int sock_fd, std::vector& read_buffer); - +} + +namespace other_general_utils { + std::vector read_file_bytes(const std::string& filename); }