blob: a6773bcfcb943b40c671b8347ed48e65e514de77 [file] [log] [blame]
Ed Tanous40e9b922024-09-10 13:50:16 -07001// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright OpenBMC Authors
Ed Tanous7045c8d2017-04-03 10:04:37 -07003#pragma once
Ed Tanous75312982021-02-11 14:26:02 -08004#include "bmcweb_config.h"
Adriana Kobylak0e1cf262019-12-05 13:57:57 -06005
Ed Tanousd093c992023-01-19 19:01:49 -08006#include "async_resp.hpp"
Nan Zhoud055a342022-05-25 01:15:34 +00007#include "authentication.hpp"
Ed Tanoused5f8952023-06-22 14:06:22 -07008#include "complete_response_fields.hpp"
Ed Tanousd7857202025-01-28 15:32:26 -08009#include "forward_unauthorized.hpp"
Ed Tanousfca2cbe2021-01-28 14:49:59 -080010#include "http2_connection.hpp"
Ed Tanousb2896142024-01-31 15:25:47 -080011#include "http_body.hpp"
Ed Tanousd7857202025-01-28 15:32:26 -080012#include "http_request.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070013#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070014#include "http_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070015#include "logging.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080016#include "mutual_tls.hpp"
Ed Tanousd7857202025-01-28 15:32:26 -080017#include "sessions.hpp"
Ed Tanous18f8f602023-07-18 10:07:23 -070018#include "str_utility.hpp"
Ed Tanouscd7dbb32025-02-01 12:37:56 -080019#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070020
Ed Tanousd7857202025-01-28 15:32:26 -080021#include <boost/asio/error.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080022#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070023#include <boost/asio/ssl/stream.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080024#include <boost/asio/ssl/stream_base.hpp>
25#include <boost/asio/ssl/verify_context.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080026#include <boost/asio/steady_timer.hpp>
Ed Tanous4fa45df2023-09-01 14:20:50 -070027#include <boost/beast/_experimental/test/stream.hpp>
Ed Tanous4d698612024-02-06 14:57:24 -080028#include <boost/beast/core/buffers_generator.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080029#include <boost/beast/core/flat_static_buffer.hpp>
Myung Baea4326fe2023-01-10 14:29:24 -060030#include <boost/beast/http/error.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080031#include <boost/beast/http/field.hpp>
Ed Tanous4d698612024-02-06 14:57:24 -080032#include <boost/beast/http/message_generator.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070033#include <boost/beast/http/parser.hpp>
34#include <boost/beast/http/read.hpp>
Ed Tanouscd7dbb32025-02-01 12:37:56 -080035#include <boost/beast/http/rfc7230.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080036#include <boost/beast/http/status.hpp>
37#include <boost/beast/http/verb.hpp>
38#include <boost/none.hpp>
39#include <boost/optional/optional.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050040
Ed Tanousd7857202025-01-28 15:32:26 -080041#include <bit>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050042#include <chrono>
Ed Tanousd7857202025-01-28 15:32:26 -080043#include <cstddef>
44#include <cstdint>
45#include <functional>
Jonathan Doman102a4cd2024-04-15 16:56:23 -070046#include <memory>
Ed Tanousd7857202025-01-28 15:32:26 -080047#include <optional>
48#include <string>
49#include <string_view>
50#include <system_error>
51#include <type_traits>
52#include <utility>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050053
Ed Tanous1abe55e2018-09-05 08:30:59 -070054namespace crow
55{
Ed Tanous257f5792018-03-17 14:40:09 -070056
Ed Tanouscf9e4172022-12-21 09:30:16 -080057// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080058static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070059
Ed Tanous25b54db2024-04-17 15:40:31 -070060// request body limit size set by the BMCWEB_HTTP_BODY_LIMIT option
61constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL * BMCWEB_HTTP_BODY_LIMIT;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070062
Ed Tanous1d1d7782024-04-09 12:54:08 -070063constexpr uint64_t loggedOutPostBodyLimit = 4096U;
James Feist3909dc82020-04-03 10:58:55 -070064
Ed Tanous1d1d7782024-04-09 12:54:08 -070065constexpr uint32_t httpHeaderLimit = 8192U;
James Feist3909dc82020-04-03 10:58:55 -070066
Ed Tanous4fa45df2023-09-01 14:20:50 -070067template <typename>
68struct IsTls : std::false_type
69{};
70
71template <typename T>
Ed Tanous003301a2024-04-16 09:59:19 -070072struct IsTls<boost::asio::ssl::stream<T>> : std::true_type
Ed Tanous4fa45df2023-09-01 14:20:50 -070073{};
74
Ed Tanous52cc1122020-07-18 13:51:21 -070075template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050076class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070077 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070078{
Ed Tanous7c8e0642022-02-21 12:11:14 -080079 using self_type = Connection<Adaptor, Handler>;
80
Ed Tanous1abe55e2018-09-05 08:30:59 -070081 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080082 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000083 std::function<std::string()>& getCachedDateStrF,
Ed Tanous3281bcf2024-06-25 16:02:05 -070084 Adaptor&& adaptorIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -040085 adaptor(std::move(adaptorIn)), handler(handlerIn),
86 timer(std::move(timerIn)), getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070087 {
Ed Tanous1d1d7782024-04-09 12:54:08 -070088 initParser();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020089
Ed Tanous40aa0582021-07-14 13:24:40 -070090 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080091
Ed Tanous1d1d7782024-04-09 12:54:08 -070092 BMCWEB_LOG_DEBUG("{} Connection created, total {}", logPtr(this),
Ed Tanous62598e32023-07-17 17:06:25 -070093 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070094 }
95
96 ~Connection()
97 {
Ed Tanous1d1d7782024-04-09 12:54:08 -070098 res.releaseCompleteRequestHandler();
Ed Tanous40aa0582021-07-14 13:24:40 -070099 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800100
Ed Tanous40aa0582021-07-14 13:24:40 -0700101 connectionCount--;
Ed Tanous62598e32023-07-17 17:06:25 -0700102 BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
103 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -0700104 }
105
Ed Tanousecd6a3a2022-01-07 09:18:40 -0800106 Connection(const Connection&) = delete;
107 Connection(Connection&&) = delete;
108 Connection& operator=(const Connection&) = delete;
109 Connection& operator=(Connection&&) = delete;
110
Ed Tanous7c8e0642022-02-21 12:11:14 -0800111 bool tlsVerifyCallback(bool preverified,
112 boost::asio::ssl::verify_context& ctx)
113 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700114 BMCWEB_LOG_DEBUG("{} tlsVerifyCallback called with preverified {}",
115 logPtr(this), preverified);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800116 if (preverified)
117 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700118 mtlsSession = verifyMtlsUser(ip, ctx);
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100119 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800120 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700121 BMCWEB_LOG_DEBUG("{} Generated TLS session: {}", logPtr(this),
Ed Tanous62598e32023-07-17 17:06:25 -0700122 mtlsSession->uniqueId);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800123 }
124 }
Ed Tanous3281bcf2024-06-25 16:02:05 -0700125 const persistent_data::AuthConfigMethods& c =
126 persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
127 if (c.tlsStrict)
128 {
Ed Tanous463a0e32024-10-14 11:21:48 -0700129 BMCWEB_LOG_DEBUG(
130 "{} TLS is in strict mode, returning preverified as is.",
131 logPtr(this));
Ed Tanous3281bcf2024-06-25 16:02:05 -0700132 return preverified;
133 }
134 // If tls strict mode is disabled
135 // We always return true to allow full auth flow for resources that
136 // don't require auth
Ed Tanous7c8e0642022-02-21 12:11:14 -0800137 return true;
138 }
139
Ed Tanous3281bcf2024-06-25 16:02:05 -0700140 bool prepareMutualTls()
Ed Tanous40aa0582021-07-14 13:24:40 -0700141 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700142 if constexpr (IsTls<Adaptor>::value)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100143 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700144 BMCWEB_LOG_DEBUG("prepareMutualTls");
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100145
Ed Tanous3281bcf2024-06-25 16:02:05 -0700146 constexpr std::string_view id = "bmcweb";
147
148 const char* idPtr = id.data();
149 const auto* idCPtr = std::bit_cast<const unsigned char*>(idPtr);
150 auto idLen = static_cast<unsigned int>(id.length());
151 int ret = SSL_set_session_id_context(adaptor.native_handle(),
152 idCPtr, idLen);
153 if (ret == 0)
154 {
155 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
156 return false;
Ed Tanous4fa45df2023-09-01 14:20:50 -0700157 }
158
Ed Tanous3281bcf2024-06-25 16:02:05 -0700159 BMCWEB_LOG_DEBUG("set_verify_callback");
Ed Tanous7045c8d2017-04-03 10:04:37 -0700160
Ed Tanous3281bcf2024-06-25 16:02:05 -0700161 boost::system::error_code ec;
162 adaptor.set_verify_callback(
163 std::bind_front(&self_type::tlsVerifyCallback, this), ec);
164 if (ec)
165 {
166 BMCWEB_LOG_ERROR("Failed to set verify callback {}", ec);
167 return false;
168 }
169 }
170
171 return true;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700172 }
173
Ed Tanous1abe55e2018-09-05 08:30:59 -0700174 void start()
175 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700176 BMCWEB_LOG_DEBUG("{} Connection started, total {}", logPtr(this),
177 connectionCount);
Gunnar Mills4f63be02023-10-25 09:14:07 -0500178 if (connectionCount >= 200)
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800179 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700180 BMCWEB_LOG_CRITICAL("{} Max connection count exceeded.",
Ed Tanous62598e32023-07-17 17:06:25 -0700181 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800182 return;
183 }
184
Ed Tanous3281bcf2024-06-25 16:02:05 -0700185 if constexpr (BMCWEB_MUTUAL_TLS_AUTH)
186 {
187 if (!prepareMutualTls())
188 {
189 BMCWEB_LOG_ERROR("{} Failed to prepare mTLS", logPtr(this));
190 return;
191 }
192 }
193
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800194 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500195
Ed Tanous1d1d7782024-04-09 12:54:08 -0700196 readClientIp();
197
Ed Tanousceac6f72018-12-02 11:58:47 -0800198 // TODO(ed) Abstract this to a more clever class with the idea of an
199 // asynchronous "start"
Ed Tanous4fa45df2023-09-01 14:20:50 -0700200 if constexpr (IsTls<Adaptor>::value)
Ed Tanousceac6f72018-12-02 11:58:47 -0800201 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000202 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
203 [this, self(shared_from_this())](
204 const boost::system::error_code& ec) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400205 if (ec)
206 {
207 return;
208 }
209 afterSslHandshake();
210 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800211 }
212 else
213 {
214 doReadHeaders();
215 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700216 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700217
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800218 void afterSslHandshake()
219 {
220 // If http2 is enabled, negotiate the protocol
Ed Tanous25b54db2024-04-17 15:40:31 -0700221 if constexpr (BMCWEB_EXPERIMENTAL_HTTP2)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800222 {
223 const unsigned char* alpn = nullptr;
224 unsigned int alpnlen = 0;
225 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
226 if (alpn != nullptr)
227 {
228 std::string_view selectedProtocol(
229 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700230 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
231 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800232 if (selectedProtocol == "h2")
233 {
234 auto http2 =
235 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
236 std::move(adaptor), handler, getCachedDateStr);
237 http2->start();
238 return;
239 }
240 }
241 }
242
243 doReadHeaders();
244 }
245
Ed Tanous1d1d7782024-04-09 12:54:08 -0700246 void initParser()
247 {
248 boost::beast::http::request_parser<bmcweb::HttpBody>& instance =
Ed Tanous38afdb92024-12-11 23:57:53 -0800249 parser.emplace();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700250
251 // reset header limit for newly created parser
252 instance.header_limit(httpHeaderLimit);
253
254 // Initially set no body limit. We don't yet know if the user is
255 // authenticated.
256 instance.body_limit(boost::none);
257 }
258
Ed Tanouscd7dbb32025-02-01 12:37:56 -0800259 // returns whether connection was upgraded
260 bool doUpgrade(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
261 {
262 using boost::beast::http::field;
263 using boost::beast::http::token_list;
264
265 bool isSse =
266 isContentTypeAllowed(req->getHeaderValue("Accept"),
267 http_helpers::ContentType::EventStream, false);
268
269 bool isWebsocket = false;
270 bool isH2c = false;
271 // Check connection header is upgrade
272 if (token_list{req->req[field::connection]}.exists("upgrade"))
273 {
274 BMCWEB_LOG_DEBUG("{} Connection: Upgrade header was present",
275 logPtr(this));
276 // Parse if upgrade is h2c or websocket
277 token_list upgrade{req->req[field::upgrade]};
278 isWebsocket = upgrade.exists("websocket");
279 isH2c = upgrade.exists("h2c");
280 BMCWEB_LOG_DEBUG("{} Upgrade isWebsocket: {} isH2c: {}",
281 logPtr(this), isWebsocket, isH2c);
282 }
283
284 if (BMCWEB_EXPERIMENTAL_HTTP2 && isH2c)
285 {
286 std::string_view base64settings = req->req[field::http2_settings];
287 if (utility::base64Decode<true>(base64settings, http2settings))
288 {
289 res.result(boost::beast::http::status::switching_protocols);
290 res.addHeader(boost::beast::http::field::connection, "Upgrade");
291 res.addHeader(boost::beast::http::field::upgrade, "h2c");
292 }
293 }
294
295 // websocket and SSE are only allowed on GET
296 if (req->req.method() == boost::beast::http::verb::get)
297 {
298 if (isWebsocket || isSse)
299 {
300 asyncResp->res.setCompleteRequestHandler(
301 [self(shared_from_this())](crow::Response& thisRes) {
302 if (thisRes.result() != boost::beast::http::status::ok)
303 {
304 // When any error occurs before handle upgradation,
305 // the result in response will be set to respective
306 // error. By default the Result will be OK (200),
307 // which implies successful handle upgrade. Response
308 // needs to be sent over this connection only on
309 // failure.
310 self->completeRequest(thisRes);
311 return;
312 }
313 });
314 BMCWEB_LOG_INFO("{} Upgrading socket", logPtr(this));
315 handler->handleUpgrade(req, asyncResp, std::move(adaptor));
316 return true;
317 }
318 }
319 return false;
320 }
321
Ed Tanous1abe55e2018-09-05 08:30:59 -0700322 void handle()
323 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700324 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700325 if (!parser)
326 {
327 return;
328 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700329 req = std::make_shared<crow::Request>(parser->release(), reqEc);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700330 if (reqEc)
331 {
Ed Tanous62598e32023-07-17 17:06:25 -0700332 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600333 res.result(boost::beast::http::status::bad_request);
334 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700335 return;
336 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700337 req->session = userSession;
Ed Tanous89cda632024-04-16 08:45:54 -0700338 accept = req->getHeaderValue("Accept");
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000339 // Fetch the client IP address
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700340 req->ipAddress = ip;
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000341
Ed Tanous1abe55e2018-09-05 08:30:59 -0700342 // Check for HTTP version 1.1.
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700343 if (req->version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700344 {
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700345 if (req->getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700346 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700347 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800348 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700349 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700350 }
351 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700352
Ed Tanous62598e32023-07-17 17:06:25 -0700353 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700354 req->version() / 10, req->version() % 10,
355 req->methodString(), req->target(),
356 req->ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700357
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700358 req->ioService = static_cast<decltype(req->ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700359 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200360
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700361 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700362 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800363 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700364 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700365 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700366 keepAlive = req->keepAlive();
Ed Tanous4fa45df2023-09-01 14:20:50 -0700367 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700368 {
Ed Tanous83328312024-05-09 15:48:09 -0700369 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous4fa45df2023-09-01 14:20:50 -0700370 {
Ed Tanous83328312024-05-09 15:48:09 -0700371 if (!crow::authentication::isOnAllowlist(req->url().path(),
372 req->method()) &&
373 req->session == nullptr)
374 {
375 BMCWEB_LOG_WARNING("Authentication failed");
376 forward_unauthorized::sendUnauthorized(
377 req->url().encoded_path(),
378 req->getHeaderValue("X-Requested-With"),
379 req->getHeaderValue("Accept"), res);
380 completeRequest(res);
381 return;
382 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700383 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700384 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800385 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700386 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800387 asyncResp->res.setCompleteRequestHandler(
388 [self(shared_from_this())](crow::Response& thisRes) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400389 self->completeRequest(thisRes);
390 });
Ed Tanouscd7dbb32025-02-01 12:37:56 -0800391 if (doUpgrade(asyncResp))
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700392 {
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700393 return;
394 }
Ed Tanous291d7092022-04-13 12:34:57 -0700395 std::string_view expected =
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700396 req->getHeaderValue(boost::beast::http::field::if_none_match);
Ed Tanous291d7092022-04-13 12:34:57 -0700397 if (!expected.empty())
398 {
399 res.setExpectedHash(expected);
400 }
Ed Tanous52e31622024-01-23 16:31:11 -0800401 handler->handle(req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700402 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700403
Ed Tanous1d1d7782024-04-09 12:54:08 -0700404 void hardClose()
Ed Tanouse278c182019-03-13 16:23:37 -0700405 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700406 if (mtlsSession != nullptr)
407 {
408 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
409 mtlsSession->uniqueId);
410 persistent_data::SessionStore::getInstance().removeSession(
411 mtlsSession);
412 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700413 BMCWEB_LOG_DEBUG("{} Closing socket", logPtr(this));
414 boost::beast::get_lowest_layer(adaptor).close();
415 }
416
417 void tlsShutdownComplete(const std::shared_ptr<self_type>& self,
418 const boost::system::error_code& ec)
419 {
420 if (ec)
421 {
422 BMCWEB_LOG_WARNING("{} Failed to shut down TLS cleanly {}",
423 logPtr(self.get()), ec);
424 }
425 self->hardClose();
426 }
427
428 void gracefulClose()
429 {
430 BMCWEB_LOG_DEBUG("{} Socket close requested", logPtr(this));
Ed Tanous3281bcf2024-06-25 16:02:05 -0700431
Ed Tanous4fa45df2023-09-01 14:20:50 -0700432 if constexpr (IsTls<Adaptor>::value)
Ed Tanouse278c182019-03-13 16:23:37 -0700433 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700434 adaptor.async_shutdown(std::bind_front(
435 &self_type::tlsShutdownComplete, this, shared_from_this()));
Ed Tanouse278c182019-03-13 16:23:37 -0700436 }
437 else
438 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700439 hardClose();
Ed Tanouse278c182019-03-13 16:23:37 -0700440 }
441 }
442
Nan Zhou72374eb2022-01-27 17:06:51 -0800443 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700444 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800445 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800446 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800447
Ed Tanous89cda632024-04-16 08:45:54 -0700448 completeResponseFields(accept, res);
Ed Tanous998e0cb2023-09-06 13:57:30 -0700449 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
Ed Tanous291d7092022-04-13 12:34:57 -0700450
Ed Tanous52e31622024-01-23 16:31:11 -0800451 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000452
453 // delete lambda with self shared_ptr
454 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700455 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700456 }
457
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500458 void readClientIp()
459 {
460 boost::system::error_code ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500461
Ed Tanous4fa45df2023-09-01 14:20:50 -0700462 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500463 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700464 boost::asio::ip::tcp::endpoint endpoint =
465 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
466
467 if (ec)
468 {
469 // If remote endpoint fails keep going. "ClientOriginIPAddress"
470 // will be empty.
471 BMCWEB_LOG_ERROR(
472 "Failed to get the client's IP Address. ec : {}", ec);
Ed Tanous1d1d7782024-04-09 12:54:08 -0700473 return;
Ed Tanous4fa45df2023-09-01 14:20:50 -0700474 }
475 ip = endpoint.address();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500476 }
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500477 }
478
Ed Tanous1abe55e2018-09-05 08:30:59 -0700479 private:
Ed Tanous1d1d7782024-04-09 12:54:08 -0700480 uint64_t getContentLengthLimit()
481 {
Ed Tanous83328312024-05-09 15:48:09 -0700482 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous1d1d7782024-04-09 12:54:08 -0700483 {
Ed Tanous83328312024-05-09 15:48:09 -0700484 if (userSession == nullptr)
485 {
486 return loggedOutPostBodyLimit;
487 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700488 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700489
490 return httpReqBodyLimit;
491 }
492
493 // Returns true if content length was within limits
494 // Returns false if content length error has been returned
495 bool handleContentLengthError()
496 {
497 if (!parser)
498 {
Manojkiran Edaefff2b52024-06-18 18:01:46 +0530499 BMCWEB_LOG_CRITICAL("Parser was null");
Ed Tanous1d1d7782024-04-09 12:54:08 -0700500 return false;
501 }
502 const boost::optional<uint64_t> contentLength =
503 parser->content_length();
504 if (!contentLength)
505 {
506 BMCWEB_LOG_DEBUG("{} No content length available", logPtr(this));
507 return true;
508 }
509
510 uint64_t maxAllowedContentLength = getContentLengthLimit();
511
512 if (*contentLength > maxAllowedContentLength)
513 {
514 // If the users content limit is between the logged in
515 // and logged out limits They probably just didn't log
516 // in
517 if (*contentLength > loggedOutPostBodyLimit &&
518 *contentLength < httpReqBodyLimit)
519 {
520 BMCWEB_LOG_DEBUG(
521 "{} Content length {} valid, but greater than logged out"
522 " limit of {}. Setting unauthorized",
523 logPtr(this), *contentLength, loggedOutPostBodyLimit);
524 res.result(boost::beast::http::status::unauthorized);
525 }
526 else
527 {
528 // Otherwise they're over both limits, so inform
529 // them
530 BMCWEB_LOG_DEBUG(
531 "{} Content length {} was greater than global limit {}."
532 " Setting payload too large",
533 logPtr(this), *contentLength, httpReqBodyLimit);
534 res.result(boost::beast::http::status::payload_too_large);
535 }
536
537 keepAlive = false;
538 doWrite();
539 return false;
540 }
541
542 return true;
543 }
544
Ed Tanous116370d2024-10-08 10:37:28 -0700545 void afterReadHeaders(const std::shared_ptr<self_type>& /*self*/,
546 const boost::system::error_code& ec,
547 std::size_t bytesTransferred)
548 {
549 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
550 bytesTransferred);
551
552 if (ec)
553 {
554 cancelDeadlineTimer();
555
556 if (ec == boost::beast::http::error::header_limit)
557 {
558 BMCWEB_LOG_ERROR("{} Header field too large, closing",
559 logPtr(this), ec.message());
560
561 res.result(boost::beast::http::status::
562 request_header_fields_too_large);
563 keepAlive = false;
564 doWrite();
565 return;
566 }
567 if (ec == boost::beast::http::error::end_of_stream)
568 {
569 BMCWEB_LOG_WARNING("{} End of stream, closing {}", logPtr(this),
570 ec);
571 hardClose();
572 return;
573 }
574
575 BMCWEB_LOG_DEBUG("{} Closing socket due to read error {}",
576 logPtr(this), ec.message());
577 gracefulClose();
578
579 return;
580 }
581
582 if (!parser)
583 {
584 BMCWEB_LOG_ERROR("Parser was unexpectedly null");
585 return;
586 }
587
588 constexpr bool isTest =
589 std::is_same_v<Adaptor, boost::beast::test::stream>;
590
591 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH && !isTest)
592 {
593 boost::beast::http::verb method = parser->get().method();
594 userSession = crow::authentication::authenticate(
595 ip, res, method, parser->get().base(), mtlsSession);
596 }
597
598 std::string_view expect =
599 parser->get()[boost::beast::http::field::expect];
600 if (bmcweb::asciiIEquals(expect, "100-continue"))
601 {
602 res.result(boost::beast::http::status::continue_);
603 doWrite();
604 return;
605 }
606
607 if (!handleContentLengthError())
608 {
609 return;
610 }
611
612 parser->body_limit(getContentLengthLimit());
613
614 if (parser->is_done())
615 {
616 handle();
617 return;
618 }
619
620 doRead();
621 }
622
Ed Tanous1abe55e2018-09-05 08:30:59 -0700623 void doReadHeaders()
624 {
Ed Tanous62598e32023-07-17 17:06:25 -0700625 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700626 if (!parser)
627 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700628 BMCWEB_LOG_CRITICAL("Parser was not initialized.");
Ed Tanouse01d0c32023-06-30 13:21:32 -0700629 return;
630 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700631 // Clean up any previous Connection.
632 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800633 adaptor, buffer, *parser,
Ed Tanous116370d2024-10-08 10:37:28 -0700634 std::bind_front(&self_type::afterReadHeaders, this,
635 shared_from_this()));
636 }
Ed Tanous52e31622024-01-23 16:31:11 -0800637
Ed Tanous116370d2024-10-08 10:37:28 -0700638 void afterRead(const std::shared_ptr<self_type>& /*self*/,
639 const boost::system::error_code& ec,
640 std::size_t bytesTransferred)
641 {
642 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
643 bytesTransferred);
644
645 if (ec)
646 {
647 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
648 ec.message());
649 if (ec == boost::beast::http::error::body_limit)
650 {
651 if (handleContentLengthError())
Ed Tanous1d1d7782024-04-09 12:54:08 -0700652 {
Ed Tanous116370d2024-10-08 10:37:28 -0700653 BMCWEB_LOG_CRITICAL("Body length limit reached, "
654 "but no content-length "
655 "available? Should never happen");
656 res.result(
657 boost::beast::http::status::internal_server_error);
658 keepAlive = false;
Ed Tanous1d1d7782024-04-09 12:54:08 -0700659 doWrite();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700660 }
Ed Tanous116370d2024-10-08 10:37:28 -0700661 return;
662 }
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400663
Ed Tanous116370d2024-10-08 10:37:28 -0700664 gracefulClose();
665 return;
666 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700667
Ed Tanous116370d2024-10-08 10:37:28 -0700668 // If the user is logged in, allow them to send files
669 // incrementally one piece at a time. If authentication is
670 // disabled then there is no user session hence always allow to
671 // send one piece at a time.
672 if (userSession != nullptr)
673 {
674 cancelDeadlineTimer();
675 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700676
Ed Tanous116370d2024-10-08 10:37:28 -0700677 if (!parser)
678 {
679 BMCWEB_LOG_ERROR("Parser was unexpectedly null");
680 return;
681 }
682 if (!parser->is_done())
683 {
684 doRead();
685 return;
686 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700687
Ed Tanous116370d2024-10-08 10:37:28 -0700688 cancelDeadlineTimer();
689 handle();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700690 }
691
692 void doRead()
693 {
Ed Tanous62598e32023-07-17 17:06:25 -0700694 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700695 if (!parser)
696 {
697 return;
698 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800699 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800700 boost::beast::http::async_read_some(
701 adaptor, buffer, *parser,
Ed Tanous116370d2024-10-08 10:37:28 -0700702 std::bind_front(&self_type::afterRead, this, shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700703 }
704
Ed Tanous27b0cf92023-08-07 12:02:40 -0700705 void afterDoWrite(const std::shared_ptr<self_type>& /*self*/,
706 const boost::system::error_code& ec,
707 std::size_t bytesTransferred)
708 {
Ed Tanous0242baf2024-05-16 19:52:47 -0700709 BMCWEB_LOG_DEBUG("{} async_write wrote {} bytes, ec={}", logPtr(this),
Ed Tanous1d1d7782024-04-09 12:54:08 -0700710 bytesTransferred, ec);
Ed Tanous27b0cf92023-08-07 12:02:40 -0700711
712 cancelDeadlineTimer();
713
Ed Tanous0242baf2024-05-16 19:52:47 -0700714 if (ec == boost::system::errc::operation_would_block ||
715 ec == boost::system::errc::resource_unavailable_try_again)
716 {
717 doWrite();
718 return;
719 }
Ed Tanous27b0cf92023-08-07 12:02:40 -0700720 if (ec)
721 {
722 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
723 return;
724 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700725
Ed Tanouscd7dbb32025-02-01 12:37:56 -0800726 if (res.result() == boost::beast::http::status::switching_protocols)
727 {
728 auto http2 = std::make_shared<HTTP2Connection<Adaptor, Handler>>(
729 std::move(adaptor), handler, getCachedDateStr);
730 http2->startFromSettings(http2settings);
731 return;
732 }
733
Ed Tanous1d1d7782024-04-09 12:54:08 -0700734 if (res.result() == boost::beast::http::status::continue_)
735 {
736 // Reset the result to ok
737 res.result(boost::beast::http::status::ok);
738 doRead();
739 return;
740 }
741
Ed Tanous27b0cf92023-08-07 12:02:40 -0700742 if (!keepAlive)
743 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700744 BMCWEB_LOG_DEBUG("{} keepalive not set. Closing socket",
745 logPtr(this));
746
747 gracefulClose();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700748 return;
749 }
750
751 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
752 res.clear();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700753 initParser();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700754
755 userSession = nullptr;
756
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700757 req->clear();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700758 doReadHeaders();
759 }
760
Ed Tanous52e31622024-01-23 16:31:11 -0800761 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700762 {
Ed Tanous62598e32023-07-17 17:06:25 -0700763 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Ed Tanous52e31622024-01-23 16:31:11 -0800764 res.preparePayload();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700765
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800766 startDeadline();
Ed Tanous4d698612024-02-06 14:57:24 -0800767 boost::beast::async_write(
768 adaptor,
769 boost::beast::http::message_generator(std::move(res.response)),
Ed Tanous52e31622024-01-23 16:31:11 -0800770 std::bind_front(&self_type::afterDoWrite, this,
771 shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700772 }
773
Ed Tanous1abe55e2018-09-05 08:30:59 -0700774 void cancelDeadlineTimer()
775 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800776 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700777 }
778
Ed Tanous116370d2024-10-08 10:37:28 -0700779 void afterTimerWait(const std::weak_ptr<self_type>& weakSelf,
780 const boost::system::error_code& ec)
781 {
782 // Note, we are ignoring other types of errors here; If the timer
783 // failed for any reason, we should still close the connection
784 std::shared_ptr<Connection<Adaptor, Handler>> self = weakSelf.lock();
785 if (!self)
786 {
787 if (ec == boost::asio::error::operation_aborted)
788 {
789 BMCWEB_LOG_DEBUG(
790 "{} Timer canceled on connection being destroyed",
791 logPtr(self.get()));
792 }
793 else
794 {
795 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
796 logPtr(self.get()));
797 }
798 return;
799 }
800
801 self->timerStarted = false;
802
803 if (ec)
804 {
805 if (ec == boost::asio::error::operation_aborted)
806 {
807 BMCWEB_LOG_DEBUG("{} Timer canceled", logPtr(self.get()));
808 return;
809 }
810 BMCWEB_LOG_CRITICAL("{} Timer failed {}", logPtr(self.get()), ec);
811 }
812
813 BMCWEB_LOG_WARNING("{} Connection timed out, hard closing",
814 logPtr(self.get()));
815
816 self->hardClose();
817 }
818
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800819 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700820 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800821 // Timer is already started so no further action is required.
822 if (timerStarted)
823 {
824 return;
825 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700826
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800827 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800828
829 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
830 timer.expires_after(timeout);
Ed Tanous116370d2024-10-08 10:37:28 -0700831 timer.async_wait(std::bind_front(&self_type::afterTimerWait, this,
832 weak_from_this()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800833
Ed Tanous7d243eb2023-01-23 15:57:41 -0800834 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700835 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700836 }
837
Ed Tanous1abe55e2018-09-05 08:30:59 -0700838 Adaptor adaptor;
839 Handler* handler;
Ed Tanous1d1d7782024-04-09 12:54:08 -0700840
841 boost::asio::ip::address ip;
842
Ed Tanousa24526d2018-12-10 15:17:59 -0800843 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700844 // re-created on Connection reset
Ed Tanousb2896142024-01-31 15:25:47 -0800845 std::optional<boost::beast::http::request_parser<bmcweb::HttpBody>> parser;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700846
Ed Tanous3112a142018-11-29 15:45:10 -0800847 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700848
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700849 std::shared_ptr<crow::Request> req;
Ed Tanous89cda632024-04-16 08:45:54 -0700850 std::string accept;
Ed Tanouscd7dbb32025-02-01 12:37:56 -0800851 std::string http2settings;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700852 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700853
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700854 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100855 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700856
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800857 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700858
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800859 bool keepAlive = true;
860
Ed Tanous7d243eb2023-01-23 15:57:41 -0800861 bool timerStarted = false;
862
Ed Tanous1abe55e2018-09-05 08:30:59 -0700863 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000864
865 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700866 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800867
868 using std::enable_shared_from_this<
869 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800870};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700871} // namespace crow