blob: 028222ea09af8b705f991ac1b6b72cfbb3a789f3 [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 {
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
Nan Zhoud055a342022-05-25 01:15:34 +0000227 if (!crow::authentication::isOnAllowlist(req->url, req->method()) &&
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700228 thisReq.session == nullptr)
229 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800230 BMCWEB_LOG_WARNING << "Authentication failed";
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700231 forward_unauthorized::sendUnauthorized(
Ed Tanousc127a0f2022-05-11 15:23:59 -0700232 req->url, req->getHeaderValue("X-Requested-With"),
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700233 req->getHeaderValue("Accept"), res);
Nan Zhou72374eb2022-01-27 17:06:51 -0800234 completeRequest(res);
Ed Tanous1d3c14a2021-09-22 18:54:40 -0700235 return;
236 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000237#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Nan Zhou72374eb2022-01-27 17:06:51 -0800238 auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
239 BMCWEB_LOG_DEBUG << "Setting completion handler";
240 asyncResp->res.setCompleteRequestHandler(
241 [self(shared_from_this())](crow::Response& thisRes) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700242 self->completeRequest(thisRes);
243 });
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700244
Ed Tanous596b2032021-09-13 10:32:22 -0700245 if (thisReq.isUpgrade() &&
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700246 boost::iequals(
Ed Tanous596b2032021-09-13 10:32:22 -0700247 thisReq.getHeaderValue(boost::beast::http::field::upgrade),
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700248 "websocket"))
249 {
Ed Tanous596b2032021-09-13 10:32:22 -0700250 handler->handleUpgrade(thisReq, res, std::move(adaptor));
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700251 // delete lambda with self shared_ptr
252 // to enable connection destruction
Nan Zhou72374eb2022-01-27 17:06:51 -0800253 asyncResp->res.setCompleteRequestHandler(nullptr);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700254 return;
255 }
Ed Tanous291d7092022-04-13 12:34:57 -0700256 std::string_view expected =
257 req->getHeaderValue(boost::beast::http::field::if_none_match);
258 if (!expected.empty())
259 {
260 res.setExpectedHash(expected);
261 }
Ed Tanous596b2032021-09-13 10:32:22 -0700262 handler->handle(thisReq, asyncResp);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700263 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700264
Ed Tanouse278c182019-03-13 16:23:37 -0700265 bool isAlive()
266 {
Ed Tanouse278c182019-03-13 16:23:37 -0700267 if constexpr (std::is_same_v<Adaptor,
268 boost::beast::ssl_stream<
269 boost::asio::ip::tcp::socket>>)
270 {
271 return adaptor.next_layer().is_open();
272 }
273 else
274 {
275 return adaptor.is_open();
276 }
277 }
278 void close()
279 {
Ed Tanouse278c182019-03-13 16:23:37 -0700280 if constexpr (std::is_same_v<Adaptor,
281 boost::beast::ssl_stream<
282 boost::asio::ip::tcp::socket>>)
283 {
284 adaptor.next_layer().close();
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100285 if (mtlsSession != nullptr)
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200286 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700287 BMCWEB_LOG_DEBUG
288 << this
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100289 << " Removing TLS session: " << mtlsSession->uniqueId;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700290 persistent_data::SessionStore::getInstance().removeSession(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100291 mtlsSession);
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200292 }
Ed Tanouse278c182019-03-13 16:23:37 -0700293 }
294 else
295 {
296 adaptor.close();
297 }
298 }
299
Nan Zhou72374eb2022-01-27 17:06:51 -0800300 void completeRequest(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700301 {
Ed Tanousf79b7a52021-09-22 19:04:29 -0700302 if (!req)
303 {
304 return;
305 }
Nan Zhou72374eb2022-01-27 17:06:51 -0800306 res = std::move(thisRes);
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800307 res.keepAlive(keepAlive);
Ed Tanous5ae6f922023-01-09 10:45:53 -0800308
Ed Tanous1abe55e2018-09-05 08:30:59 -0700309 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800310 << res.resultInt() << " keepalive=" << keepAlive;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700311
Ed Tanous0260d9d2021-02-07 19:31:07 +0000312 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700313
Nan Zhoud055a342022-05-25 01:15:34 +0000314 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700315
Ed Tanouse278c182019-03-13 16:23:37 -0700316 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700317 {
318 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
319 // isReading
320 // << ' ' << isWriting;
321 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000322
323 // delete lambda with self shared_ptr
324 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700325 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700326 return;
327 }
Ed Tanous291d7092022-04-13 12:34:57 -0700328
329 res.setHashAndHandleNotModified();
330
Ed Tanous1abe55e2018-09-05 08:30:59 -0700331 if (res.body().empty() && !res.jsonValue.empty())
332 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700333 using http_helpers::ContentType;
Ed Tanoused194be2022-08-07 16:50:11 -0700334 std::array<ContentType, 3> allowed{
335 ContentType::CBOR, ContentType::JSON, ContentType::HTML};
Ed Tanous99351cd2022-08-07 16:42:51 -0700336 ContentType prefered =
337 getPreferedContentType(req->getHeaderValue("Accept"), allowed);
338
339 if (prefered == ContentType::HTML)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700340 {
341 prettyPrintJson(res);
342 }
Ed Tanoused194be2022-08-07 16:50:11 -0700343 else if (prefered == ContentType::CBOR)
344 {
345 res.addHeader(boost::beast::http::field::content_type,
346 "application/cbor");
347 nlohmann::json::to_cbor(res.jsonValue, res.body());
348 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700349 else
350 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700351 // Technically prefered could also be NoMatch here, but we'd
352 // like to default to something rather than return 400 for
353 // backward compatibility.
Ed Tanousf610caa2022-03-17 08:53:00 -0700354 res.addHeader(boost::beast::http::field::content_type,
355 "application/json");
Ed Tanous71f52d92021-02-19 08:51:17 -0800356 res.body() = res.jsonValue.dump(
357 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358 }
359 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700360
Ed Tanous1abe55e2018-09-05 08:30:59 -0700361 if (res.resultInt() >= 400 && res.body().empty())
362 {
363 res.body() = std::string(res.reason());
364 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700365
366 if (res.result() == boost::beast::http::status::no_content)
367 {
368 // Boost beast throws if content is provided on a no-content
369 // response. Ideally, this would never happen, but in the case that
370 // it does, we don't want to throw.
371 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100372 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700373 res.body().clear();
374 }
375
Ed Tanous1abe55e2018-09-05 08:30:59 -0700376 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
377
Nan Zhou72374eb2022-01-27 17:06:51 -0800378 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000379
380 // delete lambda with self shared_ptr
381 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700382 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700383 }
384
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500385 void readClientIp()
386 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700387 boost::asio::ip::address ip;
388 boost::system::error_code ec = getClientIp(ip);
389 if (ec)
390 {
391 return;
392 }
393 req->ipAddress = ip;
394 }
395
396 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
397 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500398 boost::system::error_code ec;
399 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
400 boost::asio::ip::tcp::endpoint endpoint =
401 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
402
403 if (ec)
404 {
405 // If remote endpoint fails keep going. "ClientOriginIPAddress"
406 // will be empty.
407 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
408 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700409 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500410 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700411 ip = endpoint.address();
412 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500413 }
414
Ed Tanous1abe55e2018-09-05 08:30:59 -0700415 private:
416 void doReadHeaders()
417 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700418 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
419
420 // Clean up any previous Connection.
421 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800422 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000423 [this,
424 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000425 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700426 BMCWEB_LOG_DEBUG << this << " async_read_header "
427 << bytesTransferred << " Bytes";
428 bool errorWhileReading = false;
429 if (ec)
430 {
431 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600432 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700433 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700434 BMCWEB_LOG_WARNING
435 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700436 }
437 else
438 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700439 BMCWEB_LOG_ERROR
440 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700441 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700442 }
443 else
444 {
445 // if the adaptor isn't open anymore, and wasn't handed to a
446 // websocket, treat as an error
447 if (!isAlive() &&
448 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700449 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700450 errorWhileReading = true;
451 }
452 }
453
454 cancelDeadlineTimer();
455
456 if (errorWhileReading)
457 {
458 close();
459 BMCWEB_LOG_DEBUG << this << " from read(1)";
460 return;
461 }
462
463 readClientIp();
464
465 boost::asio::ip::address ip;
466 if (getClientIp(ip))
467 {
468 BMCWEB_LOG_DEBUG << "Unable to get client IP";
469 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700470#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
471 boost::beast::http::verb method = parser->get().method();
472 userSession = crow::authentication::authenticate(
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100473 ip, res, method, parser->get().base(), mtlsSession);
Ed Tanous002d39b2022-05-31 08:59:27 -0700474
475 bool loggedIn = userSession != nullptr;
476 if (!loggedIn)
477 {
478 const boost::optional<uint64_t> contentLength =
479 parser->content_length();
480 if (contentLength && *contentLength > loggedOutPostBodyLimit)
481 {
482 BMCWEB_LOG_DEBUG << "Content length greater than limit "
483 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700484 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700485 return;
486 }
487
Ed Tanous002d39b2022-05-31 08:59:27 -0700488 BMCWEB_LOG_DEBUG << "Starting quick deadline";
489 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000490#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800491
Ed Tanous002d39b2022-05-31 08:59:27 -0700492 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700493 });
494 }
495
496 void doRead()
497 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700498 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800499 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700500 boost::beast::http::async_read(adaptor, buffer, *parser,
501 [this, self(shared_from_this())](
502 const boost::system::error_code& ec,
503 std::size_t bytesTransferred) {
504 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
505 << " Bytes";
506 cancelDeadlineTimer();
507 if (ec)
508 {
509 BMCWEB_LOG_ERROR << this
510 << " Error while reading: " << ec.message();
511 close();
512 BMCWEB_LOG_DEBUG << this << " from read(1)";
513 return;
514 }
515 handle();
516 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700517 }
518
Nan Zhou72374eb2022-01-27 17:06:51 -0800519 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700520 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100521 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800522 thisRes.preparePayload();
523 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800524 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700525 boost::beast::http::async_write(adaptor, *serializer,
526 [this, self(shared_from_this())](
527 const boost::system::error_code& ec,
528 std::size_t bytesTransferred) {
529 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
530 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700531
Ed Tanous002d39b2022-05-31 08:59:27 -0700532 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700533
Ed Tanous002d39b2022-05-31 08:59:27 -0700534 if (ec)
535 {
536 BMCWEB_LOG_DEBUG << this << " from write(2)";
537 return;
538 }
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800539 if (!keepAlive)
Ed Tanous002d39b2022-05-31 08:59:27 -0700540 {
541 close();
542 BMCWEB_LOG_DEBUG << this << " from write(1)";
543 return;
544 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700545
Ed Tanous002d39b2022-05-31 08:59:27 -0700546 serializer.reset();
547 BMCWEB_LOG_DEBUG << this << " Clearing response";
548 res.clear();
549 parser.emplace(std::piecewise_construct, std::make_tuple());
550 parser->body_limit(httpReqBodyLimit); // reset body limit for
551 // newly created parser
552 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700553
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100554 userSession = nullptr;
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700555
Ed Tanous002d39b2022-05-31 08:59:27 -0700556 // Destroy the Request via the std::optional
557 req.reset();
558 doReadHeaders();
559 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700560 }
561
Ed Tanous1abe55e2018-09-05 08:30:59 -0700562 void cancelDeadlineTimer()
563 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800564 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700565 }
566
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800567 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700568 {
569 cancelDeadlineTimer();
570
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800571 std::chrono::seconds timeout(15);
572 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800573 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800574 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700575 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800576 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700577 }
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800578
579 std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
580 timer.expires_after(timeout);
581 timer.async_wait([weakSelf](const boost::system::error_code ec) {
582 // Note, we are ignoring other types of errors here; If the timer
583 // failed for any reason, we should still close the connection
584
585 std::shared_ptr<Connection<Adaptor, Handler>> self =
586 weakSelf.lock();
587 if (!self)
588 {
589 BMCWEB_LOG_CRITICAL << self << " Failed to capture connection";
590 return;
591 }
592 if (ec == boost::asio::error::operation_aborted)
593 {
594 // Canceled wait means the path succeeeded.
595 return;
596 }
597 if (ec)
598 {
599 BMCWEB_LOG_CRITICAL << self << " timer failed " << ec;
600 }
601
602 BMCWEB_LOG_WARNING << self << "Connection timed out, closing";
603
604 self->close();
605 });
606
607 BMCWEB_LOG_DEBUG << this << " timer started";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700608 }
609
Ed Tanous1abe55e2018-09-05 08:30:59 -0700610 Adaptor adaptor;
611 Handler* handler;
Ed Tanousa24526d2018-12-10 15:17:59 -0800612 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700613 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800614 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700615 boost::beast::http::request_parser<boost::beast::http::string_body>>
616 parser;
617
Ed Tanous3112a142018-11-29 15:45:10 -0800618 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700619
Ed Tanousa24526d2018-12-10 15:17:59 -0800620 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700621 boost::beast::http::string_body>>
622 serializer;
623
Ed Tanousa24526d2018-12-10 15:17:59 -0800624 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700625 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700626
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700627 std::shared_ptr<persistent_data::UserSession> userSession;
Boleslaw Ogonczyk Makowskib4963072023-02-06 09:59:58 +0100628 std::shared_ptr<persistent_data::UserSession> mtlsSession;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700629
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800630 boost::asio::steady_timer timer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700631
Ed Tanous4cdc2e82023-01-13 10:03:22 -0800632 bool keepAlive = true;
633
Ed Tanous1abe55e2018-09-05 08:30:59 -0700634 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000635
636 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700637 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800638
639 using std::enable_shared_from_this<
640 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800641};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642} // namespace crow