add lisener for socket

This commit is contained in:
2026-09-10 08:27:06 +02:00
parent bdb434d9d5
commit 751b54db18
8 changed files with 164 additions and 49 deletions
+2 -2
View File
@@ -55,7 +55,7 @@ CLANG_STDLIB ?= -stdlib=libc++
SRCS := src/Log.cpp src/main.cpp src/Server.cpp \ SRCS := src/Log.cpp src/main.cpp src/Server.cpp \
src/config/Config.cpp src/config/ConfigurationParser.cpp src/config/LocationConfig.cpp src/config/ServerConfig.cpp \ src/config/Config.cpp src/config/ConfigurationParser.cpp src/config/LocationConfig.cpp src/config/ServerConfig.cpp \
src/event/Epoll.cpp src/event/EventToken.cpp \ src/event/Epoll.cpp src/event/EventToken.cpp \
src/net/ByteBuffer.cpp src/net/Connection.cpp src/net/FileDescriptor.cpp src/net/Listener.cpp src/net/PauseMask.cpp src/net/SlotPool.cpp src/net/ByteBuffer.cpp src/net/Connection.cpp src/net/FileDescriptor.cpp src/net/Listener.cpp src/net/ListenerPlan.cpp src/net/PauseMask.cpp src/net/SlotPool.cpp
# src/http/HttpStatus.cpp \ # src/http/HttpStatus.cpp \
@@ -68,7 +68,7 @@ DEPS := $(OBJS:.o=.d)
HDRS := include/config/Config.hpp include/config/ConfigurationParser.hpp include/config/LocationConfig.hpp include/config/ServerConfig.hpp \ HDRS := include/config/Config.hpp include/config/ConfigurationParser.hpp include/config/LocationConfig.hpp include/config/ServerConfig.hpp \
include/event/Epoll.hpp include/event/EventToken.hpp \ include/event/Epoll.hpp include/event/EventToken.hpp \
include/http/HttpStatus.hpp \ include/http/HttpStatus.hpp \
include/net/ByteBuffer.hpp include/net/Connection.hpp include/net/FileDescriptor.hpp include/net/Listener.hpp include/net/PauseMask.hpp include/net/SlotPool.hpp \ include/net/ByteBuffer.hpp include/net/Connection.hpp include/net/FileDescriptor.hpp include/net/Listener.hpp include/net/ListenerPlan.hpp include/net/PauseMask.hpp include/net/SlotPool.hpp \
include/Log.hpp include/Result.hpp include/Server.hpp \ include/Log.hpp include/Result.hpp include/Server.hpp \
+1 -1
View File
@@ -1,6 +1,6 @@
/*********************************/ /*********************************/
/* */ /* */
/* o.riabenkyi@gmain.com */ /* o.riabenkyi@gmail.com */
/* */ /* */
/*********************************/ /*********************************/
+1 -1
View File
@@ -1,6 +1,6 @@
/*********************************/ /*********************************/
/* */ /* */
/* o.riabenkyi@gmain.com */ /* o.riabenkyi@gmail.com */
/* */ /* */
/*********************************/ /*********************************/
+1 -1
View File
@@ -1,6 +1,6 @@
/*********************************/ /*********************************/
/* */ /* */
/* o.riabenkyi@gmain.com */ /* o.riabenkyi@gmail.com */
/* */ /* */
/*********************************/ /*********************************/
+1 -1
View File
@@ -1,6 +1,6 @@
/*********************************/ /*********************************/
/* */ /* */
/* o.riabenkyi@gmain.com */ /* o.riabenkyi@gmail.com */
/* */ /* */
/*********************************/ /*********************************/
+60
View File
@@ -0,0 +1,60 @@
/*********************************/
/* */
/* o.riabenkyi@gmail.com */
/* */
/*********************************/
#ifndef LISTENERPLAN_HPP
#define LISTENERPLAN_HPP
#include <sys/socket.h>
#include <exception>
#include <string>
#include <vector>
#include "config/Config.hpp"
namespace webserv {
// Turns a validated Config into the deduplicated set of sockets the server
// must bind. Two server blocks may list the same host:port to share one
// socket (virtual hosting, picked apart later by server_name), so this
// groups listen directives by unique host:port instead of binding one
// socket per directive, which would make the second bind() fail.
//
// The ServerConfig pointers in routes() point into the Config passed to
// build(); that Config must outlive the ListenerPlan.
class ListenerPlan final {
public:
class Error : public std::exception {
public:
explicit Error(std::string message);
const char* what() const noexcept override;
private:
std::string msg_;
};
static ListenerPlan build(const Config& config);
const std::vector<sockaddr_storage>& endpoints() const noexcept {
return endpoints_;
}
// routes()[i] lists, in config order, every ServerConfig reachable
// through endpoints()[i]. Not consumed yet: it becomes the input to
// Host-header based virtual host selection once HTTP request routing
// exists.
const std::vector<std::vector<const ServerConfig*>>& routes() const noexcept {
return routes_;
}
private:
std::vector<sockaddr_storage> endpoints_;
std::vector<std::vector<const ServerConfig*>> routes_;
};
} // namespace webserv
#endif
+24 -43
View File
@@ -10,12 +10,8 @@
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
#include <netinet/in.h>
#include <array>
#include <cerrno> #include <cerrno>
#include <csignal> #include <csignal>
#include <cstdint>
#include <cstring> #include <cstring>
#include <exception> #include <exception>
#include <iostream> #include <iostream>
@@ -25,26 +21,10 @@
#include "Server.hpp" #include "Server.hpp"
#include "config/ConfigurationParser.hpp" #include "config/ConfigurationParser.hpp"
#include "net/ListenerPlan.hpp"
constexpr std::string_view DEFAULT_CONFIG_PATH = "conf/_default.conf"; constexpr std::string_view DEFAULT_CONFIG_PATH = "conf/_default.conf";
namespace {
// TEMP: Builds wildcard IPv4 addresses for the fixed echo server ports.
// Parsed configuration will eventually provide resolved listener addresses.
sockaddr_storage anyAddress(std::uint16_t port) {
const sockaddr_in address{.sin_family = AF_INET,
.sin_port = ::htons(port),
.sin_addr = {.s_addr = ::htonl(INADDR_ANY)},
.sin_zero = {}};
sockaddr_storage storage{};
std::memcpy(&storage, &address, sizeof(address));
return storage;
}
} // namespace
int main(int argc, char** argv) { int main(int argc, char** argv) {
if (argc > 2) { if (argc > 2) {
std::cerr << "usage: " << argv[0] << " [configuration file]\n"; std::cerr << "usage: " << argv[0] << " [configuration file]\n";
@@ -56,25 +36,29 @@ int main(int argc, char** argv) {
webserv::log::info("configuration file {}", configPath); webserv::log::info("configuration file {}", configPath);
try { // Declared here, outside the parsing try block, because ListenerPlan
ConfigurationParser parser; // keeps pointers into this Config's ServerConfig blocks and both the
Config config = parser.parse(std::string(configPath)); // plan and the running server need it to stay alive past parsing.
Config config;
try {
ConfigurationParser parser;
config = parser.parse(std::string(configPath));
const std::vector<ServerConfig> &servers = config.getServers(); const std::vector<ServerConfig> &servers = config.getServers();
std::cout << "Parsed " << servers.size() << " server block(s) from " << configPath << ":\n"; std::cout << "Parsed " << servers.size() << " server block(s) from " << configPath << ":\n";
for (size_t i = 0; i < servers.size(); ++i) { for (size_t i = 0; i < servers.size(); ++i) {
const ServerConfig &server = servers[i]; const ServerConfig &server = servers[i];
std::cout << " server " << i << ":"; std::cout << " server " << i << ":";
const std::vector<ServerConfig::Listen> &listens = server.getListens(); const std::vector<ServerConfig::Listen> &listens = server.getListens();
for (size_t l = 0; l < listens.size(); ++l) for (size_t l = 0; l < listens.size(); ++l)
std::cout << ' ' << listens[l].host << ':' << listens[l].port; std::cout << ' ' << listens[l].host << ':' << listens[l].port;
std::cout << " root=" << server.getRoot().value_or("(inherited per-location)") std::cout << " root=" << server.getRoot().value_or("(inherited per-location)")
<< " locations=" << server.getLocations().size() << '\n'; << " locations=" << server.getLocations().size() << '\n';
}
} catch (const std::exception &e) {
std::cerr << "Configuration error: " << e.what() << '\n';
return 1;
} }
} catch (const std::exception &e) {
std::cerr << "Configuration error: " << e.what() << '\n';
return 1;
}
// Ignore SIGPIPE so writing to a closed socket or pipe reports an error // Ignore SIGPIPE so writing to a closed socket or pipe reports an error
// instead of terminating the server. Other clients can then continue. // instead of terminating the server. Other clients can then continue.
@@ -84,11 +68,8 @@ int main(int argc, char** argv) {
} }
try { try {
// TEMP: The echo server listens on three fixed ports until main obtains const webserv::ListenerPlan plan = webserv::ListenerPlan::build(config);
// the listener addresses from the configuration file. webserv::Server server(plan.endpoints());
const std::array<sockaddr_storage, 3> endpoints{
anyAddress(8000), anyAddress(8001), anyAddress(8002)};
webserv::Server server(endpoints);
server.run(); server.run();
} catch (const std::exception& error) { } catch (const std::exception& error) {
webserv::log::error("{}", error.what()); webserv::log::error("{}", error.what());
+74
View File
@@ -0,0 +1,74 @@
#include "net/ListenerPlan.hpp"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <format>
namespace webserv {
namespace {
// The parser only ever produces dotted IPv4 strings ("127.0.0.1", or
// "0.0.0.0" when the config omits a host), so IPv4 is all that needs
// resolving here.
sockaddr_storage makeIPv4Endpoint(const std::string& host, int port) {
sockaddr_in address{};
address.sin_family = AF_INET;
address.sin_port = ::htons(static_cast<std::uint16_t>(port));
if (::inet_pton(AF_INET, host.c_str(), &address.sin_addr) != 1) {
throw ListenerPlan::Error(std::format("invalid listen address '{}'", host));
}
sockaddr_storage storage{};
std::memcpy(&storage, &address, sizeof(address));
return storage;
}
} // namespace
ListenerPlan::Error::Error(std::string message) : msg_(std::move(message)) {}
const char* ListenerPlan::Error::what() const noexcept { return msg_.c_str(); }
ListenerPlan ListenerPlan::build(const Config& config) {
ListenerPlan plan;
// Local key list mirroring plan.endpoints_/routes_ by index, used only to
// find which group an already-seen host:port belongs to.
std::vector<ServerConfig::Listen> keys;
for (const ServerConfig& server : config.getServers()) {
for (const ServerConfig::Listen& listen : server.getListens()) {
std::size_t index = keys.size();
bool found = false;
for (std::size_t i = 0; i < keys.size(); ++i) {
if (keys[i].host == listen.host && keys[i].port == listen.port) {
index = i;
found = true;
break;
}
}
if (!found) {
keys.push_back(listen);
plan.endpoints_.push_back(makeIPv4Endpoint(listen.host, listen.port));
plan.routes_.emplace_back();
}
// A server block that repeats the same "listen" twice must not be
// added to its own route group twice.
std::vector<const ServerConfig*>& route = plan.routes_[index];
if (std::ranges::find(route, &server) == route.end()) {
route.push_back(&server);
}
}
}
return plan;
}
} // namespace webserv