blob: d5d02e545ab0f188525646c0ecf2575fac550ae3 [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
Ed Tanous6de264c2022-01-06 12:47:59 -080048constexpr uint64_t httpReqBodyLimit =
49 1024UL * 1024UL * 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 Tanous1abe55e2018-09-05 08:30:59 -0700345 if (res.body().empty() && !res.jsonValue.empty())
346 {
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
380 if (res.result() == boost::beast::http::status::no_content)
381 {
382 // Boost beast throws if content is provided on a no-content
383 // response. Ideally, this would never happen, but in the case that
384 // it does, we don't want to throw.
385 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100386 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700387 res.body().clear();
388 }
389
Ed Tanous1abe55e2018-09-05 08:30:59 -0700390 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
391
Nan Zhou72374eb2022-01-27 17:06:51 -0800392 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000393
394 // delete lambda with self shared_ptr
395 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700396 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700397 }
398
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500399 void readClientIp()
400 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700401 boost::asio::ip::address ip;
402 boost::system::error_code ec = getClientIp(ip);
403 if (ec)
404 {
405 return;
406 }
407 req->ipAddress = ip;
408 }
409
410 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
411 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500412 boost::system::error_code ec;
413 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
414 boost::asio::ip::tcp::endpoint endpoint =
415 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
416
417 if (ec)
418 {
419 // If remote endpoint fails keep going. "ClientOriginIPAddress"
420 // will be empty.
421 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
422 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700423 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500424 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700425 ip = endpoint.address();
426 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500427 }
428
Ed Tanous1abe55e2018-09-05 08:30:59 -0700429 private:
430 void doReadHeaders()
431 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700432 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
433
434 // Clean up any previous Connection.
435 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800436 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000437 [this,
438 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000439 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700440 BMCWEB_LOG_DEBUG << this << " async_read_header "
441 << bytesTransferred << " Bytes";
442 bool errorWhileReading = false;
443 if (ec)
444 {
445 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600446 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700447 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700448 BMCWEB_LOG_WARNING
449 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700450 }
451 else
452 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700453 BMCWEB_LOG_ERROR
454 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700455 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700456 }
457 else
458 {
459 // if the adaptor isn't open anymore, and wasn't handed to a
460 // websocket, treat as an error
461 if (!isAlive() &&
462 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700463 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700464 errorWhileReading = true;
465 }
466 }
467
468 cancelDeadlineTimer();
469
470 if (errorWhileReading)
471 {
472 close();
473 BMCWEB_LOG_DEBUG << this << " from read(1)";
474 return;
475 }
476
477 readClientIp();
478
479 boost::asio::ip::address ip;
480 if (getClientIp(ip))
481 {
482 BMCWEB_LOG_DEBUG << "Unable to get client IP";
483 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700484#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
485 boost::beast::http::verb method = parser->get().method();
486 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100487 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700488
489 bool loggedIn = userSession != nullptr;
490 if (!loggedIn)
491 {
492 const boost::optional<uint64_t> contentLength =
493 parser->content_length();
494 if (contentLength && *contentLength > loggedOutPostBodyLimit)
495 {
496 BMCWEB_LOG_DEBUG << "Content length greater than limit "
497 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700498 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700499 return;
500 }
501
Ed Tanous002d39b2022-05-31 08:59:27 -0700502 BMCWEB_LOG_DEBUG << "Starting quick deadline";
503 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000504#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800505
Ed Tanous7d243eb2023-01-23 15:57:41 -0800506 if (parser->is_done())
507 {
508 handle();
509 return;
510 }
511
Ed Tanous002d39b2022-05-31 08:59:27 -0700512 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700513 });
514 }
515
516 void doRead()
517 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700518 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800519 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800520 boost::beast::http::async_read_some(
521 adaptor, buffer, *parser,
522 [this,
523 self(shared_from_this())](const boost::system::error_code& ec,
524 std::size_t bytesTransferred) {
525 BMCWEB_LOG_DEBUG << this << " async_read_some " << bytesTransferred
Ed Tanous002d39b2022-05-31 08:59:27 -0700526 << " Bytes";
Ed Tanous7d243eb2023-01-23 15:57:41 -0800527
Ed Tanous002d39b2022-05-31 08:59:27 -0700528 if (ec)
529 {
530 BMCWEB_LOG_ERROR << this
531 << " Error while reading: " << ec.message();
532 close();
533 BMCWEB_LOG_DEBUG << this << " from read(1)";
534 return;
535 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800536
537 // If the user is logged in, allow them to send files incrementally
538 // one piece at a time. If authentication is disabled then there is
539 // no user session hence always allow to send one piece at a time.
540 if (userSession != nullptr)
541 {
542 cancelDeadlineTimer();
543 }
544 if (!parser->is_done())
545 {
546 doRead();
547 return;
548 }
549
550 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700551 handle();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800552 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700553 }
554
Nan Zhou72374eb2022-01-27 17:06:51 -0800555 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700556 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100557 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800558 thisRes.preparePayload();
559 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800560 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700561 boost::beast::http::async_write(adaptor, *serializer,
562 [this, self(shared_from_this())](
563 const boost::system::error_code& ec,
564 std::size_t bytesTransferred) {
565 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
566 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567
Ed Tanous002d39b2022-05-31 08:59:27 -0700568 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700569
Ed Tanous002d39b2022-05-31 08:59:27 -0700570 if (ec)
571 {
572 BMCWEB_LOG_DEBUG << this << " from write(2)";
573 return;
574 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800575 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700576 {
577 close();
578 BMCWEB_LOG_DEBUG << this << " from write(1)";
579 return;
580 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700581
Ed Tanous002d39b2022-05-31 08:59:27 -0700582 serializer.reset();
583 BMCWEB_LOG_DEBUG << this << " Clearing response";
584 res.clear();
585 parser.emplace(std::piecewise_construct, std::make_tuple());
586 parser->body_limit(httpReqBodyLimit); // reset body limit for
587 // newly created parser
588 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700589
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100590 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700591
Ed Tanous002d39b2022-05-31 08:59:27 -0700592 // Destroy the Request via the std::optional
593 req.reset();
594 doReadHeaders();
595 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700596 }
597
Ed Tanous1abe55e2018-09-05 08:30:59 -0700598 void cancelDeadlineTimer()
599 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800600 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700601 }
602
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800603 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700604 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800605 // Timer is already started so no further action is required.
606 if (timerStarted)
607 {
608 return;
609 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700610
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800611 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800612
613 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
614 timer.expires_after(timeout);
615 timer.async_wait([weakSelf](const boost::system::error_code ec) {
616 // Note, we are ignoring other types of errors here; If the timer
617 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800618 std::shared_ptr<Connection<Adaptor, Handler>> self =
619 weakSelf.lock();
620 if (!self)
621 {
622 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
623 return;
624 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800625
626 self->timerStarted = false;
627
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800628 if (ec == boost::asio::error::operation_aborted)
629 {
630 // Canceled wait means the path succeeeded.
631 return;
632 }
633 if (ec)
634 {
635 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
636 }
637
638 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
639
640 self->close();
641 });
642
Ed Tanous7d243eb2023-01-23 15:57:41 -0800643 timerStarted = true;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800644 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 }
646
Ed Tanous1abe55e2018-09-05 08:30:59 -0700647 Adaptor adaptor;
648 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800649 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700650 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800651 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700652 boost::beast::http::request_parser<boost::beast::http::string_body>>
653 parser;
654
Ed Tanous3112a142018-11-29 15:45:10 -0800655 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700656
Ed Tanousa24526d2018-12-10 15:17:59 -0800657 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700658 boost::beast::http::string_body>>
659 serializer;
660
Ed Tanousa24526d2018-12-10 15:17:59 -0800661 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700662 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700663
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700664 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100665 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700666
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800667 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700668
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800669 bool keepAlive = true;
670
Ed Tanous7d243eb2023-01-23 15:57:41 -0800671 bool timerStarted = false;
672
Ed Tanous1abe55e2018-09-05 08:30:59 -0700673 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000674
675 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700676 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800677
678 using std::enable_shared_from_this<
679 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800680};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700681} // namespace crow