blob: bd8cf3190e983f10409d3d5879951afa0560b02f [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>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050029#include <boost/beast/websocket.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050030
Manojkiran Eda44250442020-06-16 12:51:38 +053031#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050032#include <chrono>
33#include <vector>
34
Ed Tanous1abe55e2018-09-05 08:30:59 -070035namespace crow
36{
Ed Tanous257f5792018-03-17 14:40:09 -070037
Ed Tanouscf9e4172022-12-21 09:30:16 -080038// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080039static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070040
Ed Tanous0260d9d2021-02-07 19:31:07 +000041// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Patrick Williams89492a12023-05-10 07:51:34 -050042constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL *
43 bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070044
James Feist3909dc82020-04-03 10:58:55 -070045constexpr uint64_t loggedOutPostBodyLimit = 4096;
46
47constexpr uint32_t httpHeaderLimit = 8192;
48
Ed Tanous4fa45df2023-09-01 14:20:50 -070049template <typename>
50struct IsTls : std::false_type
51{};
52
53template <typename T>
Ed Tanous003301a2024-04-16 09:59:19 -070054struct IsTls<boost::asio::ssl::stream<T>> : std::true_type
Ed Tanous4fa45df2023-09-01 14:20:50 -070055{};
56
Ed Tanous52cc1122020-07-18 13:51:21 -070057template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050058class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070059 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070060{
Ed Tanous7c8e0642022-02-21 12:11:14 -080061 using self_type = Connection<Adaptor, Handler>;
62
Ed Tanous1abe55e2018-09-05 08:30:59 -070063 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080064 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000065 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080066 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080067 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080068 handler(handlerIn), timer(std::move(timerIn)),
69 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070070 {
71 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070072 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070073 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020074
75#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070076 prepareMutualTls();
77#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
78
Ed Tanous40aa0582021-07-14 13:24:40 -070079 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080080
Ed Tanous62598e32023-07-17 17:06:25 -070081 BMCWEB_LOG_DEBUG("{} Connection open, total {}", logPtr(this),
82 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070083 }
84
85 ~Connection()
86 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070087 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070088 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080089
Ed Tanous40aa0582021-07-14 13:24:40 -070090 connectionCount--;
Ed Tanous62598e32023-07-17 17:06:25 -070091 BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
92 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070093 }
94
Ed Tanousecd6a3a2022-01-07 09:18:40 -080095 Connection(const Connection&) = delete;
96 Connection(Connection&&) = delete;
97 Connection& operator=(const Connection&) = delete;
98 Connection& operator=(Connection&&) = delete;
99
Ed Tanous7c8e0642022-02-21 12:11:14 -0800100 bool tlsVerifyCallback(bool preverified,
101 boost::asio::ssl::verify_context& ctx)
102 {
103 // We always return true to allow full auth flow for resources that
104 // don't require auth
105 if (preverified)
106 {
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200107 boost::asio::ip::address ipAddress;
108 if (getClientIp(ipAddress))
Ed Tanouse01d0c32023-06-30 13:21:32 -0700109 {
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200110 return true;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700111 }
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200112
113 mtlsSession = verifyMtlsUser(ipAddress, ctx);
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100114 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800115 {
Ed Tanous62598e32023-07-17 17:06:25 -0700116 BMCWEB_LOG_DEBUG("{} Generating TLS session: {}", logPtr(this),
117 mtlsSession->uniqueId);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800118 }
119 }
120 return true;
121 }
122
Ed Tanous40aa0582021-07-14 13:24:40 -0700123 void prepareMutualTls()
124 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700125 if constexpr (IsTls<Adaptor>::value)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100126 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700127 std::error_code error;
128 std::filesystem::path caPath(ensuressl::trustStorePath);
129 auto caAvailable = !std::filesystem::is_empty(caPath, error);
130 caAvailable = caAvailable && !error;
131 if (caAvailable && persistent_data::SessionStore::getInstance()
132 .getAuthMethodsConfig()
133 .tls)
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700134 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700135 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
136 std::string id = "bmcweb";
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100137
Ed Tanous4fa45df2023-09-01 14:20:50 -0700138 const char* cStr = id.c_str();
139 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
140 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
141 int ret = SSL_set_session_id_context(
142 adaptor.native_handle(), idC,
143 static_cast<unsigned int>(id.length()));
144 if (ret == 0)
145 {
146 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
147 }
148 }
149
150 adaptor.set_verify_callback(
151 std::bind_front(&self_type::tlsVerifyCallback, this));
152 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700153 }
154
Ed Tanousceac6f72018-12-02 11:58:47 -0800155 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700156 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800157 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700158 }
159
Ed Tanous1abe55e2018-09-05 08:30:59 -0700160 void start()
161 {
Gunnar Mills4f63be02023-10-25 09:14:07 -0500162 if (connectionCount >= 200)
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800163 {
Ed Tanous62598e32023-07-17 17:06:25 -0700164 BMCWEB_LOG_CRITICAL("{}Max connection count exceeded.",
165 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800166 return;
167 }
168
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800169 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500170
Ed Tanousceac6f72018-12-02 11:58:47 -0800171 // TODO(ed) Abstract this to a more clever class with the idea of an
172 // asynchronous "start"
Ed Tanous4fa45df2023-09-01 14:20:50 -0700173 if constexpr (IsTls<Adaptor>::value)
Ed Tanousceac6f72018-12-02 11:58:47 -0800174 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000175 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
176 [this, self(shared_from_this())](
177 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700178 if (ec)
179 {
180 return;
181 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800182 afterSslHandshake();
Ed Tanous002d39b2022-05-31 08:59:27 -0700183 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800184 }
185 else
186 {
187 doReadHeaders();
188 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700189 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700190
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800191 void afterSslHandshake()
192 {
193 // If http2 is enabled, negotiate the protocol
194 if constexpr (bmcwebEnableHTTP2)
195 {
196 const unsigned char* alpn = nullptr;
197 unsigned int alpnlen = 0;
198 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
199 if (alpn != nullptr)
200 {
201 std::string_view selectedProtocol(
202 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700203 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
204 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800205 if (selectedProtocol == "h2")
206 {
207 auto http2 =
208 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
209 std::move(adaptor), handler, getCachedDateStr);
210 http2->start();
211 return;
212 }
213 }
214 }
215
216 doReadHeaders();
217 }
218
Ed Tanous1abe55e2018-09-05 08:30:59 -0700219 void handle()
220 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700221 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700222 if (!parser)
223 {
224 return;
225 }
Ed Tanous52e31622024-01-23 16:31:11 -0800226 req = crow::Request(parser->release(), reqEc);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700227 if (reqEc)
228 {
Ed Tanous62598e32023-07-17 17:06:25 -0700229 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600230 res.result(boost::beast::http::status::bad_request);
231 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700232 return;
233 }
Ed Tanous52e31622024-01-23 16:31:11 -0800234 req.session = userSession;
Ed Tanous596b2032021-09-13 10:32:22 -0700235
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000236 // Fetch the client IP address
237 readClientIp();
238
Ed Tanous1abe55e2018-09-05 08:30:59 -0700239 // Check for HTTP version 1.1.
Ed Tanous52e31622024-01-23 16:31:11 -0800240 if (req.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700241 {
Ed Tanous52e31622024-01-23 16:31:11 -0800242 if (req.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700243 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700244 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800245 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700246 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700247 }
248 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700249
Ed Tanous62598e32023-07-17 17:06:25 -0700250 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
Ed Tanous52e31622024-01-23 16:31:11 -0800251 req.version() / 10, req.version() % 10,
252 req.methodString(), req.target(),
253 req.ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700254
Ed Tanous52e31622024-01-23 16:31:11 -0800255 req.ioService = static_cast<decltype(req.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700256 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200257
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700258 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700259 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800260 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700261 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700262 }
Ed Tanous52e31622024-01-23 16:31:11 -0800263 keepAlive = req.keepAlive();
Ed Tanous4fa45df2023-09-01 14:20:50 -0700264 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700265 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700266#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous52e31622024-01-23 16:31:11 -0800267 if (!crow::authentication::isOnAllowlist(req.url().path(),
268 req.method()) &&
269 req.session == nullptr)
Ed Tanous4fa45df2023-09-01 14:20:50 -0700270 {
271 BMCWEB_LOG_WARNING("Authentication failed");
272 forward_unauthorized::sendUnauthorized(
Ed Tanous52e31622024-01-23 16:31:11 -0800273 req.url().encoded_path(),
274 req.getHeaderValue("X-Requested-With"),
275 req.getHeaderValue("Accept"), res);
Ed Tanous4fa45df2023-09-01 14:20:50 -0700276 completeRequest(res);
277 return;
278 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000279#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous4fa45df2023-09-01 14:20:50 -0700280 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800281 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700282 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800283 asyncResp->res.setCompleteRequestHandler(
284 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700285 self->completeRequest(thisRes);
286 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700287 bool isSse =
Ed Tanous52e31622024-01-23 16:31:11 -0800288 isContentTypeAllowed(req.getHeaderValue("Accept"),
Ed Tanous6fde95f2023-06-01 07:33:34 -0700289 http_helpers::ContentType::EventStream, false);
Ed Tanous18f8f602023-07-18 10:07:23 -0700290 std::string_view upgradeType(
Ed Tanous52e31622024-01-23 16:31:11 -0800291 req.getHeaderValue(boost::beast::http::field::upgrade));
292 if ((req.isUpgrade() &&
Ed Tanous18f8f602023-07-18 10:07:23 -0700293 bmcweb::asciiIEquals(upgradeType, "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700294 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700295 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530296 asyncResp->res.setCompleteRequestHandler(
297 [self(shared_from_this())](crow::Response& thisRes) {
298 if (thisRes.result() != boost::beast::http::status::ok)
299 {
300 // When any error occurs before handle upgradation,
301 // the result in response will be set to respective
302 // error. By default the Result will be OK (200),
303 // which implies successful handle upgrade. Response
304 // needs to be sent over this connection only on
305 // failure.
306 self->completeRequest(thisRes);
307 return;
308 }
309 });
Ed Tanous52e31622024-01-23 16:31:11 -0800310 handler->handleUpgrade(req, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700311 return;
312 }
Ed Tanous291d7092022-04-13 12:34:57 -0700313 std::string_view expected =
Ed Tanous52e31622024-01-23 16:31:11 -0800314 req.getHeaderValue(boost::beast::http::field::if_none_match);
Ed Tanous291d7092022-04-13 12:34:57 -0700315 if (!expected.empty())
316 {
317 res.setExpectedHash(expected);
318 }
Ed Tanous52e31622024-01-23 16:31:11 -0800319 handler->handle(req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700320 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700321
Ed Tanouse278c182019-03-13 16:23:37 -0700322 void close()
323 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700324 if constexpr (IsTls<Adaptor>::value)
Ed Tanouse278c182019-03-13 16:23:37 -0700325 {
326 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100327 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200328 {
Ed Tanous62598e32023-07-17 17:06:25 -0700329 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
330 mtlsSession->uniqueId);
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700331 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100332 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200333 }
Ed Tanouse278c182019-03-13 16:23:37 -0700334 }
335 else
336 {
337 adaptor.close();
338 }
339 }
340
Nan Zhou72374eb2022-01-27 17:06:51 -0800341 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700342 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800343 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800344 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800345
Ed Tanous52e31622024-01-23 16:31:11 -0800346 completeResponseFields(req, res);
Ed Tanous998e0cb2023-09-06 13:57:30 -0700347 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
Ed Tanous291d7092022-04-13 12:34:57 -0700348
Ed Tanous52e31622024-01-23 16:31:11 -0800349 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000350
351 // delete lambda with self shared_ptr
352 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700353 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700354 }
355
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500356 void readClientIp()
357 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700358 boost::asio::ip::address ip;
359 boost::system::error_code ec = getClientIp(ip);
360 if (ec)
361 {
362 return;
363 }
Ed Tanous52e31622024-01-23 16:31:11 -0800364 req.ipAddress = ip;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700365 }
366
367 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
368 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500369 boost::system::error_code ec;
Ed Tanous62598e32023-07-17 17:06:25 -0700370 BMCWEB_LOG_DEBUG("Fetch the client IP address");
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500371
Ed Tanous4fa45df2023-09-01 14:20:50 -0700372 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500373 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700374 boost::asio::ip::tcp::endpoint endpoint =
375 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
376
377 if (ec)
378 {
379 // If remote endpoint fails keep going. "ClientOriginIPAddress"
380 // will be empty.
381 BMCWEB_LOG_ERROR(
382 "Failed to get the client's IP Address. ec : {}", ec);
383 return ec;
384 }
385 ip = endpoint.address();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500386 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700387 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 Tanous62598e32023-07-17 17:06:25 -0700393 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700394 if (!parser)
395 {
396 return;
397 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700398 // Clean up any previous Connection.
399 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800400 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000401 [this,
402 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000403 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700404 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
405 bytesTransferred);
Ed Tanous52e31622024-01-23 16:31:11 -0800406
Ed Tanous002d39b2022-05-31 08:59:27 -0700407 if (ec)
408 {
Ed Tanous52e31622024-01-23 16:31:11 -0800409 cancelDeadlineTimer();
410
Myung Baea4326fe2023-01-10 14:29:24 -0600411 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700412 {
Ed Tanous62598e32023-07-17 17:06:25 -0700413 BMCWEB_LOG_WARNING("{} Error while reading: {}",
414 logPtr(this), ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700415 }
416 else
417 {
Ed Tanous62598e32023-07-17 17:06:25 -0700418 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
419 ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700420 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700421 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700422 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700423 return;
424 }
425
426 readClientIp();
427
428 boost::asio::ip::address ip;
429 if (getClientIp(ip))
430 {
Ed Tanous62598e32023-07-17 17:06:25 -0700431 BMCWEB_LOG_DEBUG("Unable to get client IP");
Ed Tanous002d39b2022-05-31 08:59:27 -0700432 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700433 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous002d39b2022-05-31 08:59:27 -0700434 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700435#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
436 boost::beast::http::verb method = parser->get().method();
437 userSession = crow::authentication::authenticate(
438 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700439
Ed Tanous4fa45df2023-09-01 14:20:50 -0700440 bool loggedIn = userSession != nullptr;
441 if (!loggedIn)
442 {
443 const boost::optional<uint64_t> contentLength =
444 parser->content_length();
445 if (contentLength &&
446 *contentLength > loggedOutPostBodyLimit)
447 {
448 BMCWEB_LOG_DEBUG("Content length greater than limit {}",
449 *contentLength);
450 close();
451 return;
452 }
453
454 BMCWEB_LOG_DEBUG("Starting quick deadline");
455 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000456#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous4fa45df2023-09-01 14:20:50 -0700457 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800458
Ed Tanous7d243eb2023-01-23 15:57:41 -0800459 if (parser->is_done())
460 {
461 handle();
462 return;
463 }
464
Ed Tanous002d39b2022-05-31 08:59:27 -0700465 doRead();
Patrick Williams5a39f772023-10-20 11:20:21 -0500466 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700467 }
468
469 void doRead()
470 {
Ed Tanous62598e32023-07-17 17:06:25 -0700471 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700472 if (!parser)
473 {
474 return;
475 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800476 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800477 boost::beast::http::async_read_some(
478 adaptor, buffer, *parser,
479 [this,
480 self(shared_from_this())](const boost::system::error_code& ec,
481 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700482 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
483 bytesTransferred);
Ed Tanous7d243eb2023-01-23 15:57:41 -0800484
Ed Tanous002d39b2022-05-31 08:59:27 -0700485 if (ec)
486 {
Ed Tanous62598e32023-07-17 17:06:25 -0700487 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
488 ec.message());
Ed Tanous002d39b2022-05-31 08:59:27 -0700489 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700490 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700491 return;
492 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800493
494 // If the user is logged in, allow them to send files incrementally
495 // one piece at a time. If authentication is disabled then there is
496 // no user session hence always allow to send one piece at a time.
497 if (userSession != nullptr)
498 {
499 cancelDeadlineTimer();
500 }
501 if (!parser->is_done())
502 {
503 doRead();
504 return;
505 }
506
507 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700508 handle();
Patrick Williams5a39f772023-10-20 11:20:21 -0500509 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700510 }
511
Ed Tanous27b0cf92023-08-07 12:02:40 -0700512 void afterDoWrite(const std::shared_ptr<self_type>& /*self*/,
513 const boost::system::error_code& ec,
514 std::size_t bytesTransferred)
515 {
516 BMCWEB_LOG_DEBUG("{} async_write {} bytes", logPtr(this),
517 bytesTransferred);
518
519 cancelDeadlineTimer();
520
521 if (ec)
522 {
523 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
524 return;
525 }
526 if (!keepAlive)
527 {
528 close();
529 BMCWEB_LOG_DEBUG("{} from write(1)", logPtr(this));
530 return;
531 }
532
533 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
534 res.clear();
535 parser.emplace(std::piecewise_construct, std::make_tuple());
536 parser->body_limit(httpReqBodyLimit); // reset body limit for
537 // newly created parser
538 buffer.consume(buffer.size());
539
540 userSession = nullptr;
541
542 // Destroy the Request via the std::optional
Ed Tanous52e31622024-01-23 16:31:11 -0800543 req.clear();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700544 doReadHeaders();
545 }
546
Ed Tanous52e31622024-01-23 16:31:11 -0800547 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700548 {
Ed Tanous62598e32023-07-17 17:06:25 -0700549 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Ed Tanous52e31622024-01-23 16:31:11 -0800550 res.preparePayload();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700551
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800552 startDeadline();
Ed Tanous4d698612024-02-06 14:57:24 -0800553 boost::beast::async_write(
554 adaptor,
555 boost::beast::http::message_generator(std::move(res.response)),
Ed Tanous52e31622024-01-23 16:31:11 -0800556 std::bind_front(&self_type::afterDoWrite, this,
557 shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700558 }
559
Ed Tanous1abe55e2018-09-05 08:30:59 -0700560 void cancelDeadlineTimer()
561 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800562 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700563 }
564
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800565 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700566 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800567 // Timer is already started so no further action is required.
568 if (timerStarted)
569 {
570 return;
571 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700572
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800573 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800574
575 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
576 timer.expires_after(timeout);
Ed Tanous81c4e332023-05-18 10:30:34 -0700577 timer.async_wait([weakSelf](const boost::system::error_code& ec) {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800578 // Note, we are ignoring other types of errors here; If the timer
579 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800580 std::shared_ptr<Connection<Adaptor, Handler>> self =
581 weakSelf.lock();
582 if (!self)
583 {
Ed Tanous62598e32023-07-17 17:06:25 -0700584 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
585 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800586 return;
587 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800588
589 self->timerStarted = false;
590
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800591 if (ec == boost::asio::error::operation_aborted)
592 {
Ed Tanous8ece0e42024-01-02 13:16:50 -0800593 // Canceled wait means the path succeeded.
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800594 return;
595 }
596 if (ec)
597 {
Ed Tanous62598e32023-07-17 17:06:25 -0700598 BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()),
599 ec);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800600 }
601
Ed Tanous62598e32023-07-17 17:06:25 -0700602 BMCWEB_LOG_WARNING("{}Connection timed out, closing",
603 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800604
605 self->close();
606 });
607
Ed Tanous7d243eb2023-01-23 15:57:41 -0800608 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700609 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700610 }
611
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612 Adaptor adaptor;
613 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800614 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700615 // re-created on Connection reset
Ed Tanousb2896142024-01-31 15:25:47 -0800616 std::optional<boost::beast::http::request_parser<bmcweb::HttpBody>> parser;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700617
Ed Tanous3112a142018-11-29 15:45:10 -0800618 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700619
Ed Tanous52e31622024-01-23 16:31:11 -0800620 crow::Request req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700621 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700622
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700623 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100624 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700625
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800626 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700627
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800628 bool keepAlive = true;
629
Ed Tanous7d243eb2023-01-23 15:57:41 -0800630 bool timerStarted = false;
631
Ed Tanous1abe55e2018-09-05 08:30:59 -0700632 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000633
634 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700635 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800636
637 using std::enable_shared_from_this<
638 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800639};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700640} // namespace crow