blob: bea10aa0d4c61dd65ba4185010c4d0c9f45b7537 [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>
Jonathan Doman102a4cd2024-04-15 16:56:23 -070033#include <memory>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050034#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 Tanous25b54db2024-04-17 15:40:31 -070042// request body limit size set by the BMCWEB_HTTP_BODY_LIMIT option
43constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL * BMCWEB_HTTP_BODY_LIMIT;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070044
Ed Tanous1d1d7782024-04-09 12:54:08 -070045constexpr uint64_t loggedOutPostBodyLimit = 4096U;
James Feist3909dc82020-04-03 10:58:55 -070046
Ed Tanous1d1d7782024-04-09 12:54:08 -070047constexpr uint32_t httpHeaderLimit = 8192U;
James Feist3909dc82020-04-03 10:58:55 -070048
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 Tanous3281bcf2024-06-25 16:02:05 -070066 Adaptor&& adaptorIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -040067 adaptor(std::move(adaptorIn)), handler(handlerIn),
68 timer(std::move(timerIn)), getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070069 {
Ed Tanous1d1d7782024-04-09 12:54:08 -070070 initParser();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020071
Ed Tanous40aa0582021-07-14 13:24:40 -070072 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080073
Ed Tanous1d1d7782024-04-09 12:54:08 -070074 BMCWEB_LOG_DEBUG("{} Connection created, total {}", logPtr(this),
Ed Tanous62598e32023-07-17 17:06:25 -070075 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070076 }
77
78 ~Connection()
79 {
Ed Tanous1d1d7782024-04-09 12:54:08 -070080 res.releaseCompleteRequestHandler();
Ed Tanous40aa0582021-07-14 13:24:40 -070081 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080082
Ed Tanous40aa0582021-07-14 13:24:40 -070083 connectionCount--;
Ed Tanous62598e32023-07-17 17:06:25 -070084 BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
85 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070086 }
87
Ed Tanousecd6a3a2022-01-07 09:18:40 -080088 Connection(const Connection&) = delete;
89 Connection(Connection&&) = delete;
90 Connection& operator=(const Connection&) = delete;
91 Connection& operator=(Connection&&) = delete;
92
Ed Tanous7c8e0642022-02-21 12:11:14 -080093 bool tlsVerifyCallback(bool preverified,
94 boost::asio::ssl::verify_context& ctx)
95 {
Ed Tanous3281bcf2024-06-25 16:02:05 -070096 BMCWEB_LOG_DEBUG("{} tlsVerifyCallback called with preverified {}",
97 logPtr(this), preverified);
Ed Tanous7c8e0642022-02-21 12:11:14 -080098 if (preverified)
99 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700100 mtlsSession = verifyMtlsUser(ip, ctx);
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100101 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800102 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700103 BMCWEB_LOG_DEBUG("{} Generated TLS session: {}", logPtr(this),
Ed Tanous62598e32023-07-17 17:06:25 -0700104 mtlsSession->uniqueId);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800105 }
106 }
Ed Tanous3281bcf2024-06-25 16:02:05 -0700107 const persistent_data::AuthConfigMethods& c =
108 persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
109 if (c.tlsStrict)
110 {
111 return preverified;
112 }
113 // If tls strict mode is disabled
114 // We always return true to allow full auth flow for resources that
115 // don't require auth
Ed Tanous7c8e0642022-02-21 12:11:14 -0800116 return true;
117 }
118
Ed Tanous3281bcf2024-06-25 16:02:05 -0700119 bool prepareMutualTls()
Ed Tanous40aa0582021-07-14 13:24:40 -0700120 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700121 if constexpr (IsTls<Adaptor>::value)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100122 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700123 BMCWEB_LOG_DEBUG("prepareMutualTls");
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100124
Ed Tanous3281bcf2024-06-25 16:02:05 -0700125 constexpr std::string_view id = "bmcweb";
126
127 const char* idPtr = id.data();
128 const auto* idCPtr = std::bit_cast<const unsigned char*>(idPtr);
129 auto idLen = static_cast<unsigned int>(id.length());
130 int ret = SSL_set_session_id_context(adaptor.native_handle(),
131 idCPtr, idLen);
132 if (ret == 0)
133 {
134 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
135 return false;
Ed Tanous4fa45df2023-09-01 14:20:50 -0700136 }
137
Ed Tanous3281bcf2024-06-25 16:02:05 -0700138 BMCWEB_LOG_DEBUG("set_verify_callback");
Ed Tanous7045c8d2017-04-03 10:04:37 -0700139
Ed Tanous3281bcf2024-06-25 16:02:05 -0700140 boost::system::error_code ec;
141 adaptor.set_verify_callback(
142 std::bind_front(&self_type::tlsVerifyCallback, this), ec);
143 if (ec)
144 {
145 BMCWEB_LOG_ERROR("Failed to set verify callback {}", ec);
146 return false;
147 }
148 }
149
150 return true;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700151 }
152
Ed Tanous1abe55e2018-09-05 08:30:59 -0700153 void start()
154 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700155 BMCWEB_LOG_DEBUG("{} Connection started, total {}", logPtr(this),
156 connectionCount);
Gunnar Mills4f63be02023-10-25 09:14:07 -0500157 if (connectionCount >= 200)
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800158 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700159 BMCWEB_LOG_CRITICAL("{} Max connection count exceeded.",
Ed Tanous62598e32023-07-17 17:06:25 -0700160 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800161 return;
162 }
163
Ed Tanous3281bcf2024-06-25 16:02:05 -0700164 if constexpr (BMCWEB_MUTUAL_TLS_AUTH)
165 {
166 if (!prepareMutualTls())
167 {
168 BMCWEB_LOG_ERROR("{} Failed to prepare mTLS", logPtr(this));
169 return;
170 }
171 }
172
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800173 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500174
Ed Tanous1d1d7782024-04-09 12:54:08 -0700175 readClientIp();
176
Ed Tanousceac6f72018-12-02 11:58:47 -0800177 // TODO(ed) Abstract this to a more clever class with the idea of an
178 // asynchronous "start"
Ed Tanous4fa45df2023-09-01 14:20:50 -0700179 if constexpr (IsTls<Adaptor>::value)
Ed Tanousceac6f72018-12-02 11:58:47 -0800180 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000181 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
182 [this, self(shared_from_this())](
183 const boost::system::error_code& ec) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400184 if (ec)
185 {
186 return;
187 }
188 afterSslHandshake();
189 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800190 }
191 else
192 {
193 doReadHeaders();
194 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700195 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700196
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800197 void afterSslHandshake()
198 {
199 // If http2 is enabled, negotiate the protocol
Ed Tanous25b54db2024-04-17 15:40:31 -0700200 if constexpr (BMCWEB_EXPERIMENTAL_HTTP2)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800201 {
202 const unsigned char* alpn = nullptr;
203 unsigned int alpnlen = 0;
204 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
205 if (alpn != nullptr)
206 {
207 std::string_view selectedProtocol(
208 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700209 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
210 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800211 if (selectedProtocol == "h2")
212 {
213 auto http2 =
214 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
215 std::move(adaptor), handler, getCachedDateStr);
216 http2->start();
217 return;
218 }
219 }
220 }
221
222 doReadHeaders();
223 }
224
Ed Tanous1d1d7782024-04-09 12:54:08 -0700225 void initParser()
226 {
227 boost::beast::http::request_parser<bmcweb::HttpBody>& instance =
228 parser.emplace(std::piecewise_construct, std::make_tuple());
229
230 // reset header limit for newly created parser
231 instance.header_limit(httpHeaderLimit);
232
233 // Initially set no body limit. We don't yet know if the user is
234 // authenticated.
235 instance.body_limit(boost::none);
236 }
237
Ed Tanous1abe55e2018-09-05 08:30:59 -0700238 void handle()
239 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700240 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700241 if (!parser)
242 {
243 return;
244 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700245 req = std::make_shared<crow::Request>(parser->release(), reqEc);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700246 if (reqEc)
247 {
Ed Tanous62598e32023-07-17 17:06:25 -0700248 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600249 res.result(boost::beast::http::status::bad_request);
250 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700251 return;
252 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700253 req->session = userSession;
Ed Tanous89cda632024-04-16 08:45:54 -0700254 accept = req->getHeaderValue("Accept");
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000255 // Fetch the client IP address
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700256 req->ipAddress = ip;
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000257
Ed Tanous1abe55e2018-09-05 08:30:59 -0700258 // Check for HTTP version 1.1.
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700259 if (req->version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700260 {
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700261 if (req->getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700262 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700263 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800264 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700265 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700266 }
267 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700268
Ed Tanous62598e32023-07-17 17:06:25 -0700269 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700270 req->version() / 10, req->version() % 10,
271 req->methodString(), req->target(),
272 req->ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700273
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700274 req->ioService = static_cast<decltype(req->ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700275 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200276
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700277 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700278 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800279 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700280 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700281 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700282 keepAlive = req->keepAlive();
Ed Tanous4fa45df2023-09-01 14:20:50 -0700283 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700284 {
Ed Tanous83328312024-05-09 15:48:09 -0700285 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous4fa45df2023-09-01 14:20:50 -0700286 {
Ed Tanous83328312024-05-09 15:48:09 -0700287 if (!crow::authentication::isOnAllowlist(req->url().path(),
288 req->method()) &&
289 req->session == nullptr)
290 {
291 BMCWEB_LOG_WARNING("Authentication failed");
292 forward_unauthorized::sendUnauthorized(
293 req->url().encoded_path(),
294 req->getHeaderValue("X-Requested-With"),
295 req->getHeaderValue("Accept"), res);
296 completeRequest(res);
297 return;
298 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700299 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700300 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800301 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700302 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800303 asyncResp->res.setCompleteRequestHandler(
304 [self(shared_from_this())](crow::Response& thisRes) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400305 self->completeRequest(thisRes);
306 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700307 bool isSse =
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700308 isContentTypeAllowed(req->getHeaderValue("Accept"),
Ed Tanous6fde95f2023-06-01 07:33:34 -0700309 http_helpers::ContentType::EventStream, false);
Ed Tanous18f8f602023-07-18 10:07:23 -0700310 std::string_view upgradeType(
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700311 req->getHeaderValue(boost::beast::http::field::upgrade));
312 if ((req->isUpgrade() &&
Ed Tanous18f8f602023-07-18 10:07:23 -0700313 bmcweb::asciiIEquals(upgradeType, "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700314 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700315 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530316 asyncResp->res.setCompleteRequestHandler(
317 [self(shared_from_this())](crow::Response& thisRes) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400318 if (thisRes.result() != boost::beast::http::status::ok)
319 {
320 // When any error occurs before handle upgradation,
321 // the result in response will be set to respective
322 // error. By default the Result will be OK (200),
323 // which implies successful handle upgrade. Response
324 // needs to be sent over this connection only on
325 // failure.
326 self->completeRequest(thisRes);
327 return;
328 }
329 });
Ed Tanous52e31622024-01-23 16:31:11 -0800330 handler->handleUpgrade(req, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700331 return;
332 }
Ed Tanous291d7092022-04-13 12:34:57 -0700333 std::string_view expected =
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700334 req->getHeaderValue(boost::beast::http::field::if_none_match);
Ed Tanous291d7092022-04-13 12:34:57 -0700335 if (!expected.empty())
336 {
337 res.setExpectedHash(expected);
338 }
Ed Tanous52e31622024-01-23 16:31:11 -0800339 handler->handle(req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700340 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700341
Ed Tanous1d1d7782024-04-09 12:54:08 -0700342 void hardClose()
Ed Tanouse278c182019-03-13 16:23:37 -0700343 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700344 if (mtlsSession != nullptr)
345 {
346 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
347 mtlsSession->uniqueId);
348 persistent_data::SessionStore::getInstance().removeSession(
349 mtlsSession);
350 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700351 BMCWEB_LOG_DEBUG("{} Closing socket", logPtr(this));
352 boost::beast::get_lowest_layer(adaptor).close();
353 }
354
355 void tlsShutdownComplete(const std::shared_ptr<self_type>& self,
356 const boost::system::error_code& ec)
357 {
358 if (ec)
359 {
360 BMCWEB_LOG_WARNING("{} Failed to shut down TLS cleanly {}",
361 logPtr(self.get()), ec);
362 }
363 self->hardClose();
364 }
365
366 void gracefulClose()
367 {
368 BMCWEB_LOG_DEBUG("{} Socket close requested", logPtr(this));
Ed Tanous3281bcf2024-06-25 16:02:05 -0700369
Ed Tanous4fa45df2023-09-01 14:20:50 -0700370 if constexpr (IsTls<Adaptor>::value)
Ed Tanouse278c182019-03-13 16:23:37 -0700371 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700372 adaptor.async_shutdown(std::bind_front(
373 &self_type::tlsShutdownComplete, this, shared_from_this()));
Ed Tanouse278c182019-03-13 16:23:37 -0700374 }
375 else
376 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700377 hardClose();
Ed Tanouse278c182019-03-13 16:23:37 -0700378 }
379 }
380
Nan Zhou72374eb2022-01-27 17:06:51 -0800381 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700382 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800383 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800384 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800385
Ed Tanous89cda632024-04-16 08:45:54 -0700386 completeResponseFields(accept, res);
Ed Tanous998e0cb2023-09-06 13:57:30 -0700387 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
Ed Tanous291d7092022-04-13 12:34:57 -0700388
Ed Tanous52e31622024-01-23 16:31:11 -0800389 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000390
391 // delete lambda with self shared_ptr
392 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700393 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700394 }
395
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500396 void readClientIp()
397 {
398 boost::system::error_code ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500399
Ed Tanous4fa45df2023-09-01 14:20:50 -0700400 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500401 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700402 boost::asio::ip::tcp::endpoint endpoint =
403 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
404
405 if (ec)
406 {
407 // If remote endpoint fails keep going. "ClientOriginIPAddress"
408 // will be empty.
409 BMCWEB_LOG_ERROR(
410 "Failed to get the client's IP Address. ec : {}", ec);
Ed Tanous1d1d7782024-04-09 12:54:08 -0700411 return;
Ed Tanous4fa45df2023-09-01 14:20:50 -0700412 }
413 ip = endpoint.address();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500414 }
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500415 }
416
Ed Tanous1abe55e2018-09-05 08:30:59 -0700417 private:
Ed Tanous1d1d7782024-04-09 12:54:08 -0700418 uint64_t getContentLengthLimit()
419 {
Ed Tanous83328312024-05-09 15:48:09 -0700420 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous1d1d7782024-04-09 12:54:08 -0700421 {
Ed Tanous83328312024-05-09 15:48:09 -0700422 if (userSession == nullptr)
423 {
424 return loggedOutPostBodyLimit;
425 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700426 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700427
428 return httpReqBodyLimit;
429 }
430
431 // Returns true if content length was within limits
432 // Returns false if content length error has been returned
433 bool handleContentLengthError()
434 {
435 if (!parser)
436 {
Manojkiran Edaefff2b52024-06-18 18:01:46 +0530437 BMCWEB_LOG_CRITICAL("Parser was null");
Ed Tanous1d1d7782024-04-09 12:54:08 -0700438 return false;
439 }
440 const boost::optional<uint64_t> contentLength =
441 parser->content_length();
442 if (!contentLength)
443 {
444 BMCWEB_LOG_DEBUG("{} No content length available", logPtr(this));
445 return true;
446 }
447
448 uint64_t maxAllowedContentLength = getContentLengthLimit();
449
450 if (*contentLength > maxAllowedContentLength)
451 {
452 // If the users content limit is between the logged in
453 // and logged out limits They probably just didn't log
454 // in
455 if (*contentLength > loggedOutPostBodyLimit &&
456 *contentLength < httpReqBodyLimit)
457 {
458 BMCWEB_LOG_DEBUG(
459 "{} Content length {} valid, but greater than logged out"
460 " limit of {}. Setting unauthorized",
461 logPtr(this), *contentLength, loggedOutPostBodyLimit);
462 res.result(boost::beast::http::status::unauthorized);
463 }
464 else
465 {
466 // Otherwise they're over both limits, so inform
467 // them
468 BMCWEB_LOG_DEBUG(
469 "{} Content length {} was greater than global limit {}."
470 " Setting payload too large",
471 logPtr(this), *contentLength, httpReqBodyLimit);
472 res.result(boost::beast::http::status::payload_too_large);
473 }
474
475 keepAlive = false;
476 doWrite();
477 return false;
478 }
479
480 return true;
481 }
482
Ed Tanous116370d2024-10-08 10:37:28 -0700483 void afterReadHeaders(const std::shared_ptr<self_type>& /*self*/,
484 const boost::system::error_code& ec,
485 std::size_t bytesTransferred)
486 {
487 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
488 bytesTransferred);
489
490 if (ec)
491 {
492 cancelDeadlineTimer();
493
494 if (ec == boost::beast::http::error::header_limit)
495 {
496 BMCWEB_LOG_ERROR("{} Header field too large, closing",
497 logPtr(this), ec.message());
498
499 res.result(boost::beast::http::status::
500 request_header_fields_too_large);
501 keepAlive = false;
502 doWrite();
503 return;
504 }
505 if (ec == boost::beast::http::error::end_of_stream)
506 {
507 BMCWEB_LOG_WARNING("{} End of stream, closing {}", logPtr(this),
508 ec);
509 hardClose();
510 return;
511 }
512
513 BMCWEB_LOG_DEBUG("{} Closing socket due to read error {}",
514 logPtr(this), ec.message());
515 gracefulClose();
516
517 return;
518 }
519
520 if (!parser)
521 {
522 BMCWEB_LOG_ERROR("Parser was unexpectedly null");
523 return;
524 }
525
526 constexpr bool isTest =
527 std::is_same_v<Adaptor, boost::beast::test::stream>;
528
529 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH && !isTest)
530 {
531 boost::beast::http::verb method = parser->get().method();
532 userSession = crow::authentication::authenticate(
533 ip, res, method, parser->get().base(), mtlsSession);
534 }
535
536 std::string_view expect =
537 parser->get()[boost::beast::http::field::expect];
538 if (bmcweb::asciiIEquals(expect, "100-continue"))
539 {
540 res.result(boost::beast::http::status::continue_);
541 doWrite();
542 return;
543 }
544
545 if (!handleContentLengthError())
546 {
547 return;
548 }
549
550 parser->body_limit(getContentLengthLimit());
551
552 if (parser->is_done())
553 {
554 handle();
555 return;
556 }
557
558 doRead();
559 }
560
Ed Tanous1abe55e2018-09-05 08:30:59 -0700561 void doReadHeaders()
562 {
Ed Tanous62598e32023-07-17 17:06:25 -0700563 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700564 if (!parser)
565 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700566 BMCWEB_LOG_CRITICAL("Parser was not initialized.");
Ed Tanouse01d0c32023-06-30 13:21:32 -0700567 return;
568 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700569 // Clean up any previous Connection.
570 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800571 adaptor, buffer, *parser,
Ed Tanous116370d2024-10-08 10:37:28 -0700572 std::bind_front(&self_type::afterReadHeaders, this,
573 shared_from_this()));
574 }
Ed Tanous52e31622024-01-23 16:31:11 -0800575
Ed Tanous116370d2024-10-08 10:37:28 -0700576 void afterRead(const std::shared_ptr<self_type>& /*self*/,
577 const boost::system::error_code& ec,
578 std::size_t bytesTransferred)
579 {
580 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
581 bytesTransferred);
582
583 if (ec)
584 {
585 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
586 ec.message());
587 if (ec == boost::beast::http::error::body_limit)
588 {
589 if (handleContentLengthError())
Ed Tanous1d1d7782024-04-09 12:54:08 -0700590 {
Ed Tanous116370d2024-10-08 10:37:28 -0700591 BMCWEB_LOG_CRITICAL("Body length limit reached, "
592 "but no content-length "
593 "available? Should never happen");
594 res.result(
595 boost::beast::http::status::internal_server_error);
596 keepAlive = false;
Ed Tanous1d1d7782024-04-09 12:54:08 -0700597 doWrite();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700598 }
Ed Tanous116370d2024-10-08 10:37:28 -0700599 return;
600 }
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400601
Ed Tanous116370d2024-10-08 10:37:28 -0700602 gracefulClose();
603 return;
604 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700605
Ed Tanous116370d2024-10-08 10:37:28 -0700606 // If the user is logged in, allow them to send files
607 // incrementally one piece at a time. If authentication is
608 // disabled then there is no user session hence always allow to
609 // send one piece at a time.
610 if (userSession != nullptr)
611 {
612 cancelDeadlineTimer();
613 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700614
Ed Tanous116370d2024-10-08 10:37:28 -0700615 if (!parser)
616 {
617 BMCWEB_LOG_ERROR("Parser was unexpectedly null");
618 return;
619 }
620 if (!parser->is_done())
621 {
622 doRead();
623 return;
624 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700625
Ed Tanous116370d2024-10-08 10:37:28 -0700626 cancelDeadlineTimer();
627 handle();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700628 }
629
630 void doRead()
631 {
Ed Tanous62598e32023-07-17 17:06:25 -0700632 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700633 if (!parser)
634 {
635 return;
636 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800637 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800638 boost::beast::http::async_read_some(
639 adaptor, buffer, *parser,
Ed Tanous116370d2024-10-08 10:37:28 -0700640 std::bind_front(&self_type::afterRead, this, shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 }
642
Ed Tanous27b0cf92023-08-07 12:02:40 -0700643 void afterDoWrite(const std::shared_ptr<self_type>& /*self*/,
644 const boost::system::error_code& ec,
645 std::size_t bytesTransferred)
646 {
Ed Tanous0242baf2024-05-16 19:52:47 -0700647 BMCWEB_LOG_DEBUG("{} async_write wrote {} bytes, ec={}", logPtr(this),
Ed Tanous1d1d7782024-04-09 12:54:08 -0700648 bytesTransferred, ec);
Ed Tanous27b0cf92023-08-07 12:02:40 -0700649
650 cancelDeadlineTimer();
651
Ed Tanous0242baf2024-05-16 19:52:47 -0700652 if (ec == boost::system::errc::operation_would_block ||
653 ec == boost::system::errc::resource_unavailable_try_again)
654 {
655 doWrite();
656 return;
657 }
Ed Tanous27b0cf92023-08-07 12:02:40 -0700658 if (ec)
659 {
660 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
661 return;
662 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700663
664 if (res.result() == boost::beast::http::status::continue_)
665 {
666 // Reset the result to ok
667 res.result(boost::beast::http::status::ok);
668 doRead();
669 return;
670 }
671
Ed Tanous27b0cf92023-08-07 12:02:40 -0700672 if (!keepAlive)
673 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700674 BMCWEB_LOG_DEBUG("{} keepalive not set. Closing socket",
675 logPtr(this));
676
677 gracefulClose();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700678 return;
679 }
680
681 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
682 res.clear();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700683 initParser();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700684
685 userSession = nullptr;
686
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700687 req->clear();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700688 doReadHeaders();
689 }
690
Ed Tanous52e31622024-01-23 16:31:11 -0800691 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700692 {
Ed Tanous62598e32023-07-17 17:06:25 -0700693 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Ed Tanous52e31622024-01-23 16:31:11 -0800694 res.preparePayload();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700695
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800696 startDeadline();
Ed Tanous4d698612024-02-06 14:57:24 -0800697 boost::beast::async_write(
698 adaptor,
699 boost::beast::http::message_generator(std::move(res.response)),
Ed Tanous52e31622024-01-23 16:31:11 -0800700 std::bind_front(&self_type::afterDoWrite, this,
701 shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700702 }
703
Ed Tanous1abe55e2018-09-05 08:30:59 -0700704 void cancelDeadlineTimer()
705 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800706 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700707 }
708
Ed Tanous116370d2024-10-08 10:37:28 -0700709 void afterTimerWait(const std::weak_ptr<self_type>& weakSelf,
710 const boost::system::error_code& ec)
711 {
712 // Note, we are ignoring other types of errors here; If the timer
713 // failed for any reason, we should still close the connection
714 std::shared_ptr<Connection<Adaptor, Handler>> self = weakSelf.lock();
715 if (!self)
716 {
717 if (ec == boost::asio::error::operation_aborted)
718 {
719 BMCWEB_LOG_DEBUG(
720 "{} Timer canceled on connection being destroyed",
721 logPtr(self.get()));
722 }
723 else
724 {
725 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
726 logPtr(self.get()));
727 }
728 return;
729 }
730
731 self->timerStarted = false;
732
733 if (ec)
734 {
735 if (ec == boost::asio::error::operation_aborted)
736 {
737 BMCWEB_LOG_DEBUG("{} Timer canceled", logPtr(self.get()));
738 return;
739 }
740 BMCWEB_LOG_CRITICAL("{} Timer failed {}", logPtr(self.get()), ec);
741 }
742
743 BMCWEB_LOG_WARNING("{} Connection timed out, hard closing",
744 logPtr(self.get()));
745
746 self->hardClose();
747 }
748
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800749 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700750 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800751 // Timer is already started so no further action is required.
752 if (timerStarted)
753 {
754 return;
755 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700756
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800757 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800758
759 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
760 timer.expires_after(timeout);
Ed Tanous116370d2024-10-08 10:37:28 -0700761 timer.async_wait(std::bind_front(&self_type::afterTimerWait, this,
762 weak_from_this()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800763
Ed Tanous7d243eb2023-01-23 15:57:41 -0800764 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700765 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700766 }
767
Ed Tanous1abe55e2018-09-05 08:30:59 -0700768 Adaptor adaptor;
769 Handler* handler;
Ed Tanous1d1d7782024-04-09 12:54:08 -0700770
771 boost::asio::ip::address ip;
772
Ed Tanousa24526d2018-12-10 15:17:59 -0800773 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700774 // re-created on Connection reset
Ed Tanousb2896142024-01-31 15:25:47 -0800775 std::optional<boost::beast::http::request_parser<bmcweb::HttpBody>> parser;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700776
Ed Tanous3112a142018-11-29 15:45:10 -0800777 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700778
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700779 std::shared_ptr<crow::Request> req;
Ed Tanous89cda632024-04-16 08:45:54 -0700780 std::string accept;
781
Ed Tanous1abe55e2018-09-05 08:30:59 -0700782 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700783
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700784 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100785 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700786
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800787 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700788
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800789 bool keepAlive = true;
790
Ed Tanous7d243eb2023-01-23 15:57:41 -0800791 bool timerStarted = false;
792
Ed Tanous1abe55e2018-09-05 08:30:59 -0700793 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000794
795 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700796 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800797
798 using std::enable_shared_from_this<
799 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800800};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700801} // namespace crow