blob: c28cde37aea7c15e30e51cdf629a4feedeb515c9 [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 Tanous04e438c2020-10-03 08:06:26 -07006#include "http_response.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -07007#include "http_utility.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -08008#include "json_html_serializer.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07009#include "logging.hpp"
Ed Tanous3ccb3ad2023-01-13 17:40:03 -080010#include "mutual_tls.hpp"
11#include "security_headers.hpp"
12#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 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 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100105 mtlsSession = verifyMtlsUser(req->ipAddress, ctx);
106 if (mtlsSession)
Ed Tanous7c8e0642022-02-21 12:11:14 -0800107 {
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100108 BMCWEB_LOG_DEBUG
109 << this
110 << " Generating TLS session: " << mtlsSession->uniqueId;
Ed Tanous7c8e0642022-02-21 12:11:14 -0800111 }
112 }
113 return true;
114 }
115
Ed Tanous40aa0582021-07-14 13:24:40 -0700116 void prepareMutualTls()
117 {
Jonathan Doman83deb7d2020-11-16 17:00:22 -0800118 std::error_code error;
119 std::filesystem::path caPath(ensuressl::trustStorePath);
120 auto caAvailable = !std::filesystem::is_empty(caPath, error);
121 caAvailable = caAvailable && !error;
Ed Tanous2c70f802020-09-28 14:29:23 -0700122 if (caAvailable && persistent_data::SessionStore::getInstance()
123 .getAuthMethodsConfig()
124 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100125 {
126 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700127 std::string id = "bmcweb";
Ed Tanous46ff87b2022-01-07 09:25:51 -0800128
Ed Tanous9eb808c2022-01-25 10:19:23 -0800129 const char* cStr = id.c_str();
Ed Tanous46ff87b2022-01-07 09:25:51 -0800130 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
Ed Tanous9eb808c2022-01-25 10:19:23 -0800131 const auto* idC = reinterpret_cast<const unsigned char*>(cStr);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700132 int ret = SSL_set_session_id_context(
Ed Tanous46ff87b2022-01-07 09:25:51 -0800133 adaptor.native_handle(), idC,
Ed Tanouse7d1a1c2020-09-28 09:36:35 -0700134 static_cast<unsigned int>(id.length()));
135 if (ret == 0)
136 {
137 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
138 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100139 }
140
Ed Tanous002d39b2022-05-31 08:59:27 -0700141 adaptor.set_verify_callback(
Ed Tanous7c8e0642022-02-21 12:11:14 -0800142 std::bind_front(&self_type::tlsVerifyCallback, this));
Ed Tanous7045c8d2017-04-03 10:04:37 -0700143 }
144
Ed Tanousceac6f72018-12-02 11:58:47 -0800145 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700146 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800147 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700148 }
149
Ed Tanous1abe55e2018-09-05 08:30:59 -0700150 void start()
151 {
Ed Tanous6fbdbca2021-12-06 14:36:06 -0800152 if (connectionCount >= 100)
153 {
154 BMCWEB_LOG_CRITICAL << this << "Max connection count exceeded.";
155 return;
156 }
157
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800158 startDeadline();
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500159
Ed Tanousceac6f72018-12-02 11:58:47 -0800160 // TODO(ed) Abstract this to a more clever class with the idea of an
161 // asynchronous "start"
162 if constexpr (std::is_same_v<Adaptor,
163 boost::beast::ssl_stream<
164 boost::asio::ip::tcp::socket>>)
165 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000166 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
167 [this, self(shared_from_this())](
168 const boost::system::error_code& ec) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700169 if (ec)
170 {
171 return;
172 }
173 doReadHeaders();
174 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800175 }
176 else
177 {
178 doReadHeaders();
179 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700180 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700181
Ed Tanous1abe55e2018-09-05 08:30:59 -0700182 void handle()
183 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700184 std::error_code reqEc;
185 crow::Request& thisReq = req.emplace(parser->release(), reqEc);
186 if (reqEc)
187 {
188 BMCWEB_LOG_DEBUG << "Request failed to construct" << reqEc;
Gunnar Mills262f1152022-12-20 15:18:47 -0600189 res.result(boost::beast::http::status::bad_request);
190 completeRequest(res);
Ed Tanousf79b7a52021-09-22 19:04:29 -0700191 return;
192 }
Ed Tanous596b2032021-09-13 10:32:22 -0700193 thisReq.session = userSession;
194
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000195 // Fetch the client IP address
196 readClientIp();
197
Ed Tanous1abe55e2018-09-05 08:30:59 -0700198 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700199 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700200 {
Ed Tanous596b2032021-09-13 10:32:22 -0700201 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700202 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700203 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800204 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700205 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700206 }
207 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700208
Ed Tanouse278c182019-03-13 16:23:37 -0700209 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700210 << " " << this << " HTTP/" << thisReq.version() / 10
211 << "." << thisReq.version() % 10 << ' '
212 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800213 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700214
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700215 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700216
Ed Tanous596b2032021-09-13 10:32:22 -0700217 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700218 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200219
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700220 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700221 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800222 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700223 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700224 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800225 keepAlive = thisReq.keepAlive();
Nan Zhoua43ea822022-05-27 00:42:44 +0000226#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous39662a32023-02-06 15:09:46 -0800227 if (!crow::authentication::isOnAllowlist(req->url().buffer(),
228 req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700229 thisReq.session == nullptr)
230 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800231 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700232 forward_unauthorized::sendUnauthorized(
Ed Tanous39662a32023-02-06 15:09:46 -0800233 req->url().encoded_path(),
234 req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700235 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800236 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700237 return;
238 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000239#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800240 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
241 BMCWEB_LOG_DEBUG << "Setting completion handler";
242 asyncResp->res.setCompleteRequestHandler(
243 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700244 self->completeRequest(thisRes);
245 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700246
Ed Tanous596b2032021-09-13 10:32:22 -0700247 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700248 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700249 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700250 "websocket"))
251 {
Ed Tanous596b2032021-09-13 10:32:22 -0700252 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700253 // delete lambda with self shared_ptr
254 // to enable connection destruction
Nan Zhou72374eb2022-01-27 17:06:51 -0800255 asyncResp->res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700256 return;
257 }
Ed Tanous291d7092022-04-13 12:34:57 -0700258 std::string_view expected =
259 req->getHeaderValue(boost::beast::http::field::if_none_match);
260 if (!expected.empty())
261 {
262 res.setExpectedHash(expected);
263 }
Ed Tanous596b2032021-09-13 10:32:22 -0700264 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700265 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700266
Ed Tanouse278c182019-03-13 16:23:37 -0700267 bool isAlive()
268 {
Ed Tanouse278c182019-03-13 16:23:37 -0700269 if constexpr (std::is_same_v<Adaptor,
270 boost::beast::ssl_stream<
271 boost::asio::ip::tcp::socket>>)
272 {
273 return adaptor.next_layer().is_open();
274 }
275 else
276 {
277 return adaptor.is_open();
278 }
279 }
280 void close()
281 {
Ed Tanouse278c182019-03-13 16:23:37 -0700282 if constexpr (std::is_same_v<Adaptor,
283 boost::beast::ssl_stream<
284 boost::asio::ip::tcp::socket>>)
285 {
286 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100287 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200288 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700289 BMCWEB_LOG_DEBUG
290 << this
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100291 << " Removing TLS session: " << mtlsSession->uniqueId;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700292 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100293 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200294 }
Ed Tanouse278c182019-03-13 16:23:37 -0700295 }
296 else
297 {
298 adaptor.close();
299 }
300 }
301
Nan Zhou72374eb2022-01-27 17:06:51 -0800302 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700303 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700304 if (!req)
305 {
306 return;
307 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800308 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800309 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800310
Ed Tanous39662a32023-02-06 15:09:46 -0800311 BMCWEB_LOG_INFO << "Response: " << this << ' '
312 << req->url().encoded_path() << ' ' << res.resultInt()
313 << " keepalive=" << keepAlive;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700314
Ed Tanous0260d9d2021-02-07 19:31:07 +0000315 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700316
Nan Zhoud055a342022-05-25 01:15:34 +0000317 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700318
Ed Tanouse278c182019-03-13 16:23:37 -0700319 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700320 {
321 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
322 // isReading
323 // << ' ' << isWriting;
324 // delete this;
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 return;
330 }
Ed Tanous291d7092022-04-13 12:34:57 -0700331
332 res.setHashAndHandleNotModified();
333
Ed Tanous1abe55e2018-09-05 08:30:59 -0700334 if (res.body().empty() && !res.jsonValue.empty())
335 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700336 using http_helpers::ContentType;
Ed Tanoused194be2022-08-07 16:50:11 -0700337 std::array<ContentType, 3> allowed{
338 ContentType::CBOR, ContentType::JSON, ContentType::HTML};
Ed Tanous99351cd2022-08-07 16:42:51 -0700339 ContentType prefered =
340 getPreferedContentType(req->getHeaderValue("Accept"), allowed);
341
342 if (prefered == ContentType::HTML)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700343 {
344 prettyPrintJson(res);
345 }
Ed Tanoused194be2022-08-07 16:50:11 -0700346 else if (prefered == ContentType::CBOR)
347 {
348 res.addHeader(boost::beast::http::field::content_type,
349 "application/cbor");
350 nlohmann::json::to_cbor(res.jsonValue, res.body());
351 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700352 else
353 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700354 // Technically prefered could also be NoMatch here, but we'd
355 // like to default to something rather than return 400 for
356 // backward compatibility.
Ed Tanousf610caa2022-03-17 08:53:00 -0700357 res.addHeader(boost::beast::http::field::content_type,
358 "application/json");
Ed Tanous71f52d92021-02-19 08:51:17 -0800359 res.body() = res.jsonValue.dump(
360 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700361 }
362 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700363
Ed Tanous1abe55e2018-09-05 08:30:59 -0700364 if (res.resultInt() >= 400 && res.body().empty())
365 {
366 res.body() = std::string(res.reason());
367 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700368
369 if (res.result() == boost::beast::http::status::no_content)
370 {
371 // Boost beast throws if content is provided on a no-content
372 // response. Ideally, this would never happen, but in the case that
373 // it does, we don't want to throw.
374 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100375 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700376 res.body().clear();
377 }
378
Ed Tanous1abe55e2018-09-05 08:30:59 -0700379 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
380
Nan Zhou72374eb2022-01-27 17:06:51 -0800381 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000382
383 // delete lambda with self shared_ptr
384 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700385 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700386 }
387
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500388 void readClientIp()
389 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700390 boost::asio::ip::address ip;
391 boost::system::error_code ec = getClientIp(ip);
392 if (ec)
393 {
394 return;
395 }
396 req->ipAddress = ip;
397 }
398
399 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
400 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500401 boost::system::error_code ec;
402 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
403 boost::asio::ip::tcp::endpoint endpoint =
404 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
405
406 if (ec)
407 {
408 // If remote endpoint fails keep going. "ClientOriginIPAddress"
409 // will be empty.
410 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
411 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700412 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500413 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700414 ip = endpoint.address();
415 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500416 }
417
Ed Tanous1abe55e2018-09-05 08:30:59 -0700418 private:
419 void doReadHeaders()
420 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700421 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
422
423 // Clean up any previous Connection.
424 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800425 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000426 [this,
427 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000428 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700429 BMCWEB_LOG_DEBUG << this << " async_read_header "
430 << bytesTransferred << " Bytes";
431 bool errorWhileReading = false;
432 if (ec)
433 {
434 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600435 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700436 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700437 BMCWEB_LOG_WARNING
438 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700439 }
440 else
441 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700442 BMCWEB_LOG_ERROR
443 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700444 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700445 }
446 else
447 {
448 // if the adaptor isn't open anymore, and wasn't handed to a
449 // websocket, treat as an error
450 if (!isAlive() &&
451 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700452 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700453 errorWhileReading = true;
454 }
455 }
456
457 cancelDeadlineTimer();
458
459 if (errorWhileReading)
460 {
461 close();
462 BMCWEB_LOG_DEBUG << this << " from read(1)";
463 return;
464 }
465
466 readClientIp();
467
468 boost::asio::ip::address ip;
469 if (getClientIp(ip))
470 {
471 BMCWEB_LOG_DEBUG << "Unable to get client IP";
472 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700473#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
474 boost::beast::http::verb method = parser->get().method();
475 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100476 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700477
478 bool loggedIn = userSession != nullptr;
479 if (!loggedIn)
480 {
481 const boost::optional<uint64_t> contentLength =
482 parser->content_length();
483 if (contentLength && *contentLength > loggedOutPostBodyLimit)
484 {
485 BMCWEB_LOG_DEBUG << "Content length greater than limit "
486 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700487 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700488 return;
489 }
490
Ed Tanous002d39b2022-05-31 08:59:27 -0700491 BMCWEB_LOG_DEBUG << "Starting quick deadline";
492 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000493#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800494
Ed Tanous7d243eb2023-01-23 15:57:41 -0800495 if (parser->is_done())
496 {
497 handle();
498 return;
499 }
500
Ed Tanous002d39b2022-05-31 08:59:27 -0700501 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700502 });
503 }
504
505 void doRead()
506 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700507 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800508 startDeadline();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800509 boost::beast::http::async_read_some(
510 adaptor, buffer, *parser,
511 [this,
512 self(shared_from_this())](const boost::system::error_code& ec,
513 std::size_t bytesTransferred) {
514 BMCWEB_LOG_DEBUG << this << " async_read_some " << bytesTransferred
Ed Tanous002d39b2022-05-31 08:59:27 -0700515 << " Bytes";
Ed Tanous7d243eb2023-01-23 15:57:41 -0800516
Ed Tanous002d39b2022-05-31 08:59:27 -0700517 if (ec)
518 {
519 BMCWEB_LOG_ERROR << this
520 << " Error while reading: " << ec.message();
521 close();
522 BMCWEB_LOG_DEBUG << this << " from read(1)";
523 return;
524 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800525
526 // If the user is logged in, allow them to send files incrementally
527 // one piece at a time. If authentication is disabled then there is
528 // no user session hence always allow to send one piece at a time.
529 if (userSession != nullptr)
530 {
531 cancelDeadlineTimer();
532 }
533 if (!parser->is_done())
534 {
535 doRead();
536 return;
537 }
538
539 cancelDeadlineTimer();
Ed Tanous002d39b2022-05-31 08:59:27 -0700540 handle();
Ed Tanous7d243eb2023-01-23 15:57:41 -0800541 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700542 }
543
Nan Zhou72374eb2022-01-27 17:06:51 -0800544 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700545 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100546 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800547 thisRes.preparePayload();
548 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800549 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700550 boost::beast::http::async_write(adaptor, *serializer,
551 [this, self(shared_from_this())](
552 const boost::system::error_code& ec,
553 std::size_t bytesTransferred) {
554 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
555 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700556
Ed Tanous002d39b2022-05-31 08:59:27 -0700557 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700558
Ed Tanous002d39b2022-05-31 08:59:27 -0700559 if (ec)
560 {
561 BMCWEB_LOG_DEBUG << this << " from write(2)";
562 return;
563 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800564 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700565 {
566 close();
567 BMCWEB_LOG_DEBUG << this << " from write(1)";
568 return;
569 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700570
Ed Tanous002d39b2022-05-31 08:59:27 -0700571 serializer.reset();
572 BMCWEB_LOG_DEBUG << this << " Clearing response";
573 res.clear();
574 parser.emplace(std::piecewise_construct, std::make_tuple());
575 parser->body_limit(httpReqBodyLimit); // reset body limit for
576 // newly created parser
577 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700578
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100579 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700580
Ed Tanous002d39b2022-05-31 08:59:27 -0700581 // Destroy the Request via the std::optional
582 req.reset();
583 doReadHeaders();
584 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700585 }
586
Ed Tanous1abe55e2018-09-05 08:30:59 -0700587 void cancelDeadlineTimer()
588 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800589 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700590 }
591
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800592 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700593 {
Ed Tanous7d243eb2023-01-23 15:57:41 -0800594 // Timer is already started so no further action is required.
595 if (timerStarted)
596 {
597 return;
598 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700599
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800600 std::chrono::seconds timeout(15);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800601
602 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
603 timer.expires_after(timeout);
604 timer.async_wait([weakSelf](const boost::system::error_code ec) {
605 // Note, we are ignoring other types of errors here; If the timer
606 // failed for any reason, we should still close the connection
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800607 std::shared_ptr<Connection<Adaptor, Handler>> self =
608 weakSelf.lock();
609 if (!self)
610 {
611 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
612 return;
613 }
Ed Tanous7d243eb2023-01-23 15:57:41 -0800614
615 self->timerStarted = false;
616
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800617 if (ec == boost::asio::error::operation_aborted)
618 {
619 // Canceled wait means the path succeeeded.
620 return;
621 }
622 if (ec)
623 {
624 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
625 }
626
627 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
628
629 self->close();
630 });
631
Ed Tanous7d243eb2023-01-23 15:57:41 -0800632 timerStarted = true;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800633 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700634 }
635
Ed Tanous1abe55e2018-09-05 08:30:59 -0700636 Adaptor adaptor;
637 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800638 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700639 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800640 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 boost::beast::http::request_parser<boost::beast::http::string_body>>
642 parser;
643
Ed Tanous3112a142018-11-29 15:45:10 -0800644 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645
Ed Tanousa24526d2018-12-10 15:17:59 -0800646 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700647 boost::beast::http::string_body>>
648 serializer;
649
Ed Tanousa24526d2018-12-10 15:17:59 -0800650 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700652
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700653 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100654 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700655
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800656 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700657
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800658 bool keepAlive = true;
659
Ed Tanous7d243eb2023-01-23 15:57:41 -0800660 bool timerStarted = false;
661
Ed Tanous1abe55e2018-09-05 08:30:59 -0700662 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000663
664 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700665 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800666
667 using std::enable_shared_from_this<
668 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800669};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700670} // namespace crow