blob: ed3dc07573723176ac0010405ae639d6761b20de [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 Tanous18f8f602023-07-18 10:07:23 -070013#include "str_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070014#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070015
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 Tanous4fa45df2023-09-01 14:20:50 -070020#include <boost/beast/_experimental/test/stream.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080021#include <boost/beast/core/flat_static_buffer.hpp>
Myung Baea4326fe2023-01-10 14:29:24 -060022#include <boost/beast/http/error.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070023#include <boost/beast/http/parser.hpp>
24#include <boost/beast/http/read.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070025#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 Tanous4fa45df2023-09-01 14:20:50 -070047template <typename>
48struct IsTls : std::false_type
49{};
50
51template <typename T>
52struct IsTls<boost::beast::ssl_stream<T>> : std::true_type
53{};
54
Ed Tanous52cc1122020-07-18 13:51:21 -070055template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050056class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070057 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070058{
Ed Tanous7c8e0642022-02-21 12:11:14 -080059 using self_type = Connection<Adaptor, Handler>;
60
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080062 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000063 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080064 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080065 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080066 handler(handlerIn), timer(std::move(timerIn)),
67 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070068 {
69 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070070 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070071 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020072
73#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070074 prepareMutualTls();
75#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
76
Ed Tanous40aa0582021-07-14 13:24:40 -070077 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080078
Ed Tanous62598e32023-07-17 17:06:25 -070079 BMCWEB_LOG_DEBUG("{} Connection open, total {}", logPtr(this),
80 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070081 }
82
83 ~Connection()
84 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070085 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070086 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080087
Ed Tanous40aa0582021-07-14 13:24:40 -070088 connectionCount--;
Ed Tanous62598e32023-07-17 17:06:25 -070089 BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
90 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070091 }
92
Ed Tanousecd6a3a2022-01-07 09:18:40 -080093 Connection(const Connection&) = delete;
94 Connection(Connection&&) = delete;
95 Connection& operator=(const Connection&) = delete;
96 Connection& operator=(Connection&&) = delete;
97
Ed Tanous7c8e0642022-02-21 12:11:14 -080098 bool tlsVerifyCallback(bool preverified,
99 boost::asio::ssl::verify_context& ctx)
100 {
101 // We always return true to allow full auth flow for resources that
102 // don't require auth
103 if (preverified)
104 {
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200105 boost::asio::ip::address ipAddress;
106 if (getClientIp(ipAddress))
Ed Tanouse01d0c32023-06-30 13:21:32 -0700107 {
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200108 return true;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700109 }
Michal Orzel7aa9ab02023-08-18 16:59:11 +0200110
111 mtlsSession = verifyMtlsUser(ipAddress, ctx);
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100112 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800113 {
Ed Tanous62598e32023-07-17 17:06:25 -0700114 BMCWEB_LOG_DEBUG("{} Generating TLS session: {}", logPtr(this),
115 mtlsSession->uniqueId);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800116 }
117 }
118 return true;
119 }
120
Ed Tanous40aa0582021-07-14 13:24:40 -0700121 void prepareMutualTls()
122 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700123 if constexpr (IsTls<Adaptor>::value)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100124 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700125 std::error_code error;
126 std::filesystem::path caPath(ensuressl::trustStorePath);
127 auto caAvailable = !std::filesystem::is_empty(caPath, error);
128 caAvailable = caAvailable && !error;
129 if (caAvailable && persistent_data::SessionStore::getInstance()
130 .getAuthMethodsConfig()
131 .tls)
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700132 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700133 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
134 std::string id = "bmcweb";
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100135
Ed Tanous4fa45df2023-09-01 14:20:50 -0700136 const char* cStr = id.c_str();
137 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
138 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
139 int ret = SSL_set_session_id_context(
140 adaptor.native_handle(), idC,
141 static_cast<unsigned int>(id.length()));
142 if (ret == 0)
143 {
144 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
145 }
146 }
147
148 adaptor.set_verify_callback(
149 std::bind_front(&self_type::tlsVerifyCallback, this));
150 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700151 }
152
Ed Tanousceac6f72018-12-02 11:58:47 -0800153 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700154 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800155 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700156 }
157
Ed Tanous1abe55e2018-09-05 08:30:59 -0700158 void start()
159 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800160 if (connectionCount >= 100)
161 {
Ed Tanous62598e32023-07-17 17:06:25 -0700162 BMCWEB_LOG_CRITICAL("{}Max connection count exceeded.",
163 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800164 return;
165 }
166
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800167 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500168
Ed Tanousceac6f72018-12-02 11:58:47 -0800169 // TODO(ed) Abstract this to a more clever class with the idea of an
170 // asynchronous "start"
Ed Tanous4fa45df2023-09-01 14:20:50 -0700171 if constexpr (IsTls<Adaptor>::value)
Ed Tanousceac6f72018-12-02 11:58:47 -0800172 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000173 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
174 [this, self(shared_from_this())](
175 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700176 if (ec)
177 {
178 return;
179 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800180 afterSslHandshake();
Ed Tanous002d39b2022-05-31 08:59:27 -0700181 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800182 }
183 else
184 {
185 doReadHeaders();
186 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700187 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700188
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800189 void afterSslHandshake()
190 {
191 // If http2 is enabled, negotiate the protocol
192 if constexpr (bmcwebEnableHTTP2)
193 {
194 const unsigned char* alpn = nullptr;
195 unsigned int alpnlen = 0;
196 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
197 if (alpn != nullptr)
198 {
199 std::string_view selectedProtocol(
200 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700201 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
202 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800203 if (selectedProtocol == "h2")
204 {
205 auto http2 =
206 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
207 std::move(adaptor), handler, getCachedDateStr);
208 http2->start();
209 return;
210 }
211 }
212 }
213
214 doReadHeaders();
215 }
216
Ed Tanous1abe55e2018-09-05 08:30:59 -0700217 void handle()
218 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700219 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700220 if (!parser)
221 {
222 return;
223 }
Ed Tanous52e31622024-01-23 16:31:11 -0800224 req = crow::Request(parser->release(), reqEc);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700225 if (reqEc)
226 {
Ed Tanous62598e32023-07-17 17:06:25 -0700227 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600228 res.result(boost::beast::http::status::bad_request);
229 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700230 return;
231 }
Ed Tanous52e31622024-01-23 16:31:11 -0800232 req.session = userSession;
Ed Tanous596b2032021-09-13 10:32:22 -0700233
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000234 // Fetch the client IP address
235 readClientIp();
236
Ed Tanous1abe55e2018-09-05 08:30:59 -0700237 // Check for HTTP version 1.1.
Ed Tanous52e31622024-01-23 16:31:11 -0800238 if (req.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700239 {
Ed Tanous52e31622024-01-23 16:31:11 -0800240 if (req.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700241 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700242 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800243 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700244 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700245 }
246 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700247
Ed Tanous62598e32023-07-17 17:06:25 -0700248 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
Ed Tanous52e31622024-01-23 16:31:11 -0800249 req.version() / 10, req.version() % 10,
250 req.methodString(), req.target(),
251 req.ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700252
Ed Tanous52e31622024-01-23 16:31:11 -0800253 req.ioService = static_cast<decltype(req.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700254 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200255
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700256 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700257 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800258 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700259 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700260 }
Ed Tanous52e31622024-01-23 16:31:11 -0800261 keepAlive = req.keepAlive();
Ed Tanous4fa45df2023-09-01 14:20:50 -0700262 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700263 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700264#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous52e31622024-01-23 16:31:11 -0800265 if (!crow::authentication::isOnAllowlist(req.url().path(),
266 req.method()) &&
267 req.session == nullptr)
Ed Tanous4fa45df2023-09-01 14:20:50 -0700268 {
269 BMCWEB_LOG_WARNING("Authentication failed");
270 forward_unauthorized::sendUnauthorized(
Ed Tanous52e31622024-01-23 16:31:11 -0800271 req.url().encoded_path(),
272 req.getHeaderValue("X-Requested-With"),
273 req.getHeaderValue("Accept"), res);
Ed Tanous4fa45df2023-09-01 14:20:50 -0700274 completeRequest(res);
275 return;
276 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000277#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous4fa45df2023-09-01 14:20:50 -0700278 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800279 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700280 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800281 asyncResp->res.setCompleteRequestHandler(
282 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700283 self->completeRequest(thisRes);
284 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700285 bool isSse =
Ed Tanous52e31622024-01-23 16:31:11 -0800286 isContentTypeAllowed(req.getHeaderValue("Accept"),
Ed Tanous6fde95f2023-06-01 07:33:34 -0700287 http_helpers::ContentType::EventStream, false);
Ed Tanous18f8f602023-07-18 10:07:23 -0700288 std::string_view upgradeType(
Ed Tanous52e31622024-01-23 16:31:11 -0800289 req.getHeaderValue(boost::beast::http::field::upgrade));
290 if ((req.isUpgrade() &&
Ed Tanous18f8f602023-07-18 10:07:23 -0700291 bmcweb::asciiIEquals(upgradeType, "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700292 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700293 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530294 asyncResp->res.setCompleteRequestHandler(
295 [self(shared_from_this())](crow::Response& thisRes) {
296 if (thisRes.result() != boost::beast::http::status::ok)
297 {
298 // When any error occurs before handle upgradation,
299 // the result in response will be set to respective
300 // error. By default the Result will be OK (200),
301 // which implies successful handle upgrade. Response
302 // needs to be sent over this connection only on
303 // failure.
304 self->completeRequest(thisRes);
305 return;
306 }
307 });
Ed Tanous52e31622024-01-23 16:31:11 -0800308 handler->handleUpgrade(req, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700309 return;
310 }
Ed Tanous291d7092022-04-13 12:34:57 -0700311 std::string_view expected =
Ed Tanous52e31622024-01-23 16:31:11 -0800312 req.getHeaderValue(boost::beast::http::field::if_none_match);
Ed Tanous291d7092022-04-13 12:34:57 -0700313 if (!expected.empty())
314 {
315 res.setExpectedHash(expected);
316 }
Ed Tanous52e31622024-01-23 16:31:11 -0800317 handler->handle(req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700318 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700319
Ed Tanouse278c182019-03-13 16:23:37 -0700320 void close()
321 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700322 if constexpr (IsTls<Adaptor>::value)
Ed Tanouse278c182019-03-13 16:23:37 -0700323 {
324 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100325 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200326 {
Ed Tanous62598e32023-07-17 17:06:25 -0700327 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
328 mtlsSession->uniqueId);
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700329 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100330 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200331 }
Ed Tanouse278c182019-03-13 16:23:37 -0700332 }
333 else
334 {
335 adaptor.close();
336 }
337 }
338
Nan Zhou72374eb2022-01-27 17:06:51 -0800339 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700340 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800341 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800342 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800343
Ed Tanous52e31622024-01-23 16:31:11 -0800344 completeResponseFields(req, res);
Ed Tanous998e0cb2023-09-06 13:57:30 -0700345 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
Ed Tanous291d7092022-04-13 12:34:57 -0700346
Ed Tanous52e31622024-01-23 16:31:11 -0800347 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000348
349 // delete lambda with self shared_ptr
350 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700351 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700352 }
353
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500354 void readClientIp()
355 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700356 boost::asio::ip::address ip;
357 boost::system::error_code ec = getClientIp(ip);
358 if (ec)
359 {
360 return;
361 }
Ed Tanous52e31622024-01-23 16:31:11 -0800362 req.ipAddress = ip;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700363 }
364
365 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
366 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500367 boost::system::error_code ec;
Ed Tanous62598e32023-07-17 17:06:25 -0700368 BMCWEB_LOG_DEBUG("Fetch the client IP address");
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500369
Ed Tanous4fa45df2023-09-01 14:20:50 -0700370 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500371 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700372 boost::asio::ip::tcp::endpoint endpoint =
373 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
374
375 if (ec)
376 {
377 // If remote endpoint fails keep going. "ClientOriginIPAddress"
378 // will be empty.
379 BMCWEB_LOG_ERROR(
380 "Failed to get the client's IP Address. ec : {}", ec);
381 return ec;
382 }
383 ip = endpoint.address();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500384 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700385 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500386 }
387
Ed Tanous1abe55e2018-09-05 08:30:59 -0700388 private:
389 void doReadHeaders()
390 {
Ed Tanous62598e32023-07-17 17:06:25 -0700391 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700392 if (!parser)
393 {
394 return;
395 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700396 // Clean up any previous Connection.
397 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800398 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000399 [this,
400 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000401 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700402 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
403 bytesTransferred);
Ed Tanous52e31622024-01-23 16:31:11 -0800404
Ed Tanous002d39b2022-05-31 08:59:27 -0700405 if (ec)
406 {
Ed Tanous52e31622024-01-23 16:31:11 -0800407 cancelDeadlineTimer();
408
Myung Baea4326fe2023-01-10 14:29:24 -0600409 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700410 {
Ed Tanous62598e32023-07-17 17:06:25 -0700411 BMCWEB_LOG_WARNING("{} Error while reading: {}",
412 logPtr(this), ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700413 }
414 else
415 {
Ed Tanous62598e32023-07-17 17:06:25 -0700416 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
417 ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700418 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700419 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700420 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700421 return;
422 }
423
424 readClientIp();
425
426 boost::asio::ip::address ip;
427 if (getClientIp(ip))
428 {
Ed Tanous62598e32023-07-17 17:06:25 -0700429 BMCWEB_LOG_DEBUG("Unable to get client IP");
Ed Tanous002d39b2022-05-31 08:59:27 -0700430 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700431 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous002d39b2022-05-31 08:59:27 -0700432 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700433#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
434 boost::beast::http::verb method = parser->get().method();
435 userSession = crow::authentication::authenticate(
436 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700437
Ed Tanous4fa45df2023-09-01 14:20:50 -0700438 bool loggedIn = userSession != nullptr;
439 if (!loggedIn)
440 {
441 const boost::optional<uint64_t> contentLength =
442 parser->content_length();
443 if (contentLength &&
444 *contentLength > loggedOutPostBodyLimit)
445 {
446 BMCWEB_LOG_DEBUG("Content length greater than limit {}",
447 *contentLength);
448 close();
449 return;
450 }
451
452 BMCWEB_LOG_DEBUG("Starting quick deadline");
453 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000454#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous4fa45df2023-09-01 14:20:50 -0700455 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800456
Ed Tanous7d243eb2023-01-23 15:57:41 -0800457 if (parser->is_done())
458 {
459 handle();
460 return;
461 }
462
Ed Tanous002d39b2022-05-31 08:59:27 -0700463 doRead();
Patrick Williams5a39f772023-10-20 11:20:21 -0500464 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700465 }
466
467 void doRead()
468 {
Ed Tanous62598e32023-07-17 17:06:25 -0700469 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700470 if (!parser)
471 {
472 return;
473 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800474 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800475 boost::beast::http::async_read_some(
476 adaptor, buffer, *parser,
477 [this,
478 self(shared_from_this())](const boost::system::error_code& ec,
479 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700480 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
481 bytesTransferred);
Ed Tanous7d243eb2023-01-23 15:57:41 -0800482
Ed Tanous002d39b2022-05-31 08:59:27 -0700483 if (ec)
484 {
Ed Tanous62598e32023-07-17 17:06:25 -0700485 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
486 ec.message());
Ed Tanous002d39b2022-05-31 08:59:27 -0700487 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700488 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700489 return;
490 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800491
492 // If the user is logged in, allow them to send files incrementally
493 // one piece at a time. If authentication is disabled then there is
494 // no user session hence always allow to send one piece at a time.
495 if (userSession != nullptr)
496 {
497 cancelDeadlineTimer();
498 }
499 if (!parser->is_done())
500 {
501 doRead();
502 return;
503 }
504
505 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700506 handle();
Patrick Williams5a39f772023-10-20 11:20:21 -0500507 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700508 }
509
Ed Tanous27b0cf92023-08-07 12:02:40 -0700510 void afterDoWrite(const std::shared_ptr<self_type>& /*self*/,
511 const boost::system::error_code& ec,
512 std::size_t bytesTransferred)
513 {
514 BMCWEB_LOG_DEBUG("{} async_write {} bytes", logPtr(this),
515 bytesTransferred);
516
517 cancelDeadlineTimer();
518
519 if (ec)
520 {
521 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
522 return;
523 }
524 if (!keepAlive)
525 {
526 close();
527 BMCWEB_LOG_DEBUG("{} from write(1)", logPtr(this));
528 return;
529 }
530
531 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
532 res.clear();
533 parser.emplace(std::piecewise_construct, std::make_tuple());
534 parser->body_limit(httpReqBodyLimit); // reset body limit for
535 // newly created parser
536 buffer.consume(buffer.size());
537
538 userSession = nullptr;
539
540 // Destroy the Request via the std::optional
Ed Tanous52e31622024-01-23 16:31:11 -0800541 req.clear();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700542 doReadHeaders();
543 }
544
Ed Tanous52e31622024-01-23 16:31:11 -0800545 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700546 {
Ed Tanous62598e32023-07-17 17:06:25 -0700547 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Ed Tanous52e31622024-01-23 16:31:11 -0800548 res.preparePayload();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700549
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800550 startDeadline();
Ed Tanous52e31622024-01-23 16:31:11 -0800551 serializer.emplace(res.response);
552 boost::beast::http::async_write(
553 adaptor, *serializer,
554 std::bind_front(&self_type::afterDoWrite, this,
555 shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700556 }
557
Ed Tanous1abe55e2018-09-05 08:30:59 -0700558 void cancelDeadlineTimer()
559 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800560 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700561 }
562
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800563 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700564 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800565 // Timer is already started so no further action is required.
566 if (timerStarted)
567 {
568 return;
569 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700570
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800571 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800572
573 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
574 timer.expires_after(timeout);
Ed Tanous81c4e332023-05-18 10:30:34 -0700575 timer.async_wait([weakSelf](const boost::system::error_code& ec) {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800576 // Note, we are ignoring other types of errors here; If the timer
577 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800578 std::shared_ptr<Connection<Adaptor, Handler>> self =
579 weakSelf.lock();
580 if (!self)
581 {
Ed Tanous62598e32023-07-17 17:06:25 -0700582 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
583 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800584 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 {
Ed Tanous8ece0e42024-01-02 13:16:50 -0800591 // Canceled wait means the path succeeded.
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800592 return;
593 }
594 if (ec)
595 {
Ed Tanous62598e32023-07-17 17:06:25 -0700596 BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()),
597 ec);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800598 }
599
Ed Tanous62598e32023-07-17 17:06:25 -0700600 BMCWEB_LOG_WARNING("{}Connection timed out, closing",
601 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800602
603 self->close();
604 });
605
Ed Tanous7d243eb2023-01-23 15:57:41 -0800606 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700607 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700608 }
609
Ed Tanous1abe55e2018-09-05 08:30:59 -0700610 Adaptor adaptor;
611 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800612 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700613 // re-created on Connection reset
Ed Tanous52e31622024-01-23 16:31:11 -0800614 std::optional<boost::beast::http::request_parser<bmcweb::FileBody>> parser;
615 std::optional<boost::beast::http::response_serializer<bmcweb::FileBody>>
616 serializer;
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