blob: 11964e0c3698972993e1f787ba7cdc772850b5cf [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
Ed Tanous75312982021-02-11 14:26:02 -08002#include "bmcweb_config.h"
Adriana Kobylak0e1cf262019-12-05 13:57:57 -06003
Ed Tanousd093c992023-01-19 19:01:49 -08004#include "async_resp.hpp"
Nan Zhoud055a342022-05-25 01:15:34 +00005#include "authentication.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07006#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07007#include "http_utility.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -08008#include "json_html_serializer.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07009#include "logging.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080010#include "mutual_tls.hpp"
11#include "security_headers.hpp"
12#include "ssl_key_handler.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070013#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070014
Ed Tanous257f5792018-03-17 14:40:09 -070015#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080016#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080017#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070018#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080019#include <boost/asio/steady_timer.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080020#include <boost/beast/core/flat_static_buffer.hpp>
Myung Baea4326fe2023-01-10 14:29:24 -060021#include <boost/beast/http/error.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070022#include <boost/beast/http/parser.hpp>
23#include <boost/beast/http/read.hpp>
24#include <boost/beast/http/serializer.hpp>
25#include <boost/beast/http/write.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053026#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050027#include <boost/beast/websocket.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050028
Manojkiran Eda44250442020-06-16 12:51:38 +053029#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050030#include <chrono>
31#include <vector>
32
Ed Tanous1abe55e2018-09-05 08:30:59 -070033namespace crow
34{
Ed Tanous257f5792018-03-17 14:40:09 -070035
Ed Tanouscf9e4172022-12-21 09:30:16 -080036// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080037static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070038
Ed Tanous0260d9d2021-02-07 19:31:07 +000039// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Patrick Williams89492a12023-05-10 07:51:34 -050040constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL *
41 bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070042
James Feist3909dc82020-04-03 10:58:55 -070043constexpr uint64_t loggedOutPostBodyLimit = 4096;
44
45constexpr uint32_t httpHeaderLimit = 8192;
46
Ed Tanous52cc1122020-07-18 13:51:21 -070047template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050048class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070049 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070050{
Ed Tanous7c8e0642022-02-21 12:11:14 -080051 using self_type = Connection<Adaptor, Handler>;
52
Ed Tanous1abe55e2018-09-05 08:30:59 -070053 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080054 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000055 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080056 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080057 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080058 handler(handlerIn), timer(std::move(timerIn)),
59 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070060 {
61 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070062 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070063 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020064
65#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070066 prepareMutualTls();
67#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
68
Ed Tanous40aa0582021-07-14 13:24:40 -070069 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080070
Ed Tanous40aa0582021-07-14 13:24:40 -070071 BMCWEB_LOG_DEBUG << this << " Connection open, total "
72 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070073 }
74
75 ~Connection()
76 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070077 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070078 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080079
Ed Tanous40aa0582021-07-14 13:24:40 -070080 connectionCount--;
81 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
82 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070083 }
84
Ed Tanousecd6a3a2022-01-07 09:18:40 -080085 Connection(const Connection&) = delete;
86 Connection(Connection&&) = delete;
87 Connection& operator=(const Connection&) = delete;
88 Connection& operator=(Connection&&) = delete;
89
Ed Tanous7c8e0642022-02-21 12:11:14 -080090 bool tlsVerifyCallback(bool preverified,
91 boost::asio::ssl::verify_context& ctx)
92 {
93 // We always return true to allow full auth flow for resources that
94 // don't require auth
95 if (preverified)
96 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +010097 mtlsSession = verifyMtlsUser(req->ipAddress, ctx);
98 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -080099 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100100 BMCWEB_LOG_DEBUG
101 << this
102 << " Generating TLS session: " << mtlsSession->uniqueId;
Ed Tanous7c8e0642022-02-21 12:11:14 -0800103 }
104 }
105 return true;
106 }
107
Ed Tanous40aa0582021-07-14 13:24:40 -0700108 void prepareMutualTls()
109 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -0800110 std::error_code error;
111 std::filesystem::path caPath(ensuressl::trustStorePath);
112 auto caAvailable = !std::filesystem::is_empty(caPath, error);
113 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700114 if (caAvailable && persistent_data::SessionStore::getInstance()
115 .getAuthMethodsConfig()
116 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100117 {
118 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700119 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800120
Ed Tanous9eb808c2022-01-25 10:19:23 -0800121 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800122 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800123 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700124 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800125 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700126 static_cast<unsigned int>(id.length()));
127 if (ret == 0)
128 {
129 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
130 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100131 }
132
Ed Tanous002d39b2022-05-31 08:59:27 -0700133 adaptor.set_verify_callback(
Ed Tanous7c8e0642022-02-21 12:11:14 -0800134 std::bind_front(&self_type::tlsVerifyCallback, this));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700135 }
136
Ed Tanousceac6f72018-12-02 11:58:47 -0800137 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700138 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800139 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700140 }
141
Ed Tanous1abe55e2018-09-05 08:30:59 -0700142 void start()
143 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800144 if (connectionCount >= 100)
145 {
146 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
147 return;
148 }
149
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800150 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500151
Ed Tanousceac6f72018-12-02 11:58:47 -0800152 // TODO(ed) Abstract this to a more clever class with the idea of an
153 // asynchronous "start"
154 if constexpr (std::is_same_v<Adaptor,
155 boost::beast::ssl_stream<
156 boost::asio::ip::tcp::socket>>)
157 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000158 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
159 [this, self(shared_from_this())](
160 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700161 if (ec)
162 {
163 return;
164 }
165 doReadHeaders();
166 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800167 }
168 else
169 {
170 doReadHeaders();
171 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700172 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700173
Ed Tanous1abe55e2018-09-05 08:30:59 -0700174 void handle()
175 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700176 std::error_code reqEc;
177 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
178 if (reqEc)
179 {
180 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
Gunnar Mills262f1152022-12-20 15:18:47 -0600181 res.result(boost::beast::http::status::bad_request);
182 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700183 return;
184 }
Ed Tanous596b2032021-09-13 10:32:22 -0700185 thisReq.session = userSession;
186
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000187 // Fetch the client IP address
188 readClientIp();
189
Ed Tanous1abe55e2018-09-05 08:30:59 -0700190 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700191 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700192 {
Ed Tanous596b2032021-09-13 10:32:22 -0700193 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700194 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700195 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800196 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700197 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700198 }
199 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700200
Ed Tanouse278c182019-03-13 16:23:37 -0700201 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700202 << " " << this << " HTTP/" << thisReq.version() / 10
203 << "." << thisReq.version() % 10 << ' '
204 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800205 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700206
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700207 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700208
Ed Tanous596b2032021-09-13 10:32:22 -0700209 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700210 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200211
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700212 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700213 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800214 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700215 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700216 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800217 keepAlive = thisReq.keepAlive();
Nan Zhoua43ea822022-05-27 00:42:44 +0000218#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanousc51a58e2023-03-27 14:43:19 -0700219 if (!crow::authentication::isOnAllowlist(req->url().path(),
Ed Tanous39662a32023-02-06 15:09:46 -0800220 req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700221 thisReq.session == nullptr)
222 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800223 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700224 forward_unauthorized::sendUnauthorized(
Ed Tanous39662a32023-02-06 15:09:46 -0800225 req->url().encoded_path(),
226 req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700227 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800228 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700229 return;
230 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000231#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800232 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
233 BMCWEB_LOG_DEBUG << "Setting completion handler";
234 asyncResp->res.setCompleteRequestHandler(
235 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700236 self->completeRequest(thisRes);
237 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700238 bool isSse =
239 isContentTypeAllowed(req->getHeaderValue("Accept"),
240 http_helpers::ContentType::EventStream, false);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530241 if ((thisReq.isUpgrade() &&
242 boost::iequals(
243 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
244 "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700245 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700246 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530247 asyncResp->res.setCompleteRequestHandler(
248 [self(shared_from_this())](crow::Response& thisRes) {
249 if (thisRes.result() != boost::beast::http::status::ok)
250 {
251 // When any error occurs before handle upgradation,
252 // the result in response will be set to respective
253 // error. By default the Result will be OK (200),
254 // which implies successful handle upgrade. Response
255 // needs to be sent over this connection only on
256 // failure.
257 self->completeRequest(thisRes);
258 return;
259 }
260 });
261 handler->handleUpgrade(thisReq, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700262 return;
263 }
Ed Tanous291d7092022-04-13 12:34:57 -0700264 std::string_view expected =
265 req->getHeaderValue(boost::beast::http::field::if_none_match);
266 if (!expected.empty())
267 {
268 res.setExpectedHash(expected);
269 }
Ed Tanous596b2032021-09-13 10:32:22 -0700270 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700271 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700272
Ed Tanouse278c182019-03-13 16:23:37 -0700273 bool isAlive()
274 {
Ed Tanouse278c182019-03-13 16:23:37 -0700275 if constexpr (std::is_same_v<Adaptor,
276 boost::beast::ssl_stream<
277 boost::asio::ip::tcp::socket>>)
278 {
279 return adaptor.next_layer().is_open();
280 }
281 else
282 {
283 return adaptor.is_open();
284 }
285 }
286 void close()
287 {
Ed Tanouse278c182019-03-13 16:23:37 -0700288 if constexpr (std::is_same_v<Adaptor,
289 boost::beast::ssl_stream<
290 boost::asio::ip::tcp::socket>>)
291 {
292 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100293 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200294 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700295 BMCWEB_LOG_DEBUG
296 << this
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100297 << " Removing TLS session: " << mtlsSession->uniqueId;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700298 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100299 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200300 }
Ed Tanouse278c182019-03-13 16:23:37 -0700301 }
302 else
303 {
304 adaptor.close();
305 }
306 }
307
Nan Zhou72374eb2022-01-27 17:06:51 -0800308 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700309 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700310 if (!req)
311 {
312 return;
313 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800314 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800315 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800316
Ed Tanous39662a32023-02-06 15:09:46 -0800317 BMCWEB_LOG_INFO << "Response: " << this << ' '
318 << req->url().encoded_path() << ' ' << res.resultInt()
319 << " keepalive=" << keepAlive;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700320
Ed Tanous0260d9d2021-02-07 19:31:07 +0000321 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700322
Nan Zhoud055a342022-05-25 01:15:34 +0000323 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700324
Ed Tanouse278c182019-03-13 16:23:37 -0700325 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700326 {
327 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
328 // isReading
329 // << ' ' << isWriting;
330 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000331
332 // delete lambda with self shared_ptr
333 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700334 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700335 return;
336 }
Ed Tanous291d7092022-04-13 12:34:57 -0700337
338 res.setHashAndHandleNotModified();
339
Ed Tanousad2b2eb2023-05-16 08:57:20 -0700340 if (res.body().empty() && res.jsonValue.is_structured())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700341 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700342 using http_helpers::ContentType;
Ed Tanoused194be2022-08-07 16:50:11 -0700343 std::array<ContentType, 3> allowed{
344 ContentType::CBOR, ContentType::JSON, ContentType::HTML};
Ed Tanous99351cd2022-08-07 16:42:51 -0700345 ContentType prefered =
346 getPreferedContentType(req->getHeaderValue("Accept"), allowed);
347
348 if (prefered == ContentType::HTML)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700349 {
Ed Tanous61e349a2023-05-31 11:57:43 -0700350 json_html_util::prettyPrintJson(res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700351 }
Ed Tanoused194be2022-08-07 16:50:11 -0700352 else if (prefered == ContentType::CBOR)
353 {
354 res.addHeader(boost::beast::http::field::content_type,
355 "application/cbor");
356 nlohmann::json::to_cbor(res.jsonValue, res.body());
357 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358 else
359 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700360 // Technically prefered could also be NoMatch here, but we'd
361 // like to default to something rather than return 400 for
362 // backward compatibility.
Ed Tanousf610caa2022-03-17 08:53:00 -0700363 res.addHeader(boost::beast::http::field::content_type,
364 "application/json");
Ed Tanous71f52d92021-02-19 08:51:17 -0800365 res.body() = res.jsonValue.dump(
366 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700367 }
368 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700369
Ed Tanous1abe55e2018-09-05 08:30:59 -0700370 if (res.resultInt() >= 400 && res.body().empty())
371 {
372 res.body() = std::string(res.reason());
373 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700374
Ed Tanous1abe55e2018-09-05 08:30:59 -0700375 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
376
Nan Zhou72374eb2022-01-27 17:06:51 -0800377 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000378
379 // delete lambda with self shared_ptr
380 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700381 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700382 }
383
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500384 void readClientIp()
385 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700386 boost::asio::ip::address ip;
387 boost::system::error_code ec = getClientIp(ip);
388 if (ec)
389 {
390 return;
391 }
392 req->ipAddress = ip;
393 }
394
395 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
396 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500397 boost::system::error_code ec;
398 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
399 boost::asio::ip::tcp::endpoint endpoint =
400 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
401
402 if (ec)
403 {
404 // If remote endpoint fails keep going. "ClientOriginIPAddress"
405 // will be empty.
406 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
407 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700408 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500409 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700410 ip = endpoint.address();
411 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500412 }
413
Ed Tanous1abe55e2018-09-05 08:30:59 -0700414 private:
415 void doReadHeaders()
416 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700417 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
418
419 // Clean up any previous Connection.
420 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800421 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000422 [this,
423 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000424 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700425 BMCWEB_LOG_DEBUG << this << " async_read_header "
426 << bytesTransferred << " Bytes";
427 bool errorWhileReading = false;
428 if (ec)
429 {
430 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600431 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700432 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700433 BMCWEB_LOG_WARNING
434 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700435 }
436 else
437 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700438 BMCWEB_LOG_ERROR
439 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700440 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700441 }
442 else
443 {
444 // if the adaptor isn't open anymore, and wasn't handed to a
445 // websocket, treat as an error
446 if (!isAlive() &&
447 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700448 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700449 errorWhileReading = true;
450 }
451 }
452
453 cancelDeadlineTimer();
454
455 if (errorWhileReading)
456 {
457 close();
458 BMCWEB_LOG_DEBUG << this << " from read(1)";
459 return;
460 }
461
462 readClientIp();
463
464 boost::asio::ip::address ip;
465 if (getClientIp(ip))
466 {
467 BMCWEB_LOG_DEBUG << "Unable to get client IP";
468 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700469#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
470 boost::beast::http::verb method = parser->get().method();
471 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100472 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700473
474 bool loggedIn = userSession != nullptr;
475 if (!loggedIn)
476 {
477 const boost::optional<uint64_t> contentLength =
478 parser->content_length();
479 if (contentLength && *contentLength > loggedOutPostBodyLimit)
480 {
481 BMCWEB_LOG_DEBUG << "Content length greater than limit "
482 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700483 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700484 return;
485 }
486
Ed Tanous002d39b2022-05-31 08:59:27 -0700487 BMCWEB_LOG_DEBUG << "Starting quick deadline";
488 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000489#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800490
Ed Tanous7d243eb2023-01-23 15:57:41 -0800491 if (parser->is_done())
492 {
493 handle();
494 return;
495 }
496
Ed Tanous002d39b2022-05-31 08:59:27 -0700497 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700498 });
499 }
500
501 void doRead()
502 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700503 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800504 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800505 boost::beast::http::async_read_some(
506 adaptor, buffer, *parser,
507 [this,
508 self(shared_from_this())](const boost::system::error_code& ec,
509 std::size_t bytesTransferred) {
510 BMCWEB_LOG_DEBUG << this << " async_read_some " << bytesTransferred
Ed Tanous002d39b2022-05-31 08:59:27 -0700511 << " Bytes";
Ed Tanous7d243eb2023-01-23 15:57:41 -0800512
Ed Tanous002d39b2022-05-31 08:59:27 -0700513 if (ec)
514 {
515 BMCWEB_LOG_ERROR << this
516 << " Error while reading: " << ec.message();
517 close();
518 BMCWEB_LOG_DEBUG << this << " from read(1)";
519 return;
520 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800521
522 // If the user is logged in, allow them to send files incrementally
523 // one piece at a time. If authentication is disabled then there is
524 // no user session hence always allow to send one piece at a time.
525 if (userSession != nullptr)
526 {
527 cancelDeadlineTimer();
528 }
529 if (!parser->is_done())
530 {
531 doRead();
532 return;
533 }
534
535 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700536 handle();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800537 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700538 }
539
Nan Zhou72374eb2022-01-27 17:06:51 -0800540 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700541 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100542 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800543 thisRes.preparePayload();
544 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800545 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700546 boost::beast::http::async_write(adaptor, *serializer,
547 [this, self(shared_from_this())](
548 const boost::system::error_code& ec,
549 std::size_t bytesTransferred) {
550 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
551 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700552
Ed Tanous002d39b2022-05-31 08:59:27 -0700553 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700554
Ed Tanous002d39b2022-05-31 08:59:27 -0700555 if (ec)
556 {
557 BMCWEB_LOG_DEBUG << this << " from write(2)";
558 return;
559 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800560 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700561 {
562 close();
563 BMCWEB_LOG_DEBUG << this << " from write(1)";
564 return;
565 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700566
Ed Tanous002d39b2022-05-31 08:59:27 -0700567 serializer.reset();
568 BMCWEB_LOG_DEBUG << this << " Clearing response";
569 res.clear();
570 parser.emplace(std::piecewise_construct, std::make_tuple());
571 parser->body_limit(httpReqBodyLimit); // reset body limit for
572 // newly created parser
573 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700574
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100575 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700576
Ed Tanous002d39b2022-05-31 08:59:27 -0700577 // Destroy the Request via the std::optional
578 req.reset();
579 doReadHeaders();
580 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700581 }
582
Ed Tanous1abe55e2018-09-05 08:30:59 -0700583 void cancelDeadlineTimer()
584 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800585 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700586 }
587
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800588 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700589 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800590 // Timer is already started so no further action is required.
591 if (timerStarted)
592 {
593 return;
594 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700595
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800596 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800597
598 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
599 timer.expires_after(timeout);
Ed Tanous81c4e332023-05-18 10:30:34 -0700600 timer.async_wait([weakSelf](const boost::system::error_code& ec) {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800601 // Note, we are ignoring other types of errors here; If the timer
602 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800603 std::shared_ptr<Connection<Adaptor, Handler>> self =
604 weakSelf.lock();
605 if (!self)
606 {
607 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
608 return;
609 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800610
611 self->timerStarted = false;
612
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800613 if (ec == boost::asio::error::operation_aborted)
614 {
615 // Canceled wait means the path succeeeded.
616 return;
617 }
618 if (ec)
619 {
620 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
621 }
622
623 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
624
625 self->close();
626 });
627
Ed Tanous7d243eb2023-01-23 15:57:41 -0800628 timerStarted = true;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800629 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700630 }
631
Ed Tanous1abe55e2018-09-05 08:30:59 -0700632 Adaptor adaptor;
633 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800634 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700635 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800636 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700637 boost::beast::http::request_parser<boost::beast::http::string_body>>
638 parser;
639
Ed Tanous3112a142018-11-29 15:45:10 -0800640 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641
Ed Tanousa24526d2018-12-10 15:17:59 -0800642 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700643 boost::beast::http::string_body>>
644 serializer;
645
Ed Tanousa24526d2018-12-10 15:17:59 -0800646 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700647 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700648
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700649 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100650 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800652 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700653
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800654 bool keepAlive = true;
655
Ed Tanous7d243eb2023-01-23 15:57:41 -0800656 bool timerStarted = false;
657
Ed Tanous1abe55e2018-09-05 08:30:59 -0700658 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000659
660 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700661 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800662
663 using std::enable_shared_from_this<
664 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800665};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700666} // namespace crow