blob: 70693311632d0f7946fd1c86ed54173493e7e696 [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 Tanous1abe55e2018-09-05 08:30:59 -070019
Ed Tanousd7857202025-01-28 15:32:26 -080020#include <boost/asio/error.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080021#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070022#include <boost/asio/ssl/stream.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080023#include <boost/asio/ssl/stream_base.hpp>
24#include <boost/asio/ssl/verify_context.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080025#include <boost/asio/steady_timer.hpp>
Ed Tanous4fa45df2023-09-01 14:20:50 -070026#include <boost/beast/_experimental/test/stream.hpp>
Ed Tanous4d698612024-02-06 14:57:24 -080027#include <boost/beast/core/buffers_generator.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080028#include <boost/beast/core/flat_static_buffer.hpp>
Myung Baea4326fe2023-01-10 14:29:24 -060029#include <boost/beast/http/error.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080030#include <boost/beast/http/field.hpp>
Ed Tanous4d698612024-02-06 14:57:24 -080031#include <boost/beast/http/message_generator.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070032#include <boost/beast/http/parser.hpp>
33#include <boost/beast/http/read.hpp>
Ed Tanousd7857202025-01-28 15:32:26 -080034#include <boost/beast/http/status.hpp>
35#include <boost/beast/http/verb.hpp>
36#include <boost/none.hpp>
37#include <boost/optional/optional.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050038
Ed Tanousd7857202025-01-28 15:32:26 -080039#include <bit>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050040#include <chrono>
Ed Tanousd7857202025-01-28 15:32:26 -080041#include <cstddef>
42#include <cstdint>
43#include <functional>
Jonathan Doman102a4cd2024-04-15 16:56:23 -070044#include <memory>
Ed Tanousd7857202025-01-28 15:32:26 -080045#include <optional>
46#include <string>
47#include <string_view>
48#include <system_error>
49#include <type_traits>
50#include <utility>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050051
Ed Tanous1abe55e2018-09-05 08:30:59 -070052namespace crow
53{
Ed Tanous257f5792018-03-17 14:40:09 -070054
Ed Tanouscf9e4172022-12-21 09:30:16 -080055// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080056static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070057
Ed Tanous25b54db2024-04-17 15:40:31 -070058// request body limit size set by the BMCWEB_HTTP_BODY_LIMIT option
59constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL * BMCWEB_HTTP_BODY_LIMIT;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070060
Ed Tanous1d1d7782024-04-09 12:54:08 -070061constexpr uint64_t loggedOutPostBodyLimit = 4096U;
James Feist3909dc82020-04-03 10:58:55 -070062
Ed Tanous1d1d7782024-04-09 12:54:08 -070063constexpr uint32_t httpHeaderLimit = 8192U;
James Feist3909dc82020-04-03 10:58:55 -070064
Ed Tanous4fa45df2023-09-01 14:20:50 -070065template <typename>
66struct IsTls : std::false_type
67{};
68
69template <typename T>
Ed Tanous003301a2024-04-16 09:59:19 -070070struct IsTls<boost::asio::ssl::stream<T>> : std::true_type
Ed Tanous4fa45df2023-09-01 14:20:50 -070071{};
72
Ed Tanous52cc1122020-07-18 13:51:21 -070073template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050074class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070075 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070076{
Ed Tanous7c8e0642022-02-21 12:11:14 -080077 using self_type = Connection<Adaptor, Handler>;
78
Ed Tanous1abe55e2018-09-05 08:30:59 -070079 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080080 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000081 std::function<std::string()>& getCachedDateStrF,
Ed Tanous3281bcf2024-06-25 16:02:05 -070082 Adaptor&& adaptorIn) :
Patrick Williamsbd79bce2024-08-16 15:22:20 -040083 adaptor(std::move(adaptorIn)), handler(handlerIn),
84 timer(std::move(timerIn)), getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070085 {
Ed Tanous1d1d7782024-04-09 12:54:08 -070086 initParser();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020087
Ed Tanous40aa0582021-07-14 13:24:40 -070088 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080089
Ed Tanous1d1d7782024-04-09 12:54:08 -070090 BMCWEB_LOG_DEBUG("{} Connection created, total {}", logPtr(this),
Ed Tanous62598e32023-07-17 17:06:25 -070091 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070092 }
93
94 ~Connection()
95 {
Ed Tanous1d1d7782024-04-09 12:54:08 -070096 res.releaseCompleteRequestHandler();
Ed Tanous40aa0582021-07-14 13:24:40 -070097 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080098
Ed Tanous40aa0582021-07-14 13:24:40 -070099 connectionCount--;
Ed Tanous62598e32023-07-17 17:06:25 -0700100 BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
101 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -0700102 }
103
Ed Tanousecd6a3a2022-01-07 09:18:40 -0800104 Connection(const Connection&) = delete;
105 Connection(Connection&&) = delete;
106 Connection& operator=(const Connection&) = delete;
107 Connection& operator=(Connection&&) = delete;
108
Ed Tanous7c8e0642022-02-21 12:11:14 -0800109 bool tlsVerifyCallback(bool preverified,
110 boost::asio::ssl::verify_context& ctx)
111 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700112 BMCWEB_LOG_DEBUG("{} tlsVerifyCallback called with preverified {}",
113 logPtr(this), preverified);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800114 if (preverified)
115 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700116 mtlsSession = verifyMtlsUser(ip, ctx);
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100117 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800118 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700119 BMCWEB_LOG_DEBUG("{} Generated TLS session: {}", logPtr(this),
Ed Tanous62598e32023-07-17 17:06:25 -0700120 mtlsSession->uniqueId);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800121 }
122 }
Ed Tanous3281bcf2024-06-25 16:02:05 -0700123 const persistent_data::AuthConfigMethods& c =
124 persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
125 if (c.tlsStrict)
126 {
Ed Tanous463a0e32024-10-14 11:21:48 -0700127 BMCWEB_LOG_DEBUG(
128 "{} TLS is in strict mode, returning preverified as is.",
129 logPtr(this));
Ed Tanous3281bcf2024-06-25 16:02:05 -0700130 return preverified;
131 }
132 // If tls strict mode is disabled
133 // We always return true to allow full auth flow for resources that
134 // don't require auth
Ed Tanous7c8e0642022-02-21 12:11:14 -0800135 return true;
136 }
137
Ed Tanous3281bcf2024-06-25 16:02:05 -0700138 bool prepareMutualTls()
Ed Tanous40aa0582021-07-14 13:24:40 -0700139 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700140 if constexpr (IsTls<Adaptor>::value)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100141 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700142 BMCWEB_LOG_DEBUG("prepareMutualTls");
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100143
Ed Tanous3281bcf2024-06-25 16:02:05 -0700144 constexpr std::string_view id = "bmcweb";
145
146 const char* idPtr = id.data();
147 const auto* idCPtr = std::bit_cast<const unsigned char*>(idPtr);
148 auto idLen = static_cast<unsigned int>(id.length());
149 int ret = SSL_set_session_id_context(adaptor.native_handle(),
150 idCPtr, idLen);
151 if (ret == 0)
152 {
153 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
154 return false;
Ed Tanous4fa45df2023-09-01 14:20:50 -0700155 }
156
Ed Tanous3281bcf2024-06-25 16:02:05 -0700157 BMCWEB_LOG_DEBUG("set_verify_callback");
Ed Tanous7045c8d2017-04-03 10:04:37 -0700158
Ed Tanous3281bcf2024-06-25 16:02:05 -0700159 boost::system::error_code ec;
160 adaptor.set_verify_callback(
161 std::bind_front(&self_type::tlsVerifyCallback, this), ec);
162 if (ec)
163 {
164 BMCWEB_LOG_ERROR("Failed to set verify callback {}", ec);
165 return false;
166 }
167 }
168
169 return true;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700170 }
171
Ed Tanous1abe55e2018-09-05 08:30:59 -0700172 void start()
173 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700174 BMCWEB_LOG_DEBUG("{} Connection started, total {}", logPtr(this),
175 connectionCount);
Gunnar Mills4f63be02023-10-25 09:14:07 -0500176 if (connectionCount >= 200)
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800177 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700178 BMCWEB_LOG_CRITICAL("{} Max connection count exceeded.",
Ed Tanous62598e32023-07-17 17:06:25 -0700179 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800180 return;
181 }
182
Ed Tanous3281bcf2024-06-25 16:02:05 -0700183 if constexpr (BMCWEB_MUTUAL_TLS_AUTH)
184 {
185 if (!prepareMutualTls())
186 {
187 BMCWEB_LOG_ERROR("{} Failed to prepare mTLS", logPtr(this));
188 return;
189 }
190 }
191
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800192 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500193
Ed Tanous1d1d7782024-04-09 12:54:08 -0700194 readClientIp();
195
Ed Tanousceac6f72018-12-02 11:58:47 -0800196 // TODO(ed) Abstract this to a more clever class with the idea of an
197 // asynchronous "start"
Ed Tanous4fa45df2023-09-01 14:20:50 -0700198 if constexpr (IsTls<Adaptor>::value)
Ed Tanousceac6f72018-12-02 11:58:47 -0800199 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000200 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
201 [this, self(shared_from_this())](
202 const boost::system::error_code& ec) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400203 if (ec)
204 {
205 return;
206 }
207 afterSslHandshake();
208 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800209 }
210 else
211 {
212 doReadHeaders();
213 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700214 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700215
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800216 void afterSslHandshake()
217 {
218 // If http2 is enabled, negotiate the protocol
Ed Tanous25b54db2024-04-17 15:40:31 -0700219 if constexpr (BMCWEB_EXPERIMENTAL_HTTP2)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800220 {
221 const unsigned char* alpn = nullptr;
222 unsigned int alpnlen = 0;
223 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
224 if (alpn != nullptr)
225 {
226 std::string_view selectedProtocol(
227 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700228 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
229 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800230 if (selectedProtocol == "h2")
231 {
232 auto http2 =
233 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
234 std::move(adaptor), handler, getCachedDateStr);
235 http2->start();
236 return;
237 }
238 }
239 }
240
241 doReadHeaders();
242 }
243
Ed Tanous1d1d7782024-04-09 12:54:08 -0700244 void initParser()
245 {
246 boost::beast::http::request_parser<bmcweb::HttpBody>& instance =
Ed Tanous38afdb92024-12-11 23:57:53 -0800247 parser.emplace();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700248
249 // reset header limit for newly created parser
250 instance.header_limit(httpHeaderLimit);
251
252 // Initially set no body limit. We don't yet know if the user is
253 // authenticated.
254 instance.body_limit(boost::none);
255 }
256
Ed Tanous1abe55e2018-09-05 08:30:59 -0700257 void handle()
258 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700259 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700260 if (!parser)
261 {
262 return;
263 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700264 req = std::make_shared<crow::Request>(parser->release(), reqEc);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700265 if (reqEc)
266 {
Ed Tanous62598e32023-07-17 17:06:25 -0700267 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600268 res.result(boost::beast::http::status::bad_request);
269 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700270 return;
271 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700272 req->session = userSession;
Ed Tanous89cda632024-04-16 08:45:54 -0700273 accept = req->getHeaderValue("Accept");
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000274 // Fetch the client IP address
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700275 req->ipAddress = ip;
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000276
Ed Tanous1abe55e2018-09-05 08:30:59 -0700277 // Check for HTTP version 1.1.
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700278 if (req->version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700279 {
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700280 if (req->getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700281 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700282 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800283 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700284 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700285 }
286 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700287
Ed Tanous62598e32023-07-17 17:06:25 -0700288 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700289 req->version() / 10, req->version() % 10,
290 req->methodString(), req->target(),
291 req->ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700292
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700293 req->ioService = static_cast<decltype(req->ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700294 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200295
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700296 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700297 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800298 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700299 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700300 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700301 keepAlive = req->keepAlive();
Ed Tanous4fa45df2023-09-01 14:20:50 -0700302 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700303 {
Ed Tanous83328312024-05-09 15:48:09 -0700304 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous4fa45df2023-09-01 14:20:50 -0700305 {
Ed Tanous83328312024-05-09 15:48:09 -0700306 if (!crow::authentication::isOnAllowlist(req->url().path(),
307 req->method()) &&
308 req->session == nullptr)
309 {
310 BMCWEB_LOG_WARNING("Authentication failed");
311 forward_unauthorized::sendUnauthorized(
312 req->url().encoded_path(),
313 req->getHeaderValue("X-Requested-With"),
314 req->getHeaderValue("Accept"), res);
315 completeRequest(res);
316 return;
317 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700318 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700319 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800320 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700321 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800322 asyncResp->res.setCompleteRequestHandler(
323 [self(shared_from_this())](crow::Response& thisRes) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400324 self->completeRequest(thisRes);
325 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700326 bool isSse =
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700327 isContentTypeAllowed(req->getHeaderValue("Accept"),
Ed Tanous6fde95f2023-06-01 07:33:34 -0700328 http_helpers::ContentType::EventStream, false);
Ed Tanous18f8f602023-07-18 10:07:23 -0700329 std::string_view upgradeType(
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700330 req->getHeaderValue(boost::beast::http::field::upgrade));
331 if ((req->isUpgrade() &&
Ed Tanous18f8f602023-07-18 10:07:23 -0700332 bmcweb::asciiIEquals(upgradeType, "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700333 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700334 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530335 asyncResp->res.setCompleteRequestHandler(
336 [self(shared_from_this())](crow::Response& thisRes) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400337 if (thisRes.result() != boost::beast::http::status::ok)
338 {
339 // When any error occurs before handle upgradation,
340 // the result in response will be set to respective
341 // error. By default the Result will be OK (200),
342 // which implies successful handle upgrade. Response
343 // needs to be sent over this connection only on
344 // failure.
345 self->completeRequest(thisRes);
346 return;
347 }
348 });
Ed Tanous52e31622024-01-23 16:31:11 -0800349 handler->handleUpgrade(req, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700350 return;
351 }
Ed Tanous291d7092022-04-13 12:34:57 -0700352 std::string_view expected =
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700353 req->getHeaderValue(boost::beast::http::field::if_none_match);
Ed Tanous291d7092022-04-13 12:34:57 -0700354 if (!expected.empty())
355 {
356 res.setExpectedHash(expected);
357 }
Ed Tanous52e31622024-01-23 16:31:11 -0800358 handler->handle(req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700359 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700360
Ed Tanous1d1d7782024-04-09 12:54:08 -0700361 void hardClose()
Ed Tanouse278c182019-03-13 16:23:37 -0700362 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700363 if (mtlsSession != nullptr)
364 {
365 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
366 mtlsSession->uniqueId);
367 persistent_data::SessionStore::getInstance().removeSession(
368 mtlsSession);
369 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700370 BMCWEB_LOG_DEBUG("{} Closing socket", logPtr(this));
371 boost::beast::get_lowest_layer(adaptor).close();
372 }
373
374 void tlsShutdownComplete(const std::shared_ptr<self_type>& self,
375 const boost::system::error_code& ec)
376 {
377 if (ec)
378 {
379 BMCWEB_LOG_WARNING("{} Failed to shut down TLS cleanly {}",
380 logPtr(self.get()), ec);
381 }
382 self->hardClose();
383 }
384
385 void gracefulClose()
386 {
387 BMCWEB_LOG_DEBUG("{} Socket close requested", logPtr(this));
Ed Tanous3281bcf2024-06-25 16:02:05 -0700388
Ed Tanous4fa45df2023-09-01 14:20:50 -0700389 if constexpr (IsTls<Adaptor>::value)
Ed Tanouse278c182019-03-13 16:23:37 -0700390 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700391 adaptor.async_shutdown(std::bind_front(
392 &self_type::tlsShutdownComplete, this, shared_from_this()));
Ed Tanouse278c182019-03-13 16:23:37 -0700393 }
394 else
395 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700396 hardClose();
Ed Tanouse278c182019-03-13 16:23:37 -0700397 }
398 }
399
Nan Zhou72374eb2022-01-27 17:06:51 -0800400 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700401 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800402 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800403 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800404
Ed Tanous89cda632024-04-16 08:45:54 -0700405 completeResponseFields(accept, res);
Ed Tanous998e0cb2023-09-06 13:57:30 -0700406 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
Ed Tanous291d7092022-04-13 12:34:57 -0700407
Ed Tanous52e31622024-01-23 16:31:11 -0800408 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000409
410 // delete lambda with self shared_ptr
411 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700412 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700413 }
414
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500415 void readClientIp()
416 {
417 boost::system::error_code ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500418
Ed Tanous4fa45df2023-09-01 14:20:50 -0700419 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500420 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700421 boost::asio::ip::tcp::endpoint endpoint =
422 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
423
424 if (ec)
425 {
426 // If remote endpoint fails keep going. "ClientOriginIPAddress"
427 // will be empty.
428 BMCWEB_LOG_ERROR(
429 "Failed to get the client's IP Address. ec : {}", ec);
Ed Tanous1d1d7782024-04-09 12:54:08 -0700430 return;
Ed Tanous4fa45df2023-09-01 14:20:50 -0700431 }
432 ip = endpoint.address();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500433 }
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500434 }
435
Ed Tanous1abe55e2018-09-05 08:30:59 -0700436 private:
Ed Tanous1d1d7782024-04-09 12:54:08 -0700437 uint64_t getContentLengthLimit()
438 {
Ed Tanous83328312024-05-09 15:48:09 -0700439 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous1d1d7782024-04-09 12:54:08 -0700440 {
Ed Tanous83328312024-05-09 15:48:09 -0700441 if (userSession == nullptr)
442 {
443 return loggedOutPostBodyLimit;
444 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700445 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700446
447 return httpReqBodyLimit;
448 }
449
450 // Returns true if content length was within limits
451 // Returns false if content length error has been returned
452 bool handleContentLengthError()
453 {
454 if (!parser)
455 {
Manojkiran Edaefff2b52024-06-18 18:01:46 +0530456 BMCWEB_LOG_CRITICAL("Parser was null");
Ed Tanous1d1d7782024-04-09 12:54:08 -0700457 return false;
458 }
459 const boost::optional<uint64_t> contentLength =
460 parser->content_length();
461 if (!contentLength)
462 {
463 BMCWEB_LOG_DEBUG("{} No content length available", logPtr(this));
464 return true;
465 }
466
467 uint64_t maxAllowedContentLength = getContentLengthLimit();
468
469 if (*contentLength > maxAllowedContentLength)
470 {
471 // If the users content limit is between the logged in
472 // and logged out limits They probably just didn't log
473 // in
474 if (*contentLength > loggedOutPostBodyLimit &&
475 *contentLength < httpReqBodyLimit)
476 {
477 BMCWEB_LOG_DEBUG(
478 "{} Content length {} valid, but greater than logged out"
479 " limit of {}. Setting unauthorized",
480 logPtr(this), *contentLength, loggedOutPostBodyLimit);
481 res.result(boost::beast::http::status::unauthorized);
482 }
483 else
484 {
485 // Otherwise they're over both limits, so inform
486 // them
487 BMCWEB_LOG_DEBUG(
488 "{} Content length {} was greater than global limit {}."
489 " Setting payload too large",
490 logPtr(this), *contentLength, httpReqBodyLimit);
491 res.result(boost::beast::http::status::payload_too_large);
492 }
493
494 keepAlive = false;
495 doWrite();
496 return false;
497 }
498
499 return true;
500 }
501
Ed Tanous116370d2024-10-08 10:37:28 -0700502 void afterReadHeaders(const std::shared_ptr<self_type>& /*self*/,
503 const boost::system::error_code& ec,
504 std::size_t bytesTransferred)
505 {
506 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
507 bytesTransferred);
508
509 if (ec)
510 {
511 cancelDeadlineTimer();
512
513 if (ec == boost::beast::http::error::header_limit)
514 {
515 BMCWEB_LOG_ERROR("{} Header field too large, closing",
516 logPtr(this), ec.message());
517
518 res.result(boost::beast::http::status::
519 request_header_fields_too_large);
520 keepAlive = false;
521 doWrite();
522 return;
523 }
524 if (ec == boost::beast::http::error::end_of_stream)
525 {
526 BMCWEB_LOG_WARNING("{} End of stream, closing {}", logPtr(this),
527 ec);
528 hardClose();
529 return;
530 }
531
532 BMCWEB_LOG_DEBUG("{} Closing socket due to read error {}",
533 logPtr(this), ec.message());
534 gracefulClose();
535
536 return;
537 }
538
539 if (!parser)
540 {
541 BMCWEB_LOG_ERROR("Parser was unexpectedly null");
542 return;
543 }
544
545 constexpr bool isTest =
546 std::is_same_v<Adaptor, boost::beast::test::stream>;
547
548 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH && !isTest)
549 {
550 boost::beast::http::verb method = parser->get().method();
551 userSession = crow::authentication::authenticate(
552 ip, res, method, parser->get().base(), mtlsSession);
553 }
554
555 std::string_view expect =
556 parser->get()[boost::beast::http::field::expect];
557 if (bmcweb::asciiIEquals(expect, "100-continue"))
558 {
559 res.result(boost::beast::http::status::continue_);
560 doWrite();
561 return;
562 }
563
564 if (!handleContentLengthError())
565 {
566 return;
567 }
568
569 parser->body_limit(getContentLengthLimit());
570
571 if (parser->is_done())
572 {
573 handle();
574 return;
575 }
576
577 doRead();
578 }
579
Ed Tanous1abe55e2018-09-05 08:30:59 -0700580 void doReadHeaders()
581 {
Ed Tanous62598e32023-07-17 17:06:25 -0700582 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700583 if (!parser)
584 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700585 BMCWEB_LOG_CRITICAL("Parser was not initialized.");
Ed Tanouse01d0c32023-06-30 13:21:32 -0700586 return;
587 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700588 // Clean up any previous Connection.
589 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800590 adaptor, buffer, *parser,
Ed Tanous116370d2024-10-08 10:37:28 -0700591 std::bind_front(&self_type::afterReadHeaders, this,
592 shared_from_this()));
593 }
Ed Tanous52e31622024-01-23 16:31:11 -0800594
Ed Tanous116370d2024-10-08 10:37:28 -0700595 void afterRead(const std::shared_ptr<self_type>& /*self*/,
596 const boost::system::error_code& ec,
597 std::size_t bytesTransferred)
598 {
599 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
600 bytesTransferred);
601
602 if (ec)
603 {
604 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
605 ec.message());
606 if (ec == boost::beast::http::error::body_limit)
607 {
608 if (handleContentLengthError())
Ed Tanous1d1d7782024-04-09 12:54:08 -0700609 {
Ed Tanous116370d2024-10-08 10:37:28 -0700610 BMCWEB_LOG_CRITICAL("Body length limit reached, "
611 "but no content-length "
612 "available? Should never happen");
613 res.result(
614 boost::beast::http::status::internal_server_error);
615 keepAlive = false;
Ed Tanous1d1d7782024-04-09 12:54:08 -0700616 doWrite();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700617 }
Ed Tanous116370d2024-10-08 10:37:28 -0700618 return;
619 }
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400620
Ed Tanous116370d2024-10-08 10:37:28 -0700621 gracefulClose();
622 return;
623 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700624
Ed Tanous116370d2024-10-08 10:37:28 -0700625 // If the user is logged in, allow them to send files
626 // incrementally one piece at a time. If authentication is
627 // disabled then there is no user session hence always allow to
628 // send one piece at a time.
629 if (userSession != nullptr)
630 {
631 cancelDeadlineTimer();
632 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700633
Ed Tanous116370d2024-10-08 10:37:28 -0700634 if (!parser)
635 {
636 BMCWEB_LOG_ERROR("Parser was unexpectedly null");
637 return;
638 }
639 if (!parser->is_done())
640 {
641 doRead();
642 return;
643 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700644
Ed Tanous116370d2024-10-08 10:37:28 -0700645 cancelDeadlineTimer();
646 handle();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700647 }
648
649 void doRead()
650 {
Ed Tanous62598e32023-07-17 17:06:25 -0700651 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700652 if (!parser)
653 {
654 return;
655 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800656 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800657 boost::beast::http::async_read_some(
658 adaptor, buffer, *parser,
Ed Tanous116370d2024-10-08 10:37:28 -0700659 std::bind_front(&self_type::afterRead, this, shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700660 }
661
Ed Tanous27b0cf92023-08-07 12:02:40 -0700662 void afterDoWrite(const std::shared_ptr<self_type>& /*self*/,
663 const boost::system::error_code& ec,
664 std::size_t bytesTransferred)
665 {
Ed Tanous0242baf2024-05-16 19:52:47 -0700666 BMCWEB_LOG_DEBUG("{} async_write wrote {} bytes, ec={}", logPtr(this),
Ed Tanous1d1d7782024-04-09 12:54:08 -0700667 bytesTransferred, ec);
Ed Tanous27b0cf92023-08-07 12:02:40 -0700668
669 cancelDeadlineTimer();
670
Ed Tanous0242baf2024-05-16 19:52:47 -0700671 if (ec == boost::system::errc::operation_would_block ||
672 ec == boost::system::errc::resource_unavailable_try_again)
673 {
674 doWrite();
675 return;
676 }
Ed Tanous27b0cf92023-08-07 12:02:40 -0700677 if (ec)
678 {
679 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
680 return;
681 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700682
683 if (res.result() == boost::beast::http::status::continue_)
684 {
685 // Reset the result to ok
686 res.result(boost::beast::http::status::ok);
687 doRead();
688 return;
689 }
690
Ed Tanous27b0cf92023-08-07 12:02:40 -0700691 if (!keepAlive)
692 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700693 BMCWEB_LOG_DEBUG("{} keepalive not set. Closing socket",
694 logPtr(this));
695
696 gracefulClose();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700697 return;
698 }
699
700 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
701 res.clear();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700702 initParser();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700703
704 userSession = nullptr;
705
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700706 req->clear();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700707 doReadHeaders();
708 }
709
Ed Tanous52e31622024-01-23 16:31:11 -0800710 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700711 {
Ed Tanous62598e32023-07-17 17:06:25 -0700712 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Ed Tanous52e31622024-01-23 16:31:11 -0800713 res.preparePayload();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700714
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800715 startDeadline();
Ed Tanous4d698612024-02-06 14:57:24 -0800716 boost::beast::async_write(
717 adaptor,
718 boost::beast::http::message_generator(std::move(res.response)),
Ed Tanous52e31622024-01-23 16:31:11 -0800719 std::bind_front(&self_type::afterDoWrite, this,
720 shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700721 }
722
Ed Tanous1abe55e2018-09-05 08:30:59 -0700723 void cancelDeadlineTimer()
724 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800725 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700726 }
727
Ed Tanous116370d2024-10-08 10:37:28 -0700728 void afterTimerWait(const std::weak_ptr<self_type>& weakSelf,
729 const boost::system::error_code& ec)
730 {
731 // Note, we are ignoring other types of errors here; If the timer
732 // failed for any reason, we should still close the connection
733 std::shared_ptr<Connection<Adaptor, Handler>> self = weakSelf.lock();
734 if (!self)
735 {
736 if (ec == boost::asio::error::operation_aborted)
737 {
738 BMCWEB_LOG_DEBUG(
739 "{} Timer canceled on connection being destroyed",
740 logPtr(self.get()));
741 }
742 else
743 {
744 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
745 logPtr(self.get()));
746 }
747 return;
748 }
749
750 self->timerStarted = false;
751
752 if (ec)
753 {
754 if (ec == boost::asio::error::operation_aborted)
755 {
756 BMCWEB_LOG_DEBUG("{} Timer canceled", logPtr(self.get()));
757 return;
758 }
759 BMCWEB_LOG_CRITICAL("{} Timer failed {}", logPtr(self.get()), ec);
760 }
761
762 BMCWEB_LOG_WARNING("{} Connection timed out, hard closing",
763 logPtr(self.get()));
764
765 self->hardClose();
766 }
767
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800768 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700769 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800770 // Timer is already started so no further action is required.
771 if (timerStarted)
772 {
773 return;
774 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700775
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800776 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800777
778 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
779 timer.expires_after(timeout);
Ed Tanous116370d2024-10-08 10:37:28 -0700780 timer.async_wait(std::bind_front(&self_type::afterTimerWait, this,
781 weak_from_this()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800782
Ed Tanous7d243eb2023-01-23 15:57:41 -0800783 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700784 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700785 }
786
Ed Tanous1abe55e2018-09-05 08:30:59 -0700787 Adaptor adaptor;
788 Handler* handler;
Ed Tanous1d1d7782024-04-09 12:54:08 -0700789
790 boost::asio::ip::address ip;
791
Ed Tanousa24526d2018-12-10 15:17:59 -0800792 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700793 // re-created on Connection reset
Ed Tanousb2896142024-01-31 15:25:47 -0800794 std::optional<boost::beast::http::request_parser<bmcweb::HttpBody>> parser;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700795
Ed Tanous3112a142018-11-29 15:45:10 -0800796 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700797
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700798 std::shared_ptr<crow::Request> req;
Ed Tanous89cda632024-04-16 08:45:54 -0700799 std::string accept;
800
Ed Tanous1abe55e2018-09-05 08:30:59 -0700801 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700802
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700803 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100804 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700805
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800806 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700807
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800808 bool keepAlive = true;
809
Ed Tanous7d243eb2023-01-23 15:57:41 -0800810 bool timerStarted = false;
811
Ed Tanous1abe55e2018-09-05 08:30:59 -0700812 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000813
814 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700815 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800816
817 using std::enable_shared_from_this<
818 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800819};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700820} // namespace crow