blob: b5d0d2e59efa9e0d2b4cebac7e520191041257a3 [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 Tanous04e438c2020-10-03 08:06:26 -07008#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07009#include "http_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070010#include "logging.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080011#include "mutual_tls.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080012#include "ssl_key_handler.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070013#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070014
Ed Tanous257f5792018-03-17 14:40:09 -070015#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080016#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080017#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070018#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080019#include <boost/asio/steady_timer.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080020#include <boost/beast/core/flat_static_buffer.hpp>
Myung Baea4326fe2023-01-10 14:29:24 -060021#include <boost/beast/http/error.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070022#include <boost/beast/http/parser.hpp>
23#include <boost/beast/http/read.hpp>
24#include <boost/beast/http/serializer.hpp>
25#include <boost/beast/http/write.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053026#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050027#include <boost/beast/websocket.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050028
Manojkiran Eda44250442020-06-16 12:51:38 +053029#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050030#include <chrono>
31#include <vector>
32
Ed Tanous1abe55e2018-09-05 08:30:59 -070033namespace crow
34{
Ed Tanous257f5792018-03-17 14:40:09 -070035
Ed Tanouscf9e4172022-12-21 09:30:16 -080036// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080037static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070038
Ed Tanous0260d9d2021-02-07 19:31:07 +000039// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Patrick Williams89492a12023-05-10 07:51:34 -050040constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL *
41 bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070042
James Feist3909dc82020-04-03 10:58:55 -070043constexpr uint64_t loggedOutPostBodyLimit = 4096;
44
45constexpr uint32_t httpHeaderLimit = 8192;
46
Ed Tanous52cc1122020-07-18 13:51:21 -070047template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050048class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070049 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070050{
Ed Tanous7c8e0642022-02-21 12:11:14 -080051 using self_type = Connection<Adaptor, Handler>;
52
Ed Tanous1abe55e2018-09-05 08:30:59 -070053 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080054 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000055 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080056 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080057 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080058 handler(handlerIn), timer(std::move(timerIn)),
59 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070060 {
61 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070062 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070063 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020064
65#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070066 prepareMutualTls();
67#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
68
Ed Tanous40aa0582021-07-14 13:24:40 -070069 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080070
Ed Tanous62598e32023-07-17 17:06:25 -070071 BMCWEB_LOG_DEBUG("{} Connection open, total {}", logPtr(this),
72 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070073 }
74
75 ~Connection()
76 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070077 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070078 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080079
Ed Tanous40aa0582021-07-14 13:24:40 -070080 connectionCount--;
Ed Tanous62598e32023-07-17 17:06:25 -070081 BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
82 connectionCount);
Ed Tanous40aa0582021-07-14 13:24:40 -070083 }
84
Ed Tanousecd6a3a2022-01-07 09:18:40 -080085 Connection(const Connection&) = delete;
86 Connection(Connection&&) = delete;
87 Connection& operator=(const Connection&) = delete;
88 Connection& operator=(Connection&&) = delete;
89
Ed Tanous7c8e0642022-02-21 12:11:14 -080090 bool tlsVerifyCallback(bool preverified,
91 boost::asio::ssl::verify_context& ctx)
92 {
93 // We always return true to allow full auth flow for resources that
94 // don't require auth
95 if (preverified)
96 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +010097 mtlsSession = verifyMtlsUser(req->ipAddress, ctx);
98 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -080099 {
Ed Tanous62598e32023-07-17 17:06:25 -0700100 BMCWEB_LOG_DEBUG("{} Generating TLS session: {}", logPtr(this),
101 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 {
Ed Tanous62598e32023-07-17 17:06:25 -0700128 BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700129 }
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 {
Ed Tanous62598e32023-07-17 17:06:25 -0700145 BMCWEB_LOG_CRITICAL("{}Max connection count exceeded.",
146 logPtr(this));
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800147 return;
148 }
149
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800150 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500151
Ed Tanousceac6f72018-12-02 11:58:47 -0800152 // TODO(ed) Abstract this to a more clever class with the idea of an
153 // asynchronous "start"
154 if constexpr (std::is_same_v<Adaptor,
155 boost::beast::ssl_stream<
156 boost::asio::ip::tcp::socket>>)
157 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000158 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
159 [this, self(shared_from_this())](
160 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700161 if (ec)
162 {
163 return;
164 }
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800165 afterSslHandshake();
Ed Tanous002d39b2022-05-31 08:59:27 -0700166 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800167 }
168 else
169 {
170 doReadHeaders();
171 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700172 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700173
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800174 void afterSslHandshake()
175 {
176 // If http2 is enabled, negotiate the protocol
177 if constexpr (bmcwebEnableHTTP2)
178 {
179 const unsigned char* alpn = nullptr;
180 unsigned int alpnlen = 0;
181 SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
182 if (alpn != nullptr)
183 {
184 std::string_view selectedProtocol(
185 std::bit_cast<const char*>(alpn), alpnlen);
Ed Tanous62598e32023-07-17 17:06:25 -0700186 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
187 selectedProtocol, alpnlen);
Ed Tanousfca2cbe2021-01-28 14:49:59 -0800188 if (selectedProtocol == "h2")
189 {
190 auto http2 =
191 std::make_shared<HTTP2Connection<Adaptor, Handler>>(
192 std::move(adaptor), handler, getCachedDateStr);
193 http2->start();
194 return;
195 }
196 }
197 }
198
199 doReadHeaders();
200 }
201
Ed Tanous1abe55e2018-09-05 08:30:59 -0700202 void handle()
203 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700204 std::error_code reqEc;
205 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
206 if (reqEc)
207 {
Ed Tanous62598e32023-07-17 17:06:25 -0700208 BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
Gunnar Mills262f1152022-12-20 15:18:47 -0600209 res.result(boost::beast::http::status::bad_request);
210 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700211 return;
212 }
Ed Tanous596b2032021-09-13 10:32:22 -0700213 thisReq.session = userSession;
214
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000215 // Fetch the client IP address
216 readClientIp();
217
Ed Tanous1abe55e2018-09-05 08:30:59 -0700218 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700219 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700220 {
Ed Tanous596b2032021-09-13 10:32:22 -0700221 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700222 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700223 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800224 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700225 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700226 }
227 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700228
Ed Tanous62598e32023-07-17 17:06:25 -0700229 BMCWEB_LOG_INFO("Request: {} HTTP/{}.{} {} {} {}", logPtr(this),
230 thisReq.version() / 10, thisReq.version() % 10,
231 thisReq.methodString(), thisReq.target(),
232 thisReq.ipAddress.to_string());
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700233
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700234 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700235
Ed Tanous596b2032021-09-13 10:32:22 -0700236 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700237 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200238
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700239 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700240 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800241 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700242 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700243 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800244 keepAlive = thisReq.keepAlive();
Nan Zhoua43ea822022-05-27 00:42:44 +0000245#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanousc51a58e2023-03-27 14:43:19 -0700246 if (!crow::authentication::isOnAllowlist(req->url().path(),
Ed Tanous39662a32023-02-06 15:09:46 -0800247 req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700248 thisReq.session == nullptr)
249 {
Ed Tanous62598e32023-07-17 17:06:25 -0700250 BMCWEB_LOG_WARNING("Authentication failed");
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700251 forward_unauthorized::sendUnauthorized(
Ed Tanous39662a32023-02-06 15:09:46 -0800252 req->url().encoded_path(),
253 req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700254 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800255 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700256 return;
257 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000258#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800259 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
Ed Tanous62598e32023-07-17 17:06:25 -0700260 BMCWEB_LOG_DEBUG("Setting completion handler");
Nan Zhou72374eb2022-01-27 17:06:51 -0800261 asyncResp->res.setCompleteRequestHandler(
262 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700263 self->completeRequest(thisRes);
264 });
Ed Tanous6fde95f2023-06-01 07:33:34 -0700265 bool isSse =
266 isContentTypeAllowed(req->getHeaderValue("Accept"),
267 http_helpers::ContentType::EventStream, false);
V-Sanjana88ada3b2023-04-13 15:18:31 +0530268 if ((thisReq.isUpgrade() &&
269 boost::iequals(
270 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
271 "websocket")) ||
Ed Tanous6fde95f2023-06-01 07:33:34 -0700272 isSse)
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700273 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530274 asyncResp->res.setCompleteRequestHandler(
275 [self(shared_from_this())](crow::Response& thisRes) {
276 if (thisRes.result() != boost::beast::http::status::ok)
277 {
278 // When any error occurs before handle upgradation,
279 // the result in response will be set to respective
280 // error. By default the Result will be OK (200),
281 // which implies successful handle upgrade. Response
282 // needs to be sent over this connection only on
283 // failure.
284 self->completeRequest(thisRes);
285 return;
286 }
287 });
288 handler->handleUpgrade(thisReq, asyncResp, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700289 return;
290 }
Ed Tanous291d7092022-04-13 12:34:57 -0700291 std::string_view expected =
292 req->getHeaderValue(boost::beast::http::field::if_none_match);
293 if (!expected.empty())
294 {
295 res.setExpectedHash(expected);
296 }
Ed Tanous596b2032021-09-13 10:32:22 -0700297 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700298 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700299
Ed Tanouse278c182019-03-13 16:23:37 -0700300 bool isAlive()
301 {
Ed Tanouse278c182019-03-13 16:23:37 -0700302 if constexpr (std::is_same_v<Adaptor,
303 boost::beast::ssl_stream<
304 boost::asio::ip::tcp::socket>>)
305 {
306 return adaptor.next_layer().is_open();
307 }
308 else
309 {
310 return adaptor.is_open();
311 }
312 }
313 void close()
314 {
Ed Tanouse278c182019-03-13 16:23:37 -0700315 if constexpr (std::is_same_v<Adaptor,
316 boost::beast::ssl_stream<
317 boost::asio::ip::tcp::socket>>)
318 {
319 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100320 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200321 {
Ed Tanous62598e32023-07-17 17:06:25 -0700322 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
323 mtlsSession->uniqueId);
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700324 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100325 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200326 }
Ed Tanouse278c182019-03-13 16:23:37 -0700327 }
328 else
329 {
330 adaptor.close();
331 }
332 }
333
Nan Zhou72374eb2022-01-27 17:06:51 -0800334 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700335 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700336 if (!req)
337 {
338 return;
339 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800340 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800341 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800342
Ed Tanoused5f8952023-06-22 14:06:22 -0700343 completeResponseFields(*req, res);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700344
Ed Tanouse278c182019-03-13 16:23:37 -0700345 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700346 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700347 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700348 return;
349 }
Ed Tanous291d7092022-04-13 12:34:57 -0700350
Nan Zhou72374eb2022-01-27 17:06:51 -0800351 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000352
353 // delete lambda with self shared_ptr
354 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700355 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700356 }
357
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500358 void readClientIp()
359 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700360 boost::asio::ip::address ip;
361 boost::system::error_code ec = getClientIp(ip);
362 if (ec)
363 {
364 return;
365 }
366 req->ipAddress = ip;
367 }
368
369 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
370 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500371 boost::system::error_code ec;
Ed Tanous62598e32023-07-17 17:06:25 -0700372 BMCWEB_LOG_DEBUG("Fetch the client IP address");
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500373 boost::asio::ip::tcp::endpoint endpoint =
374 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
375
376 if (ec)
377 {
378 // If remote endpoint fails keep going. "ClientOriginIPAddress"
379 // will be empty.
Ed Tanous62598e32023-07-17 17:06:25 -0700380 BMCWEB_LOG_ERROR("Failed to get the client's IP Address. ec : {}",
381 ec);
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700382 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500383 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700384 ip = endpoint.address();
385 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500386 }
387
Ed Tanous1abe55e2018-09-05 08:30:59 -0700388 private:
389 void doReadHeaders()
390 {
Ed Tanous62598e32023-07-17 17:06:25 -0700391 BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700392
393 // Clean up any previous Connection.
394 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800395 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000396 [this,
397 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000398 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700399 BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
400 bytesTransferred);
Ed Tanous002d39b2022-05-31 08:59:27 -0700401 bool errorWhileReading = false;
402 if (ec)
403 {
404 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600405 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700406 {
Ed Tanous62598e32023-07-17 17:06:25 -0700407 BMCWEB_LOG_WARNING("{} Error while reading: {}",
408 logPtr(this), ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700409 }
410 else
411 {
Ed Tanous62598e32023-07-17 17:06:25 -0700412 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
413 ec.message());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700414 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700415 }
416 else
417 {
418 // if the adaptor isn't open anymore, and wasn't handed to a
419 // websocket, treat as an error
420 if (!isAlive() &&
421 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700422 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700423 errorWhileReading = true;
424 }
425 }
426
427 cancelDeadlineTimer();
428
429 if (errorWhileReading)
430 {
431 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700432 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700433 return;
434 }
435
436 readClientIp();
437
438 boost::asio::ip::address ip;
439 if (getClientIp(ip))
440 {
Ed Tanous62598e32023-07-17 17:06:25 -0700441 BMCWEB_LOG_DEBUG("Unable to get client IP");
Ed Tanous002d39b2022-05-31 08:59:27 -0700442 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700443#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
444 boost::beast::http::verb method = parser->get().method();
445 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100446 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700447
448 bool loggedIn = userSession != nullptr;
449 if (!loggedIn)
450 {
451 const boost::optional<uint64_t> contentLength =
452 parser->content_length();
453 if (contentLength && *contentLength > loggedOutPostBodyLimit)
454 {
Ed Tanous62598e32023-07-17 17:06:25 -0700455 BMCWEB_LOG_DEBUG("Content length greater than limit {}",
456 *contentLength);
Ed Tanouse278c182019-03-13 16:23:37 -0700457 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700458 return;
459 }
460
Ed Tanous62598e32023-07-17 17:06:25 -0700461 BMCWEB_LOG_DEBUG("Starting quick deadline");
Ed Tanous002d39b2022-05-31 08:59:27 -0700462 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000463#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800464
Ed Tanous7d243eb2023-01-23 15:57:41 -0800465 if (parser->is_done())
466 {
467 handle();
468 return;
469 }
470
Ed Tanous002d39b2022-05-31 08:59:27 -0700471 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700472 });
473 }
474
475 void doRead()
476 {
Ed Tanous62598e32023-07-17 17:06:25 -0700477 BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800478 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800479 boost::beast::http::async_read_some(
480 adaptor, buffer, *parser,
481 [this,
482 self(shared_from_this())](const boost::system::error_code& ec,
483 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700484 BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
485 bytesTransferred);
Ed Tanous7d243eb2023-01-23 15:57:41 -0800486
Ed Tanous002d39b2022-05-31 08:59:27 -0700487 if (ec)
488 {
Ed Tanous62598e32023-07-17 17:06:25 -0700489 BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
490 ec.message());
Ed Tanous002d39b2022-05-31 08:59:27 -0700491 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700492 BMCWEB_LOG_DEBUG("{} from read(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700493 return;
494 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800495
496 // If the user is logged in, allow them to send files incrementally
497 // one piece at a time. If authentication is disabled then there is
498 // no user session hence always allow to send one piece at a time.
499 if (userSession != nullptr)
500 {
501 cancelDeadlineTimer();
502 }
503 if (!parser->is_done())
504 {
505 doRead();
506 return;
507 }
508
509 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700510 handle();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800511 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700512 }
513
Nan Zhou72374eb2022-01-27 17:06:51 -0800514 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700515 {
Ed Tanous62598e32023-07-17 17:06:25 -0700516 BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
Nan Zhou72374eb2022-01-27 17:06:51 -0800517 thisRes.preparePayload();
518 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800519 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700520 boost::beast::http::async_write(adaptor, *serializer,
521 [this, self(shared_from_this())](
522 const boost::system::error_code& ec,
523 std::size_t bytesTransferred) {
Ed Tanous62598e32023-07-17 17:06:25 -0700524 BMCWEB_LOG_DEBUG("{} async_write {} bytes", logPtr(this),
525 bytesTransferred);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700526
Ed Tanous002d39b2022-05-31 08:59:27 -0700527 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700528
Ed Tanous002d39b2022-05-31 08:59:27 -0700529 if (ec)
530 {
Ed Tanous62598e32023-07-17 17:06:25 -0700531 BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700532 return;
533 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800534 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700535 {
536 close();
Ed Tanous62598e32023-07-17 17:06:25 -0700537 BMCWEB_LOG_DEBUG("{} from write(1)", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700538 return;
539 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700540
Ed Tanous002d39b2022-05-31 08:59:27 -0700541 serializer.reset();
Ed Tanous62598e32023-07-17 17:06:25 -0700542 BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
Ed Tanous002d39b2022-05-31 08:59:27 -0700543 res.clear();
544 parser.emplace(std::piecewise_construct, std::make_tuple());
545 parser->body_limit(httpReqBodyLimit); // reset body limit for
546 // newly created parser
547 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700548
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100549 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700550
Ed Tanous002d39b2022-05-31 08:59:27 -0700551 // Destroy the Request via the std::optional
552 req.reset();
553 doReadHeaders();
554 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700555 }
556
Ed Tanous1abe55e2018-09-05 08:30:59 -0700557 void cancelDeadlineTimer()
558 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800559 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700560 }
561
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800562 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700563 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800564 // Timer is already started so no further action is required.
565 if (timerStarted)
566 {
567 return;
568 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700569
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800570 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800571
572 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
573 timer.expires_after(timeout);
Ed Tanous81c4e332023-05-18 10:30:34 -0700574 timer.async_wait([weakSelf](const boost::system::error_code& ec) {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800575 // Note, we are ignoring other types of errors here; If the timer
576 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800577 std::shared_ptr<Connection<Adaptor, Handler>> self =
578 weakSelf.lock();
579 if (!self)
580 {
Ed Tanous62598e32023-07-17 17:06:25 -0700581 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
582 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800583 return;
584 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800585
586 self->timerStarted = false;
587
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800588 if (ec == boost::asio::error::operation_aborted)
589 {
590 // Canceled wait means the path succeeeded.
591 return;
592 }
593 if (ec)
594 {
Ed Tanous62598e32023-07-17 17:06:25 -0700595 BMCWEB_LOG_CRITICAL("{} timer failed {}", logPtr(self.get()),
596 ec);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800597 }
598
Ed Tanous62598e32023-07-17 17:06:25 -0700599 BMCWEB_LOG_WARNING("{}Connection timed out, closing",
600 logPtr(self.get()));
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800601
602 self->close();
603 });
604
Ed Tanous7d243eb2023-01-23 15:57:41 -0800605 timerStarted = true;
Ed Tanous62598e32023-07-17 17:06:25 -0700606 BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700607 }
608
Ed Tanous1abe55e2018-09-05 08:30:59 -0700609 Adaptor adaptor;
610 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800611 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800613 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700614 boost::beast::http::request_parser<boost::beast::http::string_body>>
615 parser;
616
Ed Tanous3112a142018-11-29 15:45:10 -0800617 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618
Ed Tanousa24526d2018-12-10 15:17:59 -0800619 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700620 boost::beast::http::string_body>>
621 serializer;
622
Ed Tanousa24526d2018-12-10 15:17:59 -0800623 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700624 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700625
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700626 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100627 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700628
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800629 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700630
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800631 bool keepAlive = true;
632
Ed Tanous7d243eb2023-01-23 15:57:41 -0800633 bool timerStarted = false;
634
Ed Tanous1abe55e2018-09-05 08:30:59 -0700635 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000636
637 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700638 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800639
640 using std::enable_shared_from_this<
641 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800642};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700643} // namespace crow