blob: 213960214fae6ecee71870838984e1c999f473ea [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 Tanous1abe55e2018-09-05 08:30:59 -070036inline void prettyPrintJson(crow::Response& res)
37{
Ed Tanous57fce802019-05-21 13:00:34 -070038 json_html_util::dumpHtml(res.body(), res.jsonValue);
39
Ed Tanousd9f6c622022-03-17 09:12:17 -070040 res.addHeader(boost::beast::http::field::content_type,
41 "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070042}
43
Ed Tanouscf9e4172022-12-21 09:30:16 -080044// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080045static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070046
Ed Tanous0260d9d2021-02-07 19:31:07 +000047// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Patrick Williams89492a12023-05-10 07:51:34 -050048constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL *
49 bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070050
James Feist3909dc82020-04-03 10:58:55 -070051constexpr uint64_t loggedOutPostBodyLimit = 4096;
52
53constexpr uint32_t httpHeaderLimit = 8192;
54
Ed Tanous52cc1122020-07-18 13:51:21 -070055template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050056class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070057 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070058{
Ed Tanous7c8e0642022-02-21 12:11:14 -080059 using self_type = Connection<Adaptor, Handler>;
60
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080062 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000063 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080064 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080065 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080066 handler(handlerIn), timer(std::move(timerIn)),
67 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070068 {
69 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070070 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070071 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020072
73#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070074 prepareMutualTls();
75#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
76
Ed Tanous40aa0582021-07-14 13:24:40 -070077 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080078
Ed Tanous40aa0582021-07-14 13:24:40 -070079 BMCWEB_LOG_DEBUG << this << " Connection open, total "
80 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070081 }
82
83 ~Connection()
84 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070085 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070086 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080087
Ed Tanous40aa0582021-07-14 13:24:40 -070088 connectionCount--;
89 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
90 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070091 }
92
Ed Tanousecd6a3a2022-01-07 09:18:40 -080093 Connection(const Connection&) = delete;
94 Connection(Connection&&) = delete;
95 Connection& operator=(const Connection&) = delete;
96 Connection& operator=(Connection&&) = delete;
97
Ed Tanous7c8e0642022-02-21 12:11:14 -080098 bool tlsVerifyCallback(bool preverified,
99 boost::asio::ssl::verify_context& ctx)
100 {
101 // We always return true to allow full auth flow for resources that
102 // don't require auth
103 if (preverified)
104 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100105 mtlsSession = verifyMtlsUser(req->ipAddress, ctx);
106 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800107 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100108 BMCWEB_LOG_DEBUG
109 << this
110 << " Generating TLS session: " << mtlsSession->uniqueId;
Ed Tanous7c8e0642022-02-21 12:11:14 -0800111 }
112 }
113 return true;
114 }
115
Ed Tanous40aa0582021-07-14 13:24:40 -0700116 void prepareMutualTls()
117 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -0800118 std::error_code error;
119 std::filesystem::path caPath(ensuressl::trustStorePath);
120 auto caAvailable = !std::filesystem::is_empty(caPath, error);
121 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700122 if (caAvailable && persistent_data::SessionStore::getInstance()
123 .getAuthMethodsConfig()
124 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100125 {
126 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700127 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800128
Ed Tanous9eb808c2022-01-25 10:19:23 -0800129 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800130 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800131 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700132 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800133 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700134 static_cast<unsigned int>(id.length()));
135 if (ret == 0)
136 {
137 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
138 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100139 }
140
Ed Tanous002d39b2022-05-31 08:59:27 -0700141 adaptor.set_verify_callback(
Ed Tanous7c8e0642022-02-21 12:11:14 -0800142 std::bind_front(&self_type::tlsVerifyCallback, this));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700143 }
144
Ed Tanousceac6f72018-12-02 11:58:47 -0800145 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700146 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800147 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700148 }
149
Ed Tanous1abe55e2018-09-05 08:30:59 -0700150 void start()
151 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800152 if (connectionCount >= 100)
153 {
154 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
155 return;
156 }
157
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800158 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500159
Ed Tanousceac6f72018-12-02 11:58:47 -0800160 // TODO(ed) Abstract this to a more clever class with the idea of an
161 // asynchronous "start"
162 if constexpr (std::is_same_v<Adaptor,
163 boost::beast::ssl_stream<
164 boost::asio::ip::tcp::socket>>)
165 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000166 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
167 [this, self(shared_from_this())](
168 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700169 if (ec)
170 {
171 return;
172 }
173 doReadHeaders();
174 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800175 }
176 else
177 {
178 doReadHeaders();
179 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700180 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700181
Ed Tanous1abe55e2018-09-05 08:30:59 -0700182 void handle()
183 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700184 std::error_code reqEc;
185 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
186 if (reqEc)
187 {
188 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
Gunnar Mills262f1152022-12-20 15:18:47 -0600189 res.result(boost::beast::http::status::bad_request);
190 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700191 return;
192 }
Ed Tanous596b2032021-09-13 10:32:22 -0700193 thisReq.session = userSession;
194
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000195 // Fetch the client IP address
196 readClientIp();
197
Ed Tanous1abe55e2018-09-05 08:30:59 -0700198 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700199 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700200 {
Ed Tanous596b2032021-09-13 10:32:22 -0700201 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700202 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700203 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800204 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700205 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700206 }
207 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700208
Ed Tanouse278c182019-03-13 16:23:37 -0700209 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700210 << " " << this << " HTTP/" << thisReq.version() / 10
211 << "." << thisReq.version() % 10 << ' '
212 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800213 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700214
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700215 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700216
Ed Tanous596b2032021-09-13 10:32:22 -0700217 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700218 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200219
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700220 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700221 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800222 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700223 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700224 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800225 keepAlive = thisReq.keepAlive();
Nan Zhoua43ea822022-05-27 00:42:44 +0000226#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous39662a32023-02-06 15:09:46 -0800227 if (!crow::authentication::isOnAllowlist(req->url().buffer(),
228 req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700229 thisReq.session == nullptr)
230 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800231 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700232 forward_unauthorized::sendUnauthorized(
Ed Tanous39662a32023-02-06 15:09:46 -0800233 req->url().encoded_path(),
234 req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700235 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800236 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700237 return;
238 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000239#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800240 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
241 BMCWEB_LOG_DEBUG << "Setting completion handler";
242 asyncResp->res.setCompleteRequestHandler(
243 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700244 self->completeRequest(thisRes);
245 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700246
Ed Tanous596b2032021-09-13 10:32:22 -0700247 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700248 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700249 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700250 "websocket"))
251 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530252 asyncResp->res.setCompleteRequestHandler(
253 [self(shared_from_this())](crow::Response& thisRes) {
254 if (thisRes.result() != boost::beast::http::status::ok)
255 {
256 // When any error occurs before handle upgradation,
257 // the result in response will be set to respective
258 // error. By default the Result will be OK (200),
259 // which implies successful handle upgrade. Response
260 // needs to be sent over this connection only on
261 // failure.
262 self->completeRequest(thisRes);
263 return;
264 }
265 });
266 handler->handleUpgrade(thisReq, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700267 return;
268 }
Ed Tanous291d7092022-04-13 12:34:57 -0700269 std::string_view expected =
270 req->getHeaderValue(boost::beast::http::field::if_none_match);
271 if (!expected.empty())
272 {
273 res.setExpectedHash(expected);
274 }
Ed Tanous596b2032021-09-13 10:32:22 -0700275 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700276 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700277
Ed Tanouse278c182019-03-13 16:23:37 -0700278 bool isAlive()
279 {
Ed Tanouse278c182019-03-13 16:23:37 -0700280 if constexpr (std::is_same_v<Adaptor,
281 boost::beast::ssl_stream<
282 boost::asio::ip::tcp::socket>>)
283 {
284 return adaptor.next_layer().is_open();
285 }
286 else
287 {
288 return adaptor.is_open();
289 }
290 }
291 void close()
292 {
Ed Tanouse278c182019-03-13 16:23:37 -0700293 if constexpr (std::is_same_v<Adaptor,
294 boost::beast::ssl_stream<
295 boost::asio::ip::tcp::socket>>)
296 {
297 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100298 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200299 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700300 BMCWEB_LOG_DEBUG
301 << this
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100302 << " Removing TLS session: " << mtlsSession->uniqueId;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700303 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100304 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200305 }
Ed Tanouse278c182019-03-13 16:23:37 -0700306 }
307 else
308 {
309 adaptor.close();
310 }
311 }
312
Nan Zhou72374eb2022-01-27 17:06:51 -0800313 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700314 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700315 if (!req)
316 {
317 return;
318 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800319 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800320 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800321
Ed Tanous39662a32023-02-06 15:09:46 -0800322 BMCWEB_LOG_INFO << "Response: " << this << ' '
323 << req->url().encoded_path() << ' ' << res.resultInt()
324 << " keepalive=" << keepAlive;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700325
Ed Tanous0260d9d2021-02-07 19:31:07 +0000326 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700327
Nan Zhoud055a342022-05-25 01:15:34 +0000328 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700329
Ed Tanouse278c182019-03-13 16:23:37 -0700330 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700331 {
332 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
333 // isReading
334 // << ' ' << isWriting;
335 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000336
337 // delete lambda with self shared_ptr
338 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700339 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700340 return;
341 }
Ed Tanous291d7092022-04-13 12:34:57 -0700342
343 res.setHashAndHandleNotModified();
344
Ed Tanousad2b2eb2023-05-16 08:57:20 -0700345 if (res.body().empty() && res.jsonValue.is_structured())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700346 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700347 using http_helpers::ContentType;
Ed Tanoused194be2022-08-07 16:50:11 -0700348 std::array<ContentType, 3> allowed{
349 ContentType::CBOR, ContentType::JSON, ContentType::HTML};
Ed Tanous99351cd2022-08-07 16:42:51 -0700350 ContentType prefered =
351 getPreferedContentType(req->getHeaderValue("Accept"), allowed);
352
353 if (prefered == ContentType::HTML)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700354 {
355 prettyPrintJson(res);
356 }
Ed Tanoused194be2022-08-07 16:50:11 -0700357 else if (prefered == ContentType::CBOR)
358 {
359 res.addHeader(boost::beast::http::field::content_type,
360 "application/cbor");
361 nlohmann::json::to_cbor(res.jsonValue, res.body());
362 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700363 else
364 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700365 // Technically prefered could also be NoMatch here, but we'd
366 // like to default to something rather than return 400 for
367 // backward compatibility.
Ed Tanousf610caa2022-03-17 08:53:00 -0700368 res.addHeader(boost::beast::http::field::content_type,
369 "application/json");
Ed Tanous71f52d92021-02-19 08:51:17 -0800370 res.body() = res.jsonValue.dump(
371 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700372 }
373 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700374
Ed Tanous1abe55e2018-09-05 08:30:59 -0700375 if (res.resultInt() >= 400 && res.body().empty())
376 {
377 res.body() = std::string(res.reason());
378 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700379
Ed Tanous1abe55e2018-09-05 08:30:59 -0700380 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
381
Nan Zhou72374eb2022-01-27 17:06:51 -0800382 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000383
384 // delete lambda with self shared_ptr
385 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700386 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700387 }
388
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500389 void readClientIp()
390 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700391 boost::asio::ip::address ip;
392 boost::system::error_code ec = getClientIp(ip);
393 if (ec)
394 {
395 return;
396 }
397 req->ipAddress = ip;
398 }
399
400 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
401 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500402 boost::system::error_code ec;
403 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
404 boost::asio::ip::tcp::endpoint endpoint =
405 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
406
407 if (ec)
408 {
409 // If remote endpoint fails keep going. "ClientOriginIPAddress"
410 // will be empty.
411 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
412 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700413 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500414 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700415 ip = endpoint.address();
416 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500417 }
418
Ed Tanous1abe55e2018-09-05 08:30:59 -0700419 private:
420 void doReadHeaders()
421 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700422 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
423
424 // Clean up any previous Connection.
425 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800426 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000427 [this,
428 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000429 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700430 BMCWEB_LOG_DEBUG << this << " async_read_header "
431 << bytesTransferred << " Bytes";
432 bool errorWhileReading = false;
433 if (ec)
434 {
435 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600436 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700437 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700438 BMCWEB_LOG_WARNING
439 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700440 }
441 else
442 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700443 BMCWEB_LOG_ERROR
444 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700445 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700446 }
447 else
448 {
449 // if the adaptor isn't open anymore, and wasn't handed to a
450 // websocket, treat as an error
451 if (!isAlive() &&
452 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700453 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700454 errorWhileReading = true;
455 }
456 }
457
458 cancelDeadlineTimer();
459
460 if (errorWhileReading)
461 {
462 close();
463 BMCWEB_LOG_DEBUG << this << " from read(1)";
464 return;
465 }
466
467 readClientIp();
468
469 boost::asio::ip::address ip;
470 if (getClientIp(ip))
471 {
472 BMCWEB_LOG_DEBUG << "Unable to get client IP";
473 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700474#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
475 boost::beast::http::verb method = parser->get().method();
476 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100477 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700478
479 bool loggedIn = userSession != nullptr;
480 if (!loggedIn)
481 {
482 const boost::optional<uint64_t> contentLength =
483 parser->content_length();
484 if (contentLength && *contentLength > loggedOutPostBodyLimit)
485 {
486 BMCWEB_LOG_DEBUG << "Content length greater than limit "
487 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700488 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700489 return;
490 }
491
Ed Tanous002d39b2022-05-31 08:59:27 -0700492 BMCWEB_LOG_DEBUG << "Starting quick deadline";
493 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000494#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800495
Ed Tanous7d243eb2023-01-23 15:57:41 -0800496 if (parser->is_done())
497 {
498 handle();
499 return;
500 }
501
Ed Tanous002d39b2022-05-31 08:59:27 -0700502 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700503 });
504 }
505
506 void doRead()
507 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700508 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800509 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800510 boost::beast::http::async_read_some(
511 adaptor, buffer, *parser,
512 [this,
513 self(shared_from_this())](const boost::system::error_code& ec,
514 std::size_t bytesTransferred) {
515 BMCWEB_LOG_DEBUG << this << " async_read_some " << bytesTransferred
Ed Tanous002d39b2022-05-31 08:59:27 -0700516 << " Bytes";
Ed Tanous7d243eb2023-01-23 15:57:41 -0800517
Ed Tanous002d39b2022-05-31 08:59:27 -0700518 if (ec)
519 {
520 BMCWEB_LOG_ERROR << this
521 << " Error while reading: " << ec.message();
522 close();
523 BMCWEB_LOG_DEBUG << this << " from read(1)";
524 return;
525 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800526
527 // If the user is logged in, allow them to send files incrementally
528 // one piece at a time. If authentication is disabled then there is
529 // no user session hence always allow to send one piece at a time.
530 if (userSession != nullptr)
531 {
532 cancelDeadlineTimer();
533 }
534 if (!parser->is_done())
535 {
536 doRead();
537 return;
538 }
539
540 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700541 handle();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800542 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700543 }
544
Nan Zhou72374eb2022-01-27 17:06:51 -0800545 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700546 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100547 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800548 thisRes.preparePayload();
549 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800550 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700551 boost::beast::http::async_write(adaptor, *serializer,
552 [this, self(shared_from_this())](
553 const boost::system::error_code& ec,
554 std::size_t bytesTransferred) {
555 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
556 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700557
Ed Tanous002d39b2022-05-31 08:59:27 -0700558 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700559
Ed Tanous002d39b2022-05-31 08:59:27 -0700560 if (ec)
561 {
562 BMCWEB_LOG_DEBUG << this << " from write(2)";
563 return;
564 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800565 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700566 {
567 close();
568 BMCWEB_LOG_DEBUG << this << " from write(1)";
569 return;
570 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700571
Ed Tanous002d39b2022-05-31 08:59:27 -0700572 serializer.reset();
573 BMCWEB_LOG_DEBUG << this << " Clearing response";
574 res.clear();
575 parser.emplace(std::piecewise_construct, std::make_tuple());
576 parser->body_limit(httpReqBodyLimit); // reset body limit for
577 // newly created parser
578 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700579
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100580 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700581
Ed Tanous002d39b2022-05-31 08:59:27 -0700582 // Destroy the Request via the std::optional
583 req.reset();
584 doReadHeaders();
585 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700586 }
587
Ed Tanous1abe55e2018-09-05 08:30:59 -0700588 void cancelDeadlineTimer()
589 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800590 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700591 }
592
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800593 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700594 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800595 // Timer is already started so no further action is required.
596 if (timerStarted)
597 {
598 return;
599 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700600
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800601 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800602
603 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
604 timer.expires_after(timeout);
605 timer.async_wait([weakSelf](const boost::system::error_code ec) {
606 // Note, we are ignoring other types of errors here; If the timer
607 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800608 std::shared_ptr<Connection<Adaptor, Handler>> self =
609 weakSelf.lock();
610 if (!self)
611 {
612 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
613 return;
614 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800615
616 self->timerStarted = false;
617
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800618 if (ec == boost::asio::error::operation_aborted)
619 {
620 // Canceled wait means the path succeeeded.
621 return;
622 }
623 if (ec)
624 {
625 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
626 }
627
628 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
629
630 self->close();
631 });
632
Ed Tanous7d243eb2023-01-23 15:57:41 -0800633 timerStarted = true;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800634 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700635 }
636
Ed Tanous1abe55e2018-09-05 08:30:59 -0700637 Adaptor adaptor;
638 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800639 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700640 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800641 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642 boost::beast::http::request_parser<boost::beast::http::string_body>>
643 parser;
644
Ed Tanous3112a142018-11-29 15:45:10 -0800645 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700646
Ed Tanousa24526d2018-12-10 15:17:59 -0800647 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 boost::beast::http::string_body>>
649 serializer;
650
Ed Tanousa24526d2018-12-10 15:17:59 -0800651 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700652 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700653
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700654 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100655 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700656
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800657 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700658
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800659 bool keepAlive = true;
660
Ed Tanous7d243eb2023-01-23 15:57:41 -0800661 bool timerStarted = false;
662
Ed Tanous1abe55e2018-09-05 08:30:59 -0700663 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000664
665 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700666 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800667
668 using std::enable_shared_from_this<
669 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800670};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700671} // namespace crow