blob: bb3c9dd9fd658534fe32ede131f6af2dfd2fdee5 [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
Ed Tanous1abe55e2018-09-05 08:30:59 -07002#include "http_utility.hpp"
3
Ed Tanous7045c8d2017-04-03 10:04:37 -07004#include <atomic>
Ed Tanouse0d918b2018-03-27 17:41:04 -07005#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -07006#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -08007#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -08008#include <boost/asio/ip/tcp.hpp>
Ed Tanous2f1ebcd2019-02-13 19:39:07 -08009#include <boost/asio/ssl.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080010#include <boost/beast/core/flat_static_buffer.hpp>
Ed Tanouse278c182019-03-13 16:23:37 -070011#if BOOST_VERSION >= 107000
12#include <boost/beast/ssl/ssl_stream.hpp>
13#else
Ed Tanous2f1ebcd2019-02-13 19:39:07 -080014#include <boost/beast/experimental/core/ssl_stream.hpp>
Ed Tanouse278c182019-03-13 16:23:37 -070015#endif
Ed Tanouse0d918b2018-03-27 17:41:04 -070016#include <boost/beast/http.hpp>
17#include <boost/beast/websocket.hpp>
Ed Tanous1abe55e2018-09-05 08:30:59 -070018#include <chrono>
Ed Tanous1abe55e2018-09-05 08:30:59 -070019#include <vector>
20
Ed Tanousc94ad492019-10-10 15:39:33 -070021#include "http_response.h"
22#include "logging.h"
23#include "middleware_context.h"
24#include "timer_queue.h"
25#include "utility.h"
Ed Tanous7045c8d2017-04-03 10:04:37 -070026
Ed Tanous1abe55e2018-09-05 08:30:59 -070027namespace crow
28{
Ed Tanous257f5792018-03-17 14:40:09 -070029
Ed Tanous1abe55e2018-09-05 08:30:59 -070030inline void prettyPrintJson(crow::Response& res)
31{
Jason M. Bills193ad2f2018-09-26 15:08:52 -070032 std::string value = res.jsonValue.dump(4, ' ', true);
Ed Tanousa29c9972018-11-29 15:54:32 -080033 utility::escapeHtml(value);
34 utility::convertToLinks(value);
Ed Tanous1abe55e2018-09-05 08:30:59 -070035 res.body() = "<html>\n"
36 "<head>\n"
37 "<title>Redfish API</title>\n"
38 "<link rel=\"stylesheet\" type=\"text/css\" "
39 "href=\"/styles/default.css\">\n"
40 "<script src=\"/highlight.pack.js\"></script>"
41 "<script>hljs.initHighlightingOnLoad();</script>"
42 "</head>\n"
43 "<body>\n"
44 "<div style=\"max-width: 576px;margin:0 auto;\">\n"
45 "<img src=\"/DMTF_Redfish_logo_2017.svg\" alt=\"redfish\" "
46 "height=\"406px\" "
47 "width=\"576px\">\n"
48 "<br>\n"
49 "<pre>\n"
50 "<code class=\"json\">" +
51 value +
52 "</code>\n"
53 "</pre>\n"
54 "</div>\n"
55 "</body>\n"
56 "</html>\n";
Ed Tanous93ef5802019-01-03 10:15:41 -080057 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070058}
59
Ed Tanous7045c8d2017-04-03 10:04:37 -070060using namespace boost;
61using tcp = asio::ip::tcp;
62
Ed Tanous1abe55e2018-09-05 08:30:59 -070063namespace detail
64{
65template <typename MW> struct CheckBeforeHandleArity3Const
66{
67 template <typename T,
68 void (T::*)(Request&, Response&, typename MW::Context&) const =
69 &T::beforeHandle>
70 struct Get
71 {
72 };
Ed Tanous7045c8d2017-04-03 10:04:37 -070073};
74
Ed Tanous1abe55e2018-09-05 08:30:59 -070075template <typename MW> struct CheckBeforeHandleArity3
76{
77 template <typename T, void (T::*)(Request&, Response&,
78 typename MW::Context&) = &T::beforeHandle>
79 struct Get
80 {
81 };
Ed Tanous7045c8d2017-04-03 10:04:37 -070082};
83
Ed Tanous1abe55e2018-09-05 08:30:59 -070084template <typename MW> struct CheckAfterHandleArity3Const
85{
86 template <typename T,
87 void (T::*)(Request&, Response&, typename MW::Context&) const =
88 &T::afterHandle>
89 struct Get
90 {
91 };
Ed Tanous7045c8d2017-04-03 10:04:37 -070092};
93
Ed Tanous1abe55e2018-09-05 08:30:59 -070094template <typename MW> struct CheckAfterHandleArity3
95{
96 template <typename T, void (T::*)(Request&, Response&,
97 typename MW::Context&) = &T::afterHandle>
98 struct Get
99 {
100 };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700101};
102
Ed Tanous1abe55e2018-09-05 08:30:59 -0700103template <typename T> struct IsBeforeHandleArity3Impl
104{
105 template <typename C>
106 static std::true_type
107 f(typename CheckBeforeHandleArity3Const<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700108
Ed Tanous1abe55e2018-09-05 08:30:59 -0700109 template <typename C>
110 static std::true_type
111 f(typename CheckBeforeHandleArity3<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700112
Ed Tanous1abe55e2018-09-05 08:30:59 -0700113 template <typename C> static std::false_type f(...);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700114
Ed Tanous1abe55e2018-09-05 08:30:59 -0700115 public:
Ed Tanous0c838cf2019-10-24 10:01:46 -0700116 static constexpr bool value = decltype(f<T>(nullptr))::value;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700117};
118
Ed Tanous1abe55e2018-09-05 08:30:59 -0700119template <typename T> struct IsAfterHandleArity3Impl
120{
121 template <typename C>
122 static std::true_type
123 f(typename CheckAfterHandleArity3Const<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700124
Ed Tanous1abe55e2018-09-05 08:30:59 -0700125 template <typename C>
126 static std::true_type
127 f(typename CheckAfterHandleArity3<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700128
Ed Tanous1abe55e2018-09-05 08:30:59 -0700129 template <typename C> static std::false_type f(...);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700130
Ed Tanous1abe55e2018-09-05 08:30:59 -0700131 public:
Ed Tanous0c838cf2019-10-24 10:01:46 -0700132 static constexpr bool value = decltype(f<T>(nullptr))::value;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700133};
134
135template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700136typename std::enable_if<!IsBeforeHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700137 beforeHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
138 ParentContext& /*parent_ctx*/)
139{
140 mw.beforeHandle(req, res, ctx.template get<MW>(), ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700141}
142
143template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700144typename std::enable_if<IsBeforeHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700145 beforeHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
146 ParentContext& /*parent_ctx*/)
147{
148 mw.beforeHandle(req, res, ctx.template get<MW>());
Ed Tanous7045c8d2017-04-03 10:04:37 -0700149}
150
151template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700152typename std::enable_if<!IsAfterHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700153 afterHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
154 ParentContext& /*parent_ctx*/)
155{
156 mw.afterHandle(req, res, ctx.template get<MW>(), ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700157}
158
159template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700160typename std::enable_if<IsAfterHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700161 afterHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
162 ParentContext& /*parent_ctx*/)
163{
164 mw.afterHandle(req, res, ctx.template get<MW>());
Ed Tanous7045c8d2017-04-03 10:04:37 -0700165}
166
Ed Tanous271584a2019-07-09 16:24:22 -0700167template <size_t N, typename Context, typename Container, typename CurrentMW,
Ed Tanous7045c8d2017-04-03 10:04:37 -0700168 typename... Middlewares>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700169bool middlewareCallHelper(Container& middlewares, Request& req, Response& res,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700170 Context& ctx)
171{
172 using parent_context_t = typename Context::template partial<N - 1>;
173 beforeHandlerCall<CurrentMW, Context, parent_context_t>(
Ed Tanous7045c8d2017-04-03 10:04:37 -0700174 std::get<N>(middlewares), req, res, ctx,
175 static_cast<parent_context_t&>(ctx));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700176
Ed Tanous1abe55e2018-09-05 08:30:59 -0700177 if (res.isCompleted())
178 {
179 afterHandlerCall<CurrentMW, Context, parent_context_t>(
180 std::get<N>(middlewares), req, res, ctx,
181 static_cast<parent_context_t&>(ctx));
182 return true;
183 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700184
Ed Tanous1abe55e2018-09-05 08:30:59 -0700185 if (middlewareCallHelper<N + 1, Context, Container, Middlewares...>(
186 middlewares, req, res, ctx))
187 {
188 afterHandlerCall<CurrentMW, Context, parent_context_t>(
189 std::get<N>(middlewares), req, res, ctx,
190 static_cast<parent_context_t&>(ctx));
191 return true;
192 }
193
194 return false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700195}
196
Ed Tanous271584a2019-07-09 16:24:22 -0700197template <size_t N, typename Context, typename Container>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700198bool middlewareCallHelper(Container& /*middlewares*/, Request& /*req*/,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700199 Response& /*res*/, Context& /*ctx*/)
200{
201 return false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700202}
203
Ed Tanous271584a2019-07-09 16:24:22 -0700204template <size_t N, typename Context, typename Container>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700205typename std::enable_if<(N < 0)>::type
206 afterHandlersCallHelper(Container& /*middlewares*/, Context& /*Context*/,
207 Request& /*req*/, Response& /*res*/)
208{
Ed Tanous7045c8d2017-04-03 10:04:37 -0700209}
210
Ed Tanous271584a2019-07-09 16:24:22 -0700211template <size_t N, typename Context, typename Container>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700212typename std::enable_if<(N == 0)>::type
213 afterHandlersCallHelper(Container& middlewares, Context& ctx, Request& req,
214 Response& res)
215{
216 using parent_context_t = typename Context::template partial<N - 1>;
217 using CurrentMW = typename std::tuple_element<
218 N, typename std::remove_reference<Container>::type>::type;
219 afterHandlerCall<CurrentMW, Context, parent_context_t>(
220 std::get<N>(middlewares), req, res, ctx,
221 static_cast<parent_context_t&>(ctx));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700222}
Ed Tanous1abe55e2018-09-05 08:30:59 -0700223
Ed Tanous271584a2019-07-09 16:24:22 -0700224template <size_t N, typename Context, typename Container>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700225typename std::enable_if<(N > 0)>::type
226 afterHandlersCallHelper(Container& middlewares, Context& ctx, Request& req,
227 Response& res)
228{
229 using parent_context_t = typename Context::template partial<N - 1>;
230 using CurrentMW = typename std::tuple_element<
231 N, typename std::remove_reference<Container>::type>::type;
232 afterHandlerCall<CurrentMW, Context, parent_context_t>(
233 std::get<N>(middlewares), req, res, ctx,
234 static_cast<parent_context_t&>(ctx));
235 afterHandlersCallHelper<N - 1, Context, Container>(middlewares, ctx, req,
236 res);
237}
238} // namespace detail
Ed Tanous7045c8d2017-04-03 10:04:37 -0700239
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700240#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -0700241static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700242#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -0700243
244// request body limit size: 30M
245constexpr unsigned int httpReqBodyLimit = 1024 * 1024 * 30;
246
Ed Tanous7045c8d2017-04-03 10:04:37 -0700247template <typename Adaptor, typename Handler, typename... Middlewares>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700248class Connection
249{
250 public:
Ed Tanous271584a2019-07-09 16:24:22 -0700251 Connection(boost::asio::io_context& ioService, Handler* handlerIn,
252 const std::string& ServerNameIn,
253 std::tuple<Middlewares...>* middlewaresIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700254 std::function<std::string()>& get_cached_date_str_f,
Ed Tanous271584a2019-07-09 16:24:22 -0700255 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -0800256 adaptor(std::move(adaptorIn)),
Ed Tanous271584a2019-07-09 16:24:22 -0700257 handler(handlerIn), serverName(ServerNameIn),
258 middlewares(middlewaresIn), getCachedDateStr(get_cached_date_str_f),
259 timerQueue(timerQueueIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700260 {
261 parser.emplace(std::piecewise_construct, std::make_tuple());
262 // Temporarily changed to 30MB; Need to modify uploading/authentication
263 // mechanism
264 parser->body_limit(httpReqBodyLimit);
265 req.emplace(parser->get());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200266
267#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
268 adaptor.set_verify_callback(
269 [this](bool preverified, boost::asio::ssl::verify_context& ctx) {
Zbigniew Kurzynski501f1e52019-10-02 11:22:11 +0200270 // do nothing if TLS is disabled
271 if (!crow::persistent_data::SessionStore::getInstance()
272 .getAuthMethodsConfig()
273 .tls)
274 {
275 BMCWEB_LOG_DEBUG << "TLS auth_config is disabled";
276 return true;
277 }
278
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200279 // We always return true to allow full auth flow
280 if (!preverified)
281 {
282 return true;
283 }
284
285 X509_STORE_CTX* cts = ctx.native_handle();
286 if (cts == nullptr)
287 {
288 return true;
289 }
290
291 // Get certificate
292 X509* peerCert =
293 X509_STORE_CTX_get_current_cert(ctx.native_handle());
294 if (peerCert == nullptr)
295 {
296 return true;
297 }
298
299 // Check if certificate is OK
300 int error = X509_STORE_CTX_get_error(cts);
301 if (error != X509_V_OK)
302 {
303 return true;
304 }
305 // Check that we have reached final certificate in chain
306 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
307 if (depth != 0)
308
309 {
310 BMCWEB_LOG_DEBUG
311 << "Certificate verification in progress (depth "
312 << depth << "), waiting to reach final depth";
313 return true;
314 }
315
316 BMCWEB_LOG_DEBUG << "Certificate verification of final depth";
317
318 // Verify KeyUsage
319 bool isKeyUsageDigitalSignature = false;
320 bool isKeyUsageKeyAgreement = false;
321
322 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
323 X509_get_ext_d2i(peerCert, NID_key_usage, NULL, NULL));
324
325 if (usage == nullptr)
326 {
327 return true;
328 }
329
330 for (int i = 0; i < usage->length; i++)
331 {
332 if (KU_DIGITAL_SIGNATURE & usage->data[i])
333 {
334 isKeyUsageDigitalSignature = true;
335 }
336 if (KU_KEY_AGREEMENT & usage->data[i])
337 {
338 isKeyUsageKeyAgreement = true;
339 }
340 }
341
342 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
343 {
344 BMCWEB_LOG_DEBUG << "Certificate ExtendedKeyUsage does "
345 "not allow provided certificate to "
346 "be used for user authentication";
347 return true;
348 }
349
350 // Determine that ExtendedKeyUsage includes Client Auth
351
352 stack_st_ASN1_OBJECT* extUsage =
353 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
354 peerCert, NID_ext_key_usage, NULL, NULL));
355
356 if (extUsage == nullptr)
357 {
358 return true;
359 }
360
361 bool isExKeyUsageClientAuth = false;
362 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
363 {
364 if (NID_client_auth ==
365 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
366 {
367 isExKeyUsageClientAuth = true;
368 break;
369 }
370 }
371
372 // Certificate has to have proper key usages set
373 if (!isExKeyUsageClientAuth)
374 {
375 BMCWEB_LOG_DEBUG << "Certificate ExtendedKeyUsage does "
376 "not allow provided certificate to "
377 "be used for user authentication";
378 return true;
379 }
380 std::string sslUser;
381 // Extract username contained in CommonName
382 sslUser.resize(256, '\0');
383
384 int status = X509_NAME_get_text_by_NID(
385 X509_get_subject_name(peerCert), NID_commonName,
386 sslUser.data(), static_cast<int>(sslUser.size()));
387
388 if (status == -1)
389 {
390 return true;
391 }
392
393 size_t lastChar = sslUser.find('\0');
394 if (lastChar == std::string::npos || lastChar == 0)
395 {
396 return true;
397 }
Zbigniew Lukwinski7d7034a2019-11-14 15:49:29 +0100398 sslUser.resize(lastChar);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200399
400 session =
401 persistent_data::SessionStore::getInstance()
402 .generateUserSession(
403 sslUser,
404 crow::persistent_data::PersistenceType::TIMEOUT);
405
406 return true;
407 });
408#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
409
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700410#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700411 connectionCount++;
412 BMCWEB_LOG_DEBUG << this << " Connection open, total "
413 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700414#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700415 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700416
Ed Tanous1abe55e2018-09-05 08:30:59 -0700417 ~Connection()
418 {
419 res.completeRequestHandler = nullptr;
420 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700421#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700422 connectionCount--;
423 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
424 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700425#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700426 }
427
Ed Tanousceac6f72018-12-02 11:58:47 -0800428 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700429 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800430 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700431 }
432
Ed Tanous1abe55e2018-09-05 08:30:59 -0700433 void start()
434 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700435
Ed Tanousceac6f72018-12-02 11:58:47 -0800436 startDeadline();
437 // TODO(ed) Abstract this to a more clever class with the idea of an
438 // asynchronous "start"
439 if constexpr (std::is_same_v<Adaptor,
440 boost::beast::ssl_stream<
441 boost::asio::ip::tcp::socket>>)
442 {
443 adaptor.async_handshake(
444 boost::asio::ssl::stream_base::server,
445 [this](const boost::system::error_code& ec) {
446 if (ec)
447 {
448 checkDestroy();
449 return;
450 }
451 doReadHeaders();
452 });
453 }
454 else
455 {
456 doReadHeaders();
457 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700458 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700459
Ed Tanous1abe55e2018-09-05 08:30:59 -0700460 void handle()
461 {
462 cancelDeadlineTimer();
463 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700464
Ed Tanous1abe55e2018-09-05 08:30:59 -0700465 // Check for HTTP version 1.1.
466 if (req->version() == 11)
467 {
468 if (req->getHeaderValue(boost::beast::http::field::host).empty())
469 {
470 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700471 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700472 }
473 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700474
Ed Tanouse278c182019-03-13 16:23:37 -0700475 BMCWEB_LOG_INFO << "Request: "
476 << " " << this << " HTTP/" << req->version() / 10 << "."
477 << req->version() % 10 << ' ' << req->methodString()
478 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700479
Ed Tanous1abe55e2018-09-05 08:30:59 -0700480 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700481
Ed Tanous1abe55e2018-09-05 08:30:59 -0700482 if (!isInvalidRequest)
483 {
484 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700485 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700486
Ed Tanous1abe55e2018-09-05 08:30:59 -0700487 ctx = detail::Context<Middlewares...>();
Ed Tanouse278c182019-03-13 16:23:37 -0700488 req->middlewareContext = static_cast<void*>(&ctx);
489 req->ioService = static_cast<decltype(req->ioService)>(
490 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200491
492#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
493 if (auto sp = session.lock())
494 {
495 BMCWEB_LOG_DEBUG << "TLS session: " << sp->uniqueId
496 << " will be used for this request.";
497 req->session = sp;
498 }
499#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
500
Ed Tanous1abe55e2018-09-05 08:30:59 -0700501 detail::middlewareCallHelper<
Ed Tanous271584a2019-07-09 16:24:22 -0700502 0U, decltype(ctx), decltype(*middlewares), Middlewares...>(
Ed Tanous1abe55e2018-09-05 08:30:59 -0700503 *middlewares, *req, res, ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700504
Ed Tanous1abe55e2018-09-05 08:30:59 -0700505 if (!res.completed)
506 {
507 if (req->isUpgrade() &&
508 boost::iequals(
509 req->getHeaderValue(boost::beast::http::field::upgrade),
510 "websocket"))
511 {
512 handler->handleUpgrade(*req, res, std::move(adaptor));
513 return;
514 }
515 res.completeRequestHandler = [this] {
516 this->completeRequest();
517 };
518 needToCallAfterHandlers = true;
519 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700520 }
521 else
522 {
523 completeRequest();
524 }
525 }
526 else
527 {
528 completeRequest();
529 }
530 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700531
Ed Tanouse278c182019-03-13 16:23:37 -0700532 bool isAlive()
533 {
534
535 if constexpr (std::is_same_v<Adaptor,
536 boost::beast::ssl_stream<
537 boost::asio::ip::tcp::socket>>)
538 {
539 return adaptor.next_layer().is_open();
540 }
541 else
542 {
543 return adaptor.is_open();
544 }
545 }
546 void close()
547 {
Ed Tanouse278c182019-03-13 16:23:37 -0700548 if constexpr (std::is_same_v<Adaptor,
549 boost::beast::ssl_stream<
550 boost::asio::ip::tcp::socket>>)
551 {
552 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200553#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
554 if (auto sp = session.lock())
555 {
556 BMCWEB_LOG_DEBUG << "Removing TLS session: " << sp->uniqueId;
557 persistent_data::SessionStore::getInstance().removeSession(sp);
558 }
559#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700560 }
561 else
562 {
563 adaptor.close();
564 }
565 }
566
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567 void completeRequest()
568 {
569 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
570 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700571
Ed Tanous1abe55e2018-09-05 08:30:59 -0700572 if (needToCallAfterHandlers)
573 {
574 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700575
Ed Tanous1abe55e2018-09-05 08:30:59 -0700576 // call all afterHandler of middlewares
Ed Tanous271584a2019-07-09 16:24:22 -0700577 detail::afterHandlersCallHelper<sizeof...(Middlewares) - 1,
Ed Tanousb01bf292019-03-25 19:25:26 +0000578 decltype(ctx),
579 decltype(*middlewares)>(
580 *middlewares, ctx, *req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700581 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700582
Ed Tanous1abe55e2018-09-05 08:30:59 -0700583 // auto self = this->shared_from_this();
Ed Tanousb01bf292019-03-25 19:25:26 +0000584 res.completeRequestHandler = res.completeRequestHandler = [] {};
Ed Tanous7045c8d2017-04-03 10:04:37 -0700585
Ed Tanouse278c182019-03-13 16:23:37 -0700586 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700587 {
588 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
589 // isReading
590 // << ' ' << isWriting;
591 // delete this;
592 return;
593 }
594 if (res.body().empty() && !res.jsonValue.empty())
595 {
596 if (http_helpers::requestPrefersHtml(*req))
597 {
598 prettyPrintJson(res);
599 }
600 else
601 {
602 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700603 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700604 }
605 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700606
Ed Tanous1abe55e2018-09-05 08:30:59 -0700607 if (res.resultInt() >= 400 && res.body().empty())
608 {
609 res.body() = std::string(res.reason());
610 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700611
612 if (res.result() == boost::beast::http::status::no_content)
613 {
614 // Boost beast throws if content is provided on a no-content
615 // response. Ideally, this would never happen, but in the case that
616 // it does, we don't want to throw.
617 BMCWEB_LOG_CRITICAL
618 << "Response content provided but code was no-content";
619 res.body().clear();
620 }
621
Ed Tanous1abe55e2018-09-05 08:30:59 -0700622 res.addHeader(boost::beast::http::field::server, serverName);
623 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
624
625 res.keepAlive(req->keepAlive());
626
627 doWrite();
628 }
629
630 private:
631 void doReadHeaders()
632 {
633 // auto self = this->shared_from_this();
634 isReading = true;
635 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
636
637 // Clean up any previous Connection.
638 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800639 adaptor, buffer, *parser,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700640 [this](const boost::system::error_code& ec,
641 std::size_t bytes_transferred) {
642 isReading = false;
643 BMCWEB_LOG_ERROR << this << " async_read_header "
644 << bytes_transferred << " Bytes";
645 bool errorWhileReading = false;
646 if (ec)
647 {
648 errorWhileReading = true;
649 BMCWEB_LOG_ERROR
650 << this << " Error while reading: " << ec.message();
651 }
652 else
653 {
654 // if the adaptor isn't open anymore, and wasn't handed to a
655 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700656 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700657 {
658 errorWhileReading = true;
659 }
660 }
661
662 if (errorWhileReading)
663 {
664 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700665 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700666 BMCWEB_LOG_DEBUG << this << " from read(1)";
667 checkDestroy();
668 return;
669 }
670
671 // Compute the url parameters for the request
672 req->url = req->target();
673 std::size_t index = req->url.find("?");
Ed Tanous39e77502019-03-04 17:35:53 -0800674 if (index != std::string_view::npos)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700675 {
Jason M. Bills43fcbe52018-10-16 15:19:20 -0700676 req->url = req->url.substr(0, index);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700677 }
678 req->urlParams = QueryString(std::string(req->target()));
679 doRead();
680 });
681 }
682
683 void doRead()
684 {
685 // auto self = this->shared_from_this();
686 isReading = true;
687 BMCWEB_LOG_DEBUG << this << " doRead";
688
689 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800690 adaptor, buffer, *parser,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700691 [this](const boost::system::error_code& ec,
692 std::size_t bytes_transferred) {
693 BMCWEB_LOG_ERROR << this << " async_read " << bytes_transferred
694 << " Bytes";
695 isReading = false;
696
697 bool errorWhileReading = false;
698 if (ec)
699 {
700 BMCWEB_LOG_ERROR << "Error while reading: " << ec.message();
701 errorWhileReading = true;
702 }
703 else
704 {
Ed Tanouse278c182019-03-13 16:23:37 -0700705 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700706 {
707 errorWhileReading = true;
708 }
709 }
710 if (errorWhileReading)
711 {
712 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700713 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700714 BMCWEB_LOG_DEBUG << this << " from read(1)";
715 checkDestroy();
716 return;
717 }
718 handle();
719 });
720 }
721
722 void doWrite()
723 {
724 // auto self = this->shared_from_this();
725 isWriting = true;
726 BMCWEB_LOG_DEBUG << "Doing Write";
727 res.preparePayload();
728 serializer.emplace(*res.stringResponse);
729 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800730 adaptor, *serializer,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700731 [&](const boost::system::error_code& ec,
732 std::size_t bytes_transferred) {
733 isWriting = false;
734 BMCWEB_LOG_DEBUG << this << " Wrote " << bytes_transferred
735 << " bytes";
736
737 if (ec)
738 {
739 BMCWEB_LOG_DEBUG << this << " from write(2)";
740 checkDestroy();
741 return;
742 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800743 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700744 {
Ed Tanouse278c182019-03-13 16:23:37 -0700745 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746 BMCWEB_LOG_DEBUG << this << " from write(1)";
747 checkDestroy();
748 return;
749 }
750
751 serializer.reset();
752 BMCWEB_LOG_DEBUG << this << " Clearing response";
753 res.clear();
754 parser.emplace(std::piecewise_construct, std::make_tuple());
755 parser->body_limit(httpReqBodyLimit); // reset body limit for
756 // newly created parser
757 buffer.consume(buffer.size());
758
759 req.emplace(parser->get());
760 doReadHeaders();
761 });
762 }
763
764 void checkDestroy()
765 {
766 BMCWEB_LOG_DEBUG << this << " isReading " << isReading << " isWriting "
767 << isWriting;
768 if (!isReading && !isWriting)
769 {
770 BMCWEB_LOG_DEBUG << this << " delete (idle) ";
771 delete this;
772 }
773 }
774
775 void cancelDeadlineTimer()
776 {
777 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue << ' '
778 << timerCancelKey;
779 timerQueue.cancel(timerCancelKey);
780 }
781
782 void startDeadline()
783 {
784 cancelDeadlineTimer();
785
786 timerCancelKey = timerQueue.add([this] {
Ed Tanouse278c182019-03-13 16:23:37 -0700787 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700788 {
789 return;
790 }
Ed Tanouse278c182019-03-13 16:23:37 -0700791 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700792 });
793 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
794 << timerCancelKey;
795 }
796
797 private:
798 Adaptor adaptor;
799 Handler* handler;
800
Ed Tanousa24526d2018-12-10 15:17:59 -0800801 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700802 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800803 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700804 boost::beast::http::request_parser<boost::beast::http::string_body>>
805 parser;
806
Ed Tanous3112a142018-11-29 15:45:10 -0800807 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700808
Ed Tanousa24526d2018-12-10 15:17:59 -0800809 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700810 boost::beast::http::string_body>>
811 serializer;
812
Ed Tanousa24526d2018-12-10 15:17:59 -0800813 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700814 crow::Response res;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200815#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
816 std::weak_ptr<crow::persistent_data::UserSession> session;
817#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous1abe55e2018-09-05 08:30:59 -0700818
819 const std::string& serverName;
820
Ed Tanous271584a2019-07-09 16:24:22 -0700821 size_t timerCancelKey = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700822
823 bool isReading{};
824 bool isWriting{};
825 bool needToCallAfterHandlers{};
826 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700827
828 std::tuple<Middlewares...>* middlewares;
829 detail::Context<Middlewares...> ctx;
830
831 std::function<std::string()>& getCachedDateStr;
832 detail::TimerQueue& timerQueue;
Ed Tanous3112a142018-11-29 15:45:10 -0800833};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700834} // namespace crow