-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.hpp
More file actions
227 lines (204 loc) · 9.7 KB
/
server.hpp
File metadata and controls
227 lines (204 loc) · 9.7 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
#pragma once
#include <roar/directory_server/directory_server.hpp>
#include <roar/routing/proto_route.hpp>
#include <roar/error.hpp>
#include <roar/session/session.hpp>
#include <roar/request.hpp>
#include <roar/routing/request_listener.hpp>
#include <roar/standard_response_provider.hpp>
#include <roar/standard_text_response_provider.hpp>
#include <roar/ssl/make_ssl_context.hpp>
#include <roar/filesystem/jail.hpp>
#include <boost/describe/modifiers.hpp>
#include <boost/asio/ssl/context.hpp>
#include <boost/describe/members.hpp>
#include <boost/leaf.hpp>
#include <boost/mp11/algorithm.hpp>
#include <boost/beast/http/verb.hpp>
#include <memory>
#include <string>
#include <tuple>
#include <unordered_map>
#include <functional>
#include <iterator>
#include <variant>
namespace Roar
{
class RequestListener;
class Server
{
public:
struct ConstructionArguments
{
/// Required io executor for boost::asio.
boost::asio::any_io_executor executor;
/// Supply for SSL support.
std::optional<std::variant<SslServerContext, boost::asio::ssl::context>> sslContext = std::nullopt;
/// Called when an error occurs in an asynchronous routine.
std::function<void(Error&&)> onError = [](auto&&) {};
/// Called when the server stops accepting connections for error reasons.
std::function<void(boost::system::error_code)> onAcceptAbort = [](auto) {};
/// Sometimes the server has to respond with error codes outside the library users scope. So this class
/// provides responses for errors like 404 or 500.
std::unique_ptr<StandardResponseProvider> standardResponseProvider =
std::make_unique<StandardTextResponseProvider>();
};
/**
* @brief Construct a new Server object given a boost asio io_executor.
*
* @param constructionArgs Options to construct the server with
*/
Server(ConstructionArguments constructionArgs);
~Server();
Server(Server const&) = delete;
Server(Server&&);
Server& operator=(Server const&) = delete;
Server& operator=(Server&&);
/**
* @brief Bind and listen for network interface and port.
*
* @param host An ip / hostname to identify the network interface to listen on.
* @param port A port to bind on.
*/
boost::leaf::result<void> start(unsigned short port = 0, std::string const& host = "::");
/**
* @brief Starts the server given the already resolved bind endpoint.
*
* @param bindEndpoint An endpoint to bind on.
*/
boost::leaf::result<void> start(boost::asio::ip::basic_endpoint<boost::asio::ip::tcp> const& bindEndpoint);
/**
* @brief Get the local endpoint that this server bound to.
*
* @return boost::asio::ip::basic_endpoint<boost::asio::ip::tcp> const&
*/
boost::asio::ip::basic_endpoint<boost::asio::ip::tcp> const& getLocalEndpoint() const;
/**
* @brief Stop and shutdown the server.
*/
void stop();
/**
* @brief Attach a request listener to this server to receive requests.
*
* @param listener
*/
template <typename RequestListenerT, typename... ConstructionArgsT>
std::shared_ptr<RequestListenerT> installRequestListener(ConstructionArgsT&&... args)
{
auto listener = std::make_shared<RequestListenerT>(std::forward<ConstructionArgsT>(args)...);
using routes = boost::describe::
describe_members<RequestListenerT, boost::describe::mod_any_access | boost::describe::mod_static>;
std::unordered_multimap<boost::beast::http::verb, ProtoRoute> extractedRoutes;
boost::mp11::mp_for_each<routes>([&extractedRoutes, &listener, this]<typename T>(T route) {
this->addRoute(listener, extractedRoutes, *route.pointer);
});
addRequestListenerToRouter(std::move(extractedRoutes));
return listener;
}
/**
* @brief Returns whether this server has a certificate and key and is therefore a HTTPS server.
*
* @return true is HTTPS.
* @return false is not HTTPS.
*/
bool isSecure() const;
/**
* @brief Get the Executor object
*
* @return boost::asio::any_io_executor& The ASIO any_io_executor.
*/
boost::asio::any_io_executor getExecutor() const;
private:
template <typename RequestListenerT>
void addRoute(
std::shared_ptr<RequestListenerT> listener,
std::unordered_multimap<boost::beast::http::verb, ProtoRoute>& extractedRoutes,
RouteInfo<RequestListenerT> const& info)
{
ProtoRoute protoRoute{};
switch (info.pathType)
{
case (RoutePathType::RegularString):
{
protoRoute.path = std::string{info.path};
protoRoute.matches = [p = info.path](std::string const& path, std::vector<std::string>&) {
return path == p;
};
break;
}
case (RoutePathType::Regex):
{
protoRoute.path = std::regex{info.path};
protoRoute.matches =
[p = info.path](std::string const& path, std::vector<std::string>& regexMatches) {
std::smatch smatch;
auto result = std::regex_match(path, smatch, std::regex{p});
regexMatches.reserve(smatch.size());
for (auto submatch = std::next(std::begin(smatch)), end = std::end(smatch); submatch < end;
++submatch)
regexMatches.push_back(submatch->str());
return result;
};
break;
}
default:
throw std::runtime_error("Invalid path type for route.");
}
protoRoute.routeOptions = info.routeOptions;
protoRoute.callRoute = [serverIsSecure = isSecure(),
listener,
handler = info.handler,
allowUnsecure = protoRoute.routeOptions.allowUnsecure](
Session& session, Request<boost::beast::http::empty_body> req) {
if (serverIsSecure && !session.isSecure() && !allowUnsecure)
return session.sendStrictTransportSecurityResponse();
std::invoke(handler, *listener, session, std::move(req));
};
extractedRoutes.emplace(*info.verb, protoRoute);
if (protoRoute.routeOptions.cors && protoRoute.routeOptions.cors->generatePreflightOptionsRoute)
{
auto preflightRoute = protoRoute;
protoRoute.callRoute = [serverIsSecure = isSecure(),
allowUnsecure = protoRoute.routeOptions.allowUnsecure](
Session& session, Request<boost::beast::http::empty_body> const& req) {
if (serverIsSecure && !session.isSecure() && !allowUnsecure)
return session.sendStrictTransportSecurityResponse();
session.send<boost::beast::http::empty_body>(session.prepareResponse(req))->commit();
};
extractedRoutes.emplace(boost::beast::http::verb::options, preflightRoute);
}
}
template <typename RequestListenerT>
void addRoute(
std::shared_ptr<RequestListenerT> listener,
std::unordered_multimap<boost::beast::http::verb, ProtoRoute>& extractedRoutes,
ServeInfo<RequestListenerT> const& info)
{
namespace http = boost::beast::http;
ProtoRoute protoRoute{};
protoRoute.path = Detail::ServedPath{std::string{info.path}};
protoRoute.routeOptions = info.routeOptions;
protoRoute.callRoute = [dserver = Detail::DirectoryServer<RequestListenerT>{{
.serverIsSecure_ = isSecure(),
.serveInfo_ = info,
.listener_ = listener,
}}](Session& session, Request<http::empty_body> const& req) {
auto dserverCpy = dserver;
dserverCpy(session, req);
};
protoRoute.matches = [p = info.path](std::string const& path, std::vector<std::string>&) {
return path.starts_with(p);
};
// Add the all regardeless of allowed or not, to give a proper response.
extractedRoutes.emplace(http::verb::options, protoRoute);
extractedRoutes.emplace(http::verb::head, protoRoute);
extractedRoutes.emplace(http::verb::get, protoRoute);
extractedRoutes.emplace(http::verb::put, protoRoute);
extractedRoutes.emplace(http::verb::delete_, protoRoute);
}
void addRequestListenerToRouter(std::unordered_multimap<boost::beast::http::verb, ProtoRoute>&& routes);
private:
struct Implementation;
std::shared_ptr<Implementation> impl_;
};
}