blob: 302d19bd973bdaef626218a10b676ca3a62e9855 [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
Adriana Kobylak0e1cf262019-12-05 13:57:57 -06002#include "config.h"
3
James Feist3909dc82020-04-03 10:58:55 -07004#include "authorization.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"
8#include "timer_queue.hpp"
9#include "utility.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070010
Ed Tanouse0d918b2018-03-27 17:41:04 -070011#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -070012#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080013#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080014#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070015#include <boost/asio/ssl/stream.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080016#include <boost/beast/core/flat_static_buffer.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053017#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050018#include <boost/beast/websocket.hpp>
Ed Tanous57fce802019-05-21 13:00:34 -070019#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070020#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050021#include <ssl_key_handler.hpp>
22
Manojkiran Eda44250442020-06-16 12:51:38 +053023#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050024#include <chrono>
25#include <vector>
26
Ed Tanous1abe55e2018-09-05 08:30:59 -070027namespace crow
28{
Ed Tanous257f5792018-03-17 14:40:09 -070029
Ed Tanous1abe55e2018-09-05 08:30:59 -070030inline void prettyPrintJson(crow::Response& res)
31{
Ed Tanous57fce802019-05-21 13:00:34 -070032 json_html_util::dumpHtml(res.body(), res.jsonValue);
33
Ed Tanous93ef5802019-01-03 10:15:41 -080034 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070035}
36
Ed Tanous55c7b7a2018-05-22 15:27:24 -070037#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -070038static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -070039#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070040
Adriana Kobylak0e1cf262019-12-05 13:57:57 -060041// request body limit size set by the BMCWEB_HTTP_REQ_BODY_LIMIT_MB option
42constexpr unsigned int httpReqBodyLimit =
43 1024 * 1024 * BMCWEB_HTTP_REQ_BODY_LIMIT_MB;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070044
James Feist3909dc82020-04-03 10:58:55 -070045constexpr uint64_t loggedOutPostBodyLimit = 4096;
46
47constexpr uint32_t httpHeaderLimit = 8192;
48
49// drop all connections after 1 minute, this time limit was chosen
50// arbitrarily and can be adjusted later if needed
51static constexpr const size_t loggedInAttempts =
52 (60 / timerQueueTimeoutSeconds);
53
54static constexpr const size_t loggedOutAttempts =
55 (15 / timerQueueTimeoutSeconds);
56
Ed Tanous52cc1122020-07-18 13:51:21 -070057template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050058class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070059 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070060{
61 public:
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070062 Connection(Handler* handlerIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070063 std::function<std::string()>& get_cached_date_str_f,
Ed Tanous271584a2019-07-09 16:24:22 -070064 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080065 adaptor(std::move(adaptorIn)),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070066 handler(handlerIn), getCachedDateStr(get_cached_date_str_f),
67 timerQueue(timerQueueIn)
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);
Ed Tanous1abe55e2018-09-05 08:30:59 -070072 req.emplace(parser->get());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020073
74#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous2c70f802020-09-28 14:29:23 -070075 auto caAvailable = !std::filesystem::is_empty(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010076 std::filesystem::path(ensuressl::trustStorePath));
Ed Tanous2c70f802020-09-28 14:29:23 -070077 if (caAvailable && persistent_data::SessionStore::getInstance()
78 .getAuthMethodsConfig()
79 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010080 {
81 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070082 std::string id = "bmcweb";
83 int ret = SSL_set_session_id_context(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010084 adaptor.native_handle(),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070085 reinterpret_cast<const unsigned char*>(id.c_str()),
86 static_cast<unsigned int>(id.length()));
87 if (ret == 0)
88 {
89 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
90 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010091 }
92
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +010093 adaptor.set_verify_callback([this](
94 bool preverified,
95 boost::asio::ssl::verify_context& ctx) {
96 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -070097 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +010098 .getAuthMethodsConfig()
99 .tls)
100 {
101 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200102 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100103 }
104
105 // We always return true to allow full auth flow
106 if (!preverified)
107 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100108 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100109 return true;
110 }
111
112 X509_STORE_CTX* cts = ctx.native_handle();
113 if (cts == nullptr)
114 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100115 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100116 return true;
117 }
118
119 // Get certificate
120 X509* peerCert =
121 X509_STORE_CTX_get_current_cert(ctx.native_handle());
122 if (peerCert == nullptr)
123 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100124 BMCWEB_LOG_DEBUG << this
125 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100126 return true;
127 }
128
129 // Check if certificate is OK
130 int error = X509_STORE_CTX_get_error(cts);
131 if (error != X509_V_OK)
132 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100133 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100134 return true;
135 }
136 // Check that we have reached final certificate in chain
137 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
138 if (depth != 0)
139
140 {
141 BMCWEB_LOG_DEBUG
142 << this << " Certificate verification in progress (depth "
143 << depth << "), waiting to reach final depth";
144 return true;
145 }
146
147 BMCWEB_LOG_DEBUG << this
148 << " Certificate verification of final depth";
149
150 // Verify KeyUsage
151 bool isKeyUsageDigitalSignature = false;
152 bool isKeyUsageKeyAgreement = false;
153
154 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000155 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100156
157 if (usage == nullptr)
158 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100159 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100160 return true;
161 }
162
163 for (int i = 0; i < usage->length; i++)
164 {
165 if (KU_DIGITAL_SIGNATURE & usage->data[i])
166 {
167 isKeyUsageDigitalSignature = true;
168 }
169 if (KU_KEY_AGREEMENT & usage->data[i])
170 {
171 isKeyUsageKeyAgreement = true;
172 }
173 }
174
175 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
176 {
177 BMCWEB_LOG_DEBUG << this
178 << " Certificate ExtendedKeyUsage does "
179 "not allow provided certificate to "
180 "be used for user authentication";
181 return true;
182 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200183 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100184
185 // Determine that ExtendedKeyUsage includes Client Auth
186
Ed Tanous23a21a12020-07-25 04:45:05 +0000187 stack_st_ASN1_OBJECT* extUsage =
188 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
189 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100190
191 if (extUsage == nullptr)
192 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100193 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100194 return true;
195 }
196
197 bool isExKeyUsageClientAuth = false;
198 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
199 {
200 if (NID_client_auth ==
201 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
202 {
203 isExKeyUsageClientAuth = true;
204 break;
205 }
206 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200207 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100208
209 // Certificate has to have proper key usages set
210 if (!isExKeyUsageClientAuth)
211 {
212 BMCWEB_LOG_DEBUG << this
213 << " Certificate ExtendedKeyUsage does "
214 "not allow provided certificate to "
215 "be used for user authentication";
216 return true;
217 }
218 std::string sslUser;
219 // Extract username contained in CommonName
220 sslUser.resize(256, '\0');
221
222 int status = X509_NAME_get_text_by_NID(
223 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
224 static_cast<int>(sslUser.size()));
225
226 if (status == -1)
227 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100228 BMCWEB_LOG_DEBUG
229 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100230 return true;
231 }
232
233 size_t lastChar = sslUser.find('\0');
234 if (lastChar == std::string::npos || lastChar == 0)
235 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100236 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100237 return true;
238 }
239 sslUser.resize(lastChar);
240
Ed Tanous52cc1122020-07-18 13:51:21 -0700241 session =
242 persistent_data::SessionStore::getInstance()
243 .generateUserSession(
244 sslUser, persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100245 if (auto sp = session.lock())
246 {
247 BMCWEB_LOG_DEBUG << this
248 << " Generating TLS session: " << sp->uniqueId;
249 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100250 return true;
251 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200252#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
253
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700254#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700255 connectionCount++;
256 BMCWEB_LOG_DEBUG << this << " Connection open, total "
257 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700258#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700259 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700260
Ed Tanous1abe55e2018-09-05 08:30:59 -0700261 ~Connection()
262 {
263 res.completeRequestHandler = nullptr;
264 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700265#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700266 connectionCount--;
267 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
268 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700269#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700270 }
271
Ed Tanousceac6f72018-12-02 11:58:47 -0800272 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700273 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800274 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700275 }
276
Ed Tanous1abe55e2018-09-05 08:30:59 -0700277 void start()
278 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700279
James Feist3909dc82020-04-03 10:58:55 -0700280 startDeadline(0);
Ed Tanousceac6f72018-12-02 11:58:47 -0800281 // TODO(ed) Abstract this to a more clever class with the idea of an
282 // asynchronous "start"
283 if constexpr (std::is_same_v<Adaptor,
284 boost::beast::ssl_stream<
285 boost::asio::ip::tcp::socket>>)
286 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000287 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
288 [this, self(shared_from_this())](
289 const boost::system::error_code& ec) {
290 if (ec)
291 {
292 return;
293 }
294 doReadHeaders();
295 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800296 }
297 else
298 {
299 doReadHeaders();
300 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700301 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700302
Ed Tanous1abe55e2018-09-05 08:30:59 -0700303 void handle()
304 {
305 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700306
Ed Tanous1abe55e2018-09-05 08:30:59 -0700307 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700308
Ed Tanous1abe55e2018-09-05 08:30:59 -0700309 // Check for HTTP version 1.1.
310 if (req->version() == 11)
311 {
312 if (req->getHeaderValue(boost::beast::http::field::host).empty())
313 {
314 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700315 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700316 }
317 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700318
Sunitha Harishe4360082020-09-28 02:10:59 -0500319 // Copy the client's IP address
320 req->ipAddress =
321 boost::beast::get_lowest_layer(adaptor).remote_endpoint().address();
322
Ed Tanouse278c182019-03-13 16:23:37 -0700323 BMCWEB_LOG_INFO << "Request: "
324 << " " << this << " HTTP/" << req->version() / 10 << "."
325 << req->version() % 10 << ' ' << req->methodString()
326 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700327
Ed Tanous1abe55e2018-09-05 08:30:59 -0700328 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700329
Ed Tanous1abe55e2018-09-05 08:30:59 -0700330 if (!isInvalidRequest)
331 {
332 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700333 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700334
Ed Tanouse278c182019-03-13 16:23:37 -0700335 req->ioService = static_cast<decltype(req->ioService)>(
336 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200337
Ed Tanous1abe55e2018-09-05 08:30:59 -0700338 if (!res.completed)
339 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000340 needToCallAfterHandlers = true;
341 res.completeRequestHandler = [self(shared_from_this())] {
Wludzik, Jozefc7d34222020-10-19 12:59:41 +0200342 boost::asio::post(self->adaptor.get_executor(),
343 [self] { self->completeRequest(); });
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000344 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700345 if (req->isUpgrade() &&
346 boost::iequals(
347 req->getHeaderValue(boost::beast::http::field::upgrade),
348 "websocket"))
349 {
350 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000351 // delete lambda with self shared_ptr
352 // to enable connection destruction
353 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700354 return;
355 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700356 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700357 }
358 else
359 {
360 completeRequest();
361 }
362 }
363 else
364 {
365 completeRequest();
366 }
367 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700368
Ed Tanouse278c182019-03-13 16:23:37 -0700369 bool isAlive()
370 {
371
372 if constexpr (std::is_same_v<Adaptor,
373 boost::beast::ssl_stream<
374 boost::asio::ip::tcp::socket>>)
375 {
376 return adaptor.next_layer().is_open();
377 }
378 else
379 {
380 return adaptor.is_open();
381 }
382 }
383 void close()
384 {
Ed Tanouse278c182019-03-13 16:23:37 -0700385 if constexpr (std::is_same_v<Adaptor,
386 boost::beast::ssl_stream<
387 boost::asio::ip::tcp::socket>>)
388 {
389 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200390#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
391 if (auto sp = session.lock())
392 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100393 BMCWEB_LOG_DEBUG << this
394 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200395 persistent_data::SessionStore::getInstance().removeSession(sp);
396 }
397#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700398 }
399 else
400 {
401 adaptor.close();
402 }
403 }
404
Ed Tanous1abe55e2018-09-05 08:30:59 -0700405 void completeRequest()
406 {
407 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
408 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700409
Ed Tanous52cc1122020-07-18 13:51:21 -0700410 addSecurityHeaders(res);
411
Ed Tanous1abe55e2018-09-05 08:30:59 -0700412 if (needToCallAfterHandlers)
413 {
James Feist3909dc82020-04-03 10:58:55 -0700414 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700415 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700416
Ed Tanouse278c182019-03-13 16:23:37 -0700417 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700418 {
419 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
420 // isReading
421 // << ' ' << isWriting;
422 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000423
424 // delete lambda with self shared_ptr
425 // to enable connection destruction
426 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700427 return;
428 }
429 if (res.body().empty() && !res.jsonValue.empty())
430 {
431 if (http_helpers::requestPrefersHtml(*req))
432 {
433 prettyPrintJson(res);
434 }
435 else
436 {
437 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700438 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700439 }
440 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700441
Ed Tanous1abe55e2018-09-05 08:30:59 -0700442 if (res.resultInt() >= 400 && res.body().empty())
443 {
444 res.body() = std::string(res.reason());
445 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700446
447 if (res.result() == boost::beast::http::status::no_content)
448 {
449 // Boost beast throws if content is provided on a no-content
450 // response. Ideally, this would never happen, but in the case that
451 // it does, we don't want to throw.
452 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100453 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700454 res.body().clear();
455 }
456
Ed Tanous1abe55e2018-09-05 08:30:59 -0700457 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
458
459 res.keepAlive(req->keepAlive());
460
461 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000462
463 // delete lambda with self shared_ptr
464 // to enable connection destruction
465 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700466 }
467
468 private:
469 void doReadHeaders()
470 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700471 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
472
473 // Clean up any previous Connection.
474 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800475 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000476 [this,
477 self(shared_from_this())](const boost::system::error_code& ec,
478 std::size_t bytes_transferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700479 BMCWEB_LOG_ERROR << this << " async_read_header "
480 << bytes_transferred << " Bytes";
481 bool errorWhileReading = false;
482 if (ec)
483 {
484 errorWhileReading = true;
485 BMCWEB_LOG_ERROR
486 << this << " Error while reading: " << ec.message();
487 }
488 else
489 {
490 // if the adaptor isn't open anymore, and wasn't handed to a
491 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700492 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700493 {
494 errorWhileReading = true;
495 }
496 }
497
James Feist3909dc82020-04-03 10:58:55 -0700498 cancelDeadlineTimer();
499
Ed Tanous1abe55e2018-09-05 08:30:59 -0700500 if (errorWhileReading)
501 {
Ed Tanouse278c182019-03-13 16:23:37 -0700502 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700503 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700504 return;
505 }
506
James Feist3909dc82020-04-03 10:58:55 -0700507 if (!req)
508 {
509 close();
510 return;
511 }
512
Ed Tanousdc7a7932020-08-17 15:04:58 -0700513 // Note, despite the bmcweb coding policy on use of exceptions
514 // for error handling, this one particular use of exceptions is
515 // deemed acceptible, as it solved a significant error handling
516 // problem that resulted in seg faults, the exact thing that the
517 // exceptions rule is trying to avoid. If at some point,
518 // boost::urls makes the parser object public (or we port it
519 // into bmcweb locally) this will be replaced with
520 // parser::parse, which returns a status code
James Feist5a7e8772020-07-22 09:08:38 -0700521
Ed Tanousdc7a7932020-08-17 15:04:58 -0700522 try
523 {
524 req->urlView = boost::urls::url_view(req->target());
525 req->url = req->urlView.encoded_path();
526 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700527 catch (std::exception& p)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700528 {
Ed Tanous3bcc0152020-08-25 07:47:29 -0700529 BMCWEB_LOG_ERROR << p.what();
Ed Tanousdc7a7932020-08-17 15:04:58 -0700530 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700531
James Feist6964c982020-07-28 16:10:23 -0700532 crow::authorization::authenticate(*req, res, session);
James Feist3909dc82020-04-03 10:58:55 -0700533
534 bool loggedIn = req && req->session;
535 if (loggedIn)
536 {
537 startDeadline(loggedInAttempts);
538 BMCWEB_LOG_DEBUG << "Starting slow deadline";
539
James Feist5a7e8772020-07-22 09:08:38 -0700540 req->urlParams = req->urlView.params();
541
542#ifdef BMCWEB_ENABLE_DEBUG
543 std::string paramList = "";
544 for (const auto param : req->urlParams)
545 {
546 paramList += param->key() + " " + param->value() + " ";
547 }
548 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
549#endif
James Feist3909dc82020-04-03 10:58:55 -0700550 }
551 else
552 {
553 const boost::optional<uint64_t> contentLength =
554 parser->content_length();
555 if (contentLength &&
556 *contentLength > loggedOutPostBodyLimit)
557 {
558 BMCWEB_LOG_DEBUG << "Content length greater than limit "
559 << *contentLength;
560 close();
561 return;
562 }
563
564 startDeadline(loggedOutAttempts);
565 BMCWEB_LOG_DEBUG << "Starting quick deadline";
566 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567 doRead();
568 });
569 }
570
571 void doRead()
572 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700573 BMCWEB_LOG_DEBUG << this << " doRead";
574
575 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800576 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000577 [this,
578 self(shared_from_this())](const boost::system::error_code& ec,
579 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100580 BMCWEB_LOG_DEBUG << this << " async_read " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700581 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700582
583 bool errorWhileReading = false;
584 if (ec)
585 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100586 BMCWEB_LOG_ERROR
587 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700588 errorWhileReading = true;
589 }
590 else
591 {
James Feist3909dc82020-04-03 10:58:55 -0700592 if (isAlive())
593 {
594 cancelDeadlineTimer();
595 bool loggedIn = req && req->session;
596 if (loggedIn)
597 {
598 startDeadline(loggedInAttempts);
599 }
600 else
601 {
602 startDeadline(loggedOutAttempts);
603 }
604 }
605 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700606 {
607 errorWhileReading = true;
608 }
609 }
610 if (errorWhileReading)
611 {
612 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700613 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700614 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700615 return;
616 }
617 handle();
618 });
619 }
620
621 void doWrite()
622 {
James Feist3909dc82020-04-03 10:58:55 -0700623 bool loggedIn = req && req->session;
624 if (loggedIn)
625 {
626 startDeadline(loggedInAttempts);
627 }
628 else
629 {
630 startDeadline(loggedOutAttempts);
631 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100632 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700633 res.preparePayload();
634 serializer.emplace(*res.stringResponse);
635 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800636 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000637 [this,
638 self(shared_from_this())](const boost::system::error_code& ec,
639 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100640 BMCWEB_LOG_DEBUG << this << " async_write " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 << " bytes";
642
James Feist54d8bb12020-07-20 13:28:59 -0700643 cancelDeadlineTimer();
644
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 if (ec)
646 {
647 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 return;
649 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800650 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651 {
Ed Tanouse278c182019-03-13 16:23:37 -0700652 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700653 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700654 return;
655 }
656
657 serializer.reset();
658 BMCWEB_LOG_DEBUG << this << " Clearing response";
659 res.clear();
660 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500661 parser->body_limit(httpReqBodyLimit); // reset body limit for
662 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700663 buffer.consume(buffer.size());
664
665 req.emplace(parser->get());
666 doReadHeaders();
667 });
668 }
669
Ed Tanous1abe55e2018-09-05 08:30:59 -0700670 void cancelDeadlineTimer()
671 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000672 if (timerCancelKey)
673 {
674 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
675 << ' ' << *timerCancelKey;
676 timerQueue.cancel(*timerCancelKey);
677 timerCancelKey.reset();
678 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700679 }
680
James Feist3909dc82020-04-03 10:58:55 -0700681 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700682 {
683 cancelDeadlineTimer();
684
James Feist3909dc82020-04-03 10:58:55 -0700685 if (timerIterations)
686 {
687 timerIterations--;
688 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100689
James Feist3909dc82020-04-03 10:58:55 -0700690 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700691 timerQueue.add([self(shared_from_this()), timerIterations,
692 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700693 // Mark timer as not active to avoid canceling it during
694 // Connection destructor which leads to double free issue
695 self->timerCancelKey.reset();
696 if (!self->isAlive())
697 {
698 return;
699 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100700
James Feistbe5dfca2020-07-22 08:54:59 -0700701 bool loggedIn = self->req && self->req->session;
702 // allow slow uploads for logged in users
703 if (loggedIn && self->parser->get().body().size() > readCount)
704 {
705 BMCWEB_LOG_DEBUG << self.get()
706 << " restart timer - read in progress";
707 self->startDeadline(timerIterations);
708 return;
709 }
710
James Feist3909dc82020-04-03 10:58:55 -0700711 // Threshold can be used to drop slow connections
712 // to protect against slow-rate DoS attack
713 if (timerIterations)
714 {
James Feistbe5dfca2020-07-22 08:54:59 -0700715 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700716 self->startDeadline(timerIterations);
717 return;
718 }
719
720 self->close();
721 });
James Feistcb6cb492020-04-03 13:36:17 -0700722
723 if (!timerCancelKey)
724 {
725 close();
726 return;
727 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700728 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000729 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700730 }
731
732 private:
733 Adaptor adaptor;
734 Handler* handler;
735
Ed Tanousa24526d2018-12-10 15:17:59 -0800736 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700737 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800738 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700739 boost::beast::http::request_parser<boost::beast::http::string_body>>
740 parser;
741
Ed Tanous3112a142018-11-29 15:45:10 -0800742 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700743
Ed Tanousa24526d2018-12-10 15:17:59 -0800744 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700745 boost::beast::http::string_body>>
746 serializer;
747
Ed Tanousa24526d2018-12-10 15:17:59 -0800748 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700749 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700750
751 std::weak_ptr<persistent_data::UserSession> session;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700752
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000753 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700754
Ed Tanous1abe55e2018-09-05 08:30:59 -0700755 bool needToCallAfterHandlers{};
756 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700757
Ed Tanous1abe55e2018-09-05 08:30:59 -0700758 std::function<std::string()>& getCachedDateStr;
759 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000760
761 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700762 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800763};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700764} // namespace crow