blob: ba4af3f747b852341a12d6d52966d37534277847 [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 {
Ed Tanouse01d0c32023-06-30 13:21:32 -070097 if (!req)
98 {
99 return false;
100 }
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100101 mtlsSession = verifyMtlsUser(req->ipAddress, ctx);
102 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800103 {
Ed Tanous62598e32023-07-17 17:06:25 -0700104 BMCWEB_LOG_DEBUG("{} Generating TLS session: {}", logPtr(this),
105 mtlsSession->uniqueId);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800106 }
107 }
108 return true;
109 }
110
Ed Tanous40aa0582021-07-14 13:24:40 -0700111 void prepareMutualTls()
112 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -0800113 std::error_code error;
114 std::filesystem::path caPath(ensuressl::trustStorePath);
115 auto caAvailable = !std::filesystem::is_empty(caPath, error);
116 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700117 if (caAvailable && persistent_data::SessionStore::getInstance()
118 .getAuthMethodsConfig()
119 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100120 {
121 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700122 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800123
Ed Tanous9eb808c2022-01-25 10:19:23 -0800124 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800125 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800126 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700127 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800128 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700129 static_cast<unsigned int>(id.length()));
130 if (ret == 0)
131 {
Ed Tanous62598e32023-07-17 17:06:25 -0700132 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700133 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100134 }
135
Ed Tanous002d39b2022-05-31 08:59:27 -0700136 adaptor.set_verify_callback(
Ed Tanous7c8e0642022-02-21 12:11:14 -0800137 std::bind_front(&self_type::tlsVerifyCallback, this));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700138 }
139
Ed Tanousceac6f72018-12-02 11:58:47 -0800140 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700141 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800142 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700143 }
144
Ed Tanous1abe55e2018-09-05 08:30:59 -0700145 void start()
146 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800147 if (connectionCount >= 100)
148 {
Ed Tanous62598e32023-07-17 17:06:25 -0700149 BMCWEB_LOG_CRITICAL("{}Max connection count exceeded.",
150 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800151 return;
152 }
153
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800154 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500155
Ed Tanousceac6f72018-12-02 11:58:47 -0800156 // TODO(ed) Abstract this to a more clever class with the idea of an
157 // asynchronous "start"
158 if constexpr (std::is_same_v<Adaptor,
159 boost::beast::ssl_stream<
160 boost::asio::ip::tcp::socket>>)
161 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000162 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
163 [this, self(shared_from_this())](
164 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700165 if (ec)
166 {
167 return;
168 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800169 afterSslHandshake();
Ed Tanous002d39b2022-05-31 08:59:27 -0700170 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800171 }
172 else
173 {
174 doReadHeaders();
175 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700176 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700177
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800178 void afterSslHandshake()
179 {
180 // If http2 is enabled, negotiate the protocol
181 if constexpr (bmcwebEnableHTTP2)
182 {
183 const unsigned char* alpn = nullptr;
184 unsigned int alpnlen = 0;
185 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
186 if (alpn != nullptr)
187 {
188 std::string_view selectedProtocol(
189 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700190 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
191 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800192 if (selectedProtocol == "h2")
193 {
194 auto http2 =
195 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
196 std::move(adaptor), handler, getCachedDateStr);
197 http2->start();
198 return;
199 }
200 }
201 }
202
203 doReadHeaders();
204 }
205
Ed Tanous1abe55e2018-09-05 08:30:59 -0700206 void handle()
207 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700208 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700209 if (!parser)
210 {
211 return;
212 }
Ed Tanousf79b7a52021-09-22 19:04:29 -0700213 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
214 if (reqEc)
215 {
Ed Tanous62598e32023-07-17 17:06:25 -0700216 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600217 res.result(boost::beast::http::status::bad_request);
218 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700219 return;
220 }
Ed Tanous596b2032021-09-13 10:32:22 -0700221 thisReq.session = userSession;
222
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000223 // Fetch the client IP address
224 readClientIp();
225
Ed Tanous1abe55e2018-09-05 08:30:59 -0700226 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700227 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700228 {
Ed Tanous596b2032021-09-13 10:32:22 -0700229 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700230 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700231 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800232 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700233 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700234 }
235 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700236
Ed Tanous62598e32023-07-17 17:06:25 -0700237 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
238 thisReq.version() / 10, thisReq.version() % 10,
239 thisReq.methodString(), thisReq.target(),
240 thisReq.ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700241
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700242 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700243
Ed Tanous596b2032021-09-13 10:32:22 -0700244 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700245 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200246
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700247 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700248 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800249 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700250 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700251 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800252 keepAlive = thisReq.keepAlive();
Nan Zhoua43ea822022-05-27 00:42:44 +0000253#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanousc51a58e2023-03-27 14:43:19 -0700254 if (!crow::authentication::isOnAllowlist(req->url().path(),
Ed Tanous39662a32023-02-06 15:09:46 -0800255 req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700256 thisReq.session == nullptr)
257 {
Ed Tanous62598e32023-07-17 17:06:25 -0700258 BMCWEB_LOG_WARNING("Authentication failed");
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700259 forward_unauthorized::sendUnauthorized(
Ed Tanous39662a32023-02-06 15:09:46 -0800260 req->url().encoded_path(),
261 req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700262 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800263 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700264 return;
265 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000266#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800267 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700268 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800269 asyncResp->res.setCompleteRequestHandler(
270 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700271 self->completeRequest(thisRes);
272 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700273 bool isSse =
274 isContentTypeAllowed(req->getHeaderValue("Accept"),
275 http_helpers::ContentType::EventStream, false);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530276 if ((thisReq.isUpgrade() &&
277 boost::iequals(
278 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
279 "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700280 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700281 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530282 asyncResp->res.setCompleteRequestHandler(
283 [self(shared_from_this())](crow::Response& thisRes) {
284 if (thisRes.result() != boost::beast::http::status::ok)
285 {
286 // When any error occurs before handle upgradation,
287 // the result in response will be set to respective
288 // error. By default the Result will be OK (200),
289 // which implies successful handle upgrade. Response
290 // needs to be sent over this connection only on
291 // failure.
292 self->completeRequest(thisRes);
293 return;
294 }
295 });
296 handler->handleUpgrade(thisReq, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700297 return;
298 }
Ed Tanous291d7092022-04-13 12:34:57 -0700299 std::string_view expected =
300 req->getHeaderValue(boost::beast::http::field::if_none_match);
301 if (!expected.empty())
302 {
303 res.setExpectedHash(expected);
304 }
Ed Tanous596b2032021-09-13 10:32:22 -0700305 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700306 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700307
Ed Tanouse278c182019-03-13 16:23:37 -0700308 bool isAlive()
309 {
Ed Tanouse278c182019-03-13 16:23:37 -0700310 if constexpr (std::is_same_v<Adaptor,
311 boost::beast::ssl_stream<
312 boost::asio::ip::tcp::socket>>)
313 {
314 return adaptor.next_layer().is_open();
315 }
316 else
317 {
318 return adaptor.is_open();
319 }
320 }
321 void close()
322 {
Ed Tanouse278c182019-03-13 16:23:37 -0700323 if constexpr (std::is_same_v<Adaptor,
324 boost::beast::ssl_stream<
325 boost::asio::ip::tcp::socket>>)
326 {
327 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100328 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200329 {
Ed Tanous62598e32023-07-17 17:06:25 -0700330 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
331 mtlsSession->uniqueId);
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700332 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100333 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200334 }
Ed Tanouse278c182019-03-13 16:23:37 -0700335 }
336 else
337 {
338 adaptor.close();
339 }
340 }
341
Nan Zhou72374eb2022-01-27 17:06:51 -0800342 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700343 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700344 if (!req)
345 {
346 return;
347 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800348 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800349 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800350
Ed Tanoused5f8952023-06-22 14:06:22 -0700351 completeResponseFields(*req, res);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700352
Ed Tanouse278c182019-03-13 16:23:37 -0700353 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700354 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700355 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700356 return;
357 }
Ed Tanous291d7092022-04-13 12:34:57 -0700358
Nan Zhou72374eb2022-01-27 17:06:51 -0800359 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000360
361 // delete lambda with self shared_ptr
362 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700363 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700364 }
365
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500366 void readClientIp()
367 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700368 boost::asio::ip::address ip;
369 boost::system::error_code ec = getClientIp(ip);
370 if (ec)
371 {
372 return;
373 }
Ed Tanouse01d0c32023-06-30 13:21:32 -0700374 if (!req)
375 {
376 return;
377 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700378 req->ipAddress = ip;
379 }
380
381 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
382 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500383 boost::system::error_code ec;
Ed Tanous62598e32023-07-17 17:06:25 -0700384 BMCWEB_LOG_DEBUG("Fetch the client IP address");
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500385 boost::asio::ip::tcp::endpoint endpoint =
386 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
387
388 if (ec)
389 {
390 // If remote endpoint fails keep going. "ClientOriginIPAddress"
391 // will be empty.
Ed Tanous62598e32023-07-17 17:06:25 -0700392 BMCWEB_LOG_ERROR("Failed to get the client's IP Address. ec : {}",
393 ec);
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700394 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500395 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700396 ip = endpoint.address();
397 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500398 }
399
Ed Tanous1abe55e2018-09-05 08:30:59 -0700400 private:
401 void doReadHeaders()
402 {
Ed Tanous62598e32023-07-17 17:06:25 -0700403 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700404 if (!parser)
405 {
406 return;
407 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700408 // Clean up any previous Connection.
409 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800410 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000411 [this,
412 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000413 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700414 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
415 bytesTransferred);
Ed Tanous002d39b2022-05-31 08:59:27 -0700416 bool errorWhileReading = false;
417 if (ec)
418 {
419 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600420 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700421 {
Ed Tanous62598e32023-07-17 17:06:25 -0700422 BMCWEB_LOG_WARNING("{} Error while reading: {}",
423 logPtr(this), ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700424 }
425 else
426 {
Ed Tanous62598e32023-07-17 17:06:25 -0700427 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
428 ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700429 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700430 }
431 else
432 {
433 // if the adaptor isn't open anymore, and wasn't handed to a
434 // websocket, treat as an error
435 if (!isAlive() &&
436 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700437 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700438 errorWhileReading = true;
439 }
440 }
441
442 cancelDeadlineTimer();
443
444 if (errorWhileReading)
445 {
446 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700447 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700448 return;
449 }
450
451 readClientIp();
452
453 boost::asio::ip::address ip;
454 if (getClientIp(ip))
455 {
Ed Tanous62598e32023-07-17 17:06:25 -0700456 BMCWEB_LOG_DEBUG("Unable to get client IP");
Ed Tanous002d39b2022-05-31 08:59:27 -0700457 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700458#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
459 boost::beast::http::verb method = parser->get().method();
460 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100461 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700462
463 bool loggedIn = userSession != nullptr;
464 if (!loggedIn)
465 {
466 const boost::optional<uint64_t> contentLength =
467 parser->content_length();
468 if (contentLength && *contentLength > loggedOutPostBodyLimit)
469 {
Ed Tanous62598e32023-07-17 17:06:25 -0700470 BMCWEB_LOG_DEBUG("Content length greater than limit {}",
471 *contentLength);
Ed Tanouse278c182019-03-13 16:23:37 -0700472 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700473 return;
474 }
475
Ed Tanous62598e32023-07-17 17:06:25 -0700476 BMCWEB_LOG_DEBUG("Starting quick deadline");
Ed Tanous002d39b2022-05-31 08:59:27 -0700477 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000478#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800479
Ed Tanous7d243eb2023-01-23 15:57:41 -0800480 if (parser->is_done())
481 {
482 handle();
483 return;
484 }
485
Ed Tanous002d39b2022-05-31 08:59:27 -0700486 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700487 });
488 }
489
490 void doRead()
491 {
Ed Tanous62598e32023-07-17 17:06:25 -0700492 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700493 if (!parser)
494 {
495 return;
496 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800497 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800498 boost::beast::http::async_read_some(
499 adaptor, buffer, *parser,
500 [this,
501 self(shared_from_this())](const boost::system::error_code& ec,
502 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700503 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
504 bytesTransferred);
Ed Tanous7d243eb2023-01-23 15:57:41 -0800505
Ed Tanous002d39b2022-05-31 08:59:27 -0700506 if (ec)
507 {
Ed Tanous62598e32023-07-17 17:06:25 -0700508 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
509 ec.message());
Ed Tanous002d39b2022-05-31 08:59:27 -0700510 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700511 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700512 return;
513 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800514
515 // If the user is logged in, allow them to send files incrementally
516 // one piece at a time. If authentication is disabled then there is
517 // no user session hence always allow to send one piece at a time.
518 if (userSession != nullptr)
519 {
520 cancelDeadlineTimer();
521 }
522 if (!parser->is_done())
523 {
524 doRead();
525 return;
526 }
527
528 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700529 handle();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800530 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700531 }
532
Nan Zhou72374eb2022-01-27 17:06:51 -0800533 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700534 {
Ed Tanous62598e32023-07-17 17:06:25 -0700535 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Nan Zhou72374eb2022-01-27 17:06:51 -0800536 thisRes.preparePayload();
Ed Tanouse01d0c32023-06-30 13:21:32 -0700537 serializer.emplace(thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800538 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700539 boost::beast::http::async_write(adaptor, *serializer,
540 [this, self(shared_from_this())](
541 const boost::system::error_code& ec,
542 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700543 BMCWEB_LOG_DEBUG("{} async_write {} bytes", logPtr(this),
544 bytesTransferred);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700545
Ed Tanous002d39b2022-05-31 08:59:27 -0700546 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700547
Ed Tanous002d39b2022-05-31 08:59:27 -0700548 if (ec)
549 {
Ed Tanous62598e32023-07-17 17:06:25 -0700550 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700551 return;
552 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800553 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700554 {
555 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700556 BMCWEB_LOG_DEBUG("{} from write(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700557 return;
558 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700559
Ed Tanous002d39b2022-05-31 08:59:27 -0700560 serializer.reset();
Ed Tanous62598e32023-07-17 17:06:25 -0700561 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700562 res.clear();
563 parser.emplace(std::piecewise_construct, std::make_tuple());
564 parser->body_limit(httpReqBodyLimit); // reset body limit for
565 // newly created parser
566 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100568 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700569
Ed Tanous002d39b2022-05-31 08:59:27 -0700570 // Destroy the Request via the std::optional
571 req.reset();
572 doReadHeaders();
573 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700574 }
575
Ed Tanous1abe55e2018-09-05 08:30:59 -0700576 void cancelDeadlineTimer()
577 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800578 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700579 }
580
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800581 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700582 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800583 // Timer is already started so no further action is required.
584 if (timerStarted)
585 {
586 return;
587 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700588
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800589 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800590
591 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
592 timer.expires_after(timeout);
Ed Tanous81c4e332023-05-18 10:30:34 -0700593 timer.async_wait([weakSelf](const boost::system::error_code& ec) {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800594 // Note, we are ignoring other types of errors here; If the timer
595 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800596 std::shared_ptr<Connection<Adaptor, Handler>> self =
597 weakSelf.lock();
598 if (!self)
599 {
Ed Tanous62598e32023-07-17 17:06:25 -0700600 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
601 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800602 return;
603 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800604
605 self->timerStarted = false;
606
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800607 if (ec == boost::asio::error::operation_aborted)
608 {
609 // Canceled wait means the path succeeeded.
610 return;
611 }
612 if (ec)
613 {
Ed Tanous62598e32023-07-17 17:06:25 -0700614 BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()),
615 ec);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800616 }
617
Ed Tanous62598e32023-07-17 17:06:25 -0700618 BMCWEB_LOG_WARNING("{}Connection timed out, closing",
619 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800620
621 self->close();
622 });
623
Ed Tanous7d243eb2023-01-23 15:57:41 -0800624 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700625 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700626 }
627
Ed Tanous1abe55e2018-09-05 08:30:59 -0700628 Adaptor adaptor;
629 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800630 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700631 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800632 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700633 boost::beast::http::request_parser<boost::beast::http::string_body>>
634 parser;
635
Ed Tanous3112a142018-11-29 15:45:10 -0800636 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700637
Ed Tanousa24526d2018-12-10 15:17:59 -0800638 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700639 boost::beast::http::string_body>>
640 serializer;
641
Ed Tanousa24526d2018-12-10 15:17:59 -0800642 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700643 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700644
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700645 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100646 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700647
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800648 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800650 bool keepAlive = true;
651
Ed Tanous7d243eb2023-01-23 15:57:41 -0800652 bool timerStarted = false;
653
Ed Tanous1abe55e2018-09-05 08:30:59 -0700654 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000655
656 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700657 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800658
659 using std::enable_shared_from_this<
660 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800661};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700662} // namespace crow