22#include "data/LedgerCacheInterface.hpp"
23#include "util/Taggable.hpp"
24#include "util/log/Logger.hpp"
25#include "web/AdminVerificationStrategy.hpp"
26#include "web/HttpSession.hpp"
27#include "web/ProxyIpResolver.hpp"
28#include "web/SslHttpSession.hpp"
29#include "web/dosguard/DOSGuardInterface.hpp"
30#include "web/interface/Concepts.hpp"
31#include "web/ng/impl/ServerSslContext.hpp"
33#include <boost/asio/io_context.hpp>
34#include <boost/asio/ip/address.hpp>
35#include <boost/asio/ip/tcp.hpp>
36#include <boost/asio/socket_base.hpp>
37#include <boost/asio/spawn.hpp>
38#include <boost/asio/ssl/context.hpp>
39#include <boost/asio/ssl/error.hpp>
40#include <boost/asio/strand.hpp>
41#include <boost/beast/core/error.hpp>
42#include <boost/beast/core/flat_buffer.hpp>
43#include <boost/beast/core/stream_traits.hpp>
44#include <boost/beast/core/tcp_stream.hpp>
45#include <fmt/format.h>
79 template <
typename>
class PlainSessionType,
80 template <
typename>
class SslSessionType,
82class Detector :
public std::enable_shared_from_this<Detector<PlainSessionType, SslSessionType, HandlerType>> {
86 boost::beast::tcp_stream stream_;
87 std::optional<std::reference_wrapper<boost::asio::ssl::context>> ctx_;
88 std::reference_wrapper<util::TagDecoratorFactory const> tagFactory_;
89 std::reference_wrapper<dosguard::DOSGuardInterface>
const dosGuard_;
90 std::shared_ptr<HandlerType>
const handler_;
91 std::reference_wrapper<data::LedgerCacheInterface const> cache_;
92 boost::beast::flat_buffer buffer_;
93 std::shared_ptr<AdminVerificationStrategy>
const adminVerification_;
94 std::uint32_t maxWsSendingQueueSize_;
95 std::shared_ptr<ProxyIpResolver> proxyIpResolver_;
112 tcp::socket&& socket,
113 std::optional<std::reference_wrapper<boost::asio::ssl::context>> ctx,
114 std::reference_wrapper<util::TagDecoratorFactory const> tagFactory,
115 std::reference_wrapper<dosguard::DOSGuardInterface> dosGuard,
116 std::shared_ptr<HandlerType> handler,
117 std::reference_wrapper<data::LedgerCacheInterface const> cache,
118 std::shared_ptr<AdminVerificationStrategy> adminVerification,
119 std::uint32_t maxWsSendingQueueSize,
120 std::shared_ptr<ProxyIpResolver> proxyIpResolver
122 : stream_(std::move(socket))
124 , tagFactory_(std::cref(tagFactory))
125 , dosGuard_(dosGuard)
126 , handler_(std::move(handler))
128 , adminVerification_(std::move(adminVerification))
129 , maxWsSendingQueueSize_(maxWsSendingQueueSize)
130 , proxyIpResolver_(std::move(proxyIpResolver))
141 fail(boost::system::error_code ec,
char const* message)
143 if (ec == boost::asio::ssl::error::stream_truncated)
146 LOG(log_.info()) <<
"Detector failed (" << message <<
"): " << ec.message();
153 boost::beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
154 async_detect_ssl(stream_, buffer_, boost::beast::bind_front_handler(&
Detector::onDetect, shared_from_this()));
167 return fail(ec,
"detect");
171 ip = stream_.socket().remote_endpoint().address().to_string();
172 }
catch (std::exception
const&) {
173 return fail(ec,
"cannot get remote endpoint");
178 return fail(ec,
"SSL is not supported by this server");
180 std::make_shared<SslSessionType<HandlerType>>(
181 stream_.release_socket(),
191 maxWsSendingQueueSize_
197 std::make_shared<PlainSessionType<HandlerType>>(
198 stream_.release_socket(),
207 maxWsSendingQueueSize_
223 template <
typename>
class PlainSessionType,
224 template <
typename>
class SslSessionType,
225 SomeServerHandler HandlerType>
227 public std::enable_shared_from_this<Server<PlainSessionType, SslSessionType, HandlerType>> {
231 std::reference_wrapper<boost::asio::io_context> ioc_;
232 std::optional<boost::asio::ssl::context> ctx_;
234 std::reference_wrapper<dosguard::DOSGuardInterface> dosGuard_;
235 std::shared_ptr<HandlerType> handler_;
236 std::reference_wrapper<data::LedgerCacheInterface const> cache_;
237 tcp::acceptor acceptor_;
238 std::shared_ptr<AdminVerificationStrategy> adminVerification_;
239 std::uint32_t maxWsSendingQueueSize_;
240 std::shared_ptr<ProxyIpResolver> proxyIpResolver_;
241 std::atomic_bool isStopped_{
false};
259 boost::asio::io_context& ioc,
260 std::optional<boost::asio::ssl::context> ctx,
261 tcp::endpoint endpoint,
264 std::shared_ptr<HandlerType> handler,
265 std::reference_wrapper<data::LedgerCacheInterface const> cache,
266 std::shared_ptr<AdminVerificationStrategy> adminVerification,
267 std::uint32_t maxWsSendingQueueSize,
270 : ioc_(std::ref(ioc))
271 , ctx_(std::move(ctx))
272 , tagFactory_(tagFactory)
273 , dosGuard_(std::ref(dosGuard))
274 , handler_(std::move(handler))
276 , acceptor_(boost::asio::make_strand(ioc))
277 , adminVerification_(std::move(adminVerification))
278 , maxWsSendingQueueSize_(maxWsSendingQueueSize)
279 , proxyIpResolver_(std::make_shared<
ProxyIpResolver>(std::move(proxyIpResolver)))
281 boost::beast::error_code ec;
283 acceptor_.open(endpoint.protocol(), ec);
287 acceptor_.set_option(boost::asio::socket_base::reuse_address(
true), ec);
291 acceptor_.bind(endpoint, ec);
293 LOG(log_.error()) <<
"Failed to bind to endpoint: " << endpoint <<
". message: " << ec.message();
294 throw std::runtime_error(
295 fmt::format(
"Failed to bind to endpoint: {}:{}", endpoint.address().to_string(), endpoint.port())
299 acceptor_.listen(boost::asio::socket_base::max_listen_connections, ec);
301 LOG(log_.error()) <<
"Failed to listen at endpoint: " << endpoint <<
". message: " << ec.message();
302 throw std::runtime_error(
303 fmt::format(
"Failed to listen at endpoint: {}:{}", endpoint.address().to_string(), endpoint.port())
317 stop(boost::asio::yield_context)
326 acceptor_.async_accept(
327 boost::asio::make_strand(ioc_.get()),
328 boost::beast::bind_front_handler(&Server::onAccept, shared_from_this())
333 onAccept(boost::beast::error_code ec, tcp::socket socket)
341 ctx_ ? std::optional<std::reference_wrapper<boost::asio::ssl::context>>{ctx_.value()} : std::nullopt;
343 std::make_shared<Detector<PlainSessionType, SslSessionType, HandlerType>>(
346 std::cref(tagFactory_),
351 maxWsSendingQueueSize_,
362template <
typename HandlerType>
376template <
typename HandlerType>
377static std::shared_ptr<HttpServer<HandlerType>>
380 boost::asio::io_context& ioc,
382 std::shared_ptr<HandlerType>
const& handler,
383 std::reference_wrapper<data::LedgerCacheInterface const> cache
388 auto expectedSslContext = ng::impl::makeServerSslContext(config);
389 if (not expectedSslContext) {
390 LOG(log.
error()) <<
"Failed to create SSL context: " << expectedSslContext.error();
394 auto const serverConfig = config.
getObject(
"server");
395 auto const address = boost::asio::ip::make_address(serverConfig.get<std::string>(
"ip"));
396 auto const port = serverConfig.get<
unsigned short>(
"port");
399 if (not expectedAdminVerification.has_value()) {
400 LOG(log.
error()) << expectedAdminVerification.error();
401 throw std::logic_error{expectedAdminVerification.error()};
406 auto const maxWsSendingQueueSize = serverConfig.get<uint32_t>(
"ws_max_sending_queue_size");
410 auto server = std::make_shared<HttpServer<HandlerType>>(
412 std::move(expectedSslContext).value(),
413 boost::asio::ip::tcp::endpoint{address, port},
418 std::move(expectedAdminVerification).value(),
419 maxWsSendingQueueSize,
420 std::move(proxyIpResolver)
A simple thread-safe logger for the channel specified in the constructor.
Definition Logger.hpp:95
Pump error(SourceLocationType const &loc=CURRENT_SRC_LOCATION) const
Interface for logging at Severity::ERR severity.
Definition Logger.cpp:490
A factory for TagDecorator instantiation.
Definition Taggable.hpp:182
All the config data will be stored and extracted from this class.
Definition ConfigDefinition.hpp:50
ObjectView getObject(std::string_view prefix, std::optional< std::size_t > idx=std::nullopt) const
Returns the ObjectView specified with the prefix.
Definition ConfigDefinition.cpp:63
void onDetect(boost::beast::error_code ec, bool result)
Handles detection result.
Definition Server.hpp:164
void run()
Initiate the detection.
Definition Server.hpp:151
Detector(tcp::socket &&socket, std::optional< std::reference_wrapper< boost::asio::ssl::context > > ctx, std::reference_wrapper< util::TagDecoratorFactory const > tagFactory, std::reference_wrapper< dosguard::DOSGuardInterface > dosGuard, std::shared_ptr< HandlerType > handler, std::reference_wrapper< data::LedgerCacheInterface const > cache, std::shared_ptr< AdminVerificationStrategy > adminVerification, std::uint32_t maxWsSendingQueueSize, std::shared_ptr< ProxyIpResolver > proxyIpResolver)
Create a new detector.
Definition Server.hpp:111
void fail(boost::system::error_code ec, char const *message)
A helper function that is called when any error occurs.
Definition Server.hpp:141
Resolves the client's IP address, considering proxy servers.
Definition ProxyIpResolver.hpp:44
static ProxyIpResolver fromConfig(util::config::ClioConfigDefinition const &config)
Creates a ProxyIpResolver from a configuration.
Definition ProxyIpResolver.cpp:47
The WebServer class. It creates server socket and start listening on it.
Definition Server.hpp:227
void run()
Start accepting incoming connections.
Definition Server.hpp:310
void stop(boost::asio::yield_context)
Stop accepting new connections.
Definition Server.hpp:317
Server(boost::asio::io_context &ioc, std::optional< boost::asio::ssl::context > ctx, tcp::endpoint endpoint, util::TagDecoratorFactory tagFactory, dosguard::DOSGuardInterface &dosGuard, std::shared_ptr< HandlerType > handler, std::reference_wrapper< data::LedgerCacheInterface const > cache, std::shared_ptr< AdminVerificationStrategy > adminVerification, std::uint32_t maxWsSendingQueueSize, ProxyIpResolver proxyIpResolver)
Create a new instance of the web server.
Definition Server.hpp:258
The interface of a denial of service guard.
Definition DOSGuardInterface.hpp:46
Specifies the requirements a Webserver handler must fulfill.
Definition Concepts.hpp:37
This namespace implements the web server and related components.
Definition Types.hpp:43
static std::shared_ptr< HttpServer< HandlerType > > makeHttpServer(util::config::ClioConfigDefinition const &config, boost::asio::io_context &ioc, dosguard::DOSGuardInterface &dosGuard, std::shared_ptr< HandlerType > const &handler, std::reference_wrapper< data::LedgerCacheInterface const > cache)
A factory function that spawns a ready to use HTTP server.
Definition Server.hpp:378
Server< HttpSession, SslHttpSession, HandlerType > HttpServer
The final type of the HttpServer used by Clio.
Definition Server.hpp:363
std::shared_ptr< AdminVerificationStrategy > makeAdminVerificationStrategy(std::optional< std::string > password)
Factory function for creating an admin verification strategy.
Definition AdminVerificationStrategy.cpp:67
A tag class for server to help identify Server in templated code.
Definition Concepts.hpp:46