blob: 2a6afeb635a7bda5613f536330eda108bebaa86d [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 Tanoused5f8952023-06-22 14:06:22 -07006#include "complete_response_fields.hpp"
Ed Tanousfca2cbe2021-01-28 14:49:59 -08007#include "http2_connection.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07008#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07009#include "http_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070010#include "logging.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080011#include "mutual_tls.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080012#include "ssl_key_handler.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070013#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070014
Ed Tanous257f5792018-03-17 14:40:09 -070015#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080016#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080017#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070018#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080019#include <boost/asio/steady_timer.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080020#include <boost/beast/core/flat_static_buffer.hpp>
Myung Baea4326fe2023-01-10 14:29:24 -060021#include <boost/beast/http/error.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070022#include <boost/beast/http/parser.hpp>
23#include <boost/beast/http/read.hpp>
24#include <boost/beast/http/serializer.hpp>
25#include <boost/beast/http/write.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053026#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050027#include <boost/beast/websocket.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050028
Manojkiran Eda44250442020-06-16 12:51:38 +053029#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050030#include <chrono>
31#include <vector>
32
Ed Tanous1abe55e2018-09-05 08:30:59 -070033namespace crow
34{
Ed Tanous257f5792018-03-17 14:40:09 -070035
Ed Tanouscf9e4172022-12-21 09:30:16 -080036// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080037static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070038
Ed Tanous0260d9d2021-02-07 19:31:07 +000039// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Patrick Williams89492a12023-05-10 07:51:34 -050040constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL *
41 bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070042
James Feist3909dc82020-04-03 10:58:55 -070043constexpr uint64_t loggedOutPostBodyLimit = 4096;
44
45constexpr uint32_t httpHeaderLimit = 8192;
46
Ed Tanous52cc1122020-07-18 13:51:21 -070047template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050048class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070049 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070050{
Ed Tanous7c8e0642022-02-21 12:11:14 -080051 using self_type = Connection<Adaptor, Handler>;
52
Ed Tanous1abe55e2018-09-05 08:30:59 -070053 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080054 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000055 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080056 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080057 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080058 handler(handlerIn), timer(std::move(timerIn)),
59 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070060 {
61 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070062 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070063 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020064
65#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070066 prepareMutualTls();
67#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
68
Ed Tanous40aa0582021-07-14 13:24:40 -070069 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080070
Ed Tanous62598e32023-07-17 17:06:25 -070071 BMCWEB_LOG_DEBUG("{} Connection open, total {}", logPtr(this),
72 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070073 }
74
75 ~Connection()
76 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070077 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070078 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080079
Ed Tanous40aa0582021-07-14 13:24:40 -070080 connectionCount--;
Ed Tanous62598e32023-07-17 17:06:25 -070081 BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
82 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070083 }
84
Ed Tanousecd6a3a2022-01-07 09:18:40 -080085 Connection(const Connection&) = delete;
86 Connection(Connection&&) = delete;
87 Connection& operator=(const Connection&) = delete;
88 Connection& operator=(Connection&&) = delete;
89
Ed Tanous7c8e0642022-02-21 12:11:14 -080090 bool tlsVerifyCallback(bool preverified,
91 boost::asio::ssl::verify_context& ctx)
92 {
93 // We always return true to allow full auth flow for resources that
94 // don't require auth
95 if (preverified)
96 {
Michal Orzel7aa9ab02023-08-18 16:59:11 +020097 boost::asio::ip::address ipAddress;
98 if (getClientIp(ipAddress))
Ed Tanouse01d0c32023-06-30 13:21:32 -070099 {
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200100 return true;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700101 }
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200102
103 mtlsSession = verifyMtlsUser(ipAddress, ctx);
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100104 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800105 {
Ed Tanous62598e32023-07-17 17:06:25 -0700106 BMCWEB_LOG_DEBUG("{} Generating TLS session: {}", logPtr(this),
107 mtlsSession->uniqueId);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800108 }
109 }
110 return true;
111 }
112
Ed Tanous40aa0582021-07-14 13:24:40 -0700113 void prepareMutualTls()
114 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -0800115 std::error_code error;
116 std::filesystem::path caPath(ensuressl::trustStorePath);
117 auto caAvailable = !std::filesystem::is_empty(caPath, error);
118 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700119 if (caAvailable && persistent_data::SessionStore::getInstance()
120 .getAuthMethodsConfig()
121 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100122 {
123 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700124 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800125
Ed Tanous9eb808c2022-01-25 10:19:23 -0800126 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800127 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800128 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700129 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800130 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700131 static_cast<unsigned int>(id.length()));
132 if (ret == 0)
133 {
Ed Tanous62598e32023-07-17 17:06:25 -0700134 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700135 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100136 }
137
Ed Tanous002d39b2022-05-31 08:59:27 -0700138 adaptor.set_verify_callback(
Ed Tanous7c8e0642022-02-21 12:11:14 -0800139 std::bind_front(&self_type::tlsVerifyCallback, this));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700140 }
141
Ed Tanousceac6f72018-12-02 11:58:47 -0800142 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700143 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800144 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700145 }
146
Ed Tanous1abe55e2018-09-05 08:30:59 -0700147 void start()
148 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800149 if (connectionCount >= 100)
150 {
Ed Tanous62598e32023-07-17 17:06:25 -0700151 BMCWEB_LOG_CRITICAL("{}Max connection count exceeded.",
152 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800153 return;
154 }
155
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800156 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500157
Ed Tanousceac6f72018-12-02 11:58:47 -0800158 // TODO(ed) Abstract this to a more clever class with the idea of an
159 // asynchronous "start"
160 if constexpr (std::is_same_v<Adaptor,
161 boost::beast::ssl_stream<
162 boost::asio::ip::tcp::socket>>)
163 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000164 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
165 [this, self(shared_from_this())](
166 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700167 if (ec)
168 {
169 return;
170 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800171 afterSslHandshake();
Ed Tanous002d39b2022-05-31 08:59:27 -0700172 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800173 }
174 else
175 {
176 doReadHeaders();
177 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700178 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700179
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800180 void afterSslHandshake()
181 {
182 // If http2 is enabled, negotiate the protocol
183 if constexpr (bmcwebEnableHTTP2)
184 {
185 const unsigned char* alpn = nullptr;
186 unsigned int alpnlen = 0;
187 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
188 if (alpn != nullptr)
189 {
190 std::string_view selectedProtocol(
191 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700192 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
193 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800194 if (selectedProtocol == "h2")
195 {
196 auto http2 =
197 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
198 std::move(adaptor), handler, getCachedDateStr);
199 http2->start();
200 return;
201 }
202 }
203 }
204
205 doReadHeaders();
206 }
207
Ed Tanous1abe55e2018-09-05 08:30:59 -0700208 void handle()
209 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700210 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700211 if (!parser)
212 {
213 return;
214 }
Ed Tanousf79b7a52021-09-22 19:04:29 -0700215 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
216 if (reqEc)
217 {
Ed Tanous62598e32023-07-17 17:06:25 -0700218 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600219 res.result(boost::beast::http::status::bad_request);
220 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700221 return;
222 }
Ed Tanous596b2032021-09-13 10:32:22 -0700223 thisReq.session = userSession;
224
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000225 // Fetch the client IP address
226 readClientIp();
227
Ed Tanous1abe55e2018-09-05 08:30:59 -0700228 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700229 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700230 {
Ed Tanous596b2032021-09-13 10:32:22 -0700231 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700232 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700233 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800234 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700235 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700236 }
237 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700238
Ed Tanous62598e32023-07-17 17:06:25 -0700239 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
240 thisReq.version() / 10, thisReq.version() % 10,
241 thisReq.methodString(), thisReq.target(),
242 thisReq.ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700243
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700244 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700245
Ed Tanous596b2032021-09-13 10:32:22 -0700246 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700247 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200248
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700249 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700250 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800251 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700252 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700253 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800254 keepAlive = thisReq.keepAlive();
Nan Zhoua43ea822022-05-27 00:42:44 +0000255#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanousc51a58e2023-03-27 14:43:19 -0700256 if (!crow::authentication::isOnAllowlist(req->url().path(),
Ed Tanous39662a32023-02-06 15:09:46 -0800257 req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700258 thisReq.session == nullptr)
259 {
Ed Tanous62598e32023-07-17 17:06:25 -0700260 BMCWEB_LOG_WARNING("Authentication failed");
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700261 forward_unauthorized::sendUnauthorized(
Ed Tanous39662a32023-02-06 15:09:46 -0800262 req->url().encoded_path(),
263 req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700264 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800265 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700266 return;
267 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000268#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800269 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700270 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800271 asyncResp->res.setCompleteRequestHandler(
272 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700273 self->completeRequest(thisRes);
274 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700275 bool isSse =
276 isContentTypeAllowed(req->getHeaderValue("Accept"),
277 http_helpers::ContentType::EventStream, false);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530278 if ((thisReq.isUpgrade() &&
279 boost::iequals(
280 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
281 "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700282 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700283 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530284 asyncResp->res.setCompleteRequestHandler(
285 [self(shared_from_this())](crow::Response& thisRes) {
286 if (thisRes.result() != boost::beast::http::status::ok)
287 {
288 // When any error occurs before handle upgradation,
289 // the result in response will be set to respective
290 // error. By default the Result will be OK (200),
291 // which implies successful handle upgrade. Response
292 // needs to be sent over this connection only on
293 // failure.
294 self->completeRequest(thisRes);
295 return;
296 }
297 });
298 handler->handleUpgrade(thisReq, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700299 return;
300 }
Ed Tanous291d7092022-04-13 12:34:57 -0700301 std::string_view expected =
302 req->getHeaderValue(boost::beast::http::field::if_none_match);
303 if (!expected.empty())
304 {
305 res.setExpectedHash(expected);
306 }
Ed Tanous596b2032021-09-13 10:32:22 -0700307 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700308 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700309
Ed Tanouse278c182019-03-13 16:23:37 -0700310 bool isAlive()
311 {
Ed Tanouse278c182019-03-13 16:23:37 -0700312 if constexpr (std::is_same_v<Adaptor,
313 boost::beast::ssl_stream<
314 boost::asio::ip::tcp::socket>>)
315 {
316 return adaptor.next_layer().is_open();
317 }
318 else
319 {
320 return adaptor.is_open();
321 }
322 }
323 void close()
324 {
Ed Tanouse278c182019-03-13 16:23:37 -0700325 if constexpr (std::is_same_v<Adaptor,
326 boost::beast::ssl_stream<
327 boost::asio::ip::tcp::socket>>)
328 {
329 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100330 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200331 {
Ed Tanous62598e32023-07-17 17:06:25 -0700332 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
333 mtlsSession->uniqueId);
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700334 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100335 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200336 }
Ed Tanouse278c182019-03-13 16:23:37 -0700337 }
338 else
339 {
340 adaptor.close();
341 }
342 }
343
Nan Zhou72374eb2022-01-27 17:06:51 -0800344 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700345 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700346 if (!req)
347 {
348 return;
349 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800350 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800351 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800352
Ed Tanoused5f8952023-06-22 14:06:22 -0700353 completeResponseFields(*req, res);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700354
Ed Tanouse278c182019-03-13 16:23:37 -0700355 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700356 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700357 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358 return;
359 }
Ed Tanous291d7092022-04-13 12:34:57 -0700360
Nan Zhou72374eb2022-01-27 17:06:51 -0800361 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000362
363 // delete lambda with self shared_ptr
364 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700365 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700366 }
367
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500368 void readClientIp()
369 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700370 boost::asio::ip::address ip;
371 boost::system::error_code ec = getClientIp(ip);
372 if (ec)
373 {
374 return;
375 }
Ed Tanouse01d0c32023-06-30 13:21:32 -0700376 if (!req)
377 {
378 return;
379 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700380 req->ipAddress = ip;
381 }
382
383 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
384 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500385 boost::system::error_code ec;
Ed Tanous62598e32023-07-17 17:06:25 -0700386 BMCWEB_LOG_DEBUG("Fetch the client IP address");
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500387 boost::asio::ip::tcp::endpoint endpoint =
388 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
389
390 if (ec)
391 {
392 // If remote endpoint fails keep going. "ClientOriginIPAddress"
393 // will be empty.
Ed Tanous62598e32023-07-17 17:06:25 -0700394 BMCWEB_LOG_ERROR("Failed to get the client's IP Address. ec : {}",
395 ec);
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700396 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500397 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700398 ip = endpoint.address();
399 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500400 }
401
Ed Tanous1abe55e2018-09-05 08:30:59 -0700402 private:
403 void doReadHeaders()
404 {
Ed Tanous62598e32023-07-17 17:06:25 -0700405 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700406 if (!parser)
407 {
408 return;
409 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700410 // Clean up any previous Connection.
411 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800412 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000413 [this,
414 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000415 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700416 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
417 bytesTransferred);
Ed Tanous002d39b2022-05-31 08:59:27 -0700418 bool errorWhileReading = false;
419 if (ec)
420 {
421 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600422 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700423 {
Ed Tanous62598e32023-07-17 17:06:25 -0700424 BMCWEB_LOG_WARNING("{} Error while reading: {}",
425 logPtr(this), ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700426 }
427 else
428 {
Ed Tanous62598e32023-07-17 17:06:25 -0700429 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
430 ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700431 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700432 }
433 else
434 {
435 // if the adaptor isn't open anymore, and wasn't handed to a
436 // websocket, treat as an error
437 if (!isAlive() &&
438 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700439 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700440 errorWhileReading = true;
441 }
442 }
443
444 cancelDeadlineTimer();
445
446 if (errorWhileReading)
447 {
448 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700449 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700450 return;
451 }
452
453 readClientIp();
454
455 boost::asio::ip::address ip;
456 if (getClientIp(ip))
457 {
Ed Tanous62598e32023-07-17 17:06:25 -0700458 BMCWEB_LOG_DEBUG("Unable to get client IP");
Ed Tanous002d39b2022-05-31 08:59:27 -0700459 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700460#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
461 boost::beast::http::verb method = parser->get().method();
462 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100463 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700464
465 bool loggedIn = userSession != nullptr;
466 if (!loggedIn)
467 {
468 const boost::optional<uint64_t> contentLength =
469 parser->content_length();
470 if (contentLength && *contentLength > loggedOutPostBodyLimit)
471 {
Ed Tanous62598e32023-07-17 17:06:25 -0700472 BMCWEB_LOG_DEBUG("Content length greater than limit {}",
473 *contentLength);
Ed Tanouse278c182019-03-13 16:23:37 -0700474 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700475 return;
476 }
477
Ed Tanous62598e32023-07-17 17:06:25 -0700478 BMCWEB_LOG_DEBUG("Starting quick deadline");
Ed Tanous002d39b2022-05-31 08:59:27 -0700479 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000480#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800481
Ed Tanous7d243eb2023-01-23 15:57:41 -0800482 if (parser->is_done())
483 {
484 handle();
485 return;
486 }
487
Ed Tanous002d39b2022-05-31 08:59:27 -0700488 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700489 });
490 }
491
492 void doRead()
493 {
Ed Tanous62598e32023-07-17 17:06:25 -0700494 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700495 if (!parser)
496 {
497 return;
498 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800499 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800500 boost::beast::http::async_read_some(
501 adaptor, buffer, *parser,
502 [this,
503 self(shared_from_this())](const boost::system::error_code& ec,
504 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700505 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
506 bytesTransferred);
Ed Tanous7d243eb2023-01-23 15:57:41 -0800507
Ed Tanous002d39b2022-05-31 08:59:27 -0700508 if (ec)
509 {
Ed Tanous62598e32023-07-17 17:06:25 -0700510 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
511 ec.message());
Ed Tanous002d39b2022-05-31 08:59:27 -0700512 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700513 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700514 return;
515 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800516
517 // If the user is logged in, allow them to send files incrementally
518 // one piece at a time. If authentication is disabled then there is
519 // no user session hence always allow to send one piece at a time.
520 if (userSession != nullptr)
521 {
522 cancelDeadlineTimer();
523 }
524 if (!parser->is_done())
525 {
526 doRead();
527 return;
528 }
529
530 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700531 handle();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800532 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700533 }
534
Nan Zhou72374eb2022-01-27 17:06:51 -0800535 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700536 {
Ed Tanous62598e32023-07-17 17:06:25 -0700537 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Nan Zhou72374eb2022-01-27 17:06:51 -0800538 thisRes.preparePayload();
Ed Tanouse01d0c32023-06-30 13:21:32 -0700539 serializer.emplace(thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800540 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700541 boost::beast::http::async_write(adaptor, *serializer,
542 [this, self(shared_from_this())](
543 const boost::system::error_code& ec,
544 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700545 BMCWEB_LOG_DEBUG("{} async_write {} bytes", logPtr(this),
546 bytesTransferred);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700547
Ed Tanous002d39b2022-05-31 08:59:27 -0700548 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700549
Ed Tanous002d39b2022-05-31 08:59:27 -0700550 if (ec)
551 {
Ed Tanous62598e32023-07-17 17:06:25 -0700552 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700553 return;
554 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800555 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700556 {
557 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700558 BMCWEB_LOG_DEBUG("{} from write(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700559 return;
560 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700561
Ed Tanous002d39b2022-05-31 08:59:27 -0700562 serializer.reset();
Ed Tanous62598e32023-07-17 17:06:25 -0700563 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700564 res.clear();
565 parser.emplace(std::piecewise_construct, std::make_tuple());
566 parser->body_limit(httpReqBodyLimit); // reset body limit for
567 // newly created parser
568 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700569
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100570 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700571
Ed Tanous002d39b2022-05-31 08:59:27 -0700572 // Destroy the Request via the std::optional
573 req.reset();
574 doReadHeaders();
575 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700576 }
577
Ed Tanous1abe55e2018-09-05 08:30:59 -0700578 void cancelDeadlineTimer()
579 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800580 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700581 }
582
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800583 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700584 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800585 // Timer is already started so no further action is required.
586 if (timerStarted)
587 {
588 return;
589 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700590
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800591 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800592
593 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
594 timer.expires_after(timeout);
Ed Tanous81c4e332023-05-18 10:30:34 -0700595 timer.async_wait([weakSelf](const boost::system::error_code& ec) {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800596 // Note, we are ignoring other types of errors here; If the timer
597 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800598 std::shared_ptr<Connection<Adaptor, Handler>> self =
599 weakSelf.lock();
600 if (!self)
601 {
Ed Tanous62598e32023-07-17 17:06:25 -0700602 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
603 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800604 return;
605 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800606
607 self->timerStarted = false;
608
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800609 if (ec == boost::asio::error::operation_aborted)
610 {
611 // Canceled wait means the path succeeeded.
612 return;
613 }
614 if (ec)
615 {
Ed Tanous62598e32023-07-17 17:06:25 -0700616 BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()),
617 ec);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800618 }
619
Ed Tanous62598e32023-07-17 17:06:25 -0700620 BMCWEB_LOG_WARNING("{}Connection timed out, closing",
621 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800622
623 self->close();
624 });
625
Ed Tanous7d243eb2023-01-23 15:57:41 -0800626 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700627 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700628 }
629
Ed Tanous1abe55e2018-09-05 08:30:59 -0700630 Adaptor adaptor;
631 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800632 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700633 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800634 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700635 boost::beast::http::request_parser<boost::beast::http::string_body>>
636 parser;
637
Ed Tanous3112a142018-11-29 15:45:10 -0800638 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700639
Ed Tanousa24526d2018-12-10 15:17:59 -0800640 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 boost::beast::http::string_body>>
642 serializer;
643
Ed Tanousa24526d2018-12-10 15:17:59 -0800644 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700646
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700647 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100648 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800650 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800652 bool keepAlive = true;
653
Ed Tanous7d243eb2023-01-23 15:57:41 -0800654 bool timerStarted = false;
655
Ed Tanous1abe55e2018-09-05 08:30:59 -0700656 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000657
658 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700659 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800660
661 using std::enable_shared_from_this<
662 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800663};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700664} // namespace crow