blob: 29d4fc82ab6666eef41c32b213b0679a58270feb [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 {
Ed Tanous463a0e32024-10-14 11:21:48 -0700111 BMCWEB_LOG_DEBUG(
112 "{} TLS is in strict mode, returning preverified as is.",
113 logPtr(this));
Ed Tanous3281bcf2024-06-25 16:02:05 -0700114 return preverified;
115 }
116 // If tls strict mode is disabled
117 // We always return true to allow full auth flow for resources that
118 // don't require auth
Ed Tanous7c8e0642022-02-21 12:11:14 -0800119 return true;
120 }
121
Ed Tanous3281bcf2024-06-25 16:02:05 -0700122 bool prepareMutualTls()
Ed Tanous40aa0582021-07-14 13:24:40 -0700123 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700124 if constexpr (IsTls<Adaptor>::value)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100125 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700126 BMCWEB_LOG_DEBUG("prepareMutualTls");
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100127
Ed Tanous3281bcf2024-06-25 16:02:05 -0700128 constexpr std::string_view id = "bmcweb";
129
130 const char* idPtr = id.data();
131 const auto* idCPtr = std::bit_cast<const unsigned char*>(idPtr);
132 auto idLen = static_cast<unsigned int>(id.length());
133 int ret = SSL_set_session_id_context(adaptor.native_handle(),
134 idCPtr, idLen);
135 if (ret == 0)
136 {
137 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
138 return false;
Ed Tanous4fa45df2023-09-01 14:20:50 -0700139 }
140
Ed Tanous3281bcf2024-06-25 16:02:05 -0700141 BMCWEB_LOG_DEBUG("set_verify_callback");
Ed Tanous7045c8d2017-04-03 10:04:37 -0700142
Ed Tanous3281bcf2024-06-25 16:02:05 -0700143 boost::system::error_code ec;
144 adaptor.set_verify_callback(
145 std::bind_front(&self_type::tlsVerifyCallback, this), ec);
146 if (ec)
147 {
148 BMCWEB_LOG_ERROR("Failed to set verify callback {}", ec);
149 return false;
150 }
151 }
152
153 return true;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700154 }
155
Ed Tanous1abe55e2018-09-05 08:30:59 -0700156 void start()
157 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700158 BMCWEB_LOG_DEBUG("{} Connection started, total {}", logPtr(this),
159 connectionCount);
Gunnar Mills4f63be02023-10-25 09:14:07 -0500160 if (connectionCount >= 200)
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800161 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700162 BMCWEB_LOG_CRITICAL("{} Max connection count exceeded.",
Ed Tanous62598e32023-07-17 17:06:25 -0700163 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800164 return;
165 }
166
Ed Tanous3281bcf2024-06-25 16:02:05 -0700167 if constexpr (BMCWEB_MUTUAL_TLS_AUTH)
168 {
169 if (!prepareMutualTls())
170 {
171 BMCWEB_LOG_ERROR("{} Failed to prepare mTLS", logPtr(this));
172 return;
173 }
174 }
175
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800176 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500177
Ed Tanous1d1d7782024-04-09 12:54:08 -0700178 readClientIp();
179
Ed Tanousceac6f72018-12-02 11:58:47 -0800180 // TODO(ed) Abstract this to a more clever class with the idea of an
181 // asynchronous "start"
Ed Tanous4fa45df2023-09-01 14:20:50 -0700182 if constexpr (IsTls<Adaptor>::value)
Ed Tanousceac6f72018-12-02 11:58:47 -0800183 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000184 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
185 [this, self(shared_from_this())](
186 const boost::system::error_code& ec) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400187 if (ec)
188 {
189 return;
190 }
191 afterSslHandshake();
192 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800193 }
194 else
195 {
196 doReadHeaders();
197 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700198 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700199
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800200 void afterSslHandshake()
201 {
202 // If http2 is enabled, negotiate the protocol
Ed Tanous25b54db2024-04-17 15:40:31 -0700203 if constexpr (BMCWEB_EXPERIMENTAL_HTTP2)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800204 {
205 const unsigned char* alpn = nullptr;
206 unsigned int alpnlen = 0;
207 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
208 if (alpn != nullptr)
209 {
210 std::string_view selectedProtocol(
211 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700212 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
213 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800214 if (selectedProtocol == "h2")
215 {
216 auto http2 =
217 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
218 std::move(adaptor), handler, getCachedDateStr);
219 http2->start();
220 return;
221 }
222 }
223 }
224
225 doReadHeaders();
226 }
227
Ed Tanous1d1d7782024-04-09 12:54:08 -0700228 void initParser()
229 {
230 boost::beast::http::request_parser<bmcweb::HttpBody>& instance =
231 parser.emplace(std::piecewise_construct, std::make_tuple());
232
233 // reset header limit for newly created parser
234 instance.header_limit(httpHeaderLimit);
235
236 // Initially set no body limit. We don't yet know if the user is
237 // authenticated.
238 instance.body_limit(boost::none);
239 }
240
Ed Tanous1abe55e2018-09-05 08:30:59 -0700241 void handle()
242 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700243 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700244 if (!parser)
245 {
246 return;
247 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700248 req = std::make_shared<crow::Request>(parser->release(), reqEc);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700249 if (reqEc)
250 {
Ed Tanous62598e32023-07-17 17:06:25 -0700251 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600252 res.result(boost::beast::http::status::bad_request);
253 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700254 return;
255 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700256 req->session = userSession;
Ed Tanous89cda632024-04-16 08:45:54 -0700257 accept = req->getHeaderValue("Accept");
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000258 // Fetch the client IP address
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700259 req->ipAddress = ip;
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000260
Ed Tanous1abe55e2018-09-05 08:30:59 -0700261 // Check for HTTP version 1.1.
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700262 if (req->version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700263 {
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700264 if (req->getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700265 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700266 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800267 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700268 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700269 }
270 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700271
Ed Tanous62598e32023-07-17 17:06:25 -0700272 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700273 req->version() / 10, req->version() % 10,
274 req->methodString(), req->target(),
275 req->ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700276
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700277 req->ioService = static_cast<decltype(req->ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700278 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200279
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700280 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700281 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800282 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700283 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700284 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700285 keepAlive = req->keepAlive();
Ed Tanous4fa45df2023-09-01 14:20:50 -0700286 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700287 {
Ed Tanous83328312024-05-09 15:48:09 -0700288 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous4fa45df2023-09-01 14:20:50 -0700289 {
Ed Tanous83328312024-05-09 15:48:09 -0700290 if (!crow::authentication::isOnAllowlist(req->url().path(),
291 req->method()) &&
292 req->session == nullptr)
293 {
294 BMCWEB_LOG_WARNING("Authentication failed");
295 forward_unauthorized::sendUnauthorized(
296 req->url().encoded_path(),
297 req->getHeaderValue("X-Requested-With"),
298 req->getHeaderValue("Accept"), res);
299 completeRequest(res);
300 return;
301 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700302 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700303 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800304 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700305 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800306 asyncResp->res.setCompleteRequestHandler(
307 [self(shared_from_this())](crow::Response& thisRes) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400308 self->completeRequest(thisRes);
309 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700310 bool isSse =
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700311 isContentTypeAllowed(req->getHeaderValue("Accept"),
Ed Tanous6fde95f2023-06-01 07:33:34 -0700312 http_helpers::ContentType::EventStream, false);
Ed Tanous18f8f602023-07-18 10:07:23 -0700313 std::string_view upgradeType(
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700314 req->getHeaderValue(boost::beast::http::field::upgrade));
315 if ((req->isUpgrade() &&
Ed Tanous18f8f602023-07-18 10:07:23 -0700316 bmcweb::asciiIEquals(upgradeType, "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700317 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700318 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530319 asyncResp->res.setCompleteRequestHandler(
320 [self(shared_from_this())](crow::Response& thisRes) {
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400321 if (thisRes.result() != boost::beast::http::status::ok)
322 {
323 // When any error occurs before handle upgradation,
324 // the result in response will be set to respective
325 // error. By default the Result will be OK (200),
326 // which implies successful handle upgrade. Response
327 // needs to be sent over this connection only on
328 // failure.
329 self->completeRequest(thisRes);
330 return;
331 }
332 });
Ed Tanous52e31622024-01-23 16:31:11 -0800333 handler->handleUpgrade(req, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700334 return;
335 }
Ed Tanous291d7092022-04-13 12:34:57 -0700336 std::string_view expected =
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700337 req->getHeaderValue(boost::beast::http::field::if_none_match);
Ed Tanous291d7092022-04-13 12:34:57 -0700338 if (!expected.empty())
339 {
340 res.setExpectedHash(expected);
341 }
Ed Tanous52e31622024-01-23 16:31:11 -0800342 handler->handle(req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700343 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700344
Ed Tanous1d1d7782024-04-09 12:54:08 -0700345 void hardClose()
Ed Tanouse278c182019-03-13 16:23:37 -0700346 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700347 if (mtlsSession != nullptr)
348 {
349 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
350 mtlsSession->uniqueId);
351 persistent_data::SessionStore::getInstance().removeSession(
352 mtlsSession);
353 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700354 BMCWEB_LOG_DEBUG("{} Closing socket", logPtr(this));
355 boost::beast::get_lowest_layer(adaptor).close();
356 }
357
358 void tlsShutdownComplete(const std::shared_ptr<self_type>& self,
359 const boost::system::error_code& ec)
360 {
361 if (ec)
362 {
363 BMCWEB_LOG_WARNING("{} Failed to shut down TLS cleanly {}",
364 logPtr(self.get()), ec);
365 }
366 self->hardClose();
367 }
368
369 void gracefulClose()
370 {
371 BMCWEB_LOG_DEBUG("{} Socket close requested", logPtr(this));
Ed Tanous3281bcf2024-06-25 16:02:05 -0700372
Ed Tanous4fa45df2023-09-01 14:20:50 -0700373 if constexpr (IsTls<Adaptor>::value)
Ed Tanouse278c182019-03-13 16:23:37 -0700374 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700375 adaptor.async_shutdown(std::bind_front(
376 &self_type::tlsShutdownComplete, this, shared_from_this()));
Ed Tanouse278c182019-03-13 16:23:37 -0700377 }
378 else
379 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700380 hardClose();
Ed Tanouse278c182019-03-13 16:23:37 -0700381 }
382 }
383
Nan Zhou72374eb2022-01-27 17:06:51 -0800384 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700385 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800386 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800387 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800388
Ed Tanous89cda632024-04-16 08:45:54 -0700389 completeResponseFields(accept, res);
Ed Tanous998e0cb2023-09-06 13:57:30 -0700390 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
Ed Tanous291d7092022-04-13 12:34:57 -0700391
Ed Tanous52e31622024-01-23 16:31:11 -0800392 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000393
394 // delete lambda with self shared_ptr
395 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700396 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700397 }
398
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500399 void readClientIp()
400 {
401 boost::system::error_code ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500402
Ed Tanous4fa45df2023-09-01 14:20:50 -0700403 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500404 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700405 boost::asio::ip::tcp::endpoint endpoint =
406 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
407
408 if (ec)
409 {
410 // If remote endpoint fails keep going. "ClientOriginIPAddress"
411 // will be empty.
412 BMCWEB_LOG_ERROR(
413 "Failed to get the client's IP Address. ec : {}", ec);
Ed Tanous1d1d7782024-04-09 12:54:08 -0700414 return;
Ed Tanous4fa45df2023-09-01 14:20:50 -0700415 }
416 ip = endpoint.address();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500417 }
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500418 }
419
Ed Tanous1abe55e2018-09-05 08:30:59 -0700420 private:
Ed Tanous1d1d7782024-04-09 12:54:08 -0700421 uint64_t getContentLengthLimit()
422 {
Ed Tanous83328312024-05-09 15:48:09 -0700423 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous1d1d7782024-04-09 12:54:08 -0700424 {
Ed Tanous83328312024-05-09 15:48:09 -0700425 if (userSession == nullptr)
426 {
427 return loggedOutPostBodyLimit;
428 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700429 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700430
431 return httpReqBodyLimit;
432 }
433
434 // Returns true if content length was within limits
435 // Returns false if content length error has been returned
436 bool handleContentLengthError()
437 {
438 if (!parser)
439 {
Manojkiran Edaefff2b52024-06-18 18:01:46 +0530440 BMCWEB_LOG_CRITICAL("Parser was null");
Ed Tanous1d1d7782024-04-09 12:54:08 -0700441 return false;
442 }
443 const boost::optional<uint64_t> contentLength =
444 parser->content_length();
445 if (!contentLength)
446 {
447 BMCWEB_LOG_DEBUG("{} No content length available", logPtr(this));
448 return true;
449 }
450
451 uint64_t maxAllowedContentLength = getContentLengthLimit();
452
453 if (*contentLength > maxAllowedContentLength)
454 {
455 // If the users content limit is between the logged in
456 // and logged out limits They probably just didn't log
457 // in
458 if (*contentLength > loggedOutPostBodyLimit &&
459 *contentLength < httpReqBodyLimit)
460 {
461 BMCWEB_LOG_DEBUG(
462 "{} Content length {} valid, but greater than logged out"
463 " limit of {}. Setting unauthorized",
464 logPtr(this), *contentLength, loggedOutPostBodyLimit);
465 res.result(boost::beast::http::status::unauthorized);
466 }
467 else
468 {
469 // Otherwise they're over both limits, so inform
470 // them
471 BMCWEB_LOG_DEBUG(
472 "{} Content length {} was greater than global limit {}."
473 " Setting payload too large",
474 logPtr(this), *contentLength, httpReqBodyLimit);
475 res.result(boost::beast::http::status::payload_too_large);
476 }
477
478 keepAlive = false;
479 doWrite();
480 return false;
481 }
482
483 return true;
484 }
485
Ed Tanous116370d2024-10-08 10:37:28 -0700486 void afterReadHeaders(const std::shared_ptr<self_type>& /*self*/,
487 const boost::system::error_code& ec,
488 std::size_t bytesTransferred)
489 {
490 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
491 bytesTransferred);
492
493 if (ec)
494 {
495 cancelDeadlineTimer();
496
497 if (ec == boost::beast::http::error::header_limit)
498 {
499 BMCWEB_LOG_ERROR("{} Header field too large, closing",
500 logPtr(this), ec.message());
501
502 res.result(boost::beast::http::status::
503 request_header_fields_too_large);
504 keepAlive = false;
505 doWrite();
506 return;
507 }
508 if (ec == boost::beast::http::error::end_of_stream)
509 {
510 BMCWEB_LOG_WARNING("{} End of stream, closing {}", logPtr(this),
511 ec);
512 hardClose();
513 return;
514 }
515
516 BMCWEB_LOG_DEBUG("{} Closing socket due to read error {}",
517 logPtr(this), ec.message());
518 gracefulClose();
519
520 return;
521 }
522
523 if (!parser)
524 {
525 BMCWEB_LOG_ERROR("Parser was unexpectedly null");
526 return;
527 }
528
529 constexpr bool isTest =
530 std::is_same_v<Adaptor, boost::beast::test::stream>;
531
532 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH && !isTest)
533 {
534 boost::beast::http::verb method = parser->get().method();
535 userSession = crow::authentication::authenticate(
536 ip, res, method, parser->get().base(), mtlsSession);
537 }
538
539 std::string_view expect =
540 parser->get()[boost::beast::http::field::expect];
541 if (bmcweb::asciiIEquals(expect, "100-continue"))
542 {
543 res.result(boost::beast::http::status::continue_);
544 doWrite();
545 return;
546 }
547
548 if (!handleContentLengthError())
549 {
550 return;
551 }
552
553 parser->body_limit(getContentLengthLimit());
554
555 if (parser->is_done())
556 {
557 handle();
558 return;
559 }
560
561 doRead();
562 }
563
Ed Tanous1abe55e2018-09-05 08:30:59 -0700564 void doReadHeaders()
565 {
Ed Tanous62598e32023-07-17 17:06:25 -0700566 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700567 if (!parser)
568 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700569 BMCWEB_LOG_CRITICAL("Parser was not initialized.");
Ed Tanouse01d0c32023-06-30 13:21:32 -0700570 return;
571 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700572 // Clean up any previous Connection.
573 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800574 adaptor, buffer, *parser,
Ed Tanous116370d2024-10-08 10:37:28 -0700575 std::bind_front(&self_type::afterReadHeaders, this,
576 shared_from_this()));
577 }
Ed Tanous52e31622024-01-23 16:31:11 -0800578
Ed Tanous116370d2024-10-08 10:37:28 -0700579 void afterRead(const std::shared_ptr<self_type>& /*self*/,
580 const boost::system::error_code& ec,
581 std::size_t bytesTransferred)
582 {
583 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
584 bytesTransferred);
585
586 if (ec)
587 {
588 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
589 ec.message());
590 if (ec == boost::beast::http::error::body_limit)
591 {
592 if (handleContentLengthError())
Ed Tanous1d1d7782024-04-09 12:54:08 -0700593 {
Ed Tanous116370d2024-10-08 10:37:28 -0700594 BMCWEB_LOG_CRITICAL("Body length limit reached, "
595 "but no content-length "
596 "available? Should never happen");
597 res.result(
598 boost::beast::http::status::internal_server_error);
599 keepAlive = false;
Ed Tanous1d1d7782024-04-09 12:54:08 -0700600 doWrite();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700601 }
Ed Tanous116370d2024-10-08 10:37:28 -0700602 return;
603 }
Patrick Williamsbd79bce2024-08-16 15:22:20 -0400604
Ed Tanous116370d2024-10-08 10:37:28 -0700605 gracefulClose();
606 return;
607 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700608
Ed Tanous116370d2024-10-08 10:37:28 -0700609 // If the user is logged in, allow them to send files
610 // incrementally one piece at a time. If authentication is
611 // disabled then there is no user session hence always allow to
612 // send one piece at a time.
613 if (userSession != nullptr)
614 {
615 cancelDeadlineTimer();
616 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700617
Ed Tanous116370d2024-10-08 10:37:28 -0700618 if (!parser)
619 {
620 BMCWEB_LOG_ERROR("Parser was unexpectedly null");
621 return;
622 }
623 if (!parser->is_done())
624 {
625 doRead();
626 return;
627 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700628
Ed Tanous116370d2024-10-08 10:37:28 -0700629 cancelDeadlineTimer();
630 handle();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700631 }
632
633 void doRead()
634 {
Ed Tanous62598e32023-07-17 17:06:25 -0700635 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700636 if (!parser)
637 {
638 return;
639 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800640 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800641 boost::beast::http::async_read_some(
642 adaptor, buffer, *parser,
Ed Tanous116370d2024-10-08 10:37:28 -0700643 std::bind_front(&self_type::afterRead, this, shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700644 }
645
Ed Tanous27b0cf92023-08-07 12:02:40 -0700646 void afterDoWrite(const std::shared_ptr<self_type>& /*self*/,
647 const boost::system::error_code& ec,
648 std::size_t bytesTransferred)
649 {
Ed Tanous0242baf2024-05-16 19:52:47 -0700650 BMCWEB_LOG_DEBUG("{} async_write wrote {} bytes, ec={}", logPtr(this),
Ed Tanous1d1d7782024-04-09 12:54:08 -0700651 bytesTransferred, ec);
Ed Tanous27b0cf92023-08-07 12:02:40 -0700652
653 cancelDeadlineTimer();
654
Ed Tanous0242baf2024-05-16 19:52:47 -0700655 if (ec == boost::system::errc::operation_would_block ||
656 ec == boost::system::errc::resource_unavailable_try_again)
657 {
658 doWrite();
659 return;
660 }
Ed Tanous27b0cf92023-08-07 12:02:40 -0700661 if (ec)
662 {
663 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
664 return;
665 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700666
667 if (res.result() == boost::beast::http::status::continue_)
668 {
669 // Reset the result to ok
670 res.result(boost::beast::http::status::ok);
671 doRead();
672 return;
673 }
674
Ed Tanous27b0cf92023-08-07 12:02:40 -0700675 if (!keepAlive)
676 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700677 BMCWEB_LOG_DEBUG("{} keepalive not set. Closing socket",
678 logPtr(this));
679
680 gracefulClose();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700681 return;
682 }
683
684 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
685 res.clear();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700686 initParser();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700687
688 userSession = nullptr;
689
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700690 req->clear();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700691 doReadHeaders();
692 }
693
Ed Tanous52e31622024-01-23 16:31:11 -0800694 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700695 {
Ed Tanous62598e32023-07-17 17:06:25 -0700696 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Ed Tanous52e31622024-01-23 16:31:11 -0800697 res.preparePayload();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700698
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800699 startDeadline();
Ed Tanous4d698612024-02-06 14:57:24 -0800700 boost::beast::async_write(
701 adaptor,
702 boost::beast::http::message_generator(std::move(res.response)),
Ed Tanous52e31622024-01-23 16:31:11 -0800703 std::bind_front(&self_type::afterDoWrite, this,
704 shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700705 }
706
Ed Tanous1abe55e2018-09-05 08:30:59 -0700707 void cancelDeadlineTimer()
708 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800709 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700710 }
711
Ed Tanous116370d2024-10-08 10:37:28 -0700712 void afterTimerWait(const std::weak_ptr<self_type>& weakSelf,
713 const boost::system::error_code& ec)
714 {
715 // Note, we are ignoring other types of errors here; If the timer
716 // failed for any reason, we should still close the connection
717 std::shared_ptr<Connection<Adaptor, Handler>> self = weakSelf.lock();
718 if (!self)
719 {
720 if (ec == boost::asio::error::operation_aborted)
721 {
722 BMCWEB_LOG_DEBUG(
723 "{} Timer canceled on connection being destroyed",
724 logPtr(self.get()));
725 }
726 else
727 {
728 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
729 logPtr(self.get()));
730 }
731 return;
732 }
733
734 self->timerStarted = false;
735
736 if (ec)
737 {
738 if (ec == boost::asio::error::operation_aborted)
739 {
740 BMCWEB_LOG_DEBUG("{} Timer canceled", logPtr(self.get()));
741 return;
742 }
743 BMCWEB_LOG_CRITICAL("{} Timer failed {}", logPtr(self.get()), ec);
744 }
745
746 BMCWEB_LOG_WARNING("{} Connection timed out, hard closing",
747 logPtr(self.get()));
748
749 self->hardClose();
750 }
751
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800752 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700753 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800754 // Timer is already started so no further action is required.
755 if (timerStarted)
756 {
757 return;
758 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700759
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800760 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800761
762 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
763 timer.expires_after(timeout);
Ed Tanous116370d2024-10-08 10:37:28 -0700764 timer.async_wait(std::bind_front(&self_type::afterTimerWait, this,
765 weak_from_this()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800766
Ed Tanous7d243eb2023-01-23 15:57:41 -0800767 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700768 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700769 }
770
Ed Tanous1abe55e2018-09-05 08:30:59 -0700771 Adaptor adaptor;
772 Handler* handler;
Ed Tanous1d1d7782024-04-09 12:54:08 -0700773
774 boost::asio::ip::address ip;
775
Ed Tanousa24526d2018-12-10 15:17:59 -0800776 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700777 // re-created on Connection reset
Ed Tanousb2896142024-01-31 15:25:47 -0800778 std::optional<boost::beast::http::request_parser<bmcweb::HttpBody>> parser;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700779
Ed Tanous3112a142018-11-29 15:45:10 -0800780 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700781
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700782 std::shared_ptr<crow::Request> req;
Ed Tanous89cda632024-04-16 08:45:54 -0700783 std::string accept;
784
Ed Tanous1abe55e2018-09-05 08:30:59 -0700785 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700786
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700787 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100788 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700789
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800790 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700791
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800792 bool keepAlive = true;
793
Ed Tanous7d243eb2023-01-23 15:57:41 -0800794 bool timerStarted = false;
795
Ed Tanous1abe55e2018-09-05 08:30:59 -0700796 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000797
798 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700799 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800800
801 using std::enable_shared_from_this<
802 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800803};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700804} // namespace crow