blob: ef42f8468a7144114827f85f7b35d19c4bbadd3f [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:
116 static const 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:
132 static const 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());
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700266#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700267 connectionCount++;
268 BMCWEB_LOG_DEBUG << this << " Connection open, total "
269 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700270#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700271 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700272
Ed Tanous1abe55e2018-09-05 08:30:59 -0700273 ~Connection()
274 {
275 res.completeRequestHandler = nullptr;
276 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700277#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700278 connectionCount--;
279 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
280 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700281#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700282 }
283
Ed Tanousceac6f72018-12-02 11:58:47 -0800284 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700285 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800286 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700287 }
288
Ed Tanous1abe55e2018-09-05 08:30:59 -0700289 void start()
290 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700291
Ed Tanousceac6f72018-12-02 11:58:47 -0800292 startDeadline();
293 // TODO(ed) Abstract this to a more clever class with the idea of an
294 // asynchronous "start"
295 if constexpr (std::is_same_v<Adaptor,
296 boost::beast::ssl_stream<
297 boost::asio::ip::tcp::socket>>)
298 {
299 adaptor.async_handshake(
300 boost::asio::ssl::stream_base::server,
301 [this](const boost::system::error_code& ec) {
302 if (ec)
303 {
304 checkDestroy();
305 return;
306 }
307 doReadHeaders();
308 });
309 }
310 else
311 {
312 doReadHeaders();
313 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700314 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700315
Ed Tanous1abe55e2018-09-05 08:30:59 -0700316 void handle()
317 {
318 cancelDeadlineTimer();
319 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700320
Ed Tanous1abe55e2018-09-05 08:30:59 -0700321 // Check for HTTP version 1.1.
322 if (req->version() == 11)
323 {
324 if (req->getHeaderValue(boost::beast::http::field::host).empty())
325 {
326 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700327 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700328 }
329 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700330
Ed Tanouse278c182019-03-13 16:23:37 -0700331 BMCWEB_LOG_INFO << "Request: "
332 << " " << this << " HTTP/" << req->version() / 10 << "."
333 << req->version() % 10 << ' ' << req->methodString()
334 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700335
Ed Tanous1abe55e2018-09-05 08:30:59 -0700336 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700337
Ed Tanous1abe55e2018-09-05 08:30:59 -0700338 if (!isInvalidRequest)
339 {
340 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700341 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700342
Ed Tanous1abe55e2018-09-05 08:30:59 -0700343 ctx = detail::Context<Middlewares...>();
Ed Tanouse278c182019-03-13 16:23:37 -0700344 req->middlewareContext = static_cast<void*>(&ctx);
345 req->ioService = static_cast<decltype(req->ioService)>(
346 &adaptor.get_executor().context());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700347 detail::middlewareCallHelper<
Ed Tanous271584a2019-07-09 16:24:22 -0700348 0U, decltype(ctx), decltype(*middlewares), Middlewares...>(
Ed Tanous1abe55e2018-09-05 08:30:59 -0700349 *middlewares, *req, res, ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700350
Ed Tanous1abe55e2018-09-05 08:30:59 -0700351 if (!res.completed)
352 {
353 if (req->isUpgrade() &&
354 boost::iequals(
355 req->getHeaderValue(boost::beast::http::field::upgrade),
356 "websocket"))
357 {
358 handler->handleUpgrade(*req, res, std::move(adaptor));
359 return;
360 }
361 res.completeRequestHandler = [this] {
362 this->completeRequest();
363 };
364 needToCallAfterHandlers = true;
365 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700366 }
367 else
368 {
369 completeRequest();
370 }
371 }
372 else
373 {
374 completeRequest();
375 }
376 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700377
Ed Tanouse278c182019-03-13 16:23:37 -0700378 bool isAlive()
379 {
380
381 if constexpr (std::is_same_v<Adaptor,
382 boost::beast::ssl_stream<
383 boost::asio::ip::tcp::socket>>)
384 {
385 return adaptor.next_layer().is_open();
386 }
387 else
388 {
389 return adaptor.is_open();
390 }
391 }
392 void close()
393 {
394
395 if constexpr (std::is_same_v<Adaptor,
396 boost::beast::ssl_stream<
397 boost::asio::ip::tcp::socket>>)
398 {
399 adaptor.next_layer().close();
400 }
401 else
402 {
403 adaptor.close();
404 }
405 }
406
Ed Tanous1abe55e2018-09-05 08:30:59 -0700407 void completeRequest()
408 {
409 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
410 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700411
Ed Tanous1abe55e2018-09-05 08:30:59 -0700412 if (needToCallAfterHandlers)
413 {
414 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700415
Ed Tanous1abe55e2018-09-05 08:30:59 -0700416 // call all afterHandler of middlewares
Ed Tanous271584a2019-07-09 16:24:22 -0700417 detail::afterHandlersCallHelper<sizeof...(Middlewares) - 1,
Ed Tanousb01bf292019-03-25 19:25:26 +0000418 decltype(ctx),
419 decltype(*middlewares)>(
420 *middlewares, ctx, *req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700421 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700422
Ed Tanous1abe55e2018-09-05 08:30:59 -0700423 // auto self = this->shared_from_this();
Ed Tanousb01bf292019-03-25 19:25:26 +0000424 res.completeRequestHandler = res.completeRequestHandler = [] {};
Ed Tanous7045c8d2017-04-03 10:04:37 -0700425
Ed Tanouse278c182019-03-13 16:23:37 -0700426 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700427 {
428 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
429 // isReading
430 // << ' ' << isWriting;
431 // delete this;
432 return;
433 }
434 if (res.body().empty() && !res.jsonValue.empty())
435 {
436 if (http_helpers::requestPrefersHtml(*req))
437 {
438 prettyPrintJson(res);
439 }
440 else
441 {
442 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700443 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700444 }
445 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700446
Ed Tanous1abe55e2018-09-05 08:30:59 -0700447 if (res.resultInt() >= 400 && res.body().empty())
448 {
449 res.body() = std::string(res.reason());
450 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700451
452 if (res.result() == boost::beast::http::status::no_content)
453 {
454 // Boost beast throws if content is provided on a no-content
455 // response. Ideally, this would never happen, but in the case that
456 // it does, we don't want to throw.
457 BMCWEB_LOG_CRITICAL
458 << "Response content provided but code was no-content";
459 res.body().clear();
460 }
461
Ed Tanous1abe55e2018-09-05 08:30:59 -0700462 res.addHeader(boost::beast::http::field::server, serverName);
463 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
464
465 res.keepAlive(req->keepAlive());
466
467 doWrite();
468 }
469
470 private:
471 void doReadHeaders()
472 {
473 // auto self = this->shared_from_this();
474 isReading = true;
475 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
476
477 // Clean up any previous Connection.
478 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800479 adaptor, buffer, *parser,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700480 [this](const boost::system::error_code& ec,
481 std::size_t bytes_transferred) {
482 isReading = false;
483 BMCWEB_LOG_ERROR << this << " async_read_header "
484 << bytes_transferred << " Bytes";
485 bool errorWhileReading = false;
486 if (ec)
487 {
488 errorWhileReading = true;
489 BMCWEB_LOG_ERROR
490 << this << " Error while reading: " << ec.message();
491 }
492 else
493 {
494 // if the adaptor isn't open anymore, and wasn't handed to a
495 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700496 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700497 {
498 errorWhileReading = true;
499 }
500 }
501
502 if (errorWhileReading)
503 {
504 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700505 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700506 BMCWEB_LOG_DEBUG << this << " from read(1)";
507 checkDestroy();
508 return;
509 }
510
511 // Compute the url parameters for the request
512 req->url = req->target();
513 std::size_t index = req->url.find("?");
Ed Tanous39e77502019-03-04 17:35:53 -0800514 if (index != std::string_view::npos)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700515 {
Jason M. Bills43fcbe52018-10-16 15:19:20 -0700516 req->url = req->url.substr(0, index);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700517 }
518 req->urlParams = QueryString(std::string(req->target()));
519 doRead();
520 });
521 }
522
523 void doRead()
524 {
525 // auto self = this->shared_from_this();
526 isReading = true;
527 BMCWEB_LOG_DEBUG << this << " doRead";
528
529 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800530 adaptor, buffer, *parser,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700531 [this](const boost::system::error_code& ec,
532 std::size_t bytes_transferred) {
533 BMCWEB_LOG_ERROR << this << " async_read " << bytes_transferred
534 << " Bytes";
535 isReading = false;
536
537 bool errorWhileReading = false;
538 if (ec)
539 {
540 BMCWEB_LOG_ERROR << "Error while reading: " << ec.message();
541 errorWhileReading = true;
542 }
543 else
544 {
Ed Tanouse278c182019-03-13 16:23:37 -0700545 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700546 {
547 errorWhileReading = true;
548 }
549 }
550 if (errorWhileReading)
551 {
552 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700553 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700554 BMCWEB_LOG_DEBUG << this << " from read(1)";
555 checkDestroy();
556 return;
557 }
558 handle();
559 });
560 }
561
562 void doWrite()
563 {
564 // auto self = this->shared_from_this();
565 isWriting = true;
566 BMCWEB_LOG_DEBUG << "Doing Write";
567 res.preparePayload();
568 serializer.emplace(*res.stringResponse);
569 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800570 adaptor, *serializer,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700571 [&](const boost::system::error_code& ec,
572 std::size_t bytes_transferred) {
573 isWriting = false;
574 BMCWEB_LOG_DEBUG << this << " Wrote " << bytes_transferred
575 << " bytes";
576
577 if (ec)
578 {
579 BMCWEB_LOG_DEBUG << this << " from write(2)";
580 checkDestroy();
581 return;
582 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800583 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700584 {
Ed Tanouse278c182019-03-13 16:23:37 -0700585 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700586 BMCWEB_LOG_DEBUG << this << " from write(1)";
587 checkDestroy();
588 return;
589 }
590
591 serializer.reset();
592 BMCWEB_LOG_DEBUG << this << " Clearing response";
593 res.clear();
594 parser.emplace(std::piecewise_construct, std::make_tuple());
595 parser->body_limit(httpReqBodyLimit); // reset body limit for
596 // newly created parser
597 buffer.consume(buffer.size());
598
599 req.emplace(parser->get());
600 doReadHeaders();
601 });
602 }
603
604 void checkDestroy()
605 {
606 BMCWEB_LOG_DEBUG << this << " isReading " << isReading << " isWriting "
607 << isWriting;
608 if (!isReading && !isWriting)
609 {
610 BMCWEB_LOG_DEBUG << this << " delete (idle) ";
611 delete this;
612 }
613 }
614
615 void cancelDeadlineTimer()
616 {
617 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue << ' '
618 << timerCancelKey;
619 timerQueue.cancel(timerCancelKey);
620 }
621
622 void startDeadline()
623 {
624 cancelDeadlineTimer();
625
626 timerCancelKey = timerQueue.add([this] {
Ed Tanouse278c182019-03-13 16:23:37 -0700627 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700628 {
629 return;
630 }
Ed Tanouse278c182019-03-13 16:23:37 -0700631 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700632 });
633 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
634 << timerCancelKey;
635 }
636
637 private:
638 Adaptor adaptor;
639 Handler* handler;
640
Ed Tanousa24526d2018-12-10 15:17:59 -0800641 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800643 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700644 boost::beast::http::request_parser<boost::beast::http::string_body>>
645 parser;
646
Ed Tanous3112a142018-11-29 15:45:10 -0800647 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648
Ed Tanousa24526d2018-12-10 15:17:59 -0800649 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700650 boost::beast::http::string_body>>
651 serializer;
652
Ed Tanousa24526d2018-12-10 15:17:59 -0800653 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700654 crow::Response res;
655
656 const std::string& serverName;
657
Ed Tanous271584a2019-07-09 16:24:22 -0700658 size_t timerCancelKey = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700659
660 bool isReading{};
661 bool isWriting{};
662 bool needToCallAfterHandlers{};
663 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700664
665 std::tuple<Middlewares...>* middlewares;
666 detail::Context<Middlewares...> ctx;
667
668 std::function<std::string()>& getCachedDateStr;
669 detail::TimerQueue& timerQueue;
Ed Tanous3112a142018-11-29 15:45:10 -0800670};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700671} // namespace crow