blob: 6f1dafded0a05b44dbccd306b2769a799bf59cbd [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>
9#include <boost/beast/core/flat_static_buffer.hpp>
Ed Tanouse0d918b2018-03-27 17:41:04 -070010#include <boost/beast/http.hpp>
11#include <boost/beast/websocket.hpp>
Ed Tanous1abe55e2018-09-05 08:30:59 -070012#include <chrono>
Ed Tanous1abe55e2018-09-05 08:30:59 -070013#include <vector>
14
15#include "crow/http_response.h"
16#include "crow/logging.h"
17#include "crow/middleware_context.h"
Ed Tanous1abe55e2018-09-05 08:30:59 -070018#include "crow/timer_queue.h"
Ed Tanousa29c9972018-11-29 15:54:32 -080019#include "crow/utility.h"
Ed Tanous7045c8d2017-04-03 10:04:37 -070020
Ed Tanous55c7b7a2018-05-22 15:27:24 -070021#ifdef BMCWEB_ENABLE_SSL
Ed Tanousceac6f72018-12-02 11:58:47 -080022#include <boost/asio/ssl.hpp>
23#include <boost/beast/experimental/core/ssl_stream.hpp>
Ed Tanous911ac312017-08-15 09:37:42 -070024#endif
25
Ed Tanous1abe55e2018-09-05 08:30:59 -070026namespace crow
27{
Ed Tanous257f5792018-03-17 14:40:09 -070028
Ed Tanous1abe55e2018-09-05 08:30:59 -070029inline void prettyPrintJson(crow::Response& res)
30{
Jason M. Bills193ad2f2018-09-26 15:08:52 -070031 std::string value = res.jsonValue.dump(4, ' ', true);
Ed Tanousa29c9972018-11-29 15:54:32 -080032 utility::escapeHtml(value);
33 utility::convertToLinks(value);
Ed Tanous1abe55e2018-09-05 08:30:59 -070034 res.body() = "<html>\n"
35 "<head>\n"
36 "<title>Redfish API</title>\n"
37 "<link rel=\"stylesheet\" type=\"text/css\" "
38 "href=\"/styles/default.css\">\n"
39 "<script src=\"/highlight.pack.js\"></script>"
40 "<script>hljs.initHighlightingOnLoad();</script>"
41 "</head>\n"
42 "<body>\n"
43 "<div style=\"max-width: 576px;margin:0 auto;\">\n"
44 "<img src=\"/DMTF_Redfish_logo_2017.svg\" alt=\"redfish\" "
45 "height=\"406px\" "
46 "width=\"576px\">\n"
47 "<br>\n"
48 "<pre>\n"
49 "<code class=\"json\">" +
50 value +
51 "</code>\n"
52 "</pre>\n"
53 "</div>\n"
54 "</body>\n"
55 "</html>\n";
Ed Tanous93ef5802019-01-03 10:15:41 -080056 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070057}
58
Ed Tanous7045c8d2017-04-03 10:04:37 -070059using namespace boost;
60using tcp = asio::ip::tcp;
61
Ed Tanous1abe55e2018-09-05 08:30:59 -070062namespace detail
63{
64template <typename MW> struct CheckBeforeHandleArity3Const
65{
66 template <typename T,
67 void (T::*)(Request&, Response&, typename MW::Context&) const =
68 &T::beforeHandle>
69 struct Get
70 {
71 };
Ed Tanous7045c8d2017-04-03 10:04:37 -070072};
73
Ed Tanous1abe55e2018-09-05 08:30:59 -070074template <typename MW> struct CheckBeforeHandleArity3
75{
76 template <typename T, void (T::*)(Request&, Response&,
77 typename MW::Context&) = &T::beforeHandle>
78 struct Get
79 {
80 };
Ed Tanous7045c8d2017-04-03 10:04:37 -070081};
82
Ed Tanous1abe55e2018-09-05 08:30:59 -070083template <typename MW> struct CheckAfterHandleArity3Const
84{
85 template <typename T,
86 void (T::*)(Request&, Response&, typename MW::Context&) const =
87 &T::afterHandle>
88 struct Get
89 {
90 };
Ed Tanous7045c8d2017-04-03 10:04:37 -070091};
92
Ed Tanous1abe55e2018-09-05 08:30:59 -070093template <typename MW> struct CheckAfterHandleArity3
94{
95 template <typename T, void (T::*)(Request&, Response&,
96 typename MW::Context&) = &T::afterHandle>
97 struct Get
98 {
99 };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700100};
101
Ed Tanous1abe55e2018-09-05 08:30:59 -0700102template <typename T> struct IsBeforeHandleArity3Impl
103{
104 template <typename C>
105 static std::true_type
106 f(typename CheckBeforeHandleArity3Const<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700107
Ed Tanous1abe55e2018-09-05 08:30:59 -0700108 template <typename C>
109 static std::true_type
110 f(typename CheckBeforeHandleArity3<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700111
Ed Tanous1abe55e2018-09-05 08:30:59 -0700112 template <typename C> static std::false_type f(...);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700113
Ed Tanous1abe55e2018-09-05 08:30:59 -0700114 public:
115 static const bool value = decltype(f<T>(nullptr))::value;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700116};
117
Ed Tanous1abe55e2018-09-05 08:30:59 -0700118template <typename T> struct IsAfterHandleArity3Impl
119{
120 template <typename C>
121 static std::true_type
122 f(typename CheckAfterHandleArity3Const<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700123
Ed Tanous1abe55e2018-09-05 08:30:59 -0700124 template <typename C>
125 static std::true_type
126 f(typename CheckAfterHandleArity3<T>::template Get<C>*);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700127
Ed Tanous1abe55e2018-09-05 08:30:59 -0700128 template <typename C> static std::false_type f(...);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700129
Ed Tanous1abe55e2018-09-05 08:30:59 -0700130 public:
131 static const bool value = decltype(f<T>(nullptr))::value;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700132};
133
134template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700135typename std::enable_if<!IsBeforeHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700136 beforeHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
137 ParentContext& /*parent_ctx*/)
138{
139 mw.beforeHandle(req, res, ctx.template get<MW>(), ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700140}
141
142template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700143typename std::enable_if<IsBeforeHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700144 beforeHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
145 ParentContext& /*parent_ctx*/)
146{
147 mw.beforeHandle(req, res, ctx.template get<MW>());
Ed Tanous7045c8d2017-04-03 10:04:37 -0700148}
149
150template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700151typename std::enable_if<!IsAfterHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700152 afterHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
153 ParentContext& /*parent_ctx*/)
154{
155 mw.afterHandle(req, res, ctx.template get<MW>(), ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700156}
157
158template <typename MW, typename Context, typename ParentContext>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700159typename std::enable_if<IsAfterHandleArity3Impl<MW>::value>::type
Ed Tanous1abe55e2018-09-05 08:30:59 -0700160 afterHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
161 ParentContext& /*parent_ctx*/)
162{
163 mw.afterHandle(req, res, ctx.template get<MW>());
Ed Tanous7045c8d2017-04-03 10:04:37 -0700164}
165
166template <int N, typename Context, typename Container, typename CurrentMW,
167 typename... Middlewares>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700168bool middlewareCallHelper(Container& middlewares, Request& req, Response& res,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700169 Context& ctx)
170{
171 using parent_context_t = typename Context::template partial<N - 1>;
172 beforeHandlerCall<CurrentMW, Context, parent_context_t>(
Ed Tanous7045c8d2017-04-03 10:04:37 -0700173 std::get<N>(middlewares), req, res, ctx,
174 static_cast<parent_context_t&>(ctx));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700175
Ed Tanous1abe55e2018-09-05 08:30:59 -0700176 if (res.isCompleted())
177 {
178 afterHandlerCall<CurrentMW, Context, parent_context_t>(
179 std::get<N>(middlewares), req, res, ctx,
180 static_cast<parent_context_t&>(ctx));
181 return true;
182 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700183
Ed Tanous1abe55e2018-09-05 08:30:59 -0700184 if (middlewareCallHelper<N + 1, Context, Container, Middlewares...>(
185 middlewares, req, res, ctx))
186 {
187 afterHandlerCall<CurrentMW, Context, parent_context_t>(
188 std::get<N>(middlewares), req, res, ctx,
189 static_cast<parent_context_t&>(ctx));
190 return true;
191 }
192
193 return false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700194}
195
196template <int N, typename Context, typename Container>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700197bool middlewareCallHelper(Container& /*middlewares*/, Request& /*req*/,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700198 Response& /*res*/, Context& /*ctx*/)
199{
200 return false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700201}
202
203template <int N, typename Context, typename Container>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700204typename std::enable_if<(N < 0)>::type
205 afterHandlersCallHelper(Container& /*middlewares*/, Context& /*Context*/,
206 Request& /*req*/, Response& /*res*/)
207{
Ed Tanous7045c8d2017-04-03 10:04:37 -0700208}
209
210template <int N, typename Context, typename Container>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700211typename std::enable_if<(N == 0)>::type
212 afterHandlersCallHelper(Container& middlewares, Context& ctx, Request& req,
213 Response& res)
214{
215 using parent_context_t = typename Context::template partial<N - 1>;
216 using CurrentMW = typename std::tuple_element<
217 N, typename std::remove_reference<Container>::type>::type;
218 afterHandlerCall<CurrentMW, Context, parent_context_t>(
219 std::get<N>(middlewares), req, res, ctx,
220 static_cast<parent_context_t&>(ctx));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700221}
Ed Tanous1abe55e2018-09-05 08:30:59 -0700222
223template <int N, typename Context, typename Container>
224typename std::enable_if<(N > 0)>::type
225 afterHandlersCallHelper(Container& middlewares, Context& ctx, Request& req,
226 Response& res)
227{
228 using parent_context_t = typename Context::template partial<N - 1>;
229 using CurrentMW = typename std::tuple_element<
230 N, typename std::remove_reference<Container>::type>::type;
231 afterHandlerCall<CurrentMW, Context, parent_context_t>(
232 std::get<N>(middlewares), req, res, ctx,
233 static_cast<parent_context_t&>(ctx));
234 afterHandlersCallHelper<N - 1, Context, Container>(middlewares, ctx, req,
235 res);
236}
237} // namespace detail
Ed Tanous7045c8d2017-04-03 10:04:37 -0700238
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700239#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -0700240static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700241#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -0700242
243// request body limit size: 30M
244constexpr unsigned int httpReqBodyLimit = 1024 * 1024 * 30;
245
Ed Tanous7045c8d2017-04-03 10:04:37 -0700246template <typename Adaptor, typename Handler, typename... Middlewares>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700247class Connection
248{
249 public:
Ed Tanous8f626352018-12-19 14:51:54 -0800250 Connection(boost::asio::io_context& ioService, Handler* handler,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700251 const std::string& server_name,
252 std::tuple<Middlewares...>* middlewares,
253 std::function<std::string()>& get_cached_date_str_f,
Ed Tanousceac6f72018-12-02 11:58:47 -0800254 detail::TimerQueue& timerQueue, Adaptor adaptorIn) :
255 adaptor(std::move(adaptorIn)),
Ed Tanous1abe55e2018-09-05 08:30:59 -0700256 handler(handler), serverName(server_name), middlewares(middlewares),
257 getCachedDateStr(get_cached_date_str_f), timerQueue(timerQueue)
258 {
259 parser.emplace(std::piecewise_construct, std::make_tuple());
260 // Temporarily changed to 30MB; Need to modify uploading/authentication
261 // mechanism
262 parser->body_limit(httpReqBodyLimit);
263 req.emplace(parser->get());
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700264#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700265 connectionCount++;
266 BMCWEB_LOG_DEBUG << this << " Connection open, total "
267 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700268#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700269 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700270
Ed Tanous1abe55e2018-09-05 08:30:59 -0700271 ~Connection()
272 {
273 res.completeRequestHandler = nullptr;
274 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700275#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700276 connectionCount--;
277 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
278 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700279#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700280 }
281
Ed Tanousceac6f72018-12-02 11:58:47 -0800282 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700283 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800284 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700285 }
286
Ed Tanous1abe55e2018-09-05 08:30:59 -0700287 void start()
288 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700289
Ed Tanousceac6f72018-12-02 11:58:47 -0800290 startDeadline();
291 // TODO(ed) Abstract this to a more clever class with the idea of an
292 // asynchronous "start"
293 if constexpr (std::is_same_v<Adaptor,
294 boost::beast::ssl_stream<
295 boost::asio::ip::tcp::socket>>)
296 {
297 adaptor.async_handshake(
298 boost::asio::ssl::stream_base::server,
299 [this](const boost::system::error_code& ec) {
300 if (ec)
301 {
302 checkDestroy();
303 return;
304 }
305 doReadHeaders();
306 });
307 }
308 else
309 {
310 doReadHeaders();
311 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700312 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700313
Ed Tanous1abe55e2018-09-05 08:30:59 -0700314 void handle()
315 {
316 cancelDeadlineTimer();
317 bool isInvalidRequest = false;
318 const boost::string_view connection =
319 req->getHeaderValue(boost::beast::http::field::connection);
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;
327 res = Response(boost::beast::http::status::bad_request);
328 }
329 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700330
Ed Tanousceac6f72018-12-02 11:58:47 -0800331 std::string epName;
332 boost::system::error_code ec;
333 tcp::endpoint ep = adaptor.lowest_layer().remote_endpoint(ec);
334 if (!ec)
335 {
336 epName = boost::lexical_cast<std::string>(ep);
337 }
338
339 BMCWEB_LOG_INFO << "Request: " << epName << " " << this << " HTTP/"
340 << req->version() / 10 << "." << req->version() % 10
341 << ' ' << req->methodString() << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700342
Ed Tanous1abe55e2018-09-05 08:30:59 -0700343 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700344
Ed Tanous1abe55e2018-09-05 08:30:59 -0700345 if (!isInvalidRequest)
346 {
347 res.completeRequestHandler = [] {};
Ed Tanousceac6f72018-12-02 11:58:47 -0800348 res.isAliveHelper = [this]() -> bool {
349 return adaptor.lowest_layer().is_open();
350 };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700351
Ed Tanous1abe55e2018-09-05 08:30:59 -0700352 ctx = detail::Context<Middlewares...>();
353 req->middlewareContext = (void*)&ctx;
Ed Tanousceac6f72018-12-02 11:58:47 -0800354 req->ioService = &adaptor.get_executor().context();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700355 detail::middlewareCallHelper<
356 0, decltype(ctx), decltype(*middlewares), Middlewares...>(
357 *middlewares, *req, res, ctx);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700358
Ed Tanous1abe55e2018-09-05 08:30:59 -0700359 if (!res.completed)
360 {
361 if (req->isUpgrade() &&
362 boost::iequals(
363 req->getHeaderValue(boost::beast::http::field::upgrade),
364 "websocket"))
365 {
366 handler->handleUpgrade(*req, res, std::move(adaptor));
367 return;
368 }
369 res.completeRequestHandler = [this] {
370 this->completeRequest();
371 };
372 needToCallAfterHandlers = true;
373 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700374 }
375 else
376 {
377 completeRequest();
378 }
379 }
380 else
381 {
382 completeRequest();
383 }
384 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700385
Ed Tanous1abe55e2018-09-05 08:30:59 -0700386 void completeRequest()
387 {
388 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
389 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700390
Ed Tanous1abe55e2018-09-05 08:30:59 -0700391 if (needToCallAfterHandlers)
392 {
393 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700394
Ed Tanous1abe55e2018-09-05 08:30:59 -0700395 // call all afterHandler of middlewares
396 detail::afterHandlersCallHelper<((int)sizeof...(Middlewares) - 1),
397 decltype(ctx),
398 decltype(*middlewares)>(
399 *middlewares, ctx, *req, res);
400 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700401
Ed Tanous1abe55e2018-09-05 08:30:59 -0700402 // auto self = this->shared_from_this();
Ed Tanousceac6f72018-12-02 11:58:47 -0800403 res.completeRequestHandler = res.completeRequestHandler = [] {};
Ed Tanous7045c8d2017-04-03 10:04:37 -0700404
Ed Tanousceac6f72018-12-02 11:58:47 -0800405 if (!adaptor.lowest_layer().is_open())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700406 {
407 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
408 // isReading
409 // << ' ' << isWriting;
410 // delete this;
411 return;
412 }
413 if (res.body().empty() && !res.jsonValue.empty())
414 {
415 if (http_helpers::requestPrefersHtml(*req))
416 {
417 prettyPrintJson(res);
418 }
419 else
420 {
421 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700422 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700423 }
424 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700425
Ed Tanous1abe55e2018-09-05 08:30:59 -0700426 if (res.resultInt() >= 400 && res.body().empty())
427 {
428 res.body() = std::string(res.reason());
429 }
430 res.addHeader(boost::beast::http::field::server, serverName);
431 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
432
433 res.keepAlive(req->keepAlive());
434
435 doWrite();
436 }
437
438 private:
439 void doReadHeaders()
440 {
441 // auto self = this->shared_from_this();
442 isReading = true;
443 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
444
445 // Clean up any previous Connection.
446 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800447 adaptor, buffer, *parser,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700448 [this](const boost::system::error_code& ec,
449 std::size_t bytes_transferred) {
450 isReading = false;
451 BMCWEB_LOG_ERROR << this << " async_read_header "
452 << bytes_transferred << " Bytes";
453 bool errorWhileReading = false;
454 if (ec)
455 {
456 errorWhileReading = true;
457 BMCWEB_LOG_ERROR
458 << this << " Error while reading: " << ec.message();
459 }
460 else
461 {
462 // if the adaptor isn't open anymore, and wasn't handed to a
463 // websocket, treat as an error
Ed Tanousceac6f72018-12-02 11:58:47 -0800464 if (!adaptor.lowest_layer().is_open() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700465 {
466 errorWhileReading = true;
467 }
468 }
469
470 if (errorWhileReading)
471 {
472 cancelDeadlineTimer();
Ed Tanousceac6f72018-12-02 11:58:47 -0800473 adaptor.lowest_layer().close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700474 BMCWEB_LOG_DEBUG << this << " from read(1)";
475 checkDestroy();
476 return;
477 }
478
479 // Compute the url parameters for the request
480 req->url = req->target();
481 std::size_t index = req->url.find("?");
482 if (index != boost::string_view::npos)
483 {
Jason M. Bills43fcbe52018-10-16 15:19:20 -0700484 req->url = req->url.substr(0, index);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700485 }
486 req->urlParams = QueryString(std::string(req->target()));
487 doRead();
488 });
489 }
490
491 void doRead()
492 {
493 // auto self = this->shared_from_this();
494 isReading = true;
495 BMCWEB_LOG_DEBUG << this << " doRead";
496
497 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800498 adaptor, buffer, *parser,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700499 [this](const boost::system::error_code& ec,
500 std::size_t bytes_transferred) {
501 BMCWEB_LOG_ERROR << this << " async_read " << bytes_transferred
502 << " Bytes";
503 isReading = false;
504
505 bool errorWhileReading = false;
506 if (ec)
507 {
508 BMCWEB_LOG_ERROR << "Error while reading: " << ec.message();
509 errorWhileReading = true;
510 }
511 else
512 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800513 if (!adaptor.lowest_layer().is_open())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700514 {
515 errorWhileReading = true;
516 }
517 }
518 if (errorWhileReading)
519 {
520 cancelDeadlineTimer();
Ed Tanousceac6f72018-12-02 11:58:47 -0800521 adaptor.lowest_layer().close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700522 BMCWEB_LOG_DEBUG << this << " from read(1)";
523 checkDestroy();
524 return;
525 }
526 handle();
527 });
528 }
529
530 void doWrite()
531 {
532 // auto self = this->shared_from_this();
533 isWriting = true;
534 BMCWEB_LOG_DEBUG << "Doing Write";
535 res.preparePayload();
536 serializer.emplace(*res.stringResponse);
537 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800538 adaptor, *serializer,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700539 [&](const boost::system::error_code& ec,
540 std::size_t bytes_transferred) {
541 isWriting = false;
542 BMCWEB_LOG_DEBUG << this << " Wrote " << bytes_transferred
543 << " bytes";
544
545 if (ec)
546 {
547 BMCWEB_LOG_DEBUG << this << " from write(2)";
548 checkDestroy();
549 return;
550 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800551 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700552 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800553 adaptor.lowest_layer().close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700554 BMCWEB_LOG_DEBUG << this << " from write(1)";
555 checkDestroy();
556 return;
557 }
558
559 serializer.reset();
560 BMCWEB_LOG_DEBUG << this << " Clearing response";
561 res.clear();
562 parser.emplace(std::piecewise_construct, std::make_tuple());
563 parser->body_limit(httpReqBodyLimit); // reset body limit for
564 // newly created parser
565 buffer.consume(buffer.size());
566
567 req.emplace(parser->get());
568 doReadHeaders();
569 });
570 }
571
572 void checkDestroy()
573 {
574 BMCWEB_LOG_DEBUG << this << " isReading " << isReading << " isWriting "
575 << isWriting;
576 if (!isReading && !isWriting)
577 {
578 BMCWEB_LOG_DEBUG << this << " delete (idle) ";
579 delete this;
580 }
581 }
582
583 void cancelDeadlineTimer()
584 {
585 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue << ' '
586 << timerCancelKey;
587 timerQueue.cancel(timerCancelKey);
588 }
589
590 void startDeadline()
591 {
592 cancelDeadlineTimer();
593
594 timerCancelKey = timerQueue.add([this] {
Ed Tanousceac6f72018-12-02 11:58:47 -0800595 if (!adaptor.lowest_layer().is_open())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700596 {
597 return;
598 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800599 adaptor.lowest_layer().close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700600 });
601 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
602 << timerCancelKey;
603 }
604
605 private:
606 Adaptor adaptor;
607 Handler* handler;
608
Ed Tanousa24526d2018-12-10 15:17:59 -0800609 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700610 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800611 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612 boost::beast::http::request_parser<boost::beast::http::string_body>>
613 parser;
614
Ed Tanous3112a142018-11-29 15:45:10 -0800615 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700616
Ed Tanousa24526d2018-12-10 15:17:59 -0800617 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618 boost::beast::http::string_body>>
619 serializer;
620
Ed Tanousa24526d2018-12-10 15:17:59 -0800621 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700622 crow::Response res;
623
624 const std::string& serverName;
625
626 int timerCancelKey{-1};
627
628 bool isReading{};
629 bool isWriting{};
630 bool needToCallAfterHandlers{};
631 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700632
633 std::tuple<Middlewares...>* middlewares;
634 detail::Context<Middlewares...> ctx;
635
636 std::function<std::string()>& getCachedDateStr;
637 detail::TimerQueue& timerQueue;
Ed Tanous3112a142018-11-29 15:45:10 -0800638};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700639} // namespace crow