blob: 0b15616b7205cd7dadcaf883353c34361a8b8804 [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
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100268 auto ca_available = !std::filesystem::is_empty(
269 std::filesystem::path(ensuressl::trustStorePath));
270 if (ca_available && crow::persistent_data::SessionStore::getInstance()
271 .getAuthMethodsConfig()
272 .tls)
273 {
274 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
275 SSL_set_session_id_context(
276 adaptor.native_handle(),
277 reinterpret_cast<const unsigned char*>(serverName.c_str()),
278 serverName.length());
279 BMCWEB_LOG_DEBUG << this << " TLS is enabled on this connection.";
280 }
281
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100282 adaptor.set_verify_callback([this](
283 bool preverified,
284 boost::asio::ssl::verify_context& ctx) {
285 // do nothing if TLS is disabled
286 if (!crow::persistent_data::SessionStore::getInstance()
287 .getAuthMethodsConfig()
288 .tls)
289 {
290 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200291 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100292 }
293
294 // We always return true to allow full auth flow
295 if (!preverified)
296 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100297 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100298 return true;
299 }
300
301 X509_STORE_CTX* cts = ctx.native_handle();
302 if (cts == nullptr)
303 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100304 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100305 return true;
306 }
307
308 // Get certificate
309 X509* peerCert =
310 X509_STORE_CTX_get_current_cert(ctx.native_handle());
311 if (peerCert == nullptr)
312 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100313 BMCWEB_LOG_DEBUG << this
314 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100315 return true;
316 }
317
318 // Check if certificate is OK
319 int error = X509_STORE_CTX_get_error(cts);
320 if (error != X509_V_OK)
321 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100322 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100323 return true;
324 }
325 // Check that we have reached final certificate in chain
326 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
327 if (depth != 0)
328
329 {
330 BMCWEB_LOG_DEBUG
331 << this << " Certificate verification in progress (depth "
332 << depth << "), waiting to reach final depth";
333 return true;
334 }
335
336 BMCWEB_LOG_DEBUG << this
337 << " Certificate verification of final depth";
338
339 // Verify KeyUsage
340 bool isKeyUsageDigitalSignature = false;
341 bool isKeyUsageKeyAgreement = false;
342
343 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
344 X509_get_ext_d2i(peerCert, NID_key_usage, NULL, NULL));
345
346 if (usage == nullptr)
347 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100348 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100349 return true;
350 }
351
352 for (int i = 0; i < usage->length; i++)
353 {
354 if (KU_DIGITAL_SIGNATURE & usage->data[i])
355 {
356 isKeyUsageDigitalSignature = true;
357 }
358 if (KU_KEY_AGREEMENT & usage->data[i])
359 {
360 isKeyUsageKeyAgreement = true;
361 }
362 }
363
364 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
365 {
366 BMCWEB_LOG_DEBUG << this
367 << " Certificate ExtendedKeyUsage does "
368 "not allow provided certificate to "
369 "be used for user authentication";
370 return true;
371 }
372
373 // Determine that ExtendedKeyUsage includes Client Auth
374
375 stack_st_ASN1_OBJECT* extUsage = static_cast<stack_st_ASN1_OBJECT*>(
376 X509_get_ext_d2i(peerCert, NID_ext_key_usage, NULL, NULL));
377
378 if (extUsage == nullptr)
379 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100380 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100381 return true;
382 }
383
384 bool isExKeyUsageClientAuth = false;
385 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
386 {
387 if (NID_client_auth ==
388 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
389 {
390 isExKeyUsageClientAuth = true;
391 break;
392 }
393 }
394
395 // Certificate has to have proper key usages set
396 if (!isExKeyUsageClientAuth)
397 {
398 BMCWEB_LOG_DEBUG << this
399 << " Certificate ExtendedKeyUsage does "
400 "not allow provided certificate to "
401 "be used for user authentication";
402 return true;
403 }
404 std::string sslUser;
405 // Extract username contained in CommonName
406 sslUser.resize(256, '\0');
407
408 int status = X509_NAME_get_text_by_NID(
409 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
410 static_cast<int>(sslUser.size()));
411
412 if (status == -1)
413 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100414 BMCWEB_LOG_DEBUG
415 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100416 return true;
417 }
418
419 size_t lastChar = sslUser.find('\0');
420 if (lastChar == std::string::npos || lastChar == 0)
421 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100422 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100423 return true;
424 }
425 sslUser.resize(lastChar);
426
427 session = persistent_data::SessionStore::getInstance()
428 .generateUserSession(
429 sslUser,
430 crow::persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100431 if (auto sp = session.lock())
432 {
433 BMCWEB_LOG_DEBUG << this
434 << " Generating TLS session: " << sp->uniqueId;
435 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100436 return true;
437 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200438#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
439
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700440#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700441 connectionCount++;
442 BMCWEB_LOG_DEBUG << this << " Connection open, total "
443 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700444#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700445 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700446
Ed Tanous1abe55e2018-09-05 08:30:59 -0700447 ~Connection()
448 {
449 res.completeRequestHandler = nullptr;
450 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700451#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700452 connectionCount--;
453 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
454 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700455#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700456 }
457
Ed Tanousceac6f72018-12-02 11:58:47 -0800458 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700459 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800460 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700461 }
462
Ed Tanous1abe55e2018-09-05 08:30:59 -0700463 void start()
464 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700465
Ed Tanousceac6f72018-12-02 11:58:47 -0800466 startDeadline();
467 // TODO(ed) Abstract this to a more clever class with the idea of an
468 // asynchronous "start"
469 if constexpr (std::is_same_v<Adaptor,
470 boost::beast::ssl_stream<
471 boost::asio::ip::tcp::socket>>)
472 {
473 adaptor.async_handshake(
474 boost::asio::ssl::stream_base::server,
475 [this](const boost::system::error_code& ec) {
476 if (ec)
477 {
478 checkDestroy();
479 return;
480 }
481 doReadHeaders();
482 });
483 }
484 else
485 {
486 doReadHeaders();
487 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700488 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700489
Ed Tanous1abe55e2018-09-05 08:30:59 -0700490 void handle()
491 {
492 cancelDeadlineTimer();
493 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700494
Ed Tanous1abe55e2018-09-05 08:30:59 -0700495 // Check for HTTP version 1.1.
496 if (req->version() == 11)
497 {
498 if (req->getHeaderValue(boost::beast::http::field::host).empty())
499 {
500 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700501 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700502 }
503 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700504
Ed Tanouse278c182019-03-13 16:23:37 -0700505 BMCWEB_LOG_INFO << "Request: "
506 << " " << this << " HTTP/" << req->version() / 10 << "."
507 << req->version() % 10 << ' ' << req->methodString()
508 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700509
Ed Tanous1abe55e2018-09-05 08:30:59 -0700510 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700511
Ed Tanous1abe55e2018-09-05 08:30:59 -0700512 if (!isInvalidRequest)
513 {
514 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700515 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700516
Ed Tanous1abe55e2018-09-05 08:30:59 -0700517 ctx = detail::Context<Middlewares...>();
Ed Tanouse278c182019-03-13 16:23:37 -0700518 req->middlewareContext = static_cast<void*>(&ctx);
519 req->ioService = static_cast<decltype(req->ioService)>(
520 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200521
522#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
523 if (auto sp = session.lock())
524 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100525 // set cookie only if this is req from the browser.
526 if (req->getHeaderValue("User-Agent").empty())
527 {
528 BMCWEB_LOG_DEBUG << this << " TLS session: " << sp->uniqueId
529 << " will be used for this request.";
530 req->session = sp;
531 }
532 else
533 {
534 std::string_view cookieValue =
535 req->getHeaderValue("Cookie");
536 if (cookieValue.empty() ||
537 cookieValue.find("SESSION=") == std::string::npos)
538 {
539 res.addHeader("Set-Cookie",
540 "XSRF-TOKEN=" + sp->csrfToken +
541 "; Secure\r\nSet-Cookie: SESSION=" +
542 sp->sessionToken +
543 "; Secure; HttpOnly");
544 BMCWEB_LOG_DEBUG
545 << this << " TLS session: " << sp->uniqueId
546 << " with cookie will be used for this request.";
547 req->session = sp;
548 }
549 }
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200550 }
551#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
552
Ed Tanous1abe55e2018-09-05 08:30:59 -0700553 detail::middlewareCallHelper<
Ed Tanous271584a2019-07-09 16:24:22 -0700554 0U, decltype(ctx), decltype(*middlewares), Middlewares...>(
Ed Tanous1abe55e2018-09-05 08:30:59 -0700555 *middlewares, *req, res, ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700556
Ed Tanous1abe55e2018-09-05 08:30:59 -0700557 if (!res.completed)
558 {
559 if (req->isUpgrade() &&
560 boost::iequals(
561 req->getHeaderValue(boost::beast::http::field::upgrade),
562 "websocket"))
563 {
564 handler->handleUpgrade(*req, res, std::move(adaptor));
565 return;
566 }
567 res.completeRequestHandler = [this] {
568 this->completeRequest();
569 };
570 needToCallAfterHandlers = true;
571 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700572 }
573 else
574 {
575 completeRequest();
576 }
577 }
578 else
579 {
580 completeRequest();
581 }
582 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700583
Ed Tanouse278c182019-03-13 16:23:37 -0700584 bool isAlive()
585 {
586
587 if constexpr (std::is_same_v<Adaptor,
588 boost::beast::ssl_stream<
589 boost::asio::ip::tcp::socket>>)
590 {
591 return adaptor.next_layer().is_open();
592 }
593 else
594 {
595 return adaptor.is_open();
596 }
597 }
598 void close()
599 {
Ed Tanouse278c182019-03-13 16:23:37 -0700600 if constexpr (std::is_same_v<Adaptor,
601 boost::beast::ssl_stream<
602 boost::asio::ip::tcp::socket>>)
603 {
604 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200605#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
606 if (auto sp = session.lock())
607 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100608 BMCWEB_LOG_DEBUG << this
609 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200610 persistent_data::SessionStore::getInstance().removeSession(sp);
611 }
612#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700613 }
614 else
615 {
616 adaptor.close();
617 }
618 }
619
Ed Tanous1abe55e2018-09-05 08:30:59 -0700620 void completeRequest()
621 {
622 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
623 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700624
Ed Tanous1abe55e2018-09-05 08:30:59 -0700625 if (needToCallAfterHandlers)
626 {
627 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700628
Ed Tanous1abe55e2018-09-05 08:30:59 -0700629 // call all afterHandler of middlewares
Ed Tanous271584a2019-07-09 16:24:22 -0700630 detail::afterHandlersCallHelper<sizeof...(Middlewares) - 1,
Ed Tanousb01bf292019-03-25 19:25:26 +0000631 decltype(ctx),
632 decltype(*middlewares)>(
633 *middlewares, ctx, *req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700634 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700635
Ed Tanous1abe55e2018-09-05 08:30:59 -0700636 // auto self = this->shared_from_this();
Ed Tanousb01bf292019-03-25 19:25:26 +0000637 res.completeRequestHandler = res.completeRequestHandler = [] {};
Ed Tanous7045c8d2017-04-03 10:04:37 -0700638
Ed Tanouse278c182019-03-13 16:23:37 -0700639 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700640 {
641 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
642 // isReading
643 // << ' ' << isWriting;
644 // delete this;
645 return;
646 }
647 if (res.body().empty() && !res.jsonValue.empty())
648 {
649 if (http_helpers::requestPrefersHtml(*req))
650 {
651 prettyPrintJson(res);
652 }
653 else
654 {
655 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700656 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700657 }
658 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700659
Ed Tanous1abe55e2018-09-05 08:30:59 -0700660 if (res.resultInt() >= 400 && res.body().empty())
661 {
662 res.body() = std::string(res.reason());
663 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700664
665 if (res.result() == boost::beast::http::status::no_content)
666 {
667 // Boost beast throws if content is provided on a no-content
668 // response. Ideally, this would never happen, but in the case that
669 // it does, we don't want to throw.
670 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100671 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700672 res.body().clear();
673 }
674
Ed Tanous1abe55e2018-09-05 08:30:59 -0700675 res.addHeader(boost::beast::http::field::server, serverName);
676 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
677
678 res.keepAlive(req->keepAlive());
679
680 doWrite();
681 }
682
683 private:
684 void doReadHeaders()
685 {
686 // auto self = this->shared_from_this();
687 isReading = true;
688 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
689
690 // Clean up any previous Connection.
691 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800692 adaptor, buffer, *parser,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700693 [this](const boost::system::error_code& ec,
694 std::size_t bytes_transferred) {
695 isReading = false;
696 BMCWEB_LOG_ERROR << this << " async_read_header "
697 << bytes_transferred << " Bytes";
698 bool errorWhileReading = false;
699 if (ec)
700 {
701 errorWhileReading = true;
702 BMCWEB_LOG_ERROR
703 << this << " Error while reading: " << ec.message();
704 }
705 else
706 {
707 // if the adaptor isn't open anymore, and wasn't handed to a
708 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700709 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700710 {
711 errorWhileReading = true;
712 }
713 }
714
715 if (errorWhileReading)
716 {
717 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700718 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700719 BMCWEB_LOG_DEBUG << this << " from read(1)";
720 checkDestroy();
721 return;
722 }
723
724 // Compute the url parameters for the request
725 req->url = req->target();
726 std::size_t index = req->url.find("?");
Ed Tanous39e77502019-03-04 17:35:53 -0800727 if (index != std::string_view::npos)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700728 {
Jason M. Bills43fcbe52018-10-16 15:19:20 -0700729 req->url = req->url.substr(0, index);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700730 }
731 req->urlParams = QueryString(std::string(req->target()));
732 doRead();
733 });
734 }
735
736 void doRead()
737 {
738 // auto self = this->shared_from_this();
739 isReading = true;
740 BMCWEB_LOG_DEBUG << this << " doRead";
741
742 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800743 adaptor, buffer, *parser,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700744 [this](const boost::system::error_code& ec,
745 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100746 BMCWEB_LOG_DEBUG << this << " async_read " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700747 << " Bytes";
748 isReading = false;
749
750 bool errorWhileReading = false;
751 if (ec)
752 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100753 BMCWEB_LOG_ERROR
754 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700755 errorWhileReading = true;
756 }
757 else
758 {
Ed Tanouse278c182019-03-13 16:23:37 -0700759 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700760 {
761 errorWhileReading = true;
762 }
763 }
764 if (errorWhileReading)
765 {
766 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700767 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700768 BMCWEB_LOG_DEBUG << this << " from read(1)";
769 checkDestroy();
770 return;
771 }
772 handle();
773 });
774 }
775
776 void doWrite()
777 {
778 // auto self = this->shared_from_this();
779 isWriting = true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100780 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700781 res.preparePayload();
782 serializer.emplace(*res.stringResponse);
783 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800784 adaptor, *serializer,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700785 [&](const boost::system::error_code& ec,
786 std::size_t bytes_transferred) {
787 isWriting = false;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100788 BMCWEB_LOG_DEBUG << this << " async_write " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700789 << " bytes";
790
791 if (ec)
792 {
793 BMCWEB_LOG_DEBUG << this << " from write(2)";
794 checkDestroy();
795 return;
796 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800797 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700798 {
Ed Tanouse278c182019-03-13 16:23:37 -0700799 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700800 BMCWEB_LOG_DEBUG << this << " from write(1)";
801 checkDestroy();
802 return;
803 }
804
805 serializer.reset();
806 BMCWEB_LOG_DEBUG << this << " Clearing response";
807 res.clear();
808 parser.emplace(std::piecewise_construct, std::make_tuple());
809 parser->body_limit(httpReqBodyLimit); // reset body limit for
810 // newly created parser
811 buffer.consume(buffer.size());
812
813 req.emplace(parser->get());
814 doReadHeaders();
815 });
816 }
817
818 void checkDestroy()
819 {
820 BMCWEB_LOG_DEBUG << this << " isReading " << isReading << " isWriting "
821 << isWriting;
822 if (!isReading && !isWriting)
823 {
824 BMCWEB_LOG_DEBUG << this << " delete (idle) ";
825 delete this;
826 }
827 }
828
829 void cancelDeadlineTimer()
830 {
831 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue << ' '
832 << timerCancelKey;
833 timerQueue.cancel(timerCancelKey);
834 }
835
836 void startDeadline()
837 {
838 cancelDeadlineTimer();
839
840 timerCancelKey = timerQueue.add([this] {
Ed Tanouse278c182019-03-13 16:23:37 -0700841 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700842 {
843 return;
844 }
Ed Tanouse278c182019-03-13 16:23:37 -0700845 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700846 });
847 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
848 << timerCancelKey;
849 }
850
851 private:
852 Adaptor adaptor;
853 Handler* handler;
854
Ed Tanousa24526d2018-12-10 15:17:59 -0800855 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700856 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800857 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700858 boost::beast::http::request_parser<boost::beast::http::string_body>>
859 parser;
860
Ed Tanous3112a142018-11-29 15:45:10 -0800861 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700862
Ed Tanousa24526d2018-12-10 15:17:59 -0800863 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700864 boost::beast::http::string_body>>
865 serializer;
866
Ed Tanousa24526d2018-12-10 15:17:59 -0800867 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700868 crow::Response res;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200869#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
870 std::weak_ptr<crow::persistent_data::UserSession> session;
871#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous1abe55e2018-09-05 08:30:59 -0700872
873 const std::string& serverName;
874
Ed Tanous271584a2019-07-09 16:24:22 -0700875 size_t timerCancelKey = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700876
877 bool isReading{};
878 bool isWriting{};
879 bool needToCallAfterHandlers{};
880 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700881
882 std::tuple<Middlewares...>* middlewares;
883 detail::Context<Middlewares...> ctx;
884
885 std::function<std::string()>& getCachedDateStr;
886 detail::TimerQueue& timerQueue;
Ed Tanous3112a142018-11-29 15:45:10 -0800887};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700888} // namespace crow