blob: 3548870418781a93e931fb9921029b6fd8c0e86f [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 Tanous04e438c2020-10-03 08:06:26 -07007#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07008#include "http_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07009#include "logging.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080010#include "mutual_tls.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080011#include "ssl_key_handler.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070012#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070013
Ed Tanous257f5792018-03-17 14:40:09 -070014#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080015#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080016#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070017#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080018#include <boost/asio/steady_timer.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080019#include <boost/beast/core/flat_static_buffer.hpp>
Myung Baea4326fe2023-01-10 14:29:24 -060020#include <boost/beast/http/error.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070021#include <boost/beast/http/parser.hpp>
22#include <boost/beast/http/read.hpp>
23#include <boost/beast/http/serializer.hpp>
24#include <boost/beast/http/write.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053025#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050026#include <boost/beast/websocket.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050027
Manojkiran Eda44250442020-06-16 12:51:38 +053028#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050029#include <chrono>
30#include <vector>
31
Ed Tanous1abe55e2018-09-05 08:30:59 -070032namespace crow
33{
Ed Tanous257f5792018-03-17 14:40:09 -070034
Ed Tanouscf9e4172022-12-21 09:30:16 -080035// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080036static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070037
Ed Tanous0260d9d2021-02-07 19:31:07 +000038// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Patrick Williams89492a12023-05-10 07:51:34 -050039constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL *
40 bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070041
James Feist3909dc82020-04-03 10:58:55 -070042constexpr uint64_t loggedOutPostBodyLimit = 4096;
43
44constexpr uint32_t httpHeaderLimit = 8192;
45
Ed Tanous52cc1122020-07-18 13:51:21 -070046template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050047class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070048 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070049{
Ed Tanous7c8e0642022-02-21 12:11:14 -080050 using self_type = Connection<Adaptor, Handler>;
51
Ed Tanous1abe55e2018-09-05 08:30:59 -070052 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080053 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000054 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080055 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080056 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080057 handler(handlerIn), timer(std::move(timerIn)),
58 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070059 {
60 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070062 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020063
64#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070065 prepareMutualTls();
66#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
67
Ed Tanous40aa0582021-07-14 13:24:40 -070068 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080069
Ed Tanous40aa0582021-07-14 13:24:40 -070070 BMCWEB_LOG_DEBUG << this << " Connection open, total "
71 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070072 }
73
74 ~Connection()
75 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070076 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070077 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080078
Ed Tanous40aa0582021-07-14 13:24:40 -070079 connectionCount--;
80 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
81 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070082 }
83
Ed Tanousecd6a3a2022-01-07 09:18:40 -080084 Connection(const Connection&) = delete;
85 Connection(Connection&&) = delete;
86 Connection& operator=(const Connection&) = delete;
87 Connection& operator=(Connection&&) = delete;
88
Ed Tanous7c8e0642022-02-21 12:11:14 -080089 bool tlsVerifyCallback(bool preverified,
90 boost::asio::ssl::verify_context& ctx)
91 {
92 // We always return true to allow full auth flow for resources that
93 // don't require auth
94 if (preverified)
95 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +010096 mtlsSession = verifyMtlsUser(req->ipAddress, ctx);
97 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -080098 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +010099 BMCWEB_LOG_DEBUG
100 << this
101 << " Generating TLS session: " << mtlsSession->uniqueId;
Ed Tanous7c8e0642022-02-21 12:11:14 -0800102 }
103 }
104 return true;
105 }
106
Ed Tanous40aa0582021-07-14 13:24:40 -0700107 void prepareMutualTls()
108 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -0800109 std::error_code error;
110 std::filesystem::path caPath(ensuressl::trustStorePath);
111 auto caAvailable = !std::filesystem::is_empty(caPath, error);
112 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700113 if (caAvailable && persistent_data::SessionStore::getInstance()
114 .getAuthMethodsConfig()
115 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100116 {
117 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700118 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800119
Ed Tanous9eb808c2022-01-25 10:19:23 -0800120 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800121 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800122 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700123 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800124 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700125 static_cast<unsigned int>(id.length()));
126 if (ret == 0)
127 {
128 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
129 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100130 }
131
Ed Tanous002d39b2022-05-31 08:59:27 -0700132 adaptor.set_verify_callback(
Ed Tanous7c8e0642022-02-21 12:11:14 -0800133 std::bind_front(&self_type::tlsVerifyCallback, this));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700134 }
135
Ed Tanousceac6f72018-12-02 11:58:47 -0800136 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700137 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800138 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700139 }
140
Ed Tanous1abe55e2018-09-05 08:30:59 -0700141 void start()
142 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800143 if (connectionCount >= 100)
144 {
145 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
146 return;
147 }
148
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800149 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500150
Ed Tanousceac6f72018-12-02 11:58:47 -0800151 // TODO(ed) Abstract this to a more clever class with the idea of an
152 // asynchronous "start"
153 if constexpr (std::is_same_v<Adaptor,
154 boost::beast::ssl_stream<
155 boost::asio::ip::tcp::socket>>)
156 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000157 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
158 [this, self(shared_from_this())](
159 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700160 if (ec)
161 {
162 return;
163 }
164 doReadHeaders();
165 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800166 }
167 else
168 {
169 doReadHeaders();
170 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700171 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700172
Ed Tanous1abe55e2018-09-05 08:30:59 -0700173 void handle()
174 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700175 std::error_code reqEc;
176 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
177 if (reqEc)
178 {
179 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
Gunnar Mills262f1152022-12-20 15:18:47 -0600180 res.result(boost::beast::http::status::bad_request);
181 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700182 return;
183 }
Ed Tanous596b2032021-09-13 10:32:22 -0700184 thisReq.session = userSession;
185
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000186 // Fetch the client IP address
187 readClientIp();
188
Ed Tanous1abe55e2018-09-05 08:30:59 -0700189 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700190 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700191 {
Ed Tanous596b2032021-09-13 10:32:22 -0700192 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700193 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700194 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800195 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700196 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700197 }
198 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700199
Ed Tanouse278c182019-03-13 16:23:37 -0700200 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700201 << " " << this << " HTTP/" << thisReq.version() / 10
202 << "." << thisReq.version() % 10 << ' '
203 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800204 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700205
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700206 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700207
Ed Tanous596b2032021-09-13 10:32:22 -0700208 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700209 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200210
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700211 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700212 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800213 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700214 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700215 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800216 keepAlive = thisReq.keepAlive();
Nan Zhoua43ea822022-05-27 00:42:44 +0000217#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanousc51a58e2023-03-27 14:43:19 -0700218 if (!crow::authentication::isOnAllowlist(req->url().path(),
Ed Tanous39662a32023-02-06 15:09:46 -0800219 req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700220 thisReq.session == nullptr)
221 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800222 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700223 forward_unauthorized::sendUnauthorized(
Ed Tanous39662a32023-02-06 15:09:46 -0800224 req->url().encoded_path(),
225 req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700226 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800227 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700228 return;
229 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000230#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800231 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
232 BMCWEB_LOG_DEBUG << "Setting completion handler";
233 asyncResp->res.setCompleteRequestHandler(
234 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700235 self->completeRequest(thisRes);
236 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700237 bool isSse =
238 isContentTypeAllowed(req->getHeaderValue("Accept"),
239 http_helpers::ContentType::EventStream, false);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530240 if ((thisReq.isUpgrade() &&
241 boost::iequals(
242 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
243 "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700244 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700245 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530246 asyncResp->res.setCompleteRequestHandler(
247 [self(shared_from_this())](crow::Response& thisRes) {
248 if (thisRes.result() != boost::beast::http::status::ok)
249 {
250 // When any error occurs before handle upgradation,
251 // the result in response will be set to respective
252 // error. By default the Result will be OK (200),
253 // which implies successful handle upgrade. Response
254 // needs to be sent over this connection only on
255 // failure.
256 self->completeRequest(thisRes);
257 return;
258 }
259 });
260 handler->handleUpgrade(thisReq, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700261 return;
262 }
Ed Tanous291d7092022-04-13 12:34:57 -0700263 std::string_view expected =
264 req->getHeaderValue(boost::beast::http::field::if_none_match);
265 if (!expected.empty())
266 {
267 res.setExpectedHash(expected);
268 }
Ed Tanous596b2032021-09-13 10:32:22 -0700269 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700270 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700271
Ed Tanouse278c182019-03-13 16:23:37 -0700272 bool isAlive()
273 {
Ed Tanouse278c182019-03-13 16:23:37 -0700274 if constexpr (std::is_same_v<Adaptor,
275 boost::beast::ssl_stream<
276 boost::asio::ip::tcp::socket>>)
277 {
278 return adaptor.next_layer().is_open();
279 }
280 else
281 {
282 return adaptor.is_open();
283 }
284 }
285 void close()
286 {
Ed Tanouse278c182019-03-13 16:23:37 -0700287 if constexpr (std::is_same_v<Adaptor,
288 boost::beast::ssl_stream<
289 boost::asio::ip::tcp::socket>>)
290 {
291 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100292 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200293 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700294 BMCWEB_LOG_DEBUG
295 << this
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100296 << " Removing TLS session: " << mtlsSession->uniqueId;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700297 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100298 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200299 }
Ed Tanouse278c182019-03-13 16:23:37 -0700300 }
301 else
302 {
303 adaptor.close();
304 }
305 }
306
Nan Zhou72374eb2022-01-27 17:06:51 -0800307 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700308 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700309 if (!req)
310 {
311 return;
312 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800313 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800314 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800315
Ed Tanoused5f8952023-06-22 14:06:22 -0700316 completeResponseFields(*req, res);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700317
Ed Tanouse278c182019-03-13 16:23:37 -0700318 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700319 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700320 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700321 return;
322 }
Ed Tanous291d7092022-04-13 12:34:57 -0700323
Nan Zhou72374eb2022-01-27 17:06:51 -0800324 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000325
326 // delete lambda with self shared_ptr
327 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700328 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700329 }
330
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500331 void readClientIp()
332 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700333 boost::asio::ip::address ip;
334 boost::system::error_code ec = getClientIp(ip);
335 if (ec)
336 {
337 return;
338 }
339 req->ipAddress = ip;
340 }
341
342 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
343 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500344 boost::system::error_code ec;
345 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
346 boost::asio::ip::tcp::endpoint endpoint =
347 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
348
349 if (ec)
350 {
351 // If remote endpoint fails keep going. "ClientOriginIPAddress"
352 // will be empty.
353 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
354 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700355 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500356 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700357 ip = endpoint.address();
358 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500359 }
360
Ed Tanous1abe55e2018-09-05 08:30:59 -0700361 private:
362 void doReadHeaders()
363 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700364 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
365
366 // Clean up any previous Connection.
367 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800368 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000369 [this,
370 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000371 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700372 BMCWEB_LOG_DEBUG << this << " async_read_header "
373 << bytesTransferred << " Bytes";
374 bool errorWhileReading = false;
375 if (ec)
376 {
377 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600378 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700379 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700380 BMCWEB_LOG_WARNING
381 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700382 }
383 else
384 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700385 BMCWEB_LOG_ERROR
386 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700387 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700388 }
389 else
390 {
391 // if the adaptor isn't open anymore, and wasn't handed to a
392 // websocket, treat as an error
393 if (!isAlive() &&
394 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700395 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700396 errorWhileReading = true;
397 }
398 }
399
400 cancelDeadlineTimer();
401
402 if (errorWhileReading)
403 {
404 close();
405 BMCWEB_LOG_DEBUG << this << " from read(1)";
406 return;
407 }
408
409 readClientIp();
410
411 boost::asio::ip::address ip;
412 if (getClientIp(ip))
413 {
414 BMCWEB_LOG_DEBUG << "Unable to get client IP";
415 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700416#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
417 boost::beast::http::verb method = parser->get().method();
418 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100419 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700420
421 bool loggedIn = userSession != nullptr;
422 if (!loggedIn)
423 {
424 const boost::optional<uint64_t> contentLength =
425 parser->content_length();
426 if (contentLength && *contentLength > loggedOutPostBodyLimit)
427 {
428 BMCWEB_LOG_DEBUG << "Content length greater than limit "
429 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700430 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700431 return;
432 }
433
Ed Tanous002d39b2022-05-31 08:59:27 -0700434 BMCWEB_LOG_DEBUG << "Starting quick deadline";
435 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000436#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800437
Ed Tanous7d243eb2023-01-23 15:57:41 -0800438 if (parser->is_done())
439 {
440 handle();
441 return;
442 }
443
Ed Tanous002d39b2022-05-31 08:59:27 -0700444 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700445 });
446 }
447
448 void doRead()
449 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700450 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800451 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800452 boost::beast::http::async_read_some(
453 adaptor, buffer, *parser,
454 [this,
455 self(shared_from_this())](const boost::system::error_code& ec,
456 std::size_t bytesTransferred) {
457 BMCWEB_LOG_DEBUG << this << " async_read_some " << bytesTransferred
Ed Tanous002d39b2022-05-31 08:59:27 -0700458 << " Bytes";
Ed Tanous7d243eb2023-01-23 15:57:41 -0800459
Ed Tanous002d39b2022-05-31 08:59:27 -0700460 if (ec)
461 {
462 BMCWEB_LOG_ERROR << this
463 << " Error while reading: " << ec.message();
464 close();
465 BMCWEB_LOG_DEBUG << this << " from read(1)";
466 return;
467 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800468
469 // If the user is logged in, allow them to send files incrementally
470 // one piece at a time. If authentication is disabled then there is
471 // no user session hence always allow to send one piece at a time.
472 if (userSession != nullptr)
473 {
474 cancelDeadlineTimer();
475 }
476 if (!parser->is_done())
477 {
478 doRead();
479 return;
480 }
481
482 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700483 handle();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800484 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700485 }
486
Nan Zhou72374eb2022-01-27 17:06:51 -0800487 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700488 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100489 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800490 thisRes.preparePayload();
491 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800492 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700493 boost::beast::http::async_write(adaptor, *serializer,
494 [this, self(shared_from_this())](
495 const boost::system::error_code& ec,
496 std::size_t bytesTransferred) {
497 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
498 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700499
Ed Tanous002d39b2022-05-31 08:59:27 -0700500 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700501
Ed Tanous002d39b2022-05-31 08:59:27 -0700502 if (ec)
503 {
504 BMCWEB_LOG_DEBUG << this << " from write(2)";
505 return;
506 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800507 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700508 {
509 close();
510 BMCWEB_LOG_DEBUG << this << " from write(1)";
511 return;
512 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700513
Ed Tanous002d39b2022-05-31 08:59:27 -0700514 serializer.reset();
515 BMCWEB_LOG_DEBUG << this << " Clearing response";
516 res.clear();
517 parser.emplace(std::piecewise_construct, std::make_tuple());
518 parser->body_limit(httpReqBodyLimit); // reset body limit for
519 // newly created parser
520 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700521
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100522 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700523
Ed Tanous002d39b2022-05-31 08:59:27 -0700524 // Destroy the Request via the std::optional
525 req.reset();
526 doReadHeaders();
527 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700528 }
529
Ed Tanous1abe55e2018-09-05 08:30:59 -0700530 void cancelDeadlineTimer()
531 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800532 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700533 }
534
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800535 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700536 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800537 // Timer is already started so no further action is required.
538 if (timerStarted)
539 {
540 return;
541 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700542
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800543 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800544
545 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
546 timer.expires_after(timeout);
Ed Tanous81c4e332023-05-18 10:30:34 -0700547 timer.async_wait([weakSelf](const boost::system::error_code& ec) {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800548 // Note, we are ignoring other types of errors here; If the timer
549 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800550 std::shared_ptr<Connection<Adaptor, Handler>> self =
551 weakSelf.lock();
552 if (!self)
553 {
554 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
555 return;
556 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800557
558 self->timerStarted = false;
559
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800560 if (ec == boost::asio::error::operation_aborted)
561 {
562 // Canceled wait means the path succeeeded.
563 return;
564 }
565 if (ec)
566 {
567 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
568 }
569
570 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
571
572 self->close();
573 });
574
Ed Tanous7d243eb2023-01-23 15:57:41 -0800575 timerStarted = true;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800576 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700577 }
578
Ed Tanous1abe55e2018-09-05 08:30:59 -0700579 Adaptor adaptor;
580 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800581 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700582 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800583 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700584 boost::beast::http::request_parser<boost::beast::http::string_body>>
585 parser;
586
Ed Tanous3112a142018-11-29 15:45:10 -0800587 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700588
Ed Tanousa24526d2018-12-10 15:17:59 -0800589 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700590 boost::beast::http::string_body>>
591 serializer;
592
Ed Tanousa24526d2018-12-10 15:17:59 -0800593 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700594 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700595
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700596 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100597 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700598
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800599 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700600
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800601 bool keepAlive = true;
602
Ed Tanous7d243eb2023-01-23 15:57:41 -0800603 bool timerStarted = false;
604
Ed Tanous1abe55e2018-09-05 08:30:59 -0700605 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000606
607 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700608 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800609
610 using std::enable_shared_from_this<
611 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800612};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700613} // namespace crow