blob: 7d8347638972ebf96c0c1f4da7f96cbeeae52ce5 [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
Nan Zhoud055a342022-05-25 01:15:34 +00004#include "authentication.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07005#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07006#include "http_utility.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07007#include "logging.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07008#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07009
Ed Tanous257f5792018-03-17 14:40:09 -070010#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080011#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080012#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070013#include <boost/asio/ssl/stream.hpp>
Ed Tanous5dfb5b22021-12-03 11:24:53 -080014#include <boost/asio/steady_timer.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080015#include <boost/beast/core/flat_static_buffer.hpp>
Myung Baea4326fe2023-01-10 14:29:24 -060016#include <boost/beast/http/error.hpp>
Ed Tanous918ef252022-05-25 10:40:41 -070017#include <boost/beast/http/parser.hpp>
18#include <boost/beast/http/read.hpp>
19#include <boost/beast/http/serializer.hpp>
20#include <boost/beast/http/write.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053021#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050022#include <boost/beast/websocket.hpp>
Ed Tanousd32c4fa2021-09-14 13:16:51 -070023#include <boost/url/url_view.hpp>
Ed Tanous57fce802019-05-21 13:00:34 -070024#include <json_html_serializer.hpp>
Ed Tanous7c8e0642022-02-21 12:11:14 -080025#include <mutual_tls.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070026#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050027#include <ssl_key_handler.hpp>
28
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 Tanous1abe55e2018-09-05 08:30:59 -070036inline void prettyPrintJson(crow::Response& res)
37{
Ed Tanous57fce802019-05-21 13:00:34 -070038 json_html_util::dumpHtml(res.body(), res.jsonValue);
39
Ed Tanousd9f6c622022-03-17 09:12:17 -070040 res.addHeader(boost::beast::http::field::content_type,
41 "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070042}
43
Ed Tanous6fbdbca2021-12-06 14:36:06 -080044static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070045
Ed Tanous0260d9d2021-02-07 19:31:07 +000046// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Ed Tanous6de264c2022-01-06 12:47:59 -080047constexpr uint64_t httpReqBodyLimit =
48 1024UL * 1024UL * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070049
James Feist3909dc82020-04-03 10:58:55 -070050constexpr uint64_t loggedOutPostBodyLimit = 4096;
51
52constexpr uint32_t httpHeaderLimit = 8192;
53
Ed Tanous52cc1122020-07-18 13:51:21 -070054template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050055class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070056 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070057{
Ed Tanous7c8e0642022-02-21 12:11:14 -080058 using self_type = Connection<Adaptor, Handler>;
59
Ed Tanous1abe55e2018-09-05 08:30:59 -070060 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080061 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000062 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080063 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080064 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080065 handler(handlerIn), timer(std::move(timerIn)),
66 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070067 {
68 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070069 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070070 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020071
72#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070073 prepareMutualTls();
74#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
75
Ed Tanous40aa0582021-07-14 13:24:40 -070076 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080077
Ed Tanous40aa0582021-07-14 13:24:40 -070078 BMCWEB_LOG_DEBUG << this << " Connection open, total "
79 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070080 }
81
82 ~Connection()
83 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070084 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070085 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080086
Ed Tanous40aa0582021-07-14 13:24:40 -070087 connectionCount--;
88 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
89 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070090 }
91
Ed Tanousecd6a3a2022-01-07 09:18:40 -080092 Connection(const Connection&) = delete;
93 Connection(Connection&&) = delete;
94 Connection& operator=(const Connection&) = delete;
95 Connection& operator=(Connection&&) = delete;
96
Ed Tanous7c8e0642022-02-21 12:11:14 -080097 bool tlsVerifyCallback(bool preverified,
98 boost::asio::ssl::verify_context& ctx)
99 {
100 // We always return true to allow full auth flow for resources that
101 // don't require auth
102 if (preverified)
103 {
104 userSession = verifyMtlsUser(req->ipAddress, ctx);
105 if (userSession)
106 {
107 sessionIsFromTransport = true;
108 }
109 }
110 return true;
111 }
112
Ed Tanous40aa0582021-07-14 13:24:40 -0700113 void prepareMutualTls()
114 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -0800115 std::error_code error;
116 std::filesystem::path caPath(ensuressl::trustStorePath);
117 auto caAvailable = !std::filesystem::is_empty(caPath, error);
118 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700119 if (caAvailable && persistent_data::SessionStore::getInstance()
120 .getAuthMethodsConfig()
121 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100122 {
123 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700124 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800125
Ed Tanous9eb808c2022-01-25 10:19:23 -0800126 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800127 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800128 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700129 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800130 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700131 static_cast<unsigned int>(id.length()));
132 if (ret == 0)
133 {
134 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
135 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100136 }
137
Ed Tanous002d39b2022-05-31 08:59:27 -0700138 adaptor.set_verify_callback(
Ed Tanous7c8e0642022-02-21 12:11:14 -0800139 std::bind_front(&self_type::tlsVerifyCallback, this));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700140 }
141
Ed Tanousceac6f72018-12-02 11:58:47 -0800142 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700143 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800144 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700145 }
146
Ed Tanous1abe55e2018-09-05 08:30:59 -0700147 void start()
148 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800149 if (connectionCount >= 100)
150 {
151 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
152 return;
153 }
154
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800155 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500156
Ed Tanousceac6f72018-12-02 11:58:47 -0800157 // TODO(ed) Abstract this to a more clever class with the idea of an
158 // asynchronous "start"
159 if constexpr (std::is_same_v<Adaptor,
160 boost::beast::ssl_stream<
161 boost::asio::ip::tcp::socket>>)
162 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000163 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
164 [this, self(shared_from_this())](
165 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700166 if (ec)
167 {
168 return;
169 }
170 doReadHeaders();
171 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800172 }
173 else
174 {
175 doReadHeaders();
176 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700177 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700178
Ed Tanous1abe55e2018-09-05 08:30:59 -0700179 void handle()
180 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700181 std::error_code reqEc;
182 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
183 if (reqEc)
184 {
185 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
Gunnar Mills262f1152022-12-20 15:18:47 -0600186 res.result(boost::beast::http::status::bad_request);
187 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700188 return;
189 }
Ed Tanous596b2032021-09-13 10:32:22 -0700190 thisReq.session = userSession;
191
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000192 // Fetch the client IP address
193 readClientIp();
194
Ed Tanous1abe55e2018-09-05 08:30:59 -0700195 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700196 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700197 {
Ed Tanous596b2032021-09-13 10:32:22 -0700198 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700199 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700200 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800201 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700202 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700203 }
204 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700205
Ed Tanouse278c182019-03-13 16:23:37 -0700206 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700207 << " " << this << " HTTP/" << thisReq.version() / 10
208 << "." << thisReq.version() % 10 << ' '
209 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800210 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700211
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700212 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700213
Ed Tanous596b2032021-09-13 10:32:22 -0700214 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700215 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200216
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700217 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700218 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800219 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700220 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700221 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000222#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhoud055a342022-05-25 01:15:34 +0000223 if (!crow::authentication::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700224 thisReq.session == nullptr)
225 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800226 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700227 forward_unauthorized::sendUnauthorized(
Ed Tanousc127a0f2022-05-11 15:23:59 -0700228 req->url, req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700229 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800230 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700231 return;
232 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000233#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800234 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
235 BMCWEB_LOG_DEBUG << "Setting completion handler";
236 asyncResp->res.setCompleteRequestHandler(
237 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700238 self->completeRequest(thisRes);
239 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700240
Ed Tanous596b2032021-09-13 10:32:22 -0700241 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700242 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700243 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700244 "websocket"))
245 {
Ed Tanous596b2032021-09-13 10:32:22 -0700246 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700247 // delete lambda with self shared_ptr
248 // to enable connection destruction
Nan Zhou72374eb2022-01-27 17:06:51 -0800249 asyncResp->res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700250 return;
251 }
Ed Tanous291d7092022-04-13 12:34:57 -0700252 std::string_view expected =
253 req->getHeaderValue(boost::beast::http::field::if_none_match);
254 if (!expected.empty())
255 {
256 res.setExpectedHash(expected);
257 }
Ed Tanous596b2032021-09-13 10:32:22 -0700258 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700259 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700260
Ed Tanouse278c182019-03-13 16:23:37 -0700261 bool isAlive()
262 {
Ed Tanouse278c182019-03-13 16:23:37 -0700263 if constexpr (std::is_same_v<Adaptor,
264 boost::beast::ssl_stream<
265 boost::asio::ip::tcp::socket>>)
266 {
267 return adaptor.next_layer().is_open();
268 }
269 else
270 {
271 return adaptor.is_open();
272 }
273 }
274 void close()
275 {
Ed Tanouse278c182019-03-13 16:23:37 -0700276 if constexpr (std::is_same_v<Adaptor,
277 boost::beast::ssl_stream<
278 boost::asio::ip::tcp::socket>>)
279 {
280 adaptor.next_layer().close();
Nan Zhou72374eb2022-01-27 17:06:51 -0800281 if (sessionIsFromTransport && userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200282 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700283 BMCWEB_LOG_DEBUG
284 << this
285 << " Removing TLS session: " << userSession->uniqueId;
286 persistent_data::SessionStore::getInstance().removeSession(
287 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200288 }
Ed Tanouse278c182019-03-13 16:23:37 -0700289 }
290 else
291 {
292 adaptor.close();
293 }
294 }
295
Nan Zhou72374eb2022-01-27 17:06:51 -0800296 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700297 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700298 if (!req)
299 {
300 return;
301 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800302 res = std::move(thisRes);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700303 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
304 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700305
Ed Tanous0260d9d2021-02-07 19:31:07 +0000306 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700307
Nan Zhoud055a342022-05-25 01:15:34 +0000308 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700309
Ed Tanouse278c182019-03-13 16:23:37 -0700310 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700311 {
312 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
313 // isReading
314 // << ' ' << isWriting;
315 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000316
317 // delete lambda with self shared_ptr
318 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700319 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700320 return;
321 }
Ed Tanous291d7092022-04-13 12:34:57 -0700322
323 res.setHashAndHandleNotModified();
324
Ed Tanous1abe55e2018-09-05 08:30:59 -0700325 if (res.body().empty() && !res.jsonValue.empty())
326 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700327 using http_helpers::ContentType;
Ed Tanoused194be2022-08-07 16:50:11 -0700328 std::array<ContentType, 3> allowed{
329 ContentType::CBOR, ContentType::JSON, ContentType::HTML};
Ed Tanous99351cd2022-08-07 16:42:51 -0700330 ContentType prefered =
331 getPreferedContentType(req->getHeaderValue("Accept"), allowed);
332
333 if (prefered == ContentType::HTML)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700334 {
335 prettyPrintJson(res);
336 }
Ed Tanoused194be2022-08-07 16:50:11 -0700337 else if (prefered == ContentType::CBOR)
338 {
339 res.addHeader(boost::beast::http::field::content_type,
340 "application/cbor");
341 nlohmann::json::to_cbor(res.jsonValue, res.body());
342 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700343 else
344 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700345 // Technically prefered could also be NoMatch here, but we'd
346 // like to default to something rather than return 400 for
347 // backward compatibility.
Ed Tanousf610caa2022-03-17 08:53:00 -0700348 res.addHeader(boost::beast::http::field::content_type,
349 "application/json");
Ed Tanous71f52d92021-02-19 08:51:17 -0800350 res.body() = res.jsonValue.dump(
351 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700352 }
353 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700354
Ed Tanous1abe55e2018-09-05 08:30:59 -0700355 if (res.resultInt() >= 400 && res.body().empty())
356 {
357 res.body() = std::string(res.reason());
358 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700359
360 if (res.result() == boost::beast::http::status::no_content)
361 {
362 // Boost beast throws if content is provided on a no-content
363 // response. Ideally, this would never happen, but in the case that
364 // it does, we don't want to throw.
365 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100366 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700367 res.body().clear();
368 }
369
Ed Tanous1abe55e2018-09-05 08:30:59 -0700370 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
371
372 res.keepAlive(req->keepAlive());
373
Nan Zhou72374eb2022-01-27 17:06:51 -0800374 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000375
376 // delete lambda with self shared_ptr
377 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700378 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700379 }
380
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500381 void readClientIp()
382 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700383 boost::asio::ip::address ip;
384 boost::system::error_code ec = getClientIp(ip);
385 if (ec)
386 {
387 return;
388 }
389 req->ipAddress = ip;
390 }
391
392 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
393 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500394 boost::system::error_code ec;
395 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
396 boost::asio::ip::tcp::endpoint endpoint =
397 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
398
399 if (ec)
400 {
401 // If remote endpoint fails keep going. "ClientOriginIPAddress"
402 // will be empty.
403 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
404 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700405 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500406 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700407 ip = endpoint.address();
408 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500409 }
410
Ed Tanous1abe55e2018-09-05 08:30:59 -0700411 private:
412 void doReadHeaders()
413 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700414 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
415
416 // Clean up any previous Connection.
417 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800418 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000419 [this,
420 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000421 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700422 BMCWEB_LOG_DEBUG << this << " async_read_header "
423 << bytesTransferred << " Bytes";
424 bool errorWhileReading = false;
425 if (ec)
426 {
427 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600428 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700429 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700430 BMCWEB_LOG_WARNING
431 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700432 }
433 else
434 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700435 BMCWEB_LOG_ERROR
436 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700437 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700438 }
439 else
440 {
441 // if the adaptor isn't open anymore, and wasn't handed to a
442 // websocket, treat as an error
443 if (!isAlive() &&
444 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700445 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700446 errorWhileReading = true;
447 }
448 }
449
450 cancelDeadlineTimer();
451
452 if (errorWhileReading)
453 {
454 close();
455 BMCWEB_LOG_DEBUG << this << " from read(1)";
456 return;
457 }
458
459 readClientIp();
460
461 boost::asio::ip::address ip;
462 if (getClientIp(ip))
463 {
464 BMCWEB_LOG_DEBUG << "Unable to get client IP";
465 }
466 sessionIsFromTransport = false;
467#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
468 boost::beast::http::verb method = parser->get().method();
469 userSession = crow::authentication::authenticate(
470 ip, res, method, parser->get().base(), userSession);
471
472 bool loggedIn = userSession != nullptr;
473 if (!loggedIn)
474 {
475 const boost::optional<uint64_t> contentLength =
476 parser->content_length();
477 if (contentLength && *contentLength > loggedOutPostBodyLimit)
478 {
479 BMCWEB_LOG_DEBUG << "Content length greater than limit "
480 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700481 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700482 return;
483 }
484
Ed Tanous002d39b2022-05-31 08:59:27 -0700485 BMCWEB_LOG_DEBUG << "Starting quick deadline";
486 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000487#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800488
Ed Tanous002d39b2022-05-31 08:59:27 -0700489 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700490 });
491 }
492
493 void doRead()
494 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700495 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800496 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700497 boost::beast::http::async_read(adaptor, buffer, *parser,
498 [this, self(shared_from_this())](
499 const boost::system::error_code& ec,
500 std::size_t bytesTransferred) {
501 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
502 << " Bytes";
503 cancelDeadlineTimer();
504 if (ec)
505 {
506 BMCWEB_LOG_ERROR << this
507 << " Error while reading: " << ec.message();
508 close();
509 BMCWEB_LOG_DEBUG << this << " from read(1)";
510 return;
511 }
512 handle();
513 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700514 }
515
Nan Zhou72374eb2022-01-27 17:06:51 -0800516 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700517 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100518 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800519 thisRes.preparePayload();
520 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800521 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700522 boost::beast::http::async_write(adaptor, *serializer,
523 [this, self(shared_from_this())](
524 const boost::system::error_code& ec,
525 std::size_t bytesTransferred) {
526 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
527 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700528
Ed Tanous002d39b2022-05-31 08:59:27 -0700529 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700530
Ed Tanous002d39b2022-05-31 08:59:27 -0700531 if (ec)
532 {
533 BMCWEB_LOG_DEBUG << this << " from write(2)";
534 return;
535 }
536 if (!res.keepAlive())
537 {
538 close();
539 BMCWEB_LOG_DEBUG << this << " from write(1)";
540 return;
541 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700542
Ed Tanous002d39b2022-05-31 08:59:27 -0700543 serializer.reset();
544 BMCWEB_LOG_DEBUG << this << " Clearing response";
545 res.clear();
546 parser.emplace(std::piecewise_construct, std::make_tuple());
547 parser->body_limit(httpReqBodyLimit); // reset body limit for
548 // newly created parser
549 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700550
Ed Tanous002d39b2022-05-31 08:59:27 -0700551 // If the session was built from the transport, we don't need to
552 // clear it. All other sessions are generated per request.
553 if (!sessionIsFromTransport)
554 {
555 userSession = nullptr;
556 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700557
Ed Tanous002d39b2022-05-31 08:59:27 -0700558 // Destroy the Request via the std::optional
559 req.reset();
560 doReadHeaders();
561 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700562 }
563
Ed Tanous1abe55e2018-09-05 08:30:59 -0700564 void cancelDeadlineTimer()
565 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800566 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567 }
568
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800569 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700570 {
571 cancelDeadlineTimer();
572
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800573 std::chrono::seconds timeout(15);
574 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800575 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800576 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700577 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800578 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700579 return;
580 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800581
582 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
583 timer.expires_after(timeout);
584 timer.async_wait([weakSelf](const boost::system::error_code ec) {
585 // Note, we are ignoring other types of errors here; If the timer
586 // failed for any reason, we should still close the connection
587
588 std::shared_ptr<Connection<Adaptor, Handler>> self =
589 weakSelf.lock();
590 if (!self)
591 {
592 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
593 return;
594 }
595 if (ec == boost::asio::error::operation_aborted)
596 {
597 // Canceled wait means the path succeeeded.
598 return;
599 }
600 if (ec)
601 {
602 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
603 }
604
605 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
606
607 self->close();
608 });
609
610 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700611 }
612
Ed Tanous1abe55e2018-09-05 08:30:59 -0700613 Adaptor adaptor;
614 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800615 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700616 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800617 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700618 boost::beast::http::request_parser<boost::beast::http::string_body>>
619 parser;
620
Ed Tanous3112a142018-11-29 15:45:10 -0800621 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700622
Ed Tanousa24526d2018-12-10 15:17:59 -0800623 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700624 boost::beast::http::string_body>>
625 serializer;
626
Ed Tanousa24526d2018-12-10 15:17:59 -0800627 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700628 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700629
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700630 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700631 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700632
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800633 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700634
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