blob: e5914550269182723cb92dcd15fa9f6511d2c973 [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) :
Ed Tanousceac6f72018-12-02 11:58:47 -080067 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080068 handler(handlerIn), timer(std::move(timerIn)),
69 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070070 {
Ed Tanous1d1d7782024-04-09 12:54:08 -070071 initParser();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020072
Ed Tanous40aa0582021-07-14 13:24:40 -070073 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080074
Ed Tanous1d1d7782024-04-09 12:54:08 -070075 BMCWEB_LOG_DEBUG("{} Connection created, total {}", logPtr(this),
Ed Tanous62598e32023-07-17 17:06:25 -070076 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070077 }
78
79 ~Connection()
80 {
Ed Tanous1d1d7782024-04-09 12:54:08 -070081 res.releaseCompleteRequestHandler();
Ed Tanous40aa0582021-07-14 13:24:40 -070082 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080083
Ed Tanous40aa0582021-07-14 13:24:40 -070084 connectionCount--;
Ed Tanous62598e32023-07-17 17:06:25 -070085 BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
86 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070087 }
88
Ed Tanousecd6a3a2022-01-07 09:18:40 -080089 Connection(const Connection&) = delete;
90 Connection(Connection&&) = delete;
91 Connection& operator=(const Connection&) = delete;
92 Connection& operator=(Connection&&) = delete;
93
Ed Tanous7c8e0642022-02-21 12:11:14 -080094 bool tlsVerifyCallback(bool preverified,
95 boost::asio::ssl::verify_context& ctx)
96 {
Ed Tanous3281bcf2024-06-25 16:02:05 -070097 BMCWEB_LOG_DEBUG("{} tlsVerifyCallback called with preverified {}",
98 logPtr(this), preverified);
Ed Tanous7c8e0642022-02-21 12:11:14 -080099 if (preverified)
100 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700101 mtlsSession = verifyMtlsUser(ip, ctx);
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100102 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800103 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700104 BMCWEB_LOG_DEBUG("{} Generated TLS session: {}", logPtr(this),
Ed Tanous62598e32023-07-17 17:06:25 -0700105 mtlsSession->uniqueId);
Ed Tanous7c8e0642022-02-21 12:11:14 -0800106 }
107 }
Ed Tanous3281bcf2024-06-25 16:02:05 -0700108 const persistent_data::AuthConfigMethods& c =
109 persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
110 if (c.tlsStrict)
111 {
112 return preverified;
113 }
114 // If tls strict mode is disabled
115 // We always return true to allow full auth flow for resources that
116 // don't require auth
Ed Tanous7c8e0642022-02-21 12:11:14 -0800117 return true;
118 }
119
Ed Tanous3281bcf2024-06-25 16:02:05 -0700120 bool prepareMutualTls()
Ed Tanous40aa0582021-07-14 13:24:40 -0700121 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700122 if constexpr (IsTls<Adaptor>::value)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100123 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700124 BMCWEB_LOG_DEBUG("prepareMutualTls");
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100125
Ed Tanous3281bcf2024-06-25 16:02:05 -0700126 constexpr std::string_view id = "bmcweb";
127
128 const char* idPtr = id.data();
129 const auto* idCPtr = std::bit_cast<const unsigned char*>(idPtr);
130 auto idLen = static_cast<unsigned int>(id.length());
131 int ret = SSL_set_session_id_context(adaptor.native_handle(),
132 idCPtr, idLen);
133 if (ret == 0)
134 {
135 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
136 return false;
Ed Tanous4fa45df2023-09-01 14:20:50 -0700137 }
138
Ed Tanous3281bcf2024-06-25 16:02:05 -0700139 BMCWEB_LOG_DEBUG("set_verify_callback");
Ed Tanous7045c8d2017-04-03 10:04:37 -0700140
Ed Tanous3281bcf2024-06-25 16:02:05 -0700141 boost::system::error_code ec;
142 adaptor.set_verify_callback(
143 std::bind_front(&self_type::tlsVerifyCallback, this), ec);
144 if (ec)
145 {
146 BMCWEB_LOG_ERROR("Failed to set verify callback {}", ec);
147 return false;
148 }
149 }
150
151 return true;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700152 }
153
Ed Tanous1abe55e2018-09-05 08:30:59 -0700154 void start()
155 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700156 BMCWEB_LOG_DEBUG("{} Connection started, total {}", logPtr(this),
157 connectionCount);
Gunnar Mills4f63be02023-10-25 09:14:07 -0500158 if (connectionCount >= 200)
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800159 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700160 BMCWEB_LOG_CRITICAL("{} Max connection count exceeded.",
Ed Tanous62598e32023-07-17 17:06:25 -0700161 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800162 return;
163 }
164
Ed Tanous3281bcf2024-06-25 16:02:05 -0700165 if constexpr (BMCWEB_MUTUAL_TLS_AUTH)
166 {
167 if (!prepareMutualTls())
168 {
169 BMCWEB_LOG_ERROR("{} Failed to prepare mTLS", logPtr(this));
170 return;
171 }
172 }
173
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800174 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500175
Ed Tanous1d1d7782024-04-09 12:54:08 -0700176 readClientIp();
177
Ed Tanousceac6f72018-12-02 11:58:47 -0800178 // TODO(ed) Abstract this to a more clever class with the idea of an
179 // asynchronous "start"
Ed Tanous4fa45df2023-09-01 14:20:50 -0700180 if constexpr (IsTls<Adaptor>::value)
Ed Tanousceac6f72018-12-02 11:58:47 -0800181 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000182 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
183 [this, self(shared_from_this())](
184 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700185 if (ec)
186 {
187 return;
188 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800189 afterSslHandshake();
Ed Tanous002d39b2022-05-31 08:59:27 -0700190 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800191 }
192 else
193 {
194 doReadHeaders();
195 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700196 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700197
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800198 void afterSslHandshake()
199 {
200 // If http2 is enabled, negotiate the protocol
Ed Tanous25b54db2024-04-17 15:40:31 -0700201 if constexpr (BMCWEB_EXPERIMENTAL_HTTP2)
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800202 {
203 const unsigned char* alpn = nullptr;
204 unsigned int alpnlen = 0;
205 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
206 if (alpn != nullptr)
207 {
208 std::string_view selectedProtocol(
209 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700210 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
211 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800212 if (selectedProtocol == "h2")
213 {
214 auto http2 =
215 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
216 std::move(adaptor), handler, getCachedDateStr);
217 http2->start();
218 return;
219 }
220 }
221 }
222
223 doReadHeaders();
224 }
225
Ed Tanous1d1d7782024-04-09 12:54:08 -0700226 void initParser()
227 {
228 boost::beast::http::request_parser<bmcweb::HttpBody>& instance =
229 parser.emplace(std::piecewise_construct, std::make_tuple());
230
231 // reset header limit for newly created parser
232 instance.header_limit(httpHeaderLimit);
233
234 // Initially set no body limit. We don't yet know if the user is
235 // authenticated.
236 instance.body_limit(boost::none);
237 }
238
Ed Tanous1abe55e2018-09-05 08:30:59 -0700239 void handle()
240 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700241 std::error_code reqEc;
Ed Tanouse01d0c32023-06-30 13:21:32 -0700242 if (!parser)
243 {
244 return;
245 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700246 req = std::make_shared<crow::Request>(parser->release(), reqEc);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700247 if (reqEc)
248 {
Ed Tanous62598e32023-07-17 17:06:25 -0700249 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600250 res.result(boost::beast::http::status::bad_request);
251 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700252 return;
253 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700254 req->session = userSession;
Ed Tanous89cda632024-04-16 08:45:54 -0700255 accept = req->getHeaderValue("Accept");
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000256 // Fetch the client IP address
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700257 req->ipAddress = ip;
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000258
Ed Tanous1abe55e2018-09-05 08:30:59 -0700259 // Check for HTTP version 1.1.
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700260 if (req->version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700261 {
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700262 if (req->getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700263 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700264 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800265 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700266 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700267 }
268 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700269
Ed Tanous62598e32023-07-17 17:06:25 -0700270 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700271 req->version() / 10, req->version() % 10,
272 req->methodString(), req->target(),
273 req->ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700274
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700275 req->ioService = static_cast<decltype(req->ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700276 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200277
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700278 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700279 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800280 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700281 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700282 }
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700283 keepAlive = req->keepAlive();
Ed Tanous4fa45df2023-09-01 14:20:50 -0700284 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700285 {
Ed Tanous83328312024-05-09 15:48:09 -0700286 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous4fa45df2023-09-01 14:20:50 -0700287 {
Ed Tanous83328312024-05-09 15:48:09 -0700288 if (!crow::authentication::isOnAllowlist(req->url().path(),
289 req->method()) &&
290 req->session == nullptr)
291 {
292 BMCWEB_LOG_WARNING("Authentication failed");
293 forward_unauthorized::sendUnauthorized(
294 req->url().encoded_path(),
295 req->getHeaderValue("X-Requested-With"),
296 req->getHeaderValue("Accept"), res);
297 completeRequest(res);
298 return;
299 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700300 }
Ed Tanous4fa45df2023-09-01 14:20:50 -0700301 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800302 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700303 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800304 asyncResp->res.setCompleteRequestHandler(
305 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700306 self->completeRequest(thisRes);
307 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700308 bool isSse =
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700309 isContentTypeAllowed(req->getHeaderValue("Accept"),
Ed Tanous6fde95f2023-06-01 07:33:34 -0700310 http_helpers::ContentType::EventStream, false);
Ed Tanous18f8f602023-07-18 10:07:23 -0700311 std::string_view upgradeType(
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700312 req->getHeaderValue(boost::beast::http::field::upgrade));
313 if ((req->isUpgrade() &&
Ed Tanous18f8f602023-07-18 10:07:23 -0700314 bmcweb::asciiIEquals(upgradeType, "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700315 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700316 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530317 asyncResp->res.setCompleteRequestHandler(
318 [self(shared_from_this())](crow::Response& thisRes) {
319 if (thisRes.result() != boost::beast::http::status::ok)
320 {
321 // When any error occurs before handle upgradation,
322 // the result in response will be set to respective
323 // error. By default the Result will be OK (200),
324 // which implies successful handle upgrade. Response
325 // needs to be sent over this connection only on
326 // failure.
327 self->completeRequest(thisRes);
328 return;
329 }
330 });
Ed Tanous52e31622024-01-23 16:31:11 -0800331 handler->handleUpgrade(req, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700332 return;
333 }
Ed Tanous291d7092022-04-13 12:34:57 -0700334 std::string_view expected =
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700335 req->getHeaderValue(boost::beast::http::field::if_none_match);
Ed Tanous291d7092022-04-13 12:34:57 -0700336 if (!expected.empty())
337 {
338 res.setExpectedHash(expected);
339 }
Ed Tanous52e31622024-01-23 16:31:11 -0800340 handler->handle(req, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700341 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700342
Ed Tanous1d1d7782024-04-09 12:54:08 -0700343 void hardClose()
Ed Tanouse278c182019-03-13 16:23:37 -0700344 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700345 if (mtlsSession != nullptr)
346 {
347 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
348 mtlsSession->uniqueId);
349 persistent_data::SessionStore::getInstance().removeSession(
350 mtlsSession);
351 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700352 BMCWEB_LOG_DEBUG("{} Closing socket", logPtr(this));
353 boost::beast::get_lowest_layer(adaptor).close();
354 }
355
356 void tlsShutdownComplete(const std::shared_ptr<self_type>& self,
357 const boost::system::error_code& ec)
358 {
359 if (ec)
360 {
361 BMCWEB_LOG_WARNING("{} Failed to shut down TLS cleanly {}",
362 logPtr(self.get()), ec);
363 }
364 self->hardClose();
365 }
366
367 void gracefulClose()
368 {
369 BMCWEB_LOG_DEBUG("{} Socket close requested", logPtr(this));
Ed Tanous3281bcf2024-06-25 16:02:05 -0700370
Ed Tanous4fa45df2023-09-01 14:20:50 -0700371 if constexpr (IsTls<Adaptor>::value)
Ed Tanouse278c182019-03-13 16:23:37 -0700372 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700373 adaptor.async_shutdown(std::bind_front(
374 &self_type::tlsShutdownComplete, this, shared_from_this()));
Ed Tanouse278c182019-03-13 16:23:37 -0700375 }
376 else
377 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700378 hardClose();
Ed Tanouse278c182019-03-13 16:23:37 -0700379 }
380 }
381
Nan Zhou72374eb2022-01-27 17:06:51 -0800382 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700383 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800384 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800385 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800386
Ed Tanous89cda632024-04-16 08:45:54 -0700387 completeResponseFields(accept, res);
Ed Tanous998e0cb2023-09-06 13:57:30 -0700388 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
Ed Tanous291d7092022-04-13 12:34:57 -0700389
Ed Tanous52e31622024-01-23 16:31:11 -0800390 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000391
392 // delete lambda with self shared_ptr
393 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700394 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700395 }
396
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500397 void readClientIp()
398 {
399 boost::system::error_code ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500400
Ed Tanous4fa45df2023-09-01 14:20:50 -0700401 if constexpr (!std::is_same_v<Adaptor, boost::beast::test::stream>)
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500402 {
Ed Tanous4fa45df2023-09-01 14:20:50 -0700403 boost::asio::ip::tcp::endpoint endpoint =
404 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
405
406 if (ec)
407 {
408 // If remote endpoint fails keep going. "ClientOriginIPAddress"
409 // will be empty.
410 BMCWEB_LOG_ERROR(
411 "Failed to get the client's IP Address. ec : {}", ec);
Ed Tanous1d1d7782024-04-09 12:54:08 -0700412 return;
Ed Tanous4fa45df2023-09-01 14:20:50 -0700413 }
414 ip = endpoint.address();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500415 }
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500416 }
417
Ed Tanous1abe55e2018-09-05 08:30:59 -0700418 private:
Ed Tanous1d1d7782024-04-09 12:54:08 -0700419 uint64_t getContentLengthLimit()
420 {
Ed Tanous83328312024-05-09 15:48:09 -0700421 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
Ed Tanous1d1d7782024-04-09 12:54:08 -0700422 {
Ed Tanous83328312024-05-09 15:48:09 -0700423 if (userSession == nullptr)
424 {
425 return loggedOutPostBodyLimit;
426 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700427 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700428
429 return httpReqBodyLimit;
430 }
431
432 // Returns true if content length was within limits
433 // Returns false if content length error has been returned
434 bool handleContentLengthError()
435 {
436 if (!parser)
437 {
Manojkiran Edaefff2b52024-06-18 18:01:46 +0530438 BMCWEB_LOG_CRITICAL("Parser was null");
Ed Tanous1d1d7782024-04-09 12:54:08 -0700439 return false;
440 }
441 const boost::optional<uint64_t> contentLength =
442 parser->content_length();
443 if (!contentLength)
444 {
445 BMCWEB_LOG_DEBUG("{} No content length available", logPtr(this));
446 return true;
447 }
448
449 uint64_t maxAllowedContentLength = getContentLengthLimit();
450
451 if (*contentLength > maxAllowedContentLength)
452 {
453 // If the users content limit is between the logged in
454 // and logged out limits They probably just didn't log
455 // in
456 if (*contentLength > loggedOutPostBodyLimit &&
457 *contentLength < httpReqBodyLimit)
458 {
459 BMCWEB_LOG_DEBUG(
460 "{} Content length {} valid, but greater than logged out"
461 " limit of {}. Setting unauthorized",
462 logPtr(this), *contentLength, loggedOutPostBodyLimit);
463 res.result(boost::beast::http::status::unauthorized);
464 }
465 else
466 {
467 // Otherwise they're over both limits, so inform
468 // them
469 BMCWEB_LOG_DEBUG(
470 "{} Content length {} was greater than global limit {}."
471 " Setting payload too large",
472 logPtr(this), *contentLength, httpReqBodyLimit);
473 res.result(boost::beast::http::status::payload_too_large);
474 }
475
476 keepAlive = false;
477 doWrite();
478 return false;
479 }
480
481 return true;
482 }
483
Ed Tanous1abe55e2018-09-05 08:30:59 -0700484 void doReadHeaders()
485 {
Ed Tanous62598e32023-07-17 17:06:25 -0700486 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700487 if (!parser)
488 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700489 BMCWEB_LOG_CRITICAL("Parser was not initialized.");
Ed Tanouse01d0c32023-06-30 13:21:32 -0700490 return;
491 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700492 // Clean up any previous Connection.
493 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800494 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000495 [this,
496 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000497 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700498 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
499 bytesTransferred);
Ed Tanous52e31622024-01-23 16:31:11 -0800500
Ed Tanous002d39b2022-05-31 08:59:27 -0700501 if (ec)
502 {
Ed Tanous52e31622024-01-23 16:31:11 -0800503 cancelDeadlineTimer();
504
Ed Tanous1d1d7782024-04-09 12:54:08 -0700505 if (ec == boost::beast::http::error::header_limit)
506 {
507 BMCWEB_LOG_ERROR("{} Header field too large, closing",
508 logPtr(this), ec.message());
509
510 res.result(boost::beast::http::status::
511 request_header_fields_too_large);
512 keepAlive = false;
513 doWrite();
514 return;
515 }
Myung Baea4326fe2023-01-10 14:29:24 -0600516 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700517 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700518 BMCWEB_LOG_WARNING("{} End of stream, closing {}",
519 logPtr(this), ec);
520 hardClose();
521 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700522 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700523
524 BMCWEB_LOG_DEBUG("{} Closing socket due to read error {}",
525 logPtr(this), ec.message());
526 gracefulClose();
527
Ed Tanous002d39b2022-05-31 08:59:27 -0700528 return;
529 }
530
Ed Tanous3281bcf2024-06-25 16:02:05 -0700531 constexpr bool isTest =
532 std::is_same_v<Adaptor, boost::beast::test::stream>;
533
534 if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH && !isTest)
Ed Tanous83328312024-05-09 15:48:09 -0700535 {
Ed Tanous3281bcf2024-06-25 16:02:05 -0700536 boost::beast::http::verb method = parser->get().method();
537 userSession = crow::authentication::authenticate(
538 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous83328312024-05-09 15:48:09 -0700539 }
540
Ed Tanous1d1d7782024-04-09 12:54:08 -0700541 std::string_view expect =
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700542 parser->get()[boost::beast::http::field::expect];
Ed Tanous1d1d7782024-04-09 12:54:08 -0700543 if (bmcweb::asciiIEquals(expect, "100-continue"))
Ed Tanous002d39b2022-05-31 08:59:27 -0700544 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700545 res.result(boost::beast::http::status::continue_);
546 doWrite();
547 return;
Ed Tanous002d39b2022-05-31 08:59:27 -0700548 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700549
Ed Tanous1d1d7782024-04-09 12:54:08 -0700550 if (!handleContentLengthError())
551 {
552 return;
553 }
554
555 parser->body_limit(getContentLengthLimit());
556
Ed Tanous7d243eb2023-01-23 15:57:41 -0800557 if (parser->is_done())
558 {
559 handle();
560 return;
561 }
562
Ed Tanous002d39b2022-05-31 08:59:27 -0700563 doRead();
Patrick Williams5a39f772023-10-20 11:20:21 -0500564 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700565 }
566
567 void doRead()
568 {
Ed Tanous62598e32023-07-17 17:06:25 -0700569 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanouse01d0c32023-06-30 13:21:32 -0700570 if (!parser)
571 {
572 return;
573 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800574 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800575 boost::beast::http::async_read_some(
576 adaptor, buffer, *parser,
577 [this,
578 self(shared_from_this())](const boost::system::error_code& ec,
579 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700580 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
581 bytesTransferred);
Ed Tanous7d243eb2023-01-23 15:57:41 -0800582
Ed Tanous002d39b2022-05-31 08:59:27 -0700583 if (ec)
584 {
Ed Tanous62598e32023-07-17 17:06:25 -0700585 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
586 ec.message());
Ed Tanous1d1d7782024-04-09 12:54:08 -0700587 if (ec == boost::beast::http::error::body_limit)
588 {
589 if (handleContentLengthError())
590 {
591 BMCWEB_LOG_CRITICAL("Body length limit reached, "
592 "but no content-length "
593 "available? Should never happen");
594 res.result(
595 boost::beast::http::status::internal_server_error);
596 keepAlive = false;
597 doWrite();
598 }
599 return;
600 }
601
602 gracefulClose();
Ed Tanous002d39b2022-05-31 08:59:27 -0700603 return;
604 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800605
606 // If the user is logged in, allow them to send files incrementally
607 // one piece at a time. If authentication is disabled then there is
608 // no user session hence always allow to send one piece at a time.
609 if (userSession != nullptr)
610 {
611 cancelDeadlineTimer();
612 }
613 if (!parser->is_done())
614 {
615 doRead();
616 return;
617 }
618
619 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700620 handle();
Patrick Williams5a39f772023-10-20 11:20:21 -0500621 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700622 }
623
Ed Tanous27b0cf92023-08-07 12:02:40 -0700624 void afterDoWrite(const std::shared_ptr<self_type>& /*self*/,
625 const boost::system::error_code& ec,
626 std::size_t bytesTransferred)
627 {
Ed Tanous0242baf2024-05-16 19:52:47 -0700628 BMCWEB_LOG_DEBUG("{} async_write wrote {} bytes, ec={}", logPtr(this),
Ed Tanous1d1d7782024-04-09 12:54:08 -0700629 bytesTransferred, ec);
Ed Tanous27b0cf92023-08-07 12:02:40 -0700630
631 cancelDeadlineTimer();
632
Ed Tanous0242baf2024-05-16 19:52:47 -0700633 if (ec == boost::system::errc::operation_would_block ||
634 ec == boost::system::errc::resource_unavailable_try_again)
635 {
636 doWrite();
637 return;
638 }
Ed Tanous27b0cf92023-08-07 12:02:40 -0700639 if (ec)
640 {
641 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
642 return;
643 }
Ed Tanous1d1d7782024-04-09 12:54:08 -0700644
645 if (res.result() == boost::beast::http::status::continue_)
646 {
647 // Reset the result to ok
648 res.result(boost::beast::http::status::ok);
649 doRead();
650 return;
651 }
652
Ed Tanous27b0cf92023-08-07 12:02:40 -0700653 if (!keepAlive)
654 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700655 BMCWEB_LOG_DEBUG("{} keepalive not set. Closing socket",
656 logPtr(this));
657
658 gracefulClose();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700659 return;
660 }
661
662 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
663 res.clear();
Ed Tanous1d1d7782024-04-09 12:54:08 -0700664 initParser();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700665
666 userSession = nullptr;
667
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700668 req->clear();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700669 doReadHeaders();
670 }
671
Ed Tanous52e31622024-01-23 16:31:11 -0800672 void doWrite()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700673 {
Ed Tanous62598e32023-07-17 17:06:25 -0700674 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Ed Tanous52e31622024-01-23 16:31:11 -0800675 res.preparePayload();
Ed Tanous27b0cf92023-08-07 12:02:40 -0700676
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800677 startDeadline();
Ed Tanous4d698612024-02-06 14:57:24 -0800678 boost::beast::async_write(
679 adaptor,
680 boost::beast::http::message_generator(std::move(res.response)),
Ed Tanous52e31622024-01-23 16:31:11 -0800681 std::bind_front(&self_type::afterDoWrite, this,
682 shared_from_this()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700683 }
684
Ed Tanous1abe55e2018-09-05 08:30:59 -0700685 void cancelDeadlineTimer()
686 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800687 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700688 }
689
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800690 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700691 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800692 // Timer is already started so no further action is required.
693 if (timerStarted)
694 {
695 return;
696 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700697
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800698 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800699
700 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
701 timer.expires_after(timeout);
Ed Tanous81c4e332023-05-18 10:30:34 -0700702 timer.async_wait([weakSelf](const boost::system::error_code& ec) {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800703 // Note, we are ignoring other types of errors here; If the timer
704 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800705 std::shared_ptr<Connection<Adaptor, Handler>> self =
706 weakSelf.lock();
707 if (!self)
708 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700709 if (ec == boost::asio::error::operation_aborted)
710 {
711 BMCWEB_LOG_DEBUG(
712 "{} Timer canceled on connection being destroyed",
713 logPtr(self.get()));
714 return;
715 }
Ed Tanous62598e32023-07-17 17:06:25 -0700716 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
717 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800718 return;
719 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800720
721 self->timerStarted = false;
722
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800723 if (ec)
724 {
Ed Tanous1d1d7782024-04-09 12:54:08 -0700725 if (ec == boost::asio::error::operation_aborted)
726 {
727 BMCWEB_LOG_DEBUG("{} Timer canceled", logPtr(self.get()));
728 return;
729 }
730 BMCWEB_LOG_CRITICAL("{} Timer failed {}", logPtr(self.get()),
Ed Tanous62598e32023-07-17 17:06:25 -0700731 ec);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800732 }
733
Ed Tanous1d1d7782024-04-09 12:54:08 -0700734 BMCWEB_LOG_WARNING("{} Connection timed out, hard closing",
Ed Tanous62598e32023-07-17 17:06:25 -0700735 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800736
Ed Tanous1d1d7782024-04-09 12:54:08 -0700737 self->hardClose();
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800738 });
739
Ed Tanous7d243eb2023-01-23 15:57:41 -0800740 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700741 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700742 }
743
Ed Tanous1abe55e2018-09-05 08:30:59 -0700744 Adaptor adaptor;
745 Handler* handler;
Ed Tanous1d1d7782024-04-09 12:54:08 -0700746
747 boost::asio::ip::address ip;
748
Ed Tanousa24526d2018-12-10 15:17:59 -0800749 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700750 // re-created on Connection reset
Ed Tanousb2896142024-01-31 15:25:47 -0800751 std::optional<boost::beast::http::request_parser<bmcweb::HttpBody>> parser;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700752
Ed Tanous3112a142018-11-29 15:45:10 -0800753 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700754
Jonathan Doman102a4cd2024-04-15 16:56:23 -0700755 std::shared_ptr<crow::Request> req;
Ed Tanous89cda632024-04-16 08:45:54 -0700756 std::string accept;
757
Ed Tanous1abe55e2018-09-05 08:30:59 -0700758 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700759
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700760 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100761 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700762
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800763 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700764
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800765 bool keepAlive = true;
766
Ed Tanous7d243eb2023-01-23 15:57:41 -0800767 bool timerStarted = false;
768
Ed Tanous1abe55e2018-09-05 08:30:59 -0700769 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000770
771 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700772 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800773
774 using std::enable_shared_from_this<
775 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800776};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700777} // namespace crow