blob: 83645eeeb78b5fcf6dd6c83767d0c02abc4ab11e [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 Tanousb2896142024-01-31 15:25:47 -08008#include "http_body.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07009#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070010#include "http_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070011#include "logging.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080012#include "mutual_tls.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080013#include "ssl_key_handler.hpp"
Ed Tanous18f8f602023-07-18 10:07:23 -070014#include "str_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070015#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070016
Ed Tanous8f626352018-12-19 14:51:54 -080017#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080018#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070019#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080020#include <boost/asio/steady_timer.hpp>
Ed Tanous4fa45df2023-09-01 14:20:50 -070021#include <boost/beast/_experimental/test/stream.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080022#include <boost/beast/core/flat_static_buffer.hpp>
Myung Baea4326fe2023-01-10 14:29:24 -060023#include <boost/beast/http/error.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070024#include <boost/beast/http/parser.hpp>
25#include <boost/beast/http/read.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070026#include <boost/beast/http/write.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053027#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050028#include <boost/beast/websocket.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 Tanouscf9e4172022-12-21 09:30:16 -080037// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080038static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070039
Ed Tanous0260d9d2021-02-07 19:31:07 +000040// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Patrick Williams89492a12023-05-10 07:51:34 -050041constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL *
42 bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070043
James Feist3909dc82020-04-03 10:58:55 -070044constexpr uint64_t loggedOutPostBodyLimit = 4096;
45
46constexpr uint32_t httpHeaderLimit = 8192;
47
Ed Tanous4fa45df2023-09-01 14:20:50 -070048template <typename>
49struct IsTls : std::false_type
50{};
51
52template <typename T>
53struct IsTls<boost::beast::ssl_stream<T>> : std::true_type
54{};
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 Tanous62598e32023-07-17 17:06:25 -070080 BMCWEB_LOG_DEBUG("{} Connection open, total {}", logPtr(this),
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--;
Ed Tanous62598e32023-07-17 17:06:25 -070090 BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
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 {
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200106 boost::asio::ip::address ipAddress;
107 if (getClientIp(ipAddress))
Ed Tanouse01d0c32023-06-30 13:21:32 -0700108 {
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200109 return true;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700110 }
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200111
112 mtlsSession = verifyMtlsUser(ipAddress, ctx);
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100113 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800114 {
Ed Tanous62598e32023-07-17 17:06:25 -0700115 BMCWEB_LOG_DEBUG("{} Generating TLS session: {}", logPtr(this),
116 mtlsSession->uniqueId);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800117 }
118 }
119 return true;
120 }
121
Ed Tanous40aa0582021-07-14 13:24:40 -0700122 void prepareMutualTls()
123 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700124 if constexpr (IsTls<Adaptor>::value)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100125 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700126 std::error_code error;
127 std::filesystem::path caPath(ensuressl::trustStorePath);
128 auto caAvailable = !std::filesystem::is_empty(caPath, error);
129 caAvailable = caAvailable && !error;
130 if (caAvailable && persistent_data::SessionStore::getInstance()
131 .getAuthMethodsConfig()
132 .tls)
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700133 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700134 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
135 std::string id = "bmcweb";
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100136
Ed Tanous4fa45df2023-09-01 14:20:50 -0700137 const char* cStr = id.c_str();
138 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
139 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
140 int ret = SSL_set_session_id_context(
141 adaptor.native_handle(), idC,
142 static_cast<unsigned int>(id.length()));
143 if (ret == 0)
144 {
145 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
146 }
147 }
148
149 adaptor.set_verify_callback(
150 std::bind_front(&self_type::tlsVerifyCallback, this));
151 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700152 }
153
Ed Tanousceac6f72018-12-02 11:58:47 -0800154 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700155 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800156 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700157 }
158
Ed Tanous1abe55e2018-09-05 08:30:59 -0700159 void start()
160 {
Gunnar Mills4f63be02023-10-25 09:14:07 -0500161 if (connectionCount >= 200)
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800162 {
Ed Tanous62598e32023-07-17 17:06:25 -0700163 BMCWEB_LOG_CRITICAL("{}Max connection count exceeded.",
164 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800165 return;
166 }
167
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800168 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500169
Ed Tanousceac6f72018-12-02 11:58:47 -0800170 // TODO(ed) Abstract this to a more clever class with the idea of an
171 // asynchronous "start"
Ed Tanous4fa45df2023-09-01 14:20:50 -0700172 if constexpr (IsTls<Adaptor>::value)
Ed Tanousceac6f72018-12-02 11:58:47 -0800173 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000174 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
175 [this, self(shared_from_this())](
176 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700177 if (ec)
178 {
179 return;
180 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800181 afterSslHandshake();
Ed Tanous002d39b2022-05-31 08:59:27 -0700182 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800183 }
184 else
185 {
186 doReadHeaders();
187 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700188 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700189
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800190 void afterSslHandshake()
191 {
192 // If http2 is enabled, negotiate the protocol
193 if constexpr (bmcwebEnableHTTP2)
194 {
195 const unsigned char* alpn = nullptr;
196 unsigned int alpnlen = 0;
197 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
198 if (alpn != nullptr)
199 {
200 std::string_view selectedProtocol(
201 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700202 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
203 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800204 if (selectedProtocol == "h2")
205 {
206 auto http2 =
207 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
208 std::move(adaptor), handler, getCachedDateStr);
209 http2->start();
210 return;
211 }
212 }
213 }
214
215 doReadHeaders();
216 }
217
Ed Tanous1abe55e2018-09-05 08:30:59 -0700218 void handle()
219 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700220 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700221 if (!parser)
222 {
223 return;
224 }
Ed Tanous52e31622024-01-23 16:31:11 -0800225 req = crow::Request(parser->release(), reqEc);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700226 if (reqEc)
227 {
Ed Tanous62598e32023-07-17 17:06:25 -0700228 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600229 res.result(boost::beast::http::status::bad_request);
230 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700231 return;
232 }
Ed Tanous52e31622024-01-23 16:31:11 -0800233 req.session = userSession;
Ed Tanous596b2032021-09-13 10:32:22 -0700234
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000235 // Fetch the client IP address
236 readClientIp();
237
Ed Tanous1abe55e2018-09-05 08:30:59 -0700238 // Check for HTTP version 1.1.
Ed Tanous52e31622024-01-23 16:31:11 -0800239 if (req.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700240 {
Ed Tanous52e31622024-01-23 16:31:11 -0800241 if (req.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700242 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700243 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800244 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700245 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700246 }
247 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700248
Ed Tanous62598e32023-07-17 17:06:25 -0700249 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
Ed Tanous52e31622024-01-23 16:31:11 -0800250 req.version() / 10, req.version() % 10,
251 req.methodString(), req.target(),
252 req.ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700253
Ed Tanous52e31622024-01-23 16:31:11 -0800254 req.ioService = static_cast<decltype(req.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700255 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200256
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700257 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700258 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800259 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700260 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700261 }
Ed Tanous52e31622024-01-23 16:31:11 -0800262 keepAlive = req.keepAlive();
Ed Tanous4fa45df2023-09-01 14:20:50 -0700263 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700264 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700265#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous52e31622024-01-23 16:31:11 -0800266 if (!crow::authentication::isOnAllowlist(req.url().path(),
267 req.method()) &&
268 req.session == nullptr)
Ed Tanous4fa45df2023-09-01 14:20:50 -0700269 {
270 BMCWEB_LOG_WARNING("Authentication failed");
271 forward_unauthorized::sendUnauthorized(
Ed Tanous52e31622024-01-23 16:31:11 -0800272 req.url().encoded_path(),
273 req.getHeaderValue("X-Requested-With"),
274 req.getHeaderValue("Accept"), res);
Ed Tanous4fa45df2023-09-01 14:20:50 -0700275 completeRequest(res);
276 return;
277 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000278#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous4fa45df2023-09-01 14:20:50 -0700279 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800280 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700281 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800282 asyncResp->res.setCompleteRequestHandler(
283 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700284 self->completeRequest(thisRes);
285 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700286 bool isSse =
Ed Tanous52e31622024-01-23 16:31:11 -0800287 isContentTypeAllowed(req.getHeaderValue("Accept"),
Ed Tanous6fde95f2023-06-01 07:33:34 -0700288 http_helpers::ContentType::EventStream, false);
Ed Tanous18f8f602023-07-18 10:07:23 -0700289 std::string_view upgradeType(
Ed Tanous52e31622024-01-23 16:31:11 -0800290 req.getHeaderValue(boost::beast::http::field::upgrade));
291 if ((req.isUpgrade() &&
Ed Tanous18f8f602023-07-18 10:07:23 -0700292 bmcweb::asciiIEquals(upgradeType, "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700293 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700294 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530295 asyncResp->res.setCompleteRequestHandler(
296 [self(shared_from_this())](crow::Response& thisRes) {
297 if (thisRes.result() != boost::beast::http::status::ok)
298 {
299 // When any error occurs before handle upgradation,
300 // the result in response will be set to respective
301 // error. By default the Result will be OK (200),
302 // which implies successful handle upgrade. Response
303 // needs to be sent over this connection only on
304 // failure.
305 self->completeRequest(thisRes);
306 return;
307 }
308 });
Ed Tanous52e31622024-01-23 16:31:11 -0800309 handler->handleUpgrade(req, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700310 return;
311 }
Ed Tanous291d7092022-04-13 12:34:57 -0700312 std::string_view expected =
Ed Tanous52e31622024-01-23 16:31:11 -0800313 req.getHeaderValue(boost::beast::http::field::if_none_match);
Ed Tanous291d7092022-04-13 12:34:57 -0700314 if (!expected.empty())
315 {
316 res.setExpectedHash(expected);
317 }
Ed Tanous52e31622024-01-23 16:31:11 -0800318 handler->handle(req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700319 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700320
Ed Tanouse278c182019-03-13 16:23:37 -0700321 void close()
322 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700323 if constexpr (IsTls<Adaptor>::value)
Ed Tanouse278c182019-03-13 16:23:37 -0700324 {
325 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100326 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200327 {
Ed Tanous62598e32023-07-17 17:06:25 -0700328 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
329 mtlsSession->uniqueId);
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700330 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100331 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200332 }
Ed Tanouse278c182019-03-13 16:23:37 -0700333 }
334 else
335 {
336 adaptor.close();
337 }
338 }
339
Nan Zhou72374eb2022-01-27 17:06:51 -0800340 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700341 {
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 Tanous52e31622024-01-23 16:31:11 -0800345 completeResponseFields(req, res);
Ed Tanous998e0cb2023-09-06 13:57:30 -0700346 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
Ed Tanous291d7092022-04-13 12:34:57 -0700347
Ed Tanous52e31622024-01-23 16:31:11 -0800348 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000349
350 // delete lambda with self shared_ptr
351 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700352 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700353 }
354
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500355 void readClientIp()
356 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700357 boost::asio::ip::address ip;
358 boost::system::error_code ec = getClientIp(ip);
359 if (ec)
360 {
361 return;
362 }
Ed Tanous52e31622024-01-23 16:31:11 -0800363 req.ipAddress = ip;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700364 }
365
366 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
367 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500368 boost::system::error_code ec;
Ed Tanous62598e32023-07-17 17:06:25 -0700369 BMCWEB_LOG_DEBUG("Fetch the client IP address");
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500370
Ed Tanous4fa45df2023-09-01 14:20:50 -0700371 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500372 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700373 boost::asio::ip::tcp::endpoint endpoint =
374 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
375
376 if (ec)
377 {
378 // If remote endpoint fails keep going. "ClientOriginIPAddress"
379 // will be empty.
380 BMCWEB_LOG_ERROR(
381 "Failed to get the client's IP Address. ec : {}", ec);
382 return ec;
383 }
384 ip = endpoint.address();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500385 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700386 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500387 }
388
Ed Tanous1abe55e2018-09-05 08:30:59 -0700389 private:
390 void doReadHeaders()
391 {
Ed Tanous62598e32023-07-17 17:06:25 -0700392 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700393 if (!parser)
394 {
395 return;
396 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700397 // Clean up any previous Connection.
398 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800399 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000400 [this,
401 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000402 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700403 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
404 bytesTransferred);
Ed Tanous52e31622024-01-23 16:31:11 -0800405
Ed Tanous002d39b2022-05-31 08:59:27 -0700406 if (ec)
407 {
Ed Tanous52e31622024-01-23 16:31:11 -0800408 cancelDeadlineTimer();
409
Myung Baea4326fe2023-01-10 14:29:24 -0600410 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700411 {
Ed Tanous62598e32023-07-17 17:06:25 -0700412 BMCWEB_LOG_WARNING("{} Error while reading: {}",
413 logPtr(this), ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700414 }
415 else
416 {
Ed Tanous62598e32023-07-17 17:06:25 -0700417 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
418 ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700419 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700420 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700421 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700422 return;
423 }
424
425 readClientIp();
426
427 boost::asio::ip::address ip;
428 if (getClientIp(ip))
429 {
Ed Tanous62598e32023-07-17 17:06:25 -0700430 BMCWEB_LOG_DEBUG("Unable to get client IP");
Ed Tanous002d39b2022-05-31 08:59:27 -0700431 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700432 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous002d39b2022-05-31 08:59:27 -0700433 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700434#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
435 boost::beast::http::verb method = parser->get().method();
436 userSession = crow::authentication::authenticate(
437 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700438
Ed Tanous4fa45df2023-09-01 14:20:50 -0700439 bool loggedIn = userSession != nullptr;
440 if (!loggedIn)
441 {
442 const boost::optional<uint64_t> contentLength =
443 parser->content_length();
444 if (contentLength &&
445 *contentLength > loggedOutPostBodyLimit)
446 {
447 BMCWEB_LOG_DEBUG("Content length greater than limit {}",
448 *contentLength);
449 close();
450 return;
451 }
452
453 BMCWEB_LOG_DEBUG("Starting quick deadline");
454 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000455#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous4fa45df2023-09-01 14:20:50 -0700456 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800457
Ed Tanous7d243eb2023-01-23 15:57:41 -0800458 if (parser->is_done())
459 {
460 handle();
461 return;
462 }
463
Ed Tanous002d39b2022-05-31 08:59:27 -0700464 doRead();
Patrick Williams5a39f772023-10-20 11:20:21 -0500465 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700466 }
467
468 void doRead()
469 {
Ed Tanous62598e32023-07-17 17:06:25 -0700470 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700471 if (!parser)
472 {
473 return;
474 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800475 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800476 boost::beast::http::async_read_some(
477 adaptor, buffer, *parser,
478 [this,
479 self(shared_from_this())](const boost::system::error_code& ec,
480 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700481 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
482 bytesTransferred);
Ed Tanous7d243eb2023-01-23 15:57:41 -0800483
Ed Tanous002d39b2022-05-31 08:59:27 -0700484 if (ec)
485 {
Ed Tanous62598e32023-07-17 17:06:25 -0700486 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
487 ec.message());
Ed Tanous002d39b2022-05-31 08:59:27 -0700488 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700489 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700490 return;
491 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800492
493 // If the user is logged in, allow them to send files incrementally
494 // one piece at a time. If authentication is disabled then there is
495 // no user session hence always allow to send one piece at a time.
496 if (userSession != nullptr)
497 {
498 cancelDeadlineTimer();
499 }
500 if (!parser->is_done())
501 {
502 doRead();
503 return;
504 }
505
506 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700507 handle();
Patrick Williams5a39f772023-10-20 11:20:21 -0500508 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700509 }
510
Ed Tanous27b0cf92023-08-07 12:02:40 -0700511 void afterDoWrite(const std::shared_ptr<self_type>& /*self*/,
512 const boost::system::error_code& ec,
513 std::size_t bytesTransferred)
514 {
515 BMCWEB_LOG_DEBUG("{} async_write {} bytes", logPtr(this),
516 bytesTransferred);
517
518 cancelDeadlineTimer();
519
520 if (ec)
521 {
522 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
523 return;
524 }
525 if (!keepAlive)
526 {
527 close();
528 BMCWEB_LOG_DEBUG("{} from write(1)", logPtr(this));
529 return;
530 }
531
532 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
533 res.clear();
534 parser.emplace(std::piecewise_construct, std::make_tuple());
535 parser->body_limit(httpReqBodyLimit); // reset body limit for
536 // newly created parser
537 buffer.consume(buffer.size());
538
539 userSession = nullptr;
540
541 // Destroy the Request via the std::optional
Ed Tanous52e31622024-01-23 16:31:11 -0800542 req.clear();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700543 doReadHeaders();
544 }
545
Ed Tanous52e31622024-01-23 16:31:11 -0800546 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700547 {
Ed Tanous62598e32023-07-17 17:06:25 -0700548 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Ed Tanous52e31622024-01-23 16:31:11 -0800549 res.preparePayload();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700550
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800551 startDeadline();
Ed Tanous52e31622024-01-23 16:31:11 -0800552 serializer.emplace(res.response);
553 boost::beast::http::async_write(
554 adaptor, *serializer,
555 std::bind_front(&self_type::afterDoWrite, this,
556 shared_from_this()));
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 {
Ed Tanous62598e32023-07-17 17:06:25 -0700583 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
584 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800585 return;
586 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800587
588 self->timerStarted = false;
589
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800590 if (ec == boost::asio::error::operation_aborted)
591 {
Ed Tanous8ece0e42024-01-02 13:16:50 -0800592 // Canceled wait means the path succeeded.
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800593 return;
594 }
595 if (ec)
596 {
Ed Tanous62598e32023-07-17 17:06:25 -0700597 BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()),
598 ec);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800599 }
600
Ed Tanous62598e32023-07-17 17:06:25 -0700601 BMCWEB_LOG_WARNING("{}Connection timed out, closing",
602 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800603
604 self->close();
605 });
606
Ed Tanous7d243eb2023-01-23 15:57:41 -0800607 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700608 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700609 }
610
Ed Tanous1abe55e2018-09-05 08:30:59 -0700611 Adaptor adaptor;
612 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800613 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700614 // re-created on Connection reset
Ed Tanousb2896142024-01-31 15:25:47 -0800615 std::optional<boost::beast::http::request_parser<bmcweb::HttpBody>> parser;
616 std::optional<boost::beast::http::response_serializer<bmcweb::HttpBody>>
Ed Tanous52e31622024-01-23 16:31:11 -0800617 serializer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618
Ed Tanous3112a142018-11-29 15:45:10 -0800619 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700620
Ed Tanous52e31622024-01-23 16:31:11 -0800621 crow::Request req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700622 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700623
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700624 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100625 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700626
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800627 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700628
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800629 bool keepAlive = true;
630
Ed Tanous7d243eb2023-01-23 15:57:41 -0800631 bool timerStarted = false;
632
Ed Tanous1abe55e2018-09-05 08:30:59 -0700633 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000634
635 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700636 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800637
638 using std::enable_shared_from_this<
639 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800640};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641} // namespace crow