blob: 6ec8831f527a8e8ff63291d4d00be17f1f3dc0a6 [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 Tanous4d698612024-02-06 14:57:24 -080022#include <boost/beast/core/buffers_generator.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080023#include <boost/beast/core/flat_static_buffer.hpp>
Myung Baea4326fe2023-01-10 14:29:24 -060024#include <boost/beast/http/error.hpp>
Ed Tanous4d698612024-02-06 14:57:24 -080025#include <boost/beast/http/message_generator.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070026#include <boost/beast/http/parser.hpp>
27#include <boost/beast/http/read.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070028#include <boost/beast/http/write.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053029#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050030#include <boost/beast/websocket.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050031
Manojkiran Eda44250442020-06-16 12:51:38 +053032#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050033#include <chrono>
34#include <vector>
35
Ed Tanous1abe55e2018-09-05 08:30:59 -070036namespace crow
37{
Ed Tanous257f5792018-03-17 14:40:09 -070038
Ed Tanouscf9e4172022-12-21 09:30:16 -080039// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080040static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070041
Ed Tanous0260d9d2021-02-07 19:31:07 +000042// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Patrick Williams89492a12023-05-10 07:51:34 -050043constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL *
44 bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070045
James Feist3909dc82020-04-03 10:58:55 -070046constexpr uint64_t loggedOutPostBodyLimit = 4096;
47
48constexpr uint32_t httpHeaderLimit = 8192;
49
Ed Tanous4fa45df2023-09-01 14:20:50 -070050template <typename>
51struct IsTls : std::false_type
52{};
53
54template <typename T>
55struct IsTls<boost::beast::ssl_stream<T>> : std::true_type
56{};
57
Ed Tanous52cc1122020-07-18 13:51:21 -070058template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050059class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070060 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070061{
Ed Tanous7c8e0642022-02-21 12:11:14 -080062 using self_type = Connection<Adaptor, Handler>;
63
Ed Tanous1abe55e2018-09-05 08:30:59 -070064 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080065 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000066 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080067 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080068 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080069 handler(handlerIn), timer(std::move(timerIn)),
70 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070071 {
72 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070073 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070074 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020075
76#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070077 prepareMutualTls();
78#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
79
Ed Tanous40aa0582021-07-14 13:24:40 -070080 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080081
Ed Tanous62598e32023-07-17 17:06:25 -070082 BMCWEB_LOG_DEBUG("{} Connection open, total {}", logPtr(this),
83 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070084 }
85
86 ~Connection()
87 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070088 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070089 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080090
Ed Tanous40aa0582021-07-14 13:24:40 -070091 connectionCount--;
Ed Tanous62598e32023-07-17 17:06:25 -070092 BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
93 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070094 }
95
Ed Tanousecd6a3a2022-01-07 09:18:40 -080096 Connection(const Connection&) = delete;
97 Connection(Connection&&) = delete;
98 Connection& operator=(const Connection&) = delete;
99 Connection& operator=(Connection&&) = delete;
100
Ed Tanous7c8e0642022-02-21 12:11:14 -0800101 bool tlsVerifyCallback(bool preverified,
102 boost::asio::ssl::verify_context& ctx)
103 {
104 // We always return true to allow full auth flow for resources that
105 // don't require auth
106 if (preverified)
107 {
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200108 boost::asio::ip::address ipAddress;
109 if (getClientIp(ipAddress))
Ed Tanouse01d0c32023-06-30 13:21:32 -0700110 {
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200111 return true;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700112 }
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200113
114 mtlsSession = verifyMtlsUser(ipAddress, ctx);
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100115 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800116 {
Ed Tanous62598e32023-07-17 17:06:25 -0700117 BMCWEB_LOG_DEBUG("{} Generating TLS session: {}", logPtr(this),
118 mtlsSession->uniqueId);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800119 }
120 }
121 return true;
122 }
123
Ed Tanous40aa0582021-07-14 13:24:40 -0700124 void prepareMutualTls()
125 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700126 if constexpr (IsTls<Adaptor>::value)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100127 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700128 std::error_code error;
129 std::filesystem::path caPath(ensuressl::trustStorePath);
130 auto caAvailable = !std::filesystem::is_empty(caPath, error);
131 caAvailable = caAvailable && !error;
132 if (caAvailable && persistent_data::SessionStore::getInstance()
133 .getAuthMethodsConfig()
134 .tls)
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700135 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700136 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
137 std::string id = "bmcweb";
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100138
Ed Tanous4fa45df2023-09-01 14:20:50 -0700139 const char* cStr = id.c_str();
140 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
141 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
142 int ret = SSL_set_session_id_context(
143 adaptor.native_handle(), idC,
144 static_cast<unsigned int>(id.length()));
145 if (ret == 0)
146 {
147 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
148 }
149 }
150
151 adaptor.set_verify_callback(
152 std::bind_front(&self_type::tlsVerifyCallback, this));
153 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700154 }
155
Ed Tanousceac6f72018-12-02 11:58:47 -0800156 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700157 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800158 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700159 }
160
Ed Tanous1abe55e2018-09-05 08:30:59 -0700161 void start()
162 {
Gunnar Mills4f63be02023-10-25 09:14:07 -0500163 if (connectionCount >= 200)
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800164 {
Ed Tanous62598e32023-07-17 17:06:25 -0700165 BMCWEB_LOG_CRITICAL("{}Max connection count exceeded.",
166 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800167 return;
168 }
169
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800170 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500171
Ed Tanousceac6f72018-12-02 11:58:47 -0800172 // TODO(ed) Abstract this to a more clever class with the idea of an
173 // asynchronous "start"
Ed Tanous4fa45df2023-09-01 14:20:50 -0700174 if constexpr (IsTls<Adaptor>::value)
Ed Tanousceac6f72018-12-02 11:58:47 -0800175 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000176 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
177 [this, self(shared_from_this())](
178 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700179 if (ec)
180 {
181 return;
182 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800183 afterSslHandshake();
Ed Tanous002d39b2022-05-31 08:59:27 -0700184 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800185 }
186 else
187 {
188 doReadHeaders();
189 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700190 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700191
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800192 void afterSslHandshake()
193 {
194 // If http2 is enabled, negotiate the protocol
195 if constexpr (bmcwebEnableHTTP2)
196 {
197 const unsigned char* alpn = nullptr;
198 unsigned int alpnlen = 0;
199 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
200 if (alpn != nullptr)
201 {
202 std::string_view selectedProtocol(
203 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700204 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
205 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800206 if (selectedProtocol == "h2")
207 {
208 auto http2 =
209 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
210 std::move(adaptor), handler, getCachedDateStr);
211 http2->start();
212 return;
213 }
214 }
215 }
216
217 doReadHeaders();
218 }
219
Ed Tanous1abe55e2018-09-05 08:30:59 -0700220 void handle()
221 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700222 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700223 if (!parser)
224 {
225 return;
226 }
Ed Tanous52e31622024-01-23 16:31:11 -0800227 req = crow::Request(parser->release(), reqEc);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700228 if (reqEc)
229 {
Ed Tanous62598e32023-07-17 17:06:25 -0700230 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600231 res.result(boost::beast::http::status::bad_request);
232 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700233 return;
234 }
Ed Tanous52e31622024-01-23 16:31:11 -0800235 req.session = userSession;
Ed Tanous596b2032021-09-13 10:32:22 -0700236
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000237 // Fetch the client IP address
238 readClientIp();
239
Ed Tanous1abe55e2018-09-05 08:30:59 -0700240 // Check for HTTP version 1.1.
Ed Tanous52e31622024-01-23 16:31:11 -0800241 if (req.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700242 {
Ed Tanous52e31622024-01-23 16:31:11 -0800243 if (req.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700244 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700245 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800246 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700247 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700248 }
249 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700250
Ed Tanous62598e32023-07-17 17:06:25 -0700251 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
Ed Tanous52e31622024-01-23 16:31:11 -0800252 req.version() / 10, req.version() % 10,
253 req.methodString(), req.target(),
254 req.ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700255
Ed Tanous52e31622024-01-23 16:31:11 -0800256 req.ioService = static_cast<decltype(req.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700257 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200258
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700259 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700260 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800261 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700262 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700263 }
Ed Tanous52e31622024-01-23 16:31:11 -0800264 keepAlive = req.keepAlive();
Ed Tanous4fa45df2023-09-01 14:20:50 -0700265 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700266 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700267#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous52e31622024-01-23 16:31:11 -0800268 if (!crow::authentication::isOnAllowlist(req.url().path(),
269 req.method()) &&
270 req.session == nullptr)
Ed Tanous4fa45df2023-09-01 14:20:50 -0700271 {
272 BMCWEB_LOG_WARNING("Authentication failed");
273 forward_unauthorized::sendUnauthorized(
Ed Tanous52e31622024-01-23 16:31:11 -0800274 req.url().encoded_path(),
275 req.getHeaderValue("X-Requested-With"),
276 req.getHeaderValue("Accept"), res);
Ed Tanous4fa45df2023-09-01 14:20:50 -0700277 completeRequest(res);
278 return;
279 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000280#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous4fa45df2023-09-01 14:20:50 -0700281 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800282 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700283 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800284 asyncResp->res.setCompleteRequestHandler(
285 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700286 self->completeRequest(thisRes);
287 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700288 bool isSse =
Ed Tanous52e31622024-01-23 16:31:11 -0800289 isContentTypeAllowed(req.getHeaderValue("Accept"),
Ed Tanous6fde95f2023-06-01 07:33:34 -0700290 http_helpers::ContentType::EventStream, false);
Ed Tanous18f8f602023-07-18 10:07:23 -0700291 std::string_view upgradeType(
Ed Tanous52e31622024-01-23 16:31:11 -0800292 req.getHeaderValue(boost::beast::http::field::upgrade));
293 if ((req.isUpgrade() &&
Ed Tanous18f8f602023-07-18 10:07:23 -0700294 bmcweb::asciiIEquals(upgradeType, "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700295 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700296 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530297 asyncResp->res.setCompleteRequestHandler(
298 [self(shared_from_this())](crow::Response& thisRes) {
299 if (thisRes.result() != boost::beast::http::status::ok)
300 {
301 // When any error occurs before handle upgradation,
302 // the result in response will be set to respective
303 // error. By default the Result will be OK (200),
304 // which implies successful handle upgrade. Response
305 // needs to be sent over this connection only on
306 // failure.
307 self->completeRequest(thisRes);
308 return;
309 }
310 });
Ed Tanous52e31622024-01-23 16:31:11 -0800311 handler->handleUpgrade(req, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700312 return;
313 }
Ed Tanous291d7092022-04-13 12:34:57 -0700314 std::string_view expected =
Ed Tanous52e31622024-01-23 16:31:11 -0800315 req.getHeaderValue(boost::beast::http::field::if_none_match);
Ed Tanous291d7092022-04-13 12:34:57 -0700316 if (!expected.empty())
317 {
318 res.setExpectedHash(expected);
319 }
Ed Tanous52e31622024-01-23 16:31:11 -0800320 handler->handle(req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700321 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700322
Ed Tanouse278c182019-03-13 16:23:37 -0700323 void close()
324 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700325 if constexpr (IsTls<Adaptor>::value)
Ed Tanouse278c182019-03-13 16:23:37 -0700326 {
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 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800344 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800345 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800346
Ed Tanous52e31622024-01-23 16:31:11 -0800347 completeResponseFields(req, res);
Ed Tanous998e0cb2023-09-06 13:57:30 -0700348 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
Ed Tanous291d7092022-04-13 12:34:57 -0700349
Ed Tanous52e31622024-01-23 16:31:11 -0800350 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000351
352 // delete lambda with self shared_ptr
353 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700354 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700355 }
356
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500357 void readClientIp()
358 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700359 boost::asio::ip::address ip;
360 boost::system::error_code ec = getClientIp(ip);
361 if (ec)
362 {
363 return;
364 }
Ed Tanous52e31622024-01-23 16:31:11 -0800365 req.ipAddress = ip;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700366 }
367
368 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
369 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500370 boost::system::error_code ec;
Ed Tanous62598e32023-07-17 17:06:25 -0700371 BMCWEB_LOG_DEBUG("Fetch the client IP address");
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500372
Ed Tanous4fa45df2023-09-01 14:20:50 -0700373 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500374 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700375 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(
383 "Failed to get the client's IP Address. ec : {}", ec);
384 return ec;
385 }
386 ip = endpoint.address();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500387 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700388 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500389 }
390
Ed Tanous1abe55e2018-09-05 08:30:59 -0700391 private:
392 void doReadHeaders()
393 {
Ed Tanous62598e32023-07-17 17:06:25 -0700394 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700395 if (!parser)
396 {
397 return;
398 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700399 // Clean up any previous Connection.
400 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800401 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000402 [this,
403 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000404 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700405 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
406 bytesTransferred);
Ed Tanous52e31622024-01-23 16:31:11 -0800407
Ed Tanous002d39b2022-05-31 08:59:27 -0700408 if (ec)
409 {
Ed Tanous52e31622024-01-23 16:31:11 -0800410 cancelDeadlineTimer();
411
Myung Baea4326fe2023-01-10 14:29:24 -0600412 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700413 {
Ed Tanous62598e32023-07-17 17:06:25 -0700414 BMCWEB_LOG_WARNING("{} Error while reading: {}",
415 logPtr(this), ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700416 }
417 else
418 {
Ed Tanous62598e32023-07-17 17:06:25 -0700419 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
420 ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700421 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700422 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700423 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700424 return;
425 }
426
427 readClientIp();
428
429 boost::asio::ip::address ip;
430 if (getClientIp(ip))
431 {
Ed Tanous62598e32023-07-17 17:06:25 -0700432 BMCWEB_LOG_DEBUG("Unable to get client IP");
Ed Tanous002d39b2022-05-31 08:59:27 -0700433 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700434 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous002d39b2022-05-31 08:59:27 -0700435 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700436#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
437 boost::beast::http::verb method = parser->get().method();
438 userSession = crow::authentication::authenticate(
439 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700440
Ed Tanous4fa45df2023-09-01 14:20:50 -0700441 bool loggedIn = userSession != nullptr;
442 if (!loggedIn)
443 {
444 const boost::optional<uint64_t> contentLength =
445 parser->content_length();
446 if (contentLength &&
447 *contentLength > loggedOutPostBodyLimit)
448 {
449 BMCWEB_LOG_DEBUG("Content length greater than limit {}",
450 *contentLength);
451 close();
452 return;
453 }
454
455 BMCWEB_LOG_DEBUG("Starting quick deadline");
456 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000457#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous4fa45df2023-09-01 14:20:50 -0700458 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800459
Ed Tanous7d243eb2023-01-23 15:57:41 -0800460 if (parser->is_done())
461 {
462 handle();
463 return;
464 }
465
Ed Tanous002d39b2022-05-31 08:59:27 -0700466 doRead();
Patrick Williams5a39f772023-10-20 11:20:21 -0500467 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700468 }
469
470 void doRead()
471 {
Ed Tanous62598e32023-07-17 17:06:25 -0700472 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700473 if (!parser)
474 {
475 return;
476 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800477 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800478 boost::beast::http::async_read_some(
479 adaptor, buffer, *parser,
480 [this,
481 self(shared_from_this())](const boost::system::error_code& ec,
482 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700483 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
484 bytesTransferred);
Ed Tanous7d243eb2023-01-23 15:57:41 -0800485
Ed Tanous002d39b2022-05-31 08:59:27 -0700486 if (ec)
487 {
Ed Tanous62598e32023-07-17 17:06:25 -0700488 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
489 ec.message());
Ed Tanous002d39b2022-05-31 08:59:27 -0700490 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700491 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700492 return;
493 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800494
495 // If the user is logged in, allow them to send files incrementally
496 // one piece at a time. If authentication is disabled then there is
497 // no user session hence always allow to send one piece at a time.
498 if (userSession != nullptr)
499 {
500 cancelDeadlineTimer();
501 }
502 if (!parser->is_done())
503 {
504 doRead();
505 return;
506 }
507
508 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700509 handle();
Patrick Williams5a39f772023-10-20 11:20:21 -0500510 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700511 }
512
Ed Tanous27b0cf92023-08-07 12:02:40 -0700513 void afterDoWrite(const std::shared_ptr<self_type>& /*self*/,
514 const boost::system::error_code& ec,
515 std::size_t bytesTransferred)
516 {
517 BMCWEB_LOG_DEBUG("{} async_write {} bytes", logPtr(this),
518 bytesTransferred);
519
520 cancelDeadlineTimer();
521
522 if (ec)
523 {
524 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
525 return;
526 }
527 if (!keepAlive)
528 {
529 close();
530 BMCWEB_LOG_DEBUG("{} from write(1)", logPtr(this));
531 return;
532 }
533
534 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
535 res.clear();
536 parser.emplace(std::piecewise_construct, std::make_tuple());
537 parser->body_limit(httpReqBodyLimit); // reset body limit for
538 // newly created parser
539 buffer.consume(buffer.size());
540
541 userSession = nullptr;
542
543 // Destroy the Request via the std::optional
Ed Tanous52e31622024-01-23 16:31:11 -0800544 req.clear();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700545 doReadHeaders();
546 }
547
Ed Tanous52e31622024-01-23 16:31:11 -0800548 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700549 {
Ed Tanous62598e32023-07-17 17:06:25 -0700550 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Ed Tanous52e31622024-01-23 16:31:11 -0800551 res.preparePayload();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700552
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800553 startDeadline();
Ed Tanous4d698612024-02-06 14:57:24 -0800554 boost::beast::async_write(
555 adaptor,
556 boost::beast::http::message_generator(std::move(res.response)),
Ed Tanous52e31622024-01-23 16:31:11 -0800557 std::bind_front(&self_type::afterDoWrite, this,
558 shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700559 }
560
Ed Tanous1abe55e2018-09-05 08:30:59 -0700561 void cancelDeadlineTimer()
562 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800563 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700564 }
565
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800566 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800568 // Timer is already started so no further action is required.
569 if (timerStarted)
570 {
571 return;
572 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700573
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800574 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800575
576 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
577 timer.expires_after(timeout);
Ed Tanous81c4e332023-05-18 10:30:34 -0700578 timer.async_wait([weakSelf](const boost::system::error_code& ec) {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800579 // Note, we are ignoring other types of errors here; If the timer
580 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800581 std::shared_ptr<Connection<Adaptor, Handler>> self =
582 weakSelf.lock();
583 if (!self)
584 {
Ed Tanous62598e32023-07-17 17:06:25 -0700585 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
586 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800587 return;
588 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800589
590 self->timerStarted = false;
591
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800592 if (ec == boost::asio::error::operation_aborted)
593 {
Ed Tanous8ece0e42024-01-02 13:16:50 -0800594 // Canceled wait means the path succeeded.
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800595 return;
596 }
597 if (ec)
598 {
Ed Tanous62598e32023-07-17 17:06:25 -0700599 BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()),
600 ec);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800601 }
602
Ed Tanous62598e32023-07-17 17:06:25 -0700603 BMCWEB_LOG_WARNING("{}Connection timed out, closing",
604 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800605
606 self->close();
607 });
608
Ed Tanous7d243eb2023-01-23 15:57:41 -0800609 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700610 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700611 }
612
Ed Tanous1abe55e2018-09-05 08:30:59 -0700613 Adaptor adaptor;
614 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800615 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700616 // re-created on Connection reset
Ed Tanousb2896142024-01-31 15:25:47 -0800617 std::optional<boost::beast::http::request_parser<bmcweb::HttpBody>> parser;
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