blob: b2096d493d9948476eb4def37ecd39125e0d9d1b [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 Tanous3ccb3ad2023-01-13 17:40:03 -08007#include "json_html_serializer.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07008#include "logging.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -08009#include "mutual_tls.hpp"
10#include "security_headers.hpp"
11#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>
Ed Tanousd32c4fa2021-09-14 13:16:51 -070027#include <boost/url/url_view.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 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 Tanouscf9e4172022-12-21 09:30:16 -080044// NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
Ed Tanous6fbdbca2021-12-06 14:36:06 -080045static int connectionCount = 0;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070046
Ed Tanous0260d9d2021-02-07 19:31:07 +000047// request body limit size set by the bmcwebHttpReqBodyLimitMb option
Ed Tanous6de264c2022-01-06 12:47:59 -080048constexpr uint64_t httpReqBodyLimit =
49 1024UL * 1024UL * bmcwebHttpReqBodyLimitMb;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070050
James Feist3909dc82020-04-03 10:58:55 -070051constexpr uint64_t loggedOutPostBodyLimit = 4096;
52
53constexpr uint32_t httpHeaderLimit = 8192;
54
Ed Tanous52cc1122020-07-18 13:51:21 -070055template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050056class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070057 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070058{
Ed Tanous7c8e0642022-02-21 12:11:14 -080059 using self_type = Connection<Adaptor, Handler>;
60
Ed Tanous1abe55e2018-09-05 08:30:59 -070061 public:
Ed Tanous5dfb5b22021-12-03 11:24:53 -080062 Connection(Handler* handlerIn, boost::asio::steady_timer&& timerIn,
Ed Tanous81ce6092020-12-17 16:54:55 +000063 std::function<std::string()>& getCachedDateStrF,
Ed Tanous5dfb5b22021-12-03 11:24:53 -080064 Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080065 adaptor(std::move(adaptorIn)),
Ed Tanous5dfb5b22021-12-03 11:24:53 -080066 handler(handlerIn), timer(std::move(timerIn)),
67 getCachedDateStr(getCachedDateStrF)
Ed Tanous1abe55e2018-09-05 08:30:59 -070068 {
69 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070070 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070071 parser->header_limit(httpHeaderLimit);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020072
73#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous40aa0582021-07-14 13:24:40 -070074 prepareMutualTls();
75#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
76
Ed Tanous40aa0582021-07-14 13:24:40 -070077 connectionCount++;
Ed Tanous6fbdbca2021-12-06 14:36:06 -080078
Ed Tanous40aa0582021-07-14 13:24:40 -070079 BMCWEB_LOG_DEBUG << this << " Connection open, total "
80 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070081 }
82
83 ~Connection()
84 {
John Edward Broadbent4147b8a2021-07-19 16:52:24 -070085 res.setCompleteRequestHandler(nullptr);
Ed Tanous40aa0582021-07-14 13:24:40 -070086 cancelDeadlineTimer();
Ed Tanous6fbdbca2021-12-06 14:36:06 -080087
Ed Tanous40aa0582021-07-14 13:24:40 -070088 connectionCount--;
89 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
90 << connectionCount;
Ed Tanous40aa0582021-07-14 13:24:40 -070091 }
92
Ed Tanousecd6a3a2022-01-07 09:18:40 -080093 Connection(const Connection&) = delete;
94 Connection(Connection&&) = delete;
95 Connection& operator=(const Connection&) = delete;
96 Connection& operator=(Connection&&) = delete;
97
Ed Tanous7c8e0642022-02-21 12:11:14 -080098 bool tlsVerifyCallback(bool preverified,
99 boost::asio::ssl::verify_context& ctx)
100 {
101 // We always return true to allow full auth flow for resources that
102 // don't require auth
103 if (preverified)
104 {
105 userSession = verifyMtlsUser(req->ipAddress, ctx);
106 if (userSession)
107 {
108 sessionIsFromTransport = true;
109 }
110 }
111 return true;
112 }
113
Ed Tanous40aa0582021-07-14 13:24:40 -0700114 void prepareMutualTls()
115 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -0800116 std::error_code error;
117 std::filesystem::path caPath(ensuressl::trustStorePath);
118 auto caAvailable = !std::filesystem::is_empty(caPath, error);
119 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700120 if (caAvailable && persistent_data::SessionStore::getInstance()
121 .getAuthMethodsConfig()
122 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100123 {
124 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700125 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800126
Ed Tanous9eb808c2022-01-25 10:19:23 -0800127 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800128 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800129 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700130 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800131 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700132 static_cast<unsigned int>(id.length()));
133 if (ret == 0)
134 {
135 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
136 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100137 }
138
Ed Tanous002d39b2022-05-31 08:59:27 -0700139 adaptor.set_verify_callback(
Ed Tanous7c8e0642022-02-21 12:11:14 -0800140 std::bind_front(&self_type::tlsVerifyCallback, this));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700141 }
142
Ed Tanousceac6f72018-12-02 11:58:47 -0800143 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700144 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800145 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700146 }
147
Ed Tanous1abe55e2018-09-05 08:30:59 -0700148 void start()
149 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800150 if (connectionCount >= 100)
151 {
152 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
153 return;
154 }
155
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800156 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500157
Ed Tanousceac6f72018-12-02 11:58:47 -0800158 // TODO(ed) Abstract this to a more clever class with the idea of an
159 // asynchronous "start"
160 if constexpr (std::is_same_v<Adaptor,
161 boost::beast::ssl_stream<
162 boost::asio::ip::tcp::socket>>)
163 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000164 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
165 [this, self(shared_from_this())](
166 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700167 if (ec)
168 {
169 return;
170 }
171 doReadHeaders();
172 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800173 }
174 else
175 {
176 doReadHeaders();
177 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700178 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700179
Ed Tanous1abe55e2018-09-05 08:30:59 -0700180 void handle()
181 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700182 std::error_code reqEc;
183 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
184 if (reqEc)
185 {
186 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
Gunnar Mills262f1152022-12-20 15:18:47 -0600187 res.result(boost::beast::http::status::bad_request);
188 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700189 return;
190 }
Ed Tanous596b2032021-09-13 10:32:22 -0700191 thisReq.session = userSession;
192
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000193 // Fetch the client IP address
194 readClientIp();
195
Ed Tanous1abe55e2018-09-05 08:30:59 -0700196 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700197 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700198 {
Ed Tanous596b2032021-09-13 10:32:22 -0700199 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700200 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700201 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800202 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700203 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700204 }
205 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700206
Ed Tanouse278c182019-03-13 16:23:37 -0700207 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700208 << " " << this << " HTTP/" << thisReq.version() / 10
209 << "." << thisReq.version() % 10 << ' '
210 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800211 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700212
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700213 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700214
Ed Tanous596b2032021-09-13 10:32:22 -0700215 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700216 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200217
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700218 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700219 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800220 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700221 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700222 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800223 keepAlive = thisReq.keepAlive();
Nan Zhoua43ea822022-05-27 00:42:44 +0000224#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhoud055a342022-05-25 01:15:34 +0000225 if (!crow::authentication::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700226 thisReq.session == nullptr)
227 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800228 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700229 forward_unauthorized::sendUnauthorized(
Ed Tanousc127a0f2022-05-11 15:23:59 -0700230 req->url, req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700231 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800232 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700233 return;
234 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000235#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800236 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
237 BMCWEB_LOG_DEBUG << "Setting completion handler";
238 asyncResp->res.setCompleteRequestHandler(
239 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700240 self->completeRequest(thisRes);
241 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700242
Ed Tanous596b2032021-09-13 10:32:22 -0700243 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700244 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700245 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700246 "websocket"))
247 {
Ed Tanous596b2032021-09-13 10:32:22 -0700248 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700249 // delete lambda with self shared_ptr
250 // to enable connection destruction
Nan Zhou72374eb2022-01-27 17:06:51 -0800251 asyncResp->res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700252 return;
253 }
Ed Tanous291d7092022-04-13 12:34:57 -0700254 std::string_view expected =
255 req->getHeaderValue(boost::beast::http::field::if_none_match);
256 if (!expected.empty())
257 {
258 res.setExpectedHash(expected);
259 }
Ed Tanous596b2032021-09-13 10:32:22 -0700260 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700261 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700262
Ed Tanouse278c182019-03-13 16:23:37 -0700263 bool isAlive()
264 {
Ed Tanouse278c182019-03-13 16:23:37 -0700265 if constexpr (std::is_same_v<Adaptor,
266 boost::beast::ssl_stream<
267 boost::asio::ip::tcp::socket>>)
268 {
269 return adaptor.next_layer().is_open();
270 }
271 else
272 {
273 return adaptor.is_open();
274 }
275 }
276 void close()
277 {
Ed Tanouse278c182019-03-13 16:23:37 -0700278 if constexpr (std::is_same_v<Adaptor,
279 boost::beast::ssl_stream<
280 boost::asio::ip::tcp::socket>>)
281 {
282 adaptor.next_layer().close();
Nan Zhou72374eb2022-01-27 17:06:51 -0800283 if (sessionIsFromTransport && userSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200284 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700285 BMCWEB_LOG_DEBUG
286 << this
287 << " Removing TLS session: " << userSession->uniqueId;
288 persistent_data::SessionStore::getInstance().removeSession(
289 userSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200290 }
Ed Tanouse278c182019-03-13 16:23:37 -0700291 }
292 else
293 {
294 adaptor.close();
295 }
296 }
297
Nan Zhou72374eb2022-01-27 17:06:51 -0800298 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700299 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700300 if (!req)
301 {
302 return;
303 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800304 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800305 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800306
Ed Tanous1abe55e2018-09-05 08:30:59 -0700307 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800308 << res.resultInt() << " keepalive=" << keepAlive;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700309
Ed Tanous0260d9d2021-02-07 19:31:07 +0000310 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700311
Nan Zhoud055a342022-05-25 01:15:34 +0000312 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700313
Ed Tanouse278c182019-03-13 16:23:37 -0700314 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700315 {
316 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
317 // isReading
318 // << ' ' << isWriting;
319 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000320
321 // delete lambda with self shared_ptr
322 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700323 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700324 return;
325 }
Ed Tanous291d7092022-04-13 12:34:57 -0700326
327 res.setHashAndHandleNotModified();
328
Ed Tanous1abe55e2018-09-05 08:30:59 -0700329 if (res.body().empty() && !res.jsonValue.empty())
330 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700331 using http_helpers::ContentType;
Ed Tanoused194be2022-08-07 16:50:11 -0700332 std::array<ContentType, 3> allowed{
333 ContentType::CBOR, ContentType::JSON, ContentType::HTML};
Ed Tanous99351cd2022-08-07 16:42:51 -0700334 ContentType prefered =
335 getPreferedContentType(req->getHeaderValue("Accept"), allowed);
336
337 if (prefered == ContentType::HTML)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700338 {
339 prettyPrintJson(res);
340 }
Ed Tanoused194be2022-08-07 16:50:11 -0700341 else if (prefered == ContentType::CBOR)
342 {
343 res.addHeader(boost::beast::http::field::content_type,
344 "application/cbor");
345 nlohmann::json::to_cbor(res.jsonValue, res.body());
346 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700347 else
348 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700349 // Technically prefered could also be NoMatch here, but we'd
350 // like to default to something rather than return 400 for
351 // backward compatibility.
Ed Tanousf610caa2022-03-17 08:53:00 -0700352 res.addHeader(boost::beast::http::field::content_type,
353 "application/json");
Ed Tanous71f52d92021-02-19 08:51:17 -0800354 res.body() = res.jsonValue.dump(
355 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700356 }
357 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700358
Ed Tanous1abe55e2018-09-05 08:30:59 -0700359 if (res.resultInt() >= 400 && res.body().empty())
360 {
361 res.body() = std::string(res.reason());
362 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700363
364 if (res.result() == boost::beast::http::status::no_content)
365 {
366 // Boost beast throws if content is provided on a no-content
367 // response. Ideally, this would never happen, but in the case that
368 // it does, we don't want to throw.
369 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100370 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700371 res.body().clear();
372 }
373
Ed Tanous1abe55e2018-09-05 08:30:59 -0700374 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
375
Nan Zhou72374eb2022-01-27 17:06:51 -0800376 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000377
378 // delete lambda with self shared_ptr
379 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700380 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700381 }
382
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500383 void readClientIp()
384 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700385 boost::asio::ip::address ip;
386 boost::system::error_code ec = getClientIp(ip);
387 if (ec)
388 {
389 return;
390 }
391 req->ipAddress = ip;
392 }
393
394 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
395 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500396 boost::system::error_code ec;
397 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
398 boost::asio::ip::tcp::endpoint endpoint =
399 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
400
401 if (ec)
402 {
403 // If remote endpoint fails keep going. "ClientOriginIPAddress"
404 // will be empty.
405 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
406 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700407 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500408 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700409 ip = endpoint.address();
410 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500411 }
412
Ed Tanous1abe55e2018-09-05 08:30:59 -0700413 private:
414 void doReadHeaders()
415 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700416 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
417
418 // Clean up any previous Connection.
419 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800420 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000421 [this,
422 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000423 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700424 BMCWEB_LOG_DEBUG << this << " async_read_header "
425 << bytesTransferred << " Bytes";
426 bool errorWhileReading = false;
427 if (ec)
428 {
429 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600430 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700431 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700432 BMCWEB_LOG_WARNING
433 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700434 }
435 else
436 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700437 BMCWEB_LOG_ERROR
438 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700439 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700440 }
441 else
442 {
443 // if the adaptor isn't open anymore, and wasn't handed to a
444 // websocket, treat as an error
445 if (!isAlive() &&
446 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700447 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700448 errorWhileReading = true;
449 }
450 }
451
452 cancelDeadlineTimer();
453
454 if (errorWhileReading)
455 {
456 close();
457 BMCWEB_LOG_DEBUG << this << " from read(1)";
458 return;
459 }
460
461 readClientIp();
462
463 boost::asio::ip::address ip;
464 if (getClientIp(ip))
465 {
466 BMCWEB_LOG_DEBUG << "Unable to get client IP";
467 }
468 sessionIsFromTransport = false;
469#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
470 boost::beast::http::verb method = parser->get().method();
471 userSession = crow::authentication::authenticate(
472 ip, res, method, parser->get().base(), userSession);
473
474 bool loggedIn = userSession != nullptr;
475 if (!loggedIn)
476 {
477 const boost::optional<uint64_t> contentLength =
478 parser->content_length();
479 if (contentLength && *contentLength > loggedOutPostBodyLimit)
480 {
481 BMCWEB_LOG_DEBUG << "Content length greater than limit "
482 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700483 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700484 return;
485 }
486
Ed Tanous002d39b2022-05-31 08:59:27 -0700487 BMCWEB_LOG_DEBUG << "Starting quick deadline";
488 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000489#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800490
Ed Tanous002d39b2022-05-31 08:59:27 -0700491 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700492 });
493 }
494
495 void doRead()
496 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700497 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800498 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700499 boost::beast::http::async_read(adaptor, buffer, *parser,
500 [this, self(shared_from_this())](
501 const boost::system::error_code& ec,
502 std::size_t bytesTransferred) {
503 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
504 << " Bytes";
505 cancelDeadlineTimer();
506 if (ec)
507 {
508 BMCWEB_LOG_ERROR << this
509 << " Error while reading: " << ec.message();
510 close();
511 BMCWEB_LOG_DEBUG << this << " from read(1)";
512 return;
513 }
514 handle();
515 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700516 }
517
Nan Zhou72374eb2022-01-27 17:06:51 -0800518 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700519 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100520 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800521 thisRes.preparePayload();
522 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800523 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700524 boost::beast::http::async_write(adaptor, *serializer,
525 [this, self(shared_from_this())](
526 const boost::system::error_code& ec,
527 std::size_t bytesTransferred) {
528 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
529 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700530
Ed Tanous002d39b2022-05-31 08:59:27 -0700531 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700532
Ed Tanous002d39b2022-05-31 08:59:27 -0700533 if (ec)
534 {
535 BMCWEB_LOG_DEBUG << this << " from write(2)";
536 return;
537 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800538 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700539 {
540 close();
541 BMCWEB_LOG_DEBUG << this << " from write(1)";
542 return;
543 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700544
Ed Tanous002d39b2022-05-31 08:59:27 -0700545 serializer.reset();
546 BMCWEB_LOG_DEBUG << this << " Clearing response";
547 res.clear();
548 parser.emplace(std::piecewise_construct, std::make_tuple());
549 parser->body_limit(httpReqBodyLimit); // reset body limit for
550 // newly created parser
551 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700552
Ed Tanous002d39b2022-05-31 08:59:27 -0700553 // If the session was built from the transport, we don't need to
554 // clear it. All other sessions are generated per request.
555 if (!sessionIsFromTransport)
556 {
557 userSession = nullptr;
558 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700559
Ed Tanous002d39b2022-05-31 08:59:27 -0700560 // Destroy the Request via the std::optional
561 req.reset();
562 doReadHeaders();
563 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700564 }
565
Ed Tanous1abe55e2018-09-05 08:30:59 -0700566 void cancelDeadlineTimer()
567 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800568 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700569 }
570
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800571 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700572 {
573 cancelDeadlineTimer();
574
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800575 std::chrono::seconds timeout(15);
576 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800577 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800578 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700579 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800580 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700581 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800582
583 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
584 timer.expires_after(timeout);
585 timer.async_wait([weakSelf](const boost::system::error_code ec) {
586 // Note, we are ignoring other types of errors here; If the timer
587 // failed for any reason, we should still close the connection
588
589 std::shared_ptr<Connection<Adaptor, Handler>> self =
590 weakSelf.lock();
591 if (!self)
592 {
593 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
594 return;
595 }
596 if (ec == boost::asio::error::operation_aborted)
597 {
598 // Canceled wait means the path succeeeded.
599 return;
600 }
601 if (ec)
602 {
603 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
604 }
605
606 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
607
608 self->close();
609 });
610
611 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612 }
613
Ed Tanous1abe55e2018-09-05 08:30:59 -0700614 Adaptor adaptor;
615 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800616 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700617 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800618 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700619 boost::beast::http::request_parser<boost::beast::http::string_body>>
620 parser;
621
Ed Tanous3112a142018-11-29 15:45:10 -0800622 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700623
Ed Tanousa24526d2018-12-10 15:17:59 -0800624 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700625 boost::beast::http::string_body>>
626 serializer;
627
Ed Tanousa24526d2018-12-10 15:17:59 -0800628 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700629 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700630
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700631 bool sessionIsFromTransport = false;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700632 std::shared_ptr<persistent_data::UserSession> userSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700633
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800634 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700635
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800636 bool keepAlive = true;
637
Ed Tanous1abe55e2018-09-05 08:30:59 -0700638 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000639
640 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700641 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800642
643 using std::enable_shared_from_this<
644 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800645};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700646} // namespace crow