blob: cb252f96aa93ee38fc7e7a7bf165d8d291314519 [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 Tanous40aa0582021-07-14 13:24:40 -070071 BMCWEB_LOG_DEBUG << this << " Connection open, total "
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--;
81 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
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 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +010097 mtlsSession = verifyMtlsUser(req->ipAddress, ctx);
98 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -080099 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100100 BMCWEB_LOG_DEBUG
101 << this
102 << " Generating TLS session: " << mtlsSession->uniqueId;
Ed Tanous7c8e0642022-02-21 12:11:14 -0800103 }
104 }
105 return true;
106 }
107
Ed Tanous40aa0582021-07-14 13:24:40 -0700108 void prepareMutualTls()
109 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -0800110 std::error_code error;
111 std::filesystem::path caPath(ensuressl::trustStorePath);
112 auto caAvailable = !std::filesystem::is_empty(caPath, error);
113 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700114 if (caAvailable && persistent_data::SessionStore::getInstance()
115 .getAuthMethodsConfig()
116 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100117 {
118 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700119 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800120
Ed Tanous9eb808c2022-01-25 10:19:23 -0800121 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800122 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800123 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700124 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800125 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700126 static_cast<unsigned int>(id.length()));
127 if (ret == 0)
128 {
129 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
130 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100131 }
132
Ed Tanous002d39b2022-05-31 08:59:27 -0700133 adaptor.set_verify_callback(
Ed Tanous7c8e0642022-02-21 12:11:14 -0800134 std::bind_front(&self_type::tlsVerifyCallback, this));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700135 }
136
Ed Tanousceac6f72018-12-02 11:58:47 -0800137 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700138 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800139 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700140 }
141
Ed Tanous1abe55e2018-09-05 08:30:59 -0700142 void start()
143 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800144 if (connectionCount >= 100)
145 {
146 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
147 return;
148 }
149
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800150 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500151
Ed Tanousceac6f72018-12-02 11:58:47 -0800152 // TODO(ed) Abstract this to a more clever class with the idea of an
153 // asynchronous "start"
154 if constexpr (std::is_same_v<Adaptor,
155 boost::beast::ssl_stream<
156 boost::asio::ip::tcp::socket>>)
157 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000158 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
159 [this, self(shared_from_this())](
160 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700161 if (ec)
162 {
163 return;
164 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800165 afterSslHandshake();
Ed Tanous002d39b2022-05-31 08:59:27 -0700166 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800167 }
168 else
169 {
170 doReadHeaders();
171 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700172 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700173
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800174 void afterSslHandshake()
175 {
176 // If http2 is enabled, negotiate the protocol
177 if constexpr (bmcwebEnableHTTP2)
178 {
179 const unsigned char* alpn = nullptr;
180 unsigned int alpnlen = 0;
181 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
182 if (alpn != nullptr)
183 {
184 std::string_view selectedProtocol(
185 std::bit_cast<const char*>(alpn), alpnlen);
186 BMCWEB_LOG_DEBUG << "ALPN selected protocol \""
187 << selectedProtocol << "\" len: " << alpnlen;
188 if (selectedProtocol == "h2")
189 {
190 auto http2 =
191 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
192 std::move(adaptor), handler, getCachedDateStr);
193 http2->start();
194 return;
195 }
196 }
197 }
198
199 doReadHeaders();
200 }
201
Ed Tanous1abe55e2018-09-05 08:30:59 -0700202 void handle()
203 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700204 std::error_code reqEc;
205 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
206 if (reqEc)
207 {
208 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
Gunnar Mills262f1152022-12-20 15:18:47 -0600209 res.result(boost::beast::http::status::bad_request);
210 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700211 return;
212 }
Ed Tanous596b2032021-09-13 10:32:22 -0700213 thisReq.session = userSession;
214
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000215 // Fetch the client IP address
216 readClientIp();
217
Ed Tanous1abe55e2018-09-05 08:30:59 -0700218 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700219 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700220 {
Ed Tanous596b2032021-09-13 10:32:22 -0700221 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700222 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700223 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800224 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700225 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700226 }
227 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700228
Ed Tanouse278c182019-03-13 16:23:37 -0700229 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700230 << " " << this << " HTTP/" << thisReq.version() / 10
231 << "." << thisReq.version() % 10 << ' '
232 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800233 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700234
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700235 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700236
Ed Tanous596b2032021-09-13 10:32:22 -0700237 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700238 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200239
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700240 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700241 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800242 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700243 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700244 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800245 keepAlive = thisReq.keepAlive();
Nan Zhoua43ea822022-05-27 00:42:44 +0000246#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanousc51a58e2023-03-27 14:43:19 -0700247 if (!crow::authentication::isOnAllowlist(req->url().path(),
Ed Tanous39662a32023-02-06 15:09:46 -0800248 req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700249 thisReq.session == nullptr)
250 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800251 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700252 forward_unauthorized::sendUnauthorized(
Ed Tanous39662a32023-02-06 15:09:46 -0800253 req->url().encoded_path(),
254 req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700255 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800256 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700257 return;
258 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000259#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800260 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
261 BMCWEB_LOG_DEBUG << "Setting completion handler";
262 asyncResp->res.setCompleteRequestHandler(
263 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700264 self->completeRequest(thisRes);
265 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700266 bool isSse =
267 isContentTypeAllowed(req->getHeaderValue("Accept"),
268 http_helpers::ContentType::EventStream, false);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530269 if ((thisReq.isUpgrade() &&
270 boost::iequals(
271 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
272 "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700273 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700274 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530275 asyncResp->res.setCompleteRequestHandler(
276 [self(shared_from_this())](crow::Response& thisRes) {
277 if (thisRes.result() != boost::beast::http::status::ok)
278 {
279 // When any error occurs before handle upgradation,
280 // the result in response will be set to respective
281 // error. By default the Result will be OK (200),
282 // which implies successful handle upgrade. Response
283 // needs to be sent over this connection only on
284 // failure.
285 self->completeRequest(thisRes);
286 return;
287 }
288 });
289 handler->handleUpgrade(thisReq, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700290 return;
291 }
Ed Tanous291d7092022-04-13 12:34:57 -0700292 std::string_view expected =
293 req->getHeaderValue(boost::beast::http::field::if_none_match);
294 if (!expected.empty())
295 {
296 res.setExpectedHash(expected);
297 }
Ed Tanous596b2032021-09-13 10:32:22 -0700298 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700299 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700300
Ed Tanouse278c182019-03-13 16:23:37 -0700301 bool isAlive()
302 {
Ed Tanouse278c182019-03-13 16:23:37 -0700303 if constexpr (std::is_same_v<Adaptor,
304 boost::beast::ssl_stream<
305 boost::asio::ip::tcp::socket>>)
306 {
307 return adaptor.next_layer().is_open();
308 }
309 else
310 {
311 return adaptor.is_open();
312 }
313 }
314 void close()
315 {
Ed Tanouse278c182019-03-13 16:23:37 -0700316 if constexpr (std::is_same_v<Adaptor,
317 boost::beast::ssl_stream<
318 boost::asio::ip::tcp::socket>>)
319 {
320 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100321 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200322 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700323 BMCWEB_LOG_DEBUG
324 << this
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100325 << " Removing TLS session: " << mtlsSession->uniqueId;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700326 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100327 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200328 }
Ed Tanouse278c182019-03-13 16:23:37 -0700329 }
330 else
331 {
332 adaptor.close();
333 }
334 }
335
Nan Zhou72374eb2022-01-27 17:06:51 -0800336 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700337 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700338 if (!req)
339 {
340 return;
341 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800342 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800343 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800344
Ed Tanoused5f8952023-06-22 14:06:22 -0700345 completeResponseFields(*req, res);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700346
Ed Tanouse278c182019-03-13 16:23:37 -0700347 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700348 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700349 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700350 return;
351 }
Ed Tanous291d7092022-04-13 12:34:57 -0700352
Nan Zhou72374eb2022-01-27 17:06:51 -0800353 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000354
355 // delete lambda with self shared_ptr
356 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700357 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358 }
359
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500360 void readClientIp()
361 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700362 boost::asio::ip::address ip;
363 boost::system::error_code ec = getClientIp(ip);
364 if (ec)
365 {
366 return;
367 }
368 req->ipAddress = ip;
369 }
370
371 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
372 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500373 boost::system::error_code ec;
374 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
375 boost::asio::ip::tcp::endpoint endpoint =
376 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
377
378 if (ec)
379 {
380 // If remote endpoint fails keep going. "ClientOriginIPAddress"
381 // will be empty.
382 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
383 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700384 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500385 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700386 ip = endpoint.address();
387 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500388 }
389
Ed Tanous1abe55e2018-09-05 08:30:59 -0700390 private:
391 void doReadHeaders()
392 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700393 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
394
395 // Clean up any previous Connection.
396 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800397 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000398 [this,
399 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000400 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700401 BMCWEB_LOG_DEBUG << this << " async_read_header "
402 << bytesTransferred << " Bytes";
403 bool errorWhileReading = false;
404 if (ec)
405 {
406 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600407 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700408 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700409 BMCWEB_LOG_WARNING
410 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700411 }
412 else
413 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700414 BMCWEB_LOG_ERROR
415 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700416 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700417 }
418 else
419 {
420 // if the adaptor isn't open anymore, and wasn't handed to a
421 // websocket, treat as an error
422 if (!isAlive() &&
423 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700424 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700425 errorWhileReading = true;
426 }
427 }
428
429 cancelDeadlineTimer();
430
431 if (errorWhileReading)
432 {
433 close();
434 BMCWEB_LOG_DEBUG << this << " from read(1)";
435 return;
436 }
437
438 readClientIp();
439
440 boost::asio::ip::address ip;
441 if (getClientIp(ip))
442 {
443 BMCWEB_LOG_DEBUG << "Unable to get client IP";
444 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700445#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
446 boost::beast::http::verb method = parser->get().method();
447 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100448 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700449
450 bool loggedIn = userSession != nullptr;
451 if (!loggedIn)
452 {
453 const boost::optional<uint64_t> contentLength =
454 parser->content_length();
455 if (contentLength && *contentLength > loggedOutPostBodyLimit)
456 {
457 BMCWEB_LOG_DEBUG << "Content length greater than limit "
458 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700459 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700460 return;
461 }
462
Ed Tanous002d39b2022-05-31 08:59:27 -0700463 BMCWEB_LOG_DEBUG << "Starting quick deadline";
464 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000465#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800466
Ed Tanous7d243eb2023-01-23 15:57:41 -0800467 if (parser->is_done())
468 {
469 handle();
470 return;
471 }
472
Ed Tanous002d39b2022-05-31 08:59:27 -0700473 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700474 });
475 }
476
477 void doRead()
478 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700479 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800480 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800481 boost::beast::http::async_read_some(
482 adaptor, buffer, *parser,
483 [this,
484 self(shared_from_this())](const boost::system::error_code& ec,
485 std::size_t bytesTransferred) {
486 BMCWEB_LOG_DEBUG << this << " async_read_some " << bytesTransferred
Ed Tanous002d39b2022-05-31 08:59:27 -0700487 << " Bytes";
Ed Tanous7d243eb2023-01-23 15:57:41 -0800488
Ed Tanous002d39b2022-05-31 08:59:27 -0700489 if (ec)
490 {
491 BMCWEB_LOG_ERROR << this
492 << " Error while reading: " << ec.message();
493 close();
494 BMCWEB_LOG_DEBUG << this << " from read(1)";
495 return;
496 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800497
498 // If the user is logged in, allow them to send files incrementally
499 // one piece at a time. If authentication is disabled then there is
500 // no user session hence always allow to send one piece at a time.
501 if (userSession != nullptr)
502 {
503 cancelDeadlineTimer();
504 }
505 if (!parser->is_done())
506 {
507 doRead();
508 return;
509 }
510
511 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700512 handle();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800513 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700514 }
515
Nan Zhou72374eb2022-01-27 17:06:51 -0800516 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700517 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100518 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800519 thisRes.preparePayload();
520 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800521 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700522 boost::beast::http::async_write(adaptor, *serializer,
523 [this, self(shared_from_this())](
524 const boost::system::error_code& ec,
525 std::size_t bytesTransferred) {
526 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
527 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700528
Ed Tanous002d39b2022-05-31 08:59:27 -0700529 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700530
Ed Tanous002d39b2022-05-31 08:59:27 -0700531 if (ec)
532 {
533 BMCWEB_LOG_DEBUG << this << " from write(2)";
534 return;
535 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800536 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700537 {
538 close();
539 BMCWEB_LOG_DEBUG << this << " from write(1)";
540 return;
541 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700542
Ed Tanous002d39b2022-05-31 08:59:27 -0700543 serializer.reset();
544 BMCWEB_LOG_DEBUG << this << " Clearing response";
545 res.clear();
546 parser.emplace(std::piecewise_construct, std::make_tuple());
547 parser->body_limit(httpReqBodyLimit); // reset body limit for
548 // newly created parser
549 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700550
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100551 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700552
Ed Tanous002d39b2022-05-31 08:59:27 -0700553 // Destroy the Request via the std::optional
554 req.reset();
555 doReadHeaders();
556 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700557 }
558
Ed Tanous1abe55e2018-09-05 08:30:59 -0700559 void cancelDeadlineTimer()
560 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800561 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700562 }
563
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800564 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700565 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800566 // Timer is already started so no further action is required.
567 if (timerStarted)
568 {
569 return;
570 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700571
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800572 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800573
574 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
575 timer.expires_after(timeout);
Ed Tanous81c4e332023-05-18 10:30:34 -0700576 timer.async_wait([weakSelf](const boost::system::error_code& ec) {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800577 // Note, we are ignoring other types of errors here; If the timer
578 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800579 std::shared_ptr<Connection<Adaptor, Handler>> self =
580 weakSelf.lock();
581 if (!self)
582 {
583 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
584 return;
585 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800586
587 self->timerStarted = false;
588
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800589 if (ec == boost::asio::error::operation_aborted)
590 {
591 // Canceled wait means the path succeeeded.
592 return;
593 }
594 if (ec)
595 {
596 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
597 }
598
599 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
600
601 self->close();
602 });
603
Ed Tanous7d243eb2023-01-23 15:57:41 -0800604 timerStarted = true;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800605 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700606 }
607
Ed Tanous1abe55e2018-09-05 08:30:59 -0700608 Adaptor adaptor;
609 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800610 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700611 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800612 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700613 boost::beast::http::request_parser<boost::beast::http::string_body>>
614 parser;
615
Ed Tanous3112a142018-11-29 15:45:10 -0800616 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700617
Ed Tanousa24526d2018-12-10 15:17:59 -0800618 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700619 boost::beast::http::string_body>>
620 serializer;
621
Ed Tanousa24526d2018-12-10 15:17:59 -0800622 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700623 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700624
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700625 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100626 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700627
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800628 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700629
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800630 bool keepAlive = true;
631
Ed Tanous7d243eb2023-01-23 15:57:41 -0800632 bool timerStarted = false;
633
Ed Tanous1abe55e2018-09-05 08:30:59 -0700634 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000635
636 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700637 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800638
639 using std::enable_shared_from_this<
640 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800641};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642} // namespace crow