blob: 9cf225f110779b146a6e53b018c5ef3138b443af [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
Adriana Kobylak0e1cf262019-12-05 13:57:57 -06002#include "config.h"
3
Manojkiran Eda44250442020-06-16 12:51:38 +05304#include "http_response.h"
5#include "logging.h"
6#include "middleware_context.h"
7#include "timer_queue.h"
8#include "utility.h"
9
James Feist3909dc82020-04-03 10:58:55 -070010#include "authorization.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070011#include "http_utility.hpp"
12
Ed Tanouse0d918b2018-03-27 17:41:04 -070013#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -070014#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080015#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080016#include <boost/asio/ip/tcp.hpp>
Ed Tanous2f1ebcd2019-02-13 19:39:07 -080017#include <boost/asio/ssl.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080018#include <boost/beast/core/flat_static_buffer.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050019#include <boost/beast/http.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053020#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050021#include <boost/beast/websocket.hpp>
22#include <ssl_key_handler.hpp>
23
Manojkiran Eda44250442020-06-16 12:51:38 +053024#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050025#include <chrono>
26#include <vector>
27
Ed Tanous1abe55e2018-09-05 08:30:59 -070028namespace crow
29{
Ed Tanous257f5792018-03-17 14:40:09 -070030
Ed Tanous1abe55e2018-09-05 08:30:59 -070031inline void prettyPrintJson(crow::Response& res)
32{
Jason M. Bills193ad2f2018-09-26 15:08:52 -070033 std::string value = res.jsonValue.dump(4, ' ', true);
Ed Tanousa29c9972018-11-29 15:54:32 -080034 utility::escapeHtml(value);
35 utility::convertToLinks(value);
Ed Tanous1abe55e2018-09-05 08:30:59 -070036 res.body() = "<html>\n"
37 "<head>\n"
38 "<title>Redfish API</title>\n"
39 "<link rel=\"stylesheet\" type=\"text/css\" "
40 "href=\"/styles/default.css\">\n"
41 "<script src=\"/highlight.pack.js\"></script>"
42 "<script>hljs.initHighlightingOnLoad();</script>"
43 "</head>\n"
44 "<body>\n"
45 "<div style=\"max-width: 576px;margin:0 auto;\">\n"
46 "<img src=\"/DMTF_Redfish_logo_2017.svg\" alt=\"redfish\" "
47 "height=\"406px\" "
48 "width=\"576px\">\n"
49 "<br>\n"
50 "<pre>\n"
51 "<code class=\"json\">" +
52 value +
53 "</code>\n"
54 "</pre>\n"
55 "</div>\n"
56 "</body>\n"
57 "</html>\n";
Ed Tanous93ef5802019-01-03 10:15:41 -080058 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070059}
60
Ed Tanous7045c8d2017-04-03 10:04:37 -070061using namespace boost;
62using tcp = asio::ip::tcp;
63
Ed Tanous1abe55e2018-09-05 08:30:59 -070064namespace detail
65{
Gunnar Mills1214b7e2020-06-04 10:11:30 -050066template <typename MW>
67struct CheckBeforeHandleArity3Const
Ed Tanous1abe55e2018-09-05 08:30:59 -070068{
69 template <typename T,
70 void (T::*)(Request&, Response&, typename MW::Context&) const =
71 &T::beforeHandle>
72 struct Get
Gunnar Mills1214b7e2020-06-04 10:11:30 -050073 {};
Ed Tanous7045c8d2017-04-03 10:04:37 -070074};
75
Gunnar Mills1214b7e2020-06-04 10:11:30 -050076template <typename MW>
77struct CheckBeforeHandleArity3
Ed Tanous1abe55e2018-09-05 08:30:59 -070078{
79 template <typename T, void (T::*)(Request&, Response&,
80 typename MW::Context&) = &T::beforeHandle>
81 struct Get
Gunnar Mills1214b7e2020-06-04 10:11:30 -050082 {};
Ed Tanous7045c8d2017-04-03 10:04:37 -070083};
84
Gunnar Mills1214b7e2020-06-04 10:11:30 -050085template <typename MW>
86struct CheckAfterHandleArity3Const
Ed Tanous1abe55e2018-09-05 08:30:59 -070087{
88 template <typename T,
89 void (T::*)(Request&, Response&, typename MW::Context&) const =
90 &T::afterHandle>
91 struct Get
Gunnar Mills1214b7e2020-06-04 10:11:30 -050092 {};
Ed Tanous7045c8d2017-04-03 10:04:37 -070093};
94
Gunnar Mills1214b7e2020-06-04 10:11:30 -050095template <typename MW>
96struct CheckAfterHandleArity3
Ed Tanous1abe55e2018-09-05 08:30:59 -070097{
98 template <typename T, void (T::*)(Request&, Response&,
99 typename MW::Context&) = &T::afterHandle>
100 struct Get
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500101 {};
Ed Tanous7045c8d2017-04-03 10:04:37 -0700102};
103
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500104template <typename T>
105struct IsBeforeHandleArity3Impl
Ed Tanous1abe55e2018-09-05 08:30:59 -0700106{
107 template <typename C>
108 static std::true_type
109 f(typename CheckBeforeHandleArity3Const<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700110
Ed Tanous1abe55e2018-09-05 08:30:59 -0700111 template <typename C>
112 static std::true_type
113 f(typename CheckBeforeHandleArity3<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700114
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500115 template <typename C>
116 static std::false_type f(...);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700117
Ed Tanous1abe55e2018-09-05 08:30:59 -0700118 public:
Ed Tanous0c838cf2019-10-24 10:01:46 -0700119 static constexpr bool value = decltype(f<T>(nullptr))::value;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700120};
121
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500122template <typename T>
123struct IsAfterHandleArity3Impl
Ed Tanous1abe55e2018-09-05 08:30:59 -0700124{
125 template <typename C>
126 static std::true_type
127 f(typename CheckAfterHandleArity3Const<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700128
Ed Tanous1abe55e2018-09-05 08:30:59 -0700129 template <typename C>
130 static std::true_type
131 f(typename CheckAfterHandleArity3<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700132
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500133 template <typename C>
134 static std::false_type f(...);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700135
Ed Tanous1abe55e2018-09-05 08:30:59 -0700136 public:
Ed Tanous0c838cf2019-10-24 10:01:46 -0700137 static constexpr bool value = decltype(f<T>(nullptr))::value;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700138};
139
140template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700141typename std::enable_if<!IsBeforeHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700142 beforeHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
143 ParentContext& /*parent_ctx*/)
144{
145 mw.beforeHandle(req, res, ctx.template get<MW>(), ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700146}
147
148template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700149typename std::enable_if<IsBeforeHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700150 beforeHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
151 ParentContext& /*parent_ctx*/)
152{
153 mw.beforeHandle(req, res, ctx.template get<MW>());
Ed Tanous7045c8d2017-04-03 10:04:37 -0700154}
155
156template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700157typename std::enable_if<!IsAfterHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700158 afterHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
159 ParentContext& /*parent_ctx*/)
160{
161 mw.afterHandle(req, res, ctx.template get<MW>(), ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700162}
163
164template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700165typename std::enable_if<IsAfterHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700166 afterHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
167 ParentContext& /*parent_ctx*/)
168{
169 mw.afterHandle(req, res, ctx.template get<MW>());
Ed Tanous7045c8d2017-04-03 10:04:37 -0700170}
171
Ed Tanous271584a2019-07-09 16:24:22 -0700172template <size_t N, typename Context, typename Container, typename CurrentMW,
Ed Tanous7045c8d2017-04-03 10:04:37 -0700173 typename... Middlewares>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700174bool middlewareCallHelper(Container& middlewares, Request& req, Response& res,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700175 Context& ctx)
176{
177 using parent_context_t = typename Context::template partial<N - 1>;
178 beforeHandlerCall<CurrentMW, Context, parent_context_t>(
Ed Tanous7045c8d2017-04-03 10:04:37 -0700179 std::get<N>(middlewares), req, res, ctx,
180 static_cast<parent_context_t&>(ctx));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700181
Ed Tanous1abe55e2018-09-05 08:30:59 -0700182 if (res.isCompleted())
183 {
184 afterHandlerCall<CurrentMW, Context, parent_context_t>(
185 std::get<N>(middlewares), req, res, ctx,
186 static_cast<parent_context_t&>(ctx));
187 return true;
188 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700189
Ed Tanous1abe55e2018-09-05 08:30:59 -0700190 if (middlewareCallHelper<N + 1, Context, Container, Middlewares...>(
191 middlewares, req, res, ctx))
192 {
193 afterHandlerCall<CurrentMW, Context, parent_context_t>(
194 std::get<N>(middlewares), req, res, ctx,
195 static_cast<parent_context_t&>(ctx));
196 return true;
197 }
198
199 return false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700200}
201
Ed Tanous271584a2019-07-09 16:24:22 -0700202template <size_t N, typename Context, typename Container>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700203bool middlewareCallHelper(Container& /*middlewares*/, Request& /*req*/,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700204 Response& /*res*/, Context& /*ctx*/)
205{
206 return false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700207}
208
Ed Tanous271584a2019-07-09 16:24:22 -0700209template <size_t N, typename Context, typename Container>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700210typename std::enable_if<(N < 0)>::type
211 afterHandlersCallHelper(Container& /*middlewares*/, Context& /*Context*/,
212 Request& /*req*/, Response& /*res*/)
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500213{}
Ed Tanous7045c8d2017-04-03 10:04:37 -0700214
Ed Tanous271584a2019-07-09 16:24:22 -0700215template <size_t N, typename Context, typename Container>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700216typename std::enable_if<(N == 0)>::type
217 afterHandlersCallHelper(Container& middlewares, Context& ctx, Request& req,
218 Response& res)
219{
220 using parent_context_t = typename Context::template partial<N - 1>;
221 using CurrentMW = typename std::tuple_element<
222 N, typename std::remove_reference<Container>::type>::type;
223 afterHandlerCall<CurrentMW, Context, parent_context_t>(
224 std::get<N>(middlewares), req, res, ctx,
225 static_cast<parent_context_t&>(ctx));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700226}
Ed Tanous1abe55e2018-09-05 08:30:59 -0700227
Ed Tanous271584a2019-07-09 16:24:22 -0700228template <size_t N, typename Context, typename Container>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700229typename std::enable_if<(N > 0)>::type
230 afterHandlersCallHelper(Container& middlewares, Context& ctx, Request& req,
231 Response& res)
232{
233 using parent_context_t = typename Context::template partial<N - 1>;
234 using CurrentMW = typename std::tuple_element<
235 N, typename std::remove_reference<Container>::type>::type;
236 afterHandlerCall<CurrentMW, Context, parent_context_t>(
237 std::get<N>(middlewares), req, res, ctx,
238 static_cast<parent_context_t&>(ctx));
239 afterHandlersCallHelper<N - 1, Context, Container>(middlewares, ctx, req,
240 res);
241}
242} // namespace detail
Ed Tanous7045c8d2017-04-03 10:04:37 -0700243
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700244#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -0700245static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700246#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -0700247
Adriana Kobylak0e1cf262019-12-05 13:57:57 -0600248// request body limit size set by the BMCWEB_HTTP_REQ_BODY_LIMIT_MB option
249constexpr unsigned int httpReqBodyLimit =
250 1024 * 1024 * BMCWEB_HTTP_REQ_BODY_LIMIT_MB;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -0700251
James Feist3909dc82020-04-03 10:58:55 -0700252constexpr uint64_t loggedOutPostBodyLimit = 4096;
253
254constexpr uint32_t httpHeaderLimit = 8192;
255
256// drop all connections after 1 minute, this time limit was chosen
257// arbitrarily and can be adjusted later if needed
258static constexpr const size_t loggedInAttempts =
259 (60 / timerQueueTimeoutSeconds);
260
261static constexpr const size_t loggedOutAttempts =
262 (15 / timerQueueTimeoutSeconds);
263
Ed Tanous7045c8d2017-04-03 10:04:37 -0700264template <typename Adaptor, typename Handler, typename... Middlewares>
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500265class Connection :
266 public std::enable_shared_from_this<
267 Connection<Adaptor, Handler, Middlewares...>>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700268{
269 public:
Ed Tanous271584a2019-07-09 16:24:22 -0700270 Connection(boost::asio::io_context& ioService, Handler* handlerIn,
271 const std::string& ServerNameIn,
272 std::tuple<Middlewares...>* middlewaresIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700273 std::function<std::string()>& get_cached_date_str_f,
Ed Tanous271584a2019-07-09 16:24:22 -0700274 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -0800275 adaptor(std::move(adaptorIn)),
Ed Tanous271584a2019-07-09 16:24:22 -0700276 handler(handlerIn), serverName(ServerNameIn),
277 middlewares(middlewaresIn), getCachedDateStr(get_cached_date_str_f),
278 timerQueue(timerQueueIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700279 {
280 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700281 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -0700282 parser->header_limit(httpHeaderLimit);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700283 req.emplace(parser->get());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200284
285#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100286 auto ca_available = !std::filesystem::is_empty(
287 std::filesystem::path(ensuressl::trustStorePath));
288 if (ca_available && crow::persistent_data::SessionStore::getInstance()
289 .getAuthMethodsConfig()
290 .tls)
291 {
292 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
293 SSL_set_session_id_context(
294 adaptor.native_handle(),
295 reinterpret_cast<const unsigned char*>(serverName.c_str()),
Zbigniew Kurzynskicac94c52019-11-07 12:55:04 +0100296 static_cast<unsigned int>(serverName.length()));
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100297 BMCWEB_LOG_DEBUG << this << " TLS is enabled on this connection.";
298 }
299
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100300 adaptor.set_verify_callback([this](
301 bool preverified,
302 boost::asio::ssl::verify_context& ctx) {
303 // do nothing if TLS is disabled
304 if (!crow::persistent_data::SessionStore::getInstance()
305 .getAuthMethodsConfig()
306 .tls)
307 {
308 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200309 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100310 }
311
312 // We always return true to allow full auth flow
313 if (!preverified)
314 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100315 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100316 return true;
317 }
318
319 X509_STORE_CTX* cts = ctx.native_handle();
320 if (cts == nullptr)
321 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100322 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100323 return true;
324 }
325
326 // Get certificate
327 X509* peerCert =
328 X509_STORE_CTX_get_current_cert(ctx.native_handle());
329 if (peerCert == nullptr)
330 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100331 BMCWEB_LOG_DEBUG << this
332 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100333 return true;
334 }
335
336 // Check if certificate is OK
337 int error = X509_STORE_CTX_get_error(cts);
338 if (error != X509_V_OK)
339 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100340 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100341 return true;
342 }
343 // Check that we have reached final certificate in chain
344 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
345 if (depth != 0)
346
347 {
348 BMCWEB_LOG_DEBUG
349 << this << " Certificate verification in progress (depth "
350 << depth << "), waiting to reach final depth";
351 return true;
352 }
353
354 BMCWEB_LOG_DEBUG << this
355 << " Certificate verification of final depth";
356
357 // Verify KeyUsage
358 bool isKeyUsageDigitalSignature = false;
359 bool isKeyUsageKeyAgreement = false;
360
361 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
362 X509_get_ext_d2i(peerCert, NID_key_usage, NULL, NULL));
363
364 if (usage == nullptr)
365 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100366 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100367 return true;
368 }
369
370 for (int i = 0; i < usage->length; i++)
371 {
372 if (KU_DIGITAL_SIGNATURE & usage->data[i])
373 {
374 isKeyUsageDigitalSignature = true;
375 }
376 if (KU_KEY_AGREEMENT & usage->data[i])
377 {
378 isKeyUsageKeyAgreement = true;
379 }
380 }
381
382 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
383 {
384 BMCWEB_LOG_DEBUG << this
385 << " Certificate ExtendedKeyUsage does "
386 "not allow provided certificate to "
387 "be used for user authentication";
388 return true;
389 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200390 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100391
392 // Determine that ExtendedKeyUsage includes Client Auth
393
394 stack_st_ASN1_OBJECT* extUsage = static_cast<stack_st_ASN1_OBJECT*>(
395 X509_get_ext_d2i(peerCert, NID_ext_key_usage, NULL, NULL));
396
397 if (extUsage == nullptr)
398 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100399 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100400 return true;
401 }
402
403 bool isExKeyUsageClientAuth = false;
404 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
405 {
406 if (NID_client_auth ==
407 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
408 {
409 isExKeyUsageClientAuth = true;
410 break;
411 }
412 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200413 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100414
415 // Certificate has to have proper key usages set
416 if (!isExKeyUsageClientAuth)
417 {
418 BMCWEB_LOG_DEBUG << this
419 << " Certificate ExtendedKeyUsage does "
420 "not allow provided certificate to "
421 "be used for user authentication";
422 return true;
423 }
424 std::string sslUser;
425 // Extract username contained in CommonName
426 sslUser.resize(256, '\0');
427
428 int status = X509_NAME_get_text_by_NID(
429 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
430 static_cast<int>(sslUser.size()));
431
432 if (status == -1)
433 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100434 BMCWEB_LOG_DEBUG
435 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100436 return true;
437 }
438
439 size_t lastChar = sslUser.find('\0');
440 if (lastChar == std::string::npos || lastChar == 0)
441 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100442 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100443 return true;
444 }
445 sslUser.resize(lastChar);
446
447 session = persistent_data::SessionStore::getInstance()
448 .generateUserSession(
449 sslUser,
450 crow::persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100451 if (auto sp = session.lock())
452 {
453 BMCWEB_LOG_DEBUG << this
454 << " Generating TLS session: " << sp->uniqueId;
455 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100456 return true;
457 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200458#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
459
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700460#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700461 connectionCount++;
462 BMCWEB_LOG_DEBUG << this << " Connection open, total "
463 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700464#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700465 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700466
Ed Tanous1abe55e2018-09-05 08:30:59 -0700467 ~Connection()
468 {
469 res.completeRequestHandler = nullptr;
470 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700471#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700472 connectionCount--;
473 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
474 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700475#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700476 }
477
Ed Tanousceac6f72018-12-02 11:58:47 -0800478 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700479 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800480 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700481 }
482
Ed Tanous1abe55e2018-09-05 08:30:59 -0700483 void start()
484 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700485
James Feist3909dc82020-04-03 10:58:55 -0700486 startDeadline(0);
Ed Tanousceac6f72018-12-02 11:58:47 -0800487 // TODO(ed) Abstract this to a more clever class with the idea of an
488 // asynchronous "start"
489 if constexpr (std::is_same_v<Adaptor,
490 boost::beast::ssl_stream<
491 boost::asio::ip::tcp::socket>>)
492 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000493 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
494 [this, self(shared_from_this())](
495 const boost::system::error_code& ec) {
496 if (ec)
497 {
498 return;
499 }
500 doReadHeaders();
501 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800502 }
503 else
504 {
505 doReadHeaders();
506 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700507 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700508
Ed Tanous1abe55e2018-09-05 08:30:59 -0700509 void handle()
510 {
511 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700512
Ed Tanous1abe55e2018-09-05 08:30:59 -0700513 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700514
Ed Tanous1abe55e2018-09-05 08:30:59 -0700515 // Check for HTTP version 1.1.
516 if (req->version() == 11)
517 {
518 if (req->getHeaderValue(boost::beast::http::field::host).empty())
519 {
520 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700521 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700522 }
523 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700524
Ed Tanouse278c182019-03-13 16:23:37 -0700525 BMCWEB_LOG_INFO << "Request: "
526 << " " << this << " HTTP/" << req->version() / 10 << "."
527 << req->version() % 10 << ' ' << req->methodString()
528 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700529
Ed Tanous1abe55e2018-09-05 08:30:59 -0700530 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700531
Ed Tanous1abe55e2018-09-05 08:30:59 -0700532 if (!isInvalidRequest)
533 {
raviteja-b4722efe2020-02-03 12:23:18 -0600534 req->socket = [this, self = shared_from_this()]() -> Adaptor& {
535 return self->socket();
536 };
537
Ed Tanous1abe55e2018-09-05 08:30:59 -0700538 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700539 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700540
Ed Tanous1abe55e2018-09-05 08:30:59 -0700541 ctx = detail::Context<Middlewares...>();
Ed Tanouse278c182019-03-13 16:23:37 -0700542 req->middlewareContext = static_cast<void*>(&ctx);
543 req->ioService = static_cast<decltype(req->ioService)>(
544 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200545
546#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
547 if (auto sp = session.lock())
548 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100549 // set cookie only if this is req from the browser.
550 if (req->getHeaderValue("User-Agent").empty())
551 {
552 BMCWEB_LOG_DEBUG << this << " TLS session: " << sp->uniqueId
553 << " will be used for this request.";
554 req->session = sp;
555 }
556 else
557 {
558 std::string_view cookieValue =
559 req->getHeaderValue("Cookie");
560 if (cookieValue.empty() ||
561 cookieValue.find("SESSION=") == std::string::npos)
562 {
563 res.addHeader("Set-Cookie",
564 "XSRF-TOKEN=" + sp->csrfToken +
565 "; Secure\r\nSet-Cookie: SESSION=" +
566 sp->sessionToken +
Zbigniew Kurzynski26139a52019-12-11 19:11:18 +0100567 "; Secure; HttpOnly\r\nSet-Cookie: "
568 "IsAuthenticated=true; Secure");
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100569 BMCWEB_LOG_DEBUG
570 << this << " TLS session: " << sp->uniqueId
571 << " with cookie will be used for this request.";
572 req->session = sp;
573 }
574 }
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200575 }
576#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
577
Ed Tanous1abe55e2018-09-05 08:30:59 -0700578 detail::middlewareCallHelper<
Ed Tanous271584a2019-07-09 16:24:22 -0700579 0U, decltype(ctx), decltype(*middlewares), Middlewares...>(
Ed Tanous1abe55e2018-09-05 08:30:59 -0700580 *middlewares, *req, res, ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700581
Ed Tanous1abe55e2018-09-05 08:30:59 -0700582 if (!res.completed)
583 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000584 needToCallAfterHandlers = true;
585 res.completeRequestHandler = [self(shared_from_this())] {
586 self->completeRequest();
587 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700588 if (req->isUpgrade() &&
589 boost::iequals(
590 req->getHeaderValue(boost::beast::http::field::upgrade),
591 "websocket"))
592 {
593 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000594 // delete lambda with self shared_ptr
595 // to enable connection destruction
596 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700597 return;
598 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700599 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700600 }
601 else
602 {
603 completeRequest();
604 }
605 }
606 else
607 {
608 completeRequest();
609 }
610 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700611
Ed Tanouse278c182019-03-13 16:23:37 -0700612 bool isAlive()
613 {
614
615 if constexpr (std::is_same_v<Adaptor,
616 boost::beast::ssl_stream<
617 boost::asio::ip::tcp::socket>>)
618 {
619 return adaptor.next_layer().is_open();
620 }
621 else
622 {
623 return adaptor.is_open();
624 }
625 }
626 void close()
627 {
Ed Tanouse278c182019-03-13 16:23:37 -0700628 if constexpr (std::is_same_v<Adaptor,
629 boost::beast::ssl_stream<
630 boost::asio::ip::tcp::socket>>)
631 {
632 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200633#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
634 if (auto sp = session.lock())
635 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100636 BMCWEB_LOG_DEBUG << this
637 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200638 persistent_data::SessionStore::getInstance().removeSession(sp);
639 }
640#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700641 }
642 else
643 {
644 adaptor.close();
645 }
646 }
647
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 void completeRequest()
649 {
650 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
651 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700652
Ed Tanous1abe55e2018-09-05 08:30:59 -0700653 if (needToCallAfterHandlers)
654 {
655 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700656
Ed Tanous1abe55e2018-09-05 08:30:59 -0700657 // call all afterHandler of middlewares
Ed Tanous271584a2019-07-09 16:24:22 -0700658 detail::afterHandlersCallHelper<sizeof...(Middlewares) - 1,
Ed Tanousb01bf292019-03-25 19:25:26 +0000659 decltype(ctx),
660 decltype(*middlewares)>(
661 *middlewares, ctx, *req, res);
James Feist3909dc82020-04-03 10:58:55 -0700662
663 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700664 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700665
Ed Tanouse278c182019-03-13 16:23:37 -0700666 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700667 {
668 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
669 // isReading
670 // << ' ' << isWriting;
671 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000672
673 // delete lambda with self shared_ptr
674 // to enable connection destruction
675 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700676 return;
677 }
678 if (res.body().empty() && !res.jsonValue.empty())
679 {
680 if (http_helpers::requestPrefersHtml(*req))
681 {
682 prettyPrintJson(res);
683 }
684 else
685 {
686 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700687 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700688 }
689 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700690
Ed Tanous1abe55e2018-09-05 08:30:59 -0700691 if (res.resultInt() >= 400 && res.body().empty())
692 {
693 res.body() = std::string(res.reason());
694 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700695
696 if (res.result() == boost::beast::http::status::no_content)
697 {
698 // Boost beast throws if content is provided on a no-content
699 // response. Ideally, this would never happen, but in the case that
700 // it does, we don't want to throw.
701 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100702 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700703 res.body().clear();
704 }
705
Ed Tanous1abe55e2018-09-05 08:30:59 -0700706 res.addHeader(boost::beast::http::field::server, serverName);
707 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
708
709 res.keepAlive(req->keepAlive());
710
711 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000712
713 // delete lambda with self shared_ptr
714 // to enable connection destruction
715 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700716 }
717
718 private:
719 void doReadHeaders()
720 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700721 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
722
723 // Clean up any previous Connection.
724 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800725 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000726 [this,
727 self(shared_from_this())](const boost::system::error_code& ec,
728 std::size_t bytes_transferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700729 BMCWEB_LOG_ERROR << this << " async_read_header "
730 << bytes_transferred << " Bytes";
731 bool errorWhileReading = false;
732 if (ec)
733 {
734 errorWhileReading = true;
735 BMCWEB_LOG_ERROR
736 << this << " Error while reading: " << ec.message();
737 }
738 else
739 {
740 // if the adaptor isn't open anymore, and wasn't handed to a
741 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700742 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700743 {
744 errorWhileReading = true;
745 }
746 }
747
James Feist3909dc82020-04-03 10:58:55 -0700748 cancelDeadlineTimer();
749
Ed Tanous1abe55e2018-09-05 08:30:59 -0700750 if (errorWhileReading)
751 {
Ed Tanouse278c182019-03-13 16:23:37 -0700752 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700753 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700754 return;
755 }
756
James Feist3909dc82020-04-03 10:58:55 -0700757 if (!req)
758 {
759 close();
760 return;
761 }
762
Ed Tanous1abe55e2018-09-05 08:30:59 -0700763 // Compute the url parameters for the request
764 req->url = req->target();
765 std::size_t index = req->url.find("?");
Ed Tanous39e77502019-03-04 17:35:53 -0800766 if (index != std::string_view::npos)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700767 {
Jason M. Bills43fcbe52018-10-16 15:19:20 -0700768 req->url = req->url.substr(0, index);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700769 }
James Feist3909dc82020-04-03 10:58:55 -0700770 crow::authorization::authenticate(*req, res);
771
772 bool loggedIn = req && req->session;
773 if (loggedIn)
774 {
775 startDeadline(loggedInAttempts);
776 BMCWEB_LOG_DEBUG << "Starting slow deadline";
777
778 req->urlParams = QueryString(std::string(req->target()));
779 }
780 else
781 {
782 const boost::optional<uint64_t> contentLength =
783 parser->content_length();
784 if (contentLength &&
785 *contentLength > loggedOutPostBodyLimit)
786 {
787 BMCWEB_LOG_DEBUG << "Content length greater than limit "
788 << *contentLength;
789 close();
790 return;
791 }
792
793 startDeadline(loggedOutAttempts);
794 BMCWEB_LOG_DEBUG << "Starting quick deadline";
795 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700796 doRead();
797 });
798 }
799
800 void doRead()
801 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700802 BMCWEB_LOG_DEBUG << this << " doRead";
803
804 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800805 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000806 [this,
807 self(shared_from_this())](const boost::system::error_code& ec,
808 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100809 BMCWEB_LOG_DEBUG << this << " async_read " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700810 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700811
812 bool errorWhileReading = false;
813 if (ec)
814 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100815 BMCWEB_LOG_ERROR
816 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700817 errorWhileReading = true;
818 }
819 else
820 {
James Feist3909dc82020-04-03 10:58:55 -0700821 if (isAlive())
822 {
823 cancelDeadlineTimer();
824 bool loggedIn = req && req->session;
825 if (loggedIn)
826 {
827 startDeadline(loggedInAttempts);
828 }
829 else
830 {
831 startDeadline(loggedOutAttempts);
832 }
833 }
834 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700835 {
836 errorWhileReading = true;
837 }
838 }
839 if (errorWhileReading)
840 {
841 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700842 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700843 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700844 return;
845 }
846 handle();
847 });
848 }
849
850 void doWrite()
851 {
James Feist3909dc82020-04-03 10:58:55 -0700852 bool loggedIn = req && req->session;
853 if (loggedIn)
854 {
855 startDeadline(loggedInAttempts);
856 }
857 else
858 {
859 startDeadline(loggedOutAttempts);
860 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100861 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700862 res.preparePayload();
863 serializer.emplace(*res.stringResponse);
864 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800865 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000866 [this,
867 self(shared_from_this())](const boost::system::error_code& ec,
868 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100869 BMCWEB_LOG_DEBUG << this << " async_write " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700870 << " bytes";
871
James Feist54d8bb12020-07-20 13:28:59 -0700872 cancelDeadlineTimer();
873
Ed Tanous1abe55e2018-09-05 08:30:59 -0700874 if (ec)
875 {
876 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700877 return;
878 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800879 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700880 {
Ed Tanouse278c182019-03-13 16:23:37 -0700881 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700882 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700883 return;
884 }
885
886 serializer.reset();
887 BMCWEB_LOG_DEBUG << this << " Clearing response";
888 res.clear();
889 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500890 parser->body_limit(httpReqBodyLimit); // reset body limit for
891 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700892 buffer.consume(buffer.size());
893
894 req.emplace(parser->get());
895 doReadHeaders();
896 });
897 }
898
Ed Tanous1abe55e2018-09-05 08:30:59 -0700899 void cancelDeadlineTimer()
900 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000901 if (timerCancelKey)
902 {
903 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
904 << ' ' << *timerCancelKey;
905 timerQueue.cancel(*timerCancelKey);
906 timerCancelKey.reset();
907 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700908 }
909
James Feist3909dc82020-04-03 10:58:55 -0700910 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700911 {
912 cancelDeadlineTimer();
913
James Feist3909dc82020-04-03 10:58:55 -0700914 if (timerIterations)
915 {
916 timerIterations--;
917 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100918
James Feist3909dc82020-04-03 10:58:55 -0700919 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700920 timerQueue.add([self(shared_from_this()), timerIterations,
921 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700922 // Mark timer as not active to avoid canceling it during
923 // Connection destructor which leads to double free issue
924 self->timerCancelKey.reset();
925 if (!self->isAlive())
926 {
927 return;
928 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100929
James Feistbe5dfca2020-07-22 08:54:59 -0700930 bool loggedIn = self->req && self->req->session;
931 // allow slow uploads for logged in users
932 if (loggedIn && self->parser->get().body().size() > readCount)
933 {
934 BMCWEB_LOG_DEBUG << self.get()
935 << " restart timer - read in progress";
936 self->startDeadline(timerIterations);
937 return;
938 }
939
James Feist3909dc82020-04-03 10:58:55 -0700940 // Threshold can be used to drop slow connections
941 // to protect against slow-rate DoS attack
942 if (timerIterations)
943 {
James Feistbe5dfca2020-07-22 08:54:59 -0700944 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700945 self->startDeadline(timerIterations);
946 return;
947 }
948
949 self->close();
950 });
James Feistcb6cb492020-04-03 13:36:17 -0700951
952 if (!timerCancelKey)
953 {
954 close();
955 return;
956 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700957 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000958 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700959 }
960
961 private:
962 Adaptor adaptor;
963 Handler* handler;
964
Ed Tanousa24526d2018-12-10 15:17:59 -0800965 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700966 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800967 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700968 boost::beast::http::request_parser<boost::beast::http::string_body>>
969 parser;
970
Ed Tanous3112a142018-11-29 15:45:10 -0800971 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700972
Ed Tanousa24526d2018-12-10 15:17:59 -0800973 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700974 boost::beast::http::string_body>>
975 serializer;
976
Ed Tanousa24526d2018-12-10 15:17:59 -0800977 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700978 crow::Response res;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200979#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
980 std::weak_ptr<crow::persistent_data::UserSession> session;
981#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous1abe55e2018-09-05 08:30:59 -0700982
983 const std::string& serverName;
984
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000985 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700986
Ed Tanous1abe55e2018-09-05 08:30:59 -0700987 bool needToCallAfterHandlers{};
988 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700989
990 std::tuple<Middlewares...>* middlewares;
991 detail::Context<Middlewares...> ctx;
992
993 std::function<std::string()>& getCachedDateStr;
994 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000995
996 using std::enable_shared_from_this<
997 Connection<Adaptor, Handler, Middlewares...>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800998};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700999} // namespace crow