blob: 0daf6650d4ce98e727de76f063dcf6688d262cf0 [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>
Ed Tanousd32c4fa2021-09-14 13:16:51 -070028#include <boost/url/url_view.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050029
Manojkiran Eda44250442020-06-16 12:51:38 +053030#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050031#include <chrono>
32#include <vector>
33
Ed Tanous1abe55e2018-09-05 08:30:59 -070034namespace crow
35{
Ed Tanous257f5792018-03-17 14:40:09 -070036
Ed Tanous1abe55e2018-09-05 08:30:59 -070037inline void prettyPrintJson(crow::Response& res)
38{
Ed Tanous57fce802019-05-21 13:00:34 -070039 json_html_util::dumpHtml(res.body(), res.jsonValue);
40
Ed Tanousd9f6c622022-03-17 09:12:17 -070041 res.addHeader(boost::beast::http::field::content_type,
42 "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070043}
44
Ed Tanouscf9e4172022-12-21 09:30:16 -080045// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080046static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070047
Ed Tanous0260d9d2021-02-07 19:31:07 +000048// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Ed Tanous6de264c2022-01-06 12:47:59 -080049constexpr uint64_t httpReqBodyLimit =
50 1024UL * 1024UL * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070051
James Feist3909dc82020-04-03 10:58:55 -070052constexpr uint64_t loggedOutPostBodyLimit = 4096;
53
54constexpr uint32_t httpHeaderLimit = 8192;
55
Ed Tanous52cc1122020-07-18 13:51:21 -070056template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050057class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070058 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070059{
Ed Tanous7c8e0642022-02-21 12:11:14 -080060 using self_type = Connection<Adaptor, Handler>;
61
Ed Tanous1abe55e2018-09-05 08:30:59 -070062 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080063 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000064 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080065 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080066 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080067 handler(handlerIn), timer(std::move(timerIn)),
68 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070069 {
70 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070071 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070072 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020073
74#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070075 prepareMutualTls();
76#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
77
Ed Tanous40aa0582021-07-14 13:24:40 -070078 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080079
Ed Tanous40aa0582021-07-14 13:24:40 -070080 BMCWEB_LOG_DEBUG << this << " Connection open, total "
81 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070082 }
83
84 ~Connection()
85 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070086 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070087 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080088
Ed Tanous40aa0582021-07-14 13:24:40 -070089 connectionCount--;
90 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
91 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070092 }
93
Ed Tanousecd6a3a2022-01-07 09:18:40 -080094 Connection(const Connection&) = delete;
95 Connection(Connection&&) = delete;
96 Connection& operator=(const Connection&) = delete;
97 Connection& operator=(Connection&&) = delete;
98
Ed Tanous7c8e0642022-02-21 12:11:14 -080099 bool tlsVerifyCallback(bool preverified,
100 boost::asio::ssl::verify_context& ctx)
101 {
102 // We always return true to allow full auth flow for resources that
103 // don't require auth
104 if (preverified)
105 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100106 mtlsSession = verifyMtlsUser(req->ipAddress, ctx);
107 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800108 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100109 BMCWEB_LOG_DEBUG
110 << this
111 << " Generating TLS session: " << mtlsSession->uniqueId;
Ed Tanous7c8e0642022-02-21 12:11:14 -0800112 }
113 }
114 return true;
115 }
116
Ed Tanous40aa0582021-07-14 13:24:40 -0700117 void prepareMutualTls()
118 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -0800119 std::error_code error;
120 std::filesystem::path caPath(ensuressl::trustStorePath);
121 auto caAvailable = !std::filesystem::is_empty(caPath, error);
122 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700123 if (caAvailable && persistent_data::SessionStore::getInstance()
124 .getAuthMethodsConfig()
125 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100126 {
127 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700128 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800129
Ed Tanous9eb808c2022-01-25 10:19:23 -0800130 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800131 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800132 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700133 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800134 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700135 static_cast<unsigned int>(id.length()));
136 if (ret == 0)
137 {
138 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
139 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100140 }
141
Ed Tanous002d39b2022-05-31 08:59:27 -0700142 adaptor.set_verify_callback(
Ed Tanous7c8e0642022-02-21 12:11:14 -0800143 std::bind_front(&self_type::tlsVerifyCallback, this));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700144 }
145
Ed Tanousceac6f72018-12-02 11:58:47 -0800146 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700147 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800148 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700149 }
150
Ed Tanous1abe55e2018-09-05 08:30:59 -0700151 void start()
152 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800153 if (connectionCount >= 100)
154 {
155 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
156 return;
157 }
158
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800159 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500160
Ed Tanousceac6f72018-12-02 11:58:47 -0800161 // TODO(ed) Abstract this to a more clever class with the idea of an
162 // asynchronous "start"
163 if constexpr (std::is_same_v<Adaptor,
164 boost::beast::ssl_stream<
165 boost::asio::ip::tcp::socket>>)
166 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000167 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
168 [this, self(shared_from_this())](
169 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700170 if (ec)
171 {
172 return;
173 }
174 doReadHeaders();
175 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800176 }
177 else
178 {
179 doReadHeaders();
180 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700181 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700182
Ed Tanous1abe55e2018-09-05 08:30:59 -0700183 void handle()
184 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700185 std::error_code reqEc;
186 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
187 if (reqEc)
188 {
189 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
Gunnar Mills262f1152022-12-20 15:18:47 -0600190 res.result(boost::beast::http::status::bad_request);
191 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700192 return;
193 }
Ed Tanous596b2032021-09-13 10:32:22 -0700194 thisReq.session = userSession;
195
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000196 // Fetch the client IP address
197 readClientIp();
198
Ed Tanous1abe55e2018-09-05 08:30:59 -0700199 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700200 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700201 {
Ed Tanous596b2032021-09-13 10:32:22 -0700202 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700203 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700204 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800205 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700206 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700207 }
208 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700209
Ed Tanouse278c182019-03-13 16:23:37 -0700210 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700211 << " " << this << " HTTP/" << thisReq.version() / 10
212 << "." << thisReq.version() % 10 << ' '
213 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800214 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700215
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700216 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700217
Ed Tanous596b2032021-09-13 10:32:22 -0700218 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700219 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200220
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700221 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700222 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800223 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700224 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700225 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800226 keepAlive = thisReq.keepAlive();
Nan Zhoua43ea822022-05-27 00:42:44 +0000227#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhoud055a342022-05-25 01:15:34 +0000228 if (!crow::authentication::isOnAllowlist(req->url, 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 Tanousc127a0f2022-05-11 15:23:59 -0700233 req->url, req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700234 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800235 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700236 return;
237 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000238#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800239 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
240 BMCWEB_LOG_DEBUG << "Setting completion handler";
241 asyncResp->res.setCompleteRequestHandler(
242 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700243 self->completeRequest(thisRes);
244 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700245
Ed Tanous596b2032021-09-13 10:32:22 -0700246 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700247 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700248 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700249 "websocket"))
250 {
Ed Tanous596b2032021-09-13 10:32:22 -0700251 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700252 // delete lambda with self shared_ptr
253 // to enable connection destruction
Nan Zhou72374eb2022-01-27 17:06:51 -0800254 asyncResp->res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700255 return;
256 }
Ed Tanous291d7092022-04-13 12:34:57 -0700257 std::string_view expected =
258 req->getHeaderValue(boost::beast::http::field::if_none_match);
259 if (!expected.empty())
260 {
261 res.setExpectedHash(expected);
262 }
Ed Tanous596b2032021-09-13 10:32:22 -0700263 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700264 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700265
Ed Tanouse278c182019-03-13 16:23:37 -0700266 bool isAlive()
267 {
Ed Tanouse278c182019-03-13 16:23:37 -0700268 if constexpr (std::is_same_v<Adaptor,
269 boost::beast::ssl_stream<
270 boost::asio::ip::tcp::socket>>)
271 {
272 return adaptor.next_layer().is_open();
273 }
274 else
275 {
276 return adaptor.is_open();
277 }
278 }
279 void close()
280 {
Ed Tanouse278c182019-03-13 16:23:37 -0700281 if constexpr (std::is_same_v<Adaptor,
282 boost::beast::ssl_stream<
283 boost::asio::ip::tcp::socket>>)
284 {
285 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100286 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200287 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700288 BMCWEB_LOG_DEBUG
289 << this
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100290 << " Removing TLS session: " << mtlsSession->uniqueId;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700291 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100292 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200293 }
Ed Tanouse278c182019-03-13 16:23:37 -0700294 }
295 else
296 {
297 adaptor.close();
298 }
299 }
300
Nan Zhou72374eb2022-01-27 17:06:51 -0800301 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700302 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700303 if (!req)
304 {
305 return;
306 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800307 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800308 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800309
Ed Tanous1abe55e2018-09-05 08:30:59 -0700310 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800311 << res.resultInt() << " keepalive=" << keepAlive;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700312
Ed Tanous0260d9d2021-02-07 19:31:07 +0000313 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700314
Nan Zhoud055a342022-05-25 01:15:34 +0000315 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700316
Ed Tanouse278c182019-03-13 16:23:37 -0700317 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700318 {
319 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
320 // isReading
321 // << ' ' << isWriting;
322 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000323
324 // delete lambda with self shared_ptr
325 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700326 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700327 return;
328 }
Ed Tanous291d7092022-04-13 12:34:57 -0700329
330 res.setHashAndHandleNotModified();
331
Ed Tanous1abe55e2018-09-05 08:30:59 -0700332 if (res.body().empty() && !res.jsonValue.empty())
333 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700334 using http_helpers::ContentType;
Ed Tanoused194be2022-08-07 16:50:11 -0700335 std::array<ContentType, 3> allowed{
336 ContentType::CBOR, ContentType::JSON, ContentType::HTML};
Ed Tanous99351cd2022-08-07 16:42:51 -0700337 ContentType prefered =
338 getPreferedContentType(req->getHeaderValue("Accept"), allowed);
339
340 if (prefered == ContentType::HTML)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700341 {
342 prettyPrintJson(res);
343 }
Ed Tanoused194be2022-08-07 16:50:11 -0700344 else if (prefered == ContentType::CBOR)
345 {
346 res.addHeader(boost::beast::http::field::content_type,
347 "application/cbor");
348 nlohmann::json::to_cbor(res.jsonValue, res.body());
349 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700350 else
351 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700352 // Technically prefered could also be NoMatch here, but we'd
353 // like to default to something rather than return 400 for
354 // backward compatibility.
Ed Tanousf610caa2022-03-17 08:53:00 -0700355 res.addHeader(boost::beast::http::field::content_type,
356 "application/json");
Ed Tanous71f52d92021-02-19 08:51:17 -0800357 res.body() = res.jsonValue.dump(
358 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700359 }
360 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700361
Ed Tanous1abe55e2018-09-05 08:30:59 -0700362 if (res.resultInt() >= 400 && res.body().empty())
363 {
364 res.body() = std::string(res.reason());
365 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700366
367 if (res.result() == boost::beast::http::status::no_content)
368 {
369 // Boost beast throws if content is provided on a no-content
370 // response. Ideally, this would never happen, but in the case that
371 // it does, we don't want to throw.
372 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100373 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700374 res.body().clear();
375 }
376
Ed Tanous1abe55e2018-09-05 08:30:59 -0700377 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
378
Nan Zhou72374eb2022-01-27 17:06:51 -0800379 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000380
381 // delete lambda with self shared_ptr
382 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700383 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700384 }
385
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500386 void readClientIp()
387 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700388 boost::asio::ip::address ip;
389 boost::system::error_code ec = getClientIp(ip);
390 if (ec)
391 {
392 return;
393 }
394 req->ipAddress = ip;
395 }
396
397 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
398 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500399 boost::system::error_code ec;
400 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
401 boost::asio::ip::tcp::endpoint endpoint =
402 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
403
404 if (ec)
405 {
406 // If remote endpoint fails keep going. "ClientOriginIPAddress"
407 // will be empty.
408 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
409 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700410 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500411 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700412 ip = endpoint.address();
413 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500414 }
415
Ed Tanous1abe55e2018-09-05 08:30:59 -0700416 private:
417 void doReadHeaders()
418 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700419 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
420
421 // Clean up any previous Connection.
422 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800423 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000424 [this,
425 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000426 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700427 BMCWEB_LOG_DEBUG << this << " async_read_header "
428 << bytesTransferred << " Bytes";
429 bool errorWhileReading = false;
430 if (ec)
431 {
432 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600433 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700434 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700435 BMCWEB_LOG_WARNING
436 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700437 }
438 else
439 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700440 BMCWEB_LOG_ERROR
441 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700442 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700443 }
444 else
445 {
446 // if the adaptor isn't open anymore, and wasn't handed to a
447 // websocket, treat as an error
448 if (!isAlive() &&
449 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700450 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700451 errorWhileReading = true;
452 }
453 }
454
455 cancelDeadlineTimer();
456
457 if (errorWhileReading)
458 {
459 close();
460 BMCWEB_LOG_DEBUG << this << " from read(1)";
461 return;
462 }
463
464 readClientIp();
465
466 boost::asio::ip::address ip;
467 if (getClientIp(ip))
468 {
469 BMCWEB_LOG_DEBUG << "Unable to get client IP";
470 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700471#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
472 boost::beast::http::verb method = parser->get().method();
473 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100474 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700475
476 bool loggedIn = userSession != nullptr;
477 if (!loggedIn)
478 {
479 const boost::optional<uint64_t> contentLength =
480 parser->content_length();
481 if (contentLength && *contentLength > loggedOutPostBodyLimit)
482 {
483 BMCWEB_LOG_DEBUG << "Content length greater than limit "
484 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700485 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700486 return;
487 }
488
Ed Tanous002d39b2022-05-31 08:59:27 -0700489 BMCWEB_LOG_DEBUG << "Starting quick deadline";
490 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000491#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800492
Ed Tanous7d243eb2023-01-23 15:57:41 -0800493 if (parser->is_done())
494 {
495 handle();
496 return;
497 }
498
Ed Tanous002d39b2022-05-31 08:59:27 -0700499 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700500 });
501 }
502
503 void doRead()
504 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700505 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800506 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800507 boost::beast::http::async_read_some(
508 adaptor, buffer, *parser,
509 [this,
510 self(shared_from_this())](const boost::system::error_code& ec,
511 std::size_t bytesTransferred) {
512 BMCWEB_LOG_DEBUG << this << " async_read_some " << bytesTransferred
Ed Tanous002d39b2022-05-31 08:59:27 -0700513 << " Bytes";
Ed Tanous7d243eb2023-01-23 15:57:41 -0800514
Ed Tanous002d39b2022-05-31 08:59:27 -0700515 if (ec)
516 {
517 BMCWEB_LOG_ERROR << this
518 << " Error while reading: " << ec.message();
519 close();
520 BMCWEB_LOG_DEBUG << this << " from read(1)";
521 return;
522 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800523
524 // If the user is logged in, allow them to send files incrementally
525 // one piece at a time. If authentication is disabled then there is
526 // no user session hence always allow to send one piece at a time.
527 if (userSession != nullptr)
528 {
529 cancelDeadlineTimer();
530 }
531 if (!parser->is_done())
532 {
533 doRead();
534 return;
535 }
536
537 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700538 handle();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800539 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700540 }
541
Nan Zhou72374eb2022-01-27 17:06:51 -0800542 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700543 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100544 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800545 thisRes.preparePayload();
546 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800547 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700548 boost::beast::http::async_write(adaptor, *serializer,
549 [this, self(shared_from_this())](
550 const boost::system::error_code& ec,
551 std::size_t bytesTransferred) {
552 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
553 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700554
Ed Tanous002d39b2022-05-31 08:59:27 -0700555 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700556
Ed Tanous002d39b2022-05-31 08:59:27 -0700557 if (ec)
558 {
559 BMCWEB_LOG_DEBUG << this << " from write(2)";
560 return;
561 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800562 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700563 {
564 close();
565 BMCWEB_LOG_DEBUG << this << " from write(1)";
566 return;
567 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700568
Ed Tanous002d39b2022-05-31 08:59:27 -0700569 serializer.reset();
570 BMCWEB_LOG_DEBUG << this << " Clearing response";
571 res.clear();
572 parser.emplace(std::piecewise_construct, std::make_tuple());
573 parser->body_limit(httpReqBodyLimit); // reset body limit for
574 // newly created parser
575 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700576
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100577 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700578
Ed Tanous002d39b2022-05-31 08:59:27 -0700579 // Destroy the Request via the std::optional
580 req.reset();
581 doReadHeaders();
582 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700583 }
584
Ed Tanous1abe55e2018-09-05 08:30:59 -0700585 void cancelDeadlineTimer()
586 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800587 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700588 }
589
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800590 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700591 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800592 // Timer is already started so no further action is required.
593 if (timerStarted)
594 {
595 return;
596 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700597
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800598 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800599
600 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
601 timer.expires_after(timeout);
602 timer.async_wait([weakSelf](const boost::system::error_code ec) {
603 // Note, we are ignoring other types of errors here; If the timer
604 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800605 std::shared_ptr<Connection<Adaptor, Handler>> self =
606 weakSelf.lock();
607 if (!self)
608 {
609 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
610 return;
611 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800612
613 self->timerStarted = false;
614
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800615 if (ec == boost::asio::error::operation_aborted)
616 {
617 // Canceled wait means the path succeeeded.
618 return;
619 }
620 if (ec)
621 {
622 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
623 }
624
625 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
626
627 self->close();
628 });
629
Ed Tanous7d243eb2023-01-23 15:57:41 -0800630 timerStarted = true;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800631 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700632 }
633
Ed Tanous1abe55e2018-09-05 08:30:59 -0700634 Adaptor adaptor;
635 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800636 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700637 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800638 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700639 boost::beast::http::request_parser<boost::beast::http::string_body>>
640 parser;
641
Ed Tanous3112a142018-11-29 15:45:10 -0800642 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700643
Ed Tanousa24526d2018-12-10 15:17:59 -0800644 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 boost::beast::http::string_body>>
646 serializer;
647
Ed Tanousa24526d2018-12-10 15:17:59 -0800648 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700650
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700651 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100652 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700653
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800654 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700655
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800656 bool keepAlive = true;
657
Ed Tanous7d243eb2023-01-23 15:57:41 -0800658 bool timerStarted = false;
659
Ed Tanous1abe55e2018-09-05 08:30:59 -0700660 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000661
662 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700663 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800664
665 using std::enable_shared_from_this<
666 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800667};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700668} // namespace crow