blob: 45581fdf2647d52112b171741633e921892d2954 [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 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;
Ed Tanous5ae6f922023-01-09 10:45:53 -0800192 res.keepAlive(thisReq.keepAlive());
Ed Tanous596b2032021-09-13 10:32:22 -0700193
Ivan Mikhaylovf65b0be2021-04-19 10:05:30 +0000194 // Fetch the client IP address
195 readClientIp();
196
Ed Tanous1abe55e2018-09-05 08:30:59 -0700197 // Check for HTTP version 1.1.
Ed Tanous596b2032021-09-13 10:32:22 -0700198 if (thisReq.version() == 11)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700199 {
Ed Tanous596b2032021-09-13 10:32:22 -0700200 if (thisReq.getHeaderValue(boost::beast::http::field::host).empty())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700201 {
Ed Tanousde5c9f32019-03-26 09:17:55 -0700202 res.result(boost::beast::http::status::bad_request);
Nan Zhou72374eb2022-01-27 17:06:51 -0800203 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700204 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700205 }
206 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700207
Ed Tanouse278c182019-03-13 16:23:37 -0700208 BMCWEB_LOG_INFO << "Request: "
Ed Tanous596b2032021-09-13 10:32:22 -0700209 << " " << this << " HTTP/" << thisReq.version() / 10
210 << "." << thisReq.version() % 10 << ' '
211 << thisReq.methodString() << " " << thisReq.target()
Ed Tanous8cc8ede2022-02-28 10:20:59 -0800212 << " " << thisReq.ipAddress.to_string();
Ed Tanousd32c4fa2021-09-14 13:16:51 -0700213
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700214 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700215
Ed Tanous596b2032021-09-13 10:32:22 -0700216 thisReq.ioService = static_cast<decltype(thisReq.ioService)>(
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700217 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200218
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700219 if (res.completed)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700220 {
Nan Zhou72374eb2022-01-27 17:06:51 -0800221 completeRequest(res);
Ed Tanous6c7f01d2021-08-25 13:42:35 -0700222 return;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700223 }
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 Tanous5ae6f922023-01-09 10:45:53 -0800305
Ed Tanous1abe55e2018-09-05 08:30:59 -0700306 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
Ed Tanous5ae6f922023-01-09 10:45:53 -0800307 << res.resultInt() << " keepalive=" << res.keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700308
Ed Tanous0260d9d2021-02-07 19:31:07 +0000309 addSecurityHeaders(*req, res);
Ed Tanous52cc1122020-07-18 13:51:21 -0700310
Nan Zhoud055a342022-05-25 01:15:34 +0000311 crow::authentication::cleanupTempSession(*req);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700312
Ed Tanouse278c182019-03-13 16:23:37 -0700313 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700314 {
315 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
316 // isReading
317 // << ' ' << isWriting;
318 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000319
320 // delete lambda with self shared_ptr
321 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700322 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700323 return;
324 }
Ed Tanous291d7092022-04-13 12:34:57 -0700325
326 res.setHashAndHandleNotModified();
327
Ed Tanous1abe55e2018-09-05 08:30:59 -0700328 if (res.body().empty() && !res.jsonValue.empty())
329 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700330 using http_helpers::ContentType;
Ed Tanoused194be2022-08-07 16:50:11 -0700331 std::array<ContentType, 3> allowed{
332 ContentType::CBOR, ContentType::JSON, ContentType::HTML};
Ed Tanous99351cd2022-08-07 16:42:51 -0700333 ContentType prefered =
334 getPreferedContentType(req->getHeaderValue("Accept"), allowed);
335
336 if (prefered == ContentType::HTML)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700337 {
338 prettyPrintJson(res);
339 }
Ed Tanoused194be2022-08-07 16:50:11 -0700340 else if (prefered == ContentType::CBOR)
341 {
342 res.addHeader(boost::beast::http::field::content_type,
343 "application/cbor");
344 nlohmann::json::to_cbor(res.jsonValue, res.body());
345 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700346 else
347 {
Ed Tanous99351cd2022-08-07 16:42:51 -0700348 // Technically prefered could also be NoMatch here, but we'd
349 // like to default to something rather than return 400 for
350 // backward compatibility.
Ed Tanousf610caa2022-03-17 08:53:00 -0700351 res.addHeader(boost::beast::http::field::content_type,
352 "application/json");
Ed Tanous71f52d92021-02-19 08:51:17 -0800353 res.body() = res.jsonValue.dump(
354 2, ' ', true, nlohmann::json::error_handler_t::replace);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700355 }
356 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700357
Ed Tanous1abe55e2018-09-05 08:30:59 -0700358 if (res.resultInt() >= 400 && res.body().empty())
359 {
360 res.body() = std::string(res.reason());
361 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700362
363 if (res.result() == boost::beast::http::status::no_content)
364 {
365 // Boost beast throws if content is provided on a no-content
366 // response. Ideally, this would never happen, but in the case that
367 // it does, we don't want to throw.
368 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100369 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700370 res.body().clear();
371 }
372
Ed Tanous1abe55e2018-09-05 08:30:59 -0700373 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
374
Nan Zhou72374eb2022-01-27 17:06:51 -0800375 doWrite(res);
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000376
377 // delete lambda with self shared_ptr
378 // to enable connection destruction
John Edward Broadbent4147b8a2021-07-19 16:52:24 -0700379 res.setCompleteRequestHandler(nullptr);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700380 }
381
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500382 void readClientIp()
383 {
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700384 boost::asio::ip::address ip;
385 boost::system::error_code ec = getClientIp(ip);
386 if (ec)
387 {
388 return;
389 }
390 req->ipAddress = ip;
391 }
392
393 boost::system::error_code getClientIp(boost::asio::ip::address& ip)
394 {
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500395 boost::system::error_code ec;
396 BMCWEB_LOG_DEBUG << "Fetch the client IP address";
397 boost::asio::ip::tcp::endpoint endpoint =
398 boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
399
400 if (ec)
401 {
402 // If remote endpoint fails keep going. "ClientOriginIPAddress"
403 // will be empty.
404 BMCWEB_LOG_ERROR << "Failed to get the client's IP Address. ec : "
405 << ec;
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700406 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500407 }
John Edward Broadbent59b98b22021-07-13 15:36:32 -0700408 ip = endpoint.address();
409 return ec;
Sunitha Harishc0ea7ae2020-10-30 02:37:30 -0500410 }
411
Ed Tanous1abe55e2018-09-05 08:30:59 -0700412 private:
413 void doReadHeaders()
414 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700415 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
416
417 // Clean up any previous Connection.
418 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800419 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000420 [this,
421 self(shared_from_this())](const boost::system::error_code& ec,
Ed Tanous81ce6092020-12-17 16:54:55 +0000422 std::size_t bytesTransferred) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700423 BMCWEB_LOG_DEBUG << this << " async_read_header "
424 << bytesTransferred << " Bytes";
425 bool errorWhileReading = false;
426 if (ec)
427 {
428 errorWhileReading = true;
Myung Baea4326fe2023-01-10 14:29:24 -0600429 if (ec == boost::beast::http::error::end_of_stream)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700430 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700431 BMCWEB_LOG_WARNING
432 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700433 }
434 else
435 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700436 BMCWEB_LOG_ERROR
437 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700438 }
Ed Tanous002d39b2022-05-31 08:59:27 -0700439 }
440 else
441 {
442 // if the adaptor isn't open anymore, and wasn't handed to a
443 // websocket, treat as an error
444 if (!isAlive() &&
445 !boost::beast::websocket::is_upgrade(parser->get()))
Ed Tanous1abe55e2018-09-05 08:30:59 -0700446 {
Ed Tanous002d39b2022-05-31 08:59:27 -0700447 errorWhileReading = true;
448 }
449 }
450
451 cancelDeadlineTimer();
452
453 if (errorWhileReading)
454 {
455 close();
456 BMCWEB_LOG_DEBUG << this << " from read(1)";
457 return;
458 }
459
460 readClientIp();
461
462 boost::asio::ip::address ip;
463 if (getClientIp(ip))
464 {
465 BMCWEB_LOG_DEBUG << "Unable to get client IP";
466 }
467 sessionIsFromTransport = false;
468#ifndef BMCWEB_INSECURE_DISABLE_AUTHX
469 boost::beast::http::verb method = parser->get().method();
470 userSession = crow::authentication::authenticate(
471 ip, res, method, parser->get().base(), userSession);
472
473 bool loggedIn = userSession != nullptr;
474 if (!loggedIn)
475 {
476 const boost::optional<uint64_t> contentLength =
477 parser->content_length();
478 if (contentLength && *contentLength > loggedOutPostBodyLimit)
479 {
480 BMCWEB_LOG_DEBUG << "Content length greater than limit "
481 << *contentLength;
Ed Tanouse278c182019-03-13 16:23:37 -0700482 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700483 return;
484 }
485
Ed Tanous002d39b2022-05-31 08:59:27 -0700486 BMCWEB_LOG_DEBUG << "Starting quick deadline";
487 }
Nan Zhoua43ea822022-05-27 00:42:44 +0000488#endif // BMCWEB_INSECURE_DISABLE_AUTHX
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800489
Ed Tanous002d39b2022-05-31 08:59:27 -0700490 doRead();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700491 });
492 }
493
494 void doRead()
495 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700496 BMCWEB_LOG_DEBUG << this << " doRead";
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800497 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700498 boost::beast::http::async_read(adaptor, buffer, *parser,
499 [this, self(shared_from_this())](
500 const boost::system::error_code& ec,
501 std::size_t bytesTransferred) {
502 BMCWEB_LOG_DEBUG << this << " async_read " << bytesTransferred
503 << " Bytes";
504 cancelDeadlineTimer();
505 if (ec)
506 {
507 BMCWEB_LOG_ERROR << this
508 << " Error while reading: " << ec.message();
509 close();
510 BMCWEB_LOG_DEBUG << this << " from read(1)";
511 return;
512 }
513 handle();
514 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700515 }
516
Nan Zhou72374eb2022-01-27 17:06:51 -0800517 void doWrite(crow::Response& thisRes)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700518 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100519 BMCWEB_LOG_DEBUG << this << " doWrite";
Nan Zhou72374eb2022-01-27 17:06:51 -0800520 thisRes.preparePayload();
521 serializer.emplace(*thisRes.stringResponse);
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800522 startDeadline();
Ed Tanous002d39b2022-05-31 08:59:27 -0700523 boost::beast::http::async_write(adaptor, *serializer,
524 [this, self(shared_from_this())](
525 const boost::system::error_code& ec,
526 std::size_t bytesTransferred) {
527 BMCWEB_LOG_DEBUG << this << " async_write " << bytesTransferred
528 << " bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700529
Ed Tanous002d39b2022-05-31 08:59:27 -0700530 cancelDeadlineTimer();
James Feist54d8bb12020-07-20 13:28:59 -0700531
Ed Tanous002d39b2022-05-31 08:59:27 -0700532 if (ec)
533 {
534 BMCWEB_LOG_DEBUG << this << " from write(2)";
535 return;
536 }
Ed Tanous5ae6f922023-01-09 10:45:53 -0800537 if (!serializer->get().keep_alive())
Ed Tanous002d39b2022-05-31 08:59:27 -0700538 {
539 close();
540 BMCWEB_LOG_DEBUG << this << " from write(1)";
541 return;
542 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700543
Ed Tanous002d39b2022-05-31 08:59:27 -0700544 serializer.reset();
545 BMCWEB_LOG_DEBUG << this << " Clearing response";
546 res.clear();
547 parser.emplace(std::piecewise_construct, std::make_tuple());
548 parser->body_limit(httpReqBodyLimit); // reset body limit for
549 // newly created parser
550 buffer.consume(buffer.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -0700551
Ed Tanous002d39b2022-05-31 08:59:27 -0700552 // If the session was built from the transport, we don't need to
553 // clear it. All other sessions are generated per request.
554 if (!sessionIsFromTransport)
555 {
556 userSession = nullptr;
557 }
Ed Tanous9a69d5a2021-09-13 10:23:51 -0700558
Ed Tanous002d39b2022-05-31 08:59:27 -0700559 // Destroy the Request via the std::optional
560 req.reset();
561 doReadHeaders();
562 });
Ed Tanous1abe55e2018-09-05 08:30:59 -0700563 }
564
Ed Tanous1abe55e2018-09-05 08:30:59 -0700565 void cancelDeadlineTimer()
566 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800567 timer.cancel();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700568 }
569
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800570 void startDeadline()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700571 {
572 cancelDeadlineTimer();
573
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800574 std::chrono::seconds timeout(15);
575 // allow slow uploads for logged in users
Lei YU638e2392021-12-28 18:14:13 +0800576 bool loggedIn = userSession != nullptr;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800577 if (loggedIn)
James Feist3909dc82020-04-03 10:58:55 -0700578 {
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800579 timeout = std::chrono::seconds(60);
James Feistcb6cb492020-04-03 13:36:17 -0700580 return;
581 }
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 Tanous1abe55e2018-09-05 08:30:59 -0700636 std::function<std::string()>& getCachedDateStr;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000637
638 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700639 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous5dfb5b22021-12-03 11:24:53 -0800640
641 using std::enable_shared_from_this<
642 Connection<Adaptor, Handler>>::weak_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800643};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700644} // namespace crow