blob: ddedaea0ea2d4b6cf8cda47c54102e26a2392df2 [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
Manojkiran Eda44250442020-06-16 12:51:38 +05304#include "http_response.h"
5#include "logging.h"
Manojkiran Eda44250442020-06-16 12:51:38 +05306#include "timer_queue.h"
7#include "utility.h"
8
James Feist3909dc82020-04-03 10:58:55 -07009#include "authorization.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070010#include "http_utility.hpp"
11
Ed Tanouse0d918b2018-03-27 17:41:04 -070012#include <boost/algorithm/string.hpp>
Ed Tanous257f5792018-03-17 14:40:09 -070013#include <boost/algorithm/string/predicate.hpp>
Ed Tanous8f626352018-12-19 14:51:54 -080014#include <boost/asio/io_context.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080015#include <boost/asio/ip/tcp.hpp>
Ed Tanousd43cd0c2020-09-30 20:46:53 -070016#include <boost/asio/ssl/stream.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080017#include <boost/beast/core/flat_static_buffer.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053018#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050019#include <boost/beast/websocket.hpp>
Ed Tanous57fce802019-05-21 13:00:34 -070020#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070021#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050022#include <ssl_key_handler.hpp>
23
Manojkiran Eda44250442020-06-16 12:51:38 +053024#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050025#include <chrono>
26#include <vector>
27
Ed Tanous1abe55e2018-09-05 08:30:59 -070028namespace crow
29{
Ed Tanous257f5792018-03-17 14:40:09 -070030
Ed Tanous1abe55e2018-09-05 08:30:59 -070031inline void prettyPrintJson(crow::Response& res)
32{
Ed Tanous57fce802019-05-21 13:00:34 -070033 json_html_util::dumpHtml(res.body(), res.jsonValue);
34
Ed Tanous93ef5802019-01-03 10:15:41 -080035 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070036}
37
Ed Tanous55c7b7a2018-05-22 15:27:24 -070038#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -070039static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -070040#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070041
Adriana Kobylak0e1cf262019-12-05 13:57:57 -060042// request body limit size set by the BMCWEB_HTTP_REQ_BODY_LIMIT_MB option
43constexpr unsigned int httpReqBodyLimit =
44 1024 * 1024 * BMCWEB_HTTP_REQ_BODY_LIMIT_MB;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070045
James Feist3909dc82020-04-03 10:58:55 -070046constexpr uint64_t loggedOutPostBodyLimit = 4096;
47
48constexpr uint32_t httpHeaderLimit = 8192;
49
50// drop all connections after 1 minute, this time limit was chosen
51// arbitrarily and can be adjusted later if needed
52static constexpr const size_t loggedInAttempts =
53 (60 / timerQueueTimeoutSeconds);
54
55static constexpr const size_t loggedOutAttempts =
56 (15 / timerQueueTimeoutSeconds);
57
Ed Tanous52cc1122020-07-18 13:51:21 -070058template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050059class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070060 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070061{
62 public:
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070063 Connection(Handler* handlerIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070064 std::function<std::string()>& get_cached_date_str_f,
Ed Tanous271584a2019-07-09 16:24:22 -070065 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080066 adaptor(std::move(adaptorIn)),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070067 handler(handlerIn), getCachedDateStr(get_cached_date_str_f),
68 timerQueue(timerQueueIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070069 {
70 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070071 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070072 parser->header_limit(httpHeaderLimit);
Ed Tanous1abe55e2018-09-05 08:30:59 -070073 req.emplace(parser->get());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020074
75#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous2c70f802020-09-28 14:29:23 -070076 auto caAvailable = !std::filesystem::is_empty(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010077 std::filesystem::path(ensuressl::trustStorePath));
Ed Tanous2c70f802020-09-28 14:29:23 -070078 if (caAvailable && persistent_data::SessionStore::getInstance()
79 .getAuthMethodsConfig()
80 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010081 {
82 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070083 std::string id = "bmcweb";
84 int ret = SSL_set_session_id_context(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010085 adaptor.native_handle(),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070086 reinterpret_cast<const unsigned char*>(id.c_str()),
87 static_cast<unsigned int>(id.length()));
88 if (ret == 0)
89 {
90 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
91 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010092 }
93
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +010094 adaptor.set_verify_callback([this](
95 bool preverified,
96 boost::asio::ssl::verify_context& ctx) {
97 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -070098 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +010099 .getAuthMethodsConfig()
100 .tls)
101 {
102 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200103 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100104 }
105
106 // We always return true to allow full auth flow
107 if (!preverified)
108 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100109 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100110 return true;
111 }
112
113 X509_STORE_CTX* cts = ctx.native_handle();
114 if (cts == nullptr)
115 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100116 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100117 return true;
118 }
119
120 // Get certificate
121 X509* peerCert =
122 X509_STORE_CTX_get_current_cert(ctx.native_handle());
123 if (peerCert == nullptr)
124 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100125 BMCWEB_LOG_DEBUG << this
126 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100127 return true;
128 }
129
130 // Check if certificate is OK
131 int error = X509_STORE_CTX_get_error(cts);
132 if (error != X509_V_OK)
133 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100134 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100135 return true;
136 }
137 // Check that we have reached final certificate in chain
138 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
139 if (depth != 0)
140
141 {
142 BMCWEB_LOG_DEBUG
143 << this << " Certificate verification in progress (depth "
144 << depth << "), waiting to reach final depth";
145 return true;
146 }
147
148 BMCWEB_LOG_DEBUG << this
149 << " Certificate verification of final depth";
150
151 // Verify KeyUsage
152 bool isKeyUsageDigitalSignature = false;
153 bool isKeyUsageKeyAgreement = false;
154
155 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000156 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100157
158 if (usage == nullptr)
159 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100160 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100161 return true;
162 }
163
164 for (int i = 0; i < usage->length; i++)
165 {
166 if (KU_DIGITAL_SIGNATURE & usage->data[i])
167 {
168 isKeyUsageDigitalSignature = true;
169 }
170 if (KU_KEY_AGREEMENT & usage->data[i])
171 {
172 isKeyUsageKeyAgreement = true;
173 }
174 }
175
176 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
177 {
178 BMCWEB_LOG_DEBUG << this
179 << " Certificate ExtendedKeyUsage does "
180 "not allow provided certificate to "
181 "be used for user authentication";
182 return true;
183 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200184 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100185
186 // Determine that ExtendedKeyUsage includes Client Auth
187
Ed Tanous23a21a12020-07-25 04:45:05 +0000188 stack_st_ASN1_OBJECT* extUsage =
189 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
190 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100191
192 if (extUsage == nullptr)
193 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100194 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100195 return true;
196 }
197
198 bool isExKeyUsageClientAuth = false;
199 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
200 {
201 if (NID_client_auth ==
202 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
203 {
204 isExKeyUsageClientAuth = true;
205 break;
206 }
207 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200208 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100209
210 // Certificate has to have proper key usages set
211 if (!isExKeyUsageClientAuth)
212 {
213 BMCWEB_LOG_DEBUG << this
214 << " Certificate ExtendedKeyUsage does "
215 "not allow provided certificate to "
216 "be used for user authentication";
217 return true;
218 }
219 std::string sslUser;
220 // Extract username contained in CommonName
221 sslUser.resize(256, '\0');
222
223 int status = X509_NAME_get_text_by_NID(
224 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
225 static_cast<int>(sslUser.size()));
226
227 if (status == -1)
228 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100229 BMCWEB_LOG_DEBUG
230 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100231 return true;
232 }
233
234 size_t lastChar = sslUser.find('\0');
235 if (lastChar == std::string::npos || lastChar == 0)
236 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100237 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100238 return true;
239 }
240 sslUser.resize(lastChar);
241
Ed Tanous52cc1122020-07-18 13:51:21 -0700242 session =
243 persistent_data::SessionStore::getInstance()
244 .generateUserSession(
245 sslUser, persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100246 if (auto sp = session.lock())
247 {
248 BMCWEB_LOG_DEBUG << this
249 << " Generating TLS session: " << sp->uniqueId;
250 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100251 return true;
252 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200253#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
254
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700255#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700256 connectionCount++;
257 BMCWEB_LOG_DEBUG << this << " Connection open, total "
258 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700259#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700260 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700261
Ed Tanous1abe55e2018-09-05 08:30:59 -0700262 ~Connection()
263 {
264 res.completeRequestHandler = nullptr;
265 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700266#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700267 connectionCount--;
268 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
269 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700270#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700271 }
272
Ed Tanousceac6f72018-12-02 11:58:47 -0800273 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700274 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800275 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700276 }
277
Ed Tanous1abe55e2018-09-05 08:30:59 -0700278 void start()
279 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700280
James Feist3909dc82020-04-03 10:58:55 -0700281 startDeadline(0);
Ed Tanousceac6f72018-12-02 11:58:47 -0800282 // TODO(ed) Abstract this to a more clever class with the idea of an
283 // asynchronous "start"
284 if constexpr (std::is_same_v<Adaptor,
285 boost::beast::ssl_stream<
286 boost::asio::ip::tcp::socket>>)
287 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000288 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
289 [this, self(shared_from_this())](
290 const boost::system::error_code& ec) {
291 if (ec)
292 {
293 return;
294 }
295 doReadHeaders();
296 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800297 }
298 else
299 {
300 doReadHeaders();
301 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700302 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700303
Ed Tanous1abe55e2018-09-05 08:30:59 -0700304 void handle()
305 {
306 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700307
Ed Tanous1abe55e2018-09-05 08:30:59 -0700308 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700309
Ed Tanous1abe55e2018-09-05 08:30:59 -0700310 // Check for HTTP version 1.1.
311 if (req->version() == 11)
312 {
313 if (req->getHeaderValue(boost::beast::http::field::host).empty())
314 {
315 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700316 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700317 }
318 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700319
Ed Tanouse278c182019-03-13 16:23:37 -0700320 BMCWEB_LOG_INFO << "Request: "
321 << " " << this << " HTTP/" << req->version() / 10 << "."
322 << req->version() % 10 << ' ' << req->methodString()
323 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700324
Ed Tanous1abe55e2018-09-05 08:30:59 -0700325 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700326
Ed Tanous1abe55e2018-09-05 08:30:59 -0700327 if (!isInvalidRequest)
328 {
329 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700330 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700331
Ed Tanouse278c182019-03-13 16:23:37 -0700332 req->ioService = static_cast<decltype(req->ioService)>(
333 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200334
Ed Tanous1abe55e2018-09-05 08:30:59 -0700335 if (!res.completed)
336 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000337 needToCallAfterHandlers = true;
338 res.completeRequestHandler = [self(shared_from_this())] {
339 self->completeRequest();
340 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700341 if (req->isUpgrade() &&
342 boost::iequals(
343 req->getHeaderValue(boost::beast::http::field::upgrade),
344 "websocket"))
345 {
346 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000347 // delete lambda with self shared_ptr
348 // to enable connection destruction
349 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700350 return;
351 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700352 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700353 }
354 else
355 {
356 completeRequest();
357 }
358 }
359 else
360 {
361 completeRequest();
362 }
363 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700364
Ed Tanouse278c182019-03-13 16:23:37 -0700365 bool isAlive()
366 {
367
368 if constexpr (std::is_same_v<Adaptor,
369 boost::beast::ssl_stream<
370 boost::asio::ip::tcp::socket>>)
371 {
372 return adaptor.next_layer().is_open();
373 }
374 else
375 {
376 return adaptor.is_open();
377 }
378 }
379 void close()
380 {
Ed Tanouse278c182019-03-13 16:23:37 -0700381 if constexpr (std::is_same_v<Adaptor,
382 boost::beast::ssl_stream<
383 boost::asio::ip::tcp::socket>>)
384 {
385 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200386#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
387 if (auto sp = session.lock())
388 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100389 BMCWEB_LOG_DEBUG << this
390 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200391 persistent_data::SessionStore::getInstance().removeSession(sp);
392 }
393#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700394 }
395 else
396 {
397 adaptor.close();
398 }
399 }
400
Ed Tanous1abe55e2018-09-05 08:30:59 -0700401 void completeRequest()
402 {
403 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
404 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700405
Ed Tanous52cc1122020-07-18 13:51:21 -0700406 addSecurityHeaders(res);
407
Ed Tanous1abe55e2018-09-05 08:30:59 -0700408 if (needToCallAfterHandlers)
409 {
James Feist3909dc82020-04-03 10:58:55 -0700410 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700411 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700412
Ed Tanouse278c182019-03-13 16:23:37 -0700413 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700414 {
415 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
416 // isReading
417 // << ' ' << isWriting;
418 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000419
420 // delete lambda with self shared_ptr
421 // to enable connection destruction
422 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700423 return;
424 }
425 if (res.body().empty() && !res.jsonValue.empty())
426 {
427 if (http_helpers::requestPrefersHtml(*req))
428 {
429 prettyPrintJson(res);
430 }
431 else
432 {
433 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700434 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700435 }
436 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700437
Ed Tanous1abe55e2018-09-05 08:30:59 -0700438 if (res.resultInt() >= 400 && res.body().empty())
439 {
440 res.body() = std::string(res.reason());
441 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700442
443 if (res.result() == boost::beast::http::status::no_content)
444 {
445 // Boost beast throws if content is provided on a no-content
446 // response. Ideally, this would never happen, but in the case that
447 // it does, we don't want to throw.
448 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100449 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700450 res.body().clear();
451 }
452
Ed Tanous1abe55e2018-09-05 08:30:59 -0700453 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
454
455 res.keepAlive(req->keepAlive());
456
457 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000458
459 // delete lambda with self shared_ptr
460 // to enable connection destruction
461 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700462 }
463
464 private:
465 void doReadHeaders()
466 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700467 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
468
469 // Clean up any previous Connection.
470 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800471 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000472 [this,
473 self(shared_from_this())](const boost::system::error_code& ec,
474 std::size_t bytes_transferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700475 BMCWEB_LOG_ERROR << this << " async_read_header "
476 << bytes_transferred << " Bytes";
477 bool errorWhileReading = false;
478 if (ec)
479 {
480 errorWhileReading = true;
481 BMCWEB_LOG_ERROR
482 << this << " Error while reading: " << ec.message();
483 }
484 else
485 {
486 // if the adaptor isn't open anymore, and wasn't handed to a
487 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700488 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700489 {
490 errorWhileReading = true;
491 }
492 }
493
James Feist3909dc82020-04-03 10:58:55 -0700494 cancelDeadlineTimer();
495
Ed Tanous1abe55e2018-09-05 08:30:59 -0700496 if (errorWhileReading)
497 {
Ed Tanouse278c182019-03-13 16:23:37 -0700498 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700499 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700500 return;
501 }
502
James Feist3909dc82020-04-03 10:58:55 -0700503 if (!req)
504 {
505 close();
506 return;
507 }
508
Ed Tanousdc7a7932020-08-17 15:04:58 -0700509 // Note, despite the bmcweb coding policy on use of exceptions
510 // for error handling, this one particular use of exceptions is
511 // deemed acceptible, as it solved a significant error handling
512 // problem that resulted in seg faults, the exact thing that the
513 // exceptions rule is trying to avoid. If at some point,
514 // boost::urls makes the parser object public (or we port it
515 // into bmcweb locally) this will be replaced with
516 // parser::parse, which returns a status code
James Feist5a7e8772020-07-22 09:08:38 -0700517
Ed Tanousdc7a7932020-08-17 15:04:58 -0700518 try
519 {
520 req->urlView = boost::urls::url_view(req->target());
521 req->url = req->urlView.encoded_path();
522 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700523 catch (std::exception& p)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700524 {
Ed Tanous3bcc0152020-08-25 07:47:29 -0700525 BMCWEB_LOG_ERROR << p.what();
Ed Tanousdc7a7932020-08-17 15:04:58 -0700526 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700527
James Feist6964c982020-07-28 16:10:23 -0700528 crow::authorization::authenticate(*req, res, session);
James Feist3909dc82020-04-03 10:58:55 -0700529
530 bool loggedIn = req && req->session;
531 if (loggedIn)
532 {
533 startDeadline(loggedInAttempts);
534 BMCWEB_LOG_DEBUG << "Starting slow deadline";
535
James Feist5a7e8772020-07-22 09:08:38 -0700536 req->urlParams = req->urlView.params();
537
538#ifdef BMCWEB_ENABLE_DEBUG
539 std::string paramList = "";
540 for (const auto param : req->urlParams)
541 {
542 paramList += param->key() + " " + param->value() + " ";
543 }
544 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
545#endif
James Feist3909dc82020-04-03 10:58:55 -0700546 }
547 else
548 {
549 const boost::optional<uint64_t> contentLength =
550 parser->content_length();
551 if (contentLength &&
552 *contentLength > loggedOutPostBodyLimit)
553 {
554 BMCWEB_LOG_DEBUG << "Content length greater than limit "
555 << *contentLength;
556 close();
557 return;
558 }
559
560 startDeadline(loggedOutAttempts);
561 BMCWEB_LOG_DEBUG << "Starting quick deadline";
562 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700563 doRead();
564 });
565 }
566
567 void doRead()
568 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700569 BMCWEB_LOG_DEBUG << this << " doRead";
570
571 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800572 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000573 [this,
574 self(shared_from_this())](const boost::system::error_code& ec,
575 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100576 BMCWEB_LOG_DEBUG << this << " async_read " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700577 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700578
579 bool errorWhileReading = false;
580 if (ec)
581 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100582 BMCWEB_LOG_ERROR
583 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700584 errorWhileReading = true;
585 }
586 else
587 {
James Feist3909dc82020-04-03 10:58:55 -0700588 if (isAlive())
589 {
590 cancelDeadlineTimer();
591 bool loggedIn = req && req->session;
592 if (loggedIn)
593 {
594 startDeadline(loggedInAttempts);
595 }
596 else
597 {
598 startDeadline(loggedOutAttempts);
599 }
600 }
601 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700602 {
603 errorWhileReading = true;
604 }
605 }
606 if (errorWhileReading)
607 {
608 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700609 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700610 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700611 return;
612 }
613 handle();
614 });
615 }
616
617 void doWrite()
618 {
James Feist3909dc82020-04-03 10:58:55 -0700619 bool loggedIn = req && req->session;
620 if (loggedIn)
621 {
622 startDeadline(loggedInAttempts);
623 }
624 else
625 {
626 startDeadline(loggedOutAttempts);
627 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100628 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700629 res.preparePayload();
630 serializer.emplace(*res.stringResponse);
631 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800632 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000633 [this,
634 self(shared_from_this())](const boost::system::error_code& ec,
635 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100636 BMCWEB_LOG_DEBUG << this << " async_write " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700637 << " bytes";
638
James Feist54d8bb12020-07-20 13:28:59 -0700639 cancelDeadlineTimer();
640
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 if (ec)
642 {
643 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700644 return;
645 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800646 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700647 {
Ed Tanouse278c182019-03-13 16:23:37 -0700648 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700650 return;
651 }
652
653 serializer.reset();
654 BMCWEB_LOG_DEBUG << this << " Clearing response";
655 res.clear();
656 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500657 parser->body_limit(httpReqBodyLimit); // reset body limit for
658 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700659 buffer.consume(buffer.size());
660
661 req.emplace(parser->get());
662 doReadHeaders();
663 });
664 }
665
Ed Tanous1abe55e2018-09-05 08:30:59 -0700666 void cancelDeadlineTimer()
667 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000668 if (timerCancelKey)
669 {
670 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
671 << ' ' << *timerCancelKey;
672 timerQueue.cancel(*timerCancelKey);
673 timerCancelKey.reset();
674 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700675 }
676
James Feist3909dc82020-04-03 10:58:55 -0700677 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700678 {
679 cancelDeadlineTimer();
680
James Feist3909dc82020-04-03 10:58:55 -0700681 if (timerIterations)
682 {
683 timerIterations--;
684 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100685
James Feist3909dc82020-04-03 10:58:55 -0700686 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700687 timerQueue.add([self(shared_from_this()), timerIterations,
688 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700689 // Mark timer as not active to avoid canceling it during
690 // Connection destructor which leads to double free issue
691 self->timerCancelKey.reset();
692 if (!self->isAlive())
693 {
694 return;
695 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100696
James Feistbe5dfca2020-07-22 08:54:59 -0700697 bool loggedIn = self->req && self->req->session;
698 // allow slow uploads for logged in users
699 if (loggedIn && self->parser->get().body().size() > readCount)
700 {
701 BMCWEB_LOG_DEBUG << self.get()
702 << " restart timer - read in progress";
703 self->startDeadline(timerIterations);
704 return;
705 }
706
James Feist3909dc82020-04-03 10:58:55 -0700707 // Threshold can be used to drop slow connections
708 // to protect against slow-rate DoS attack
709 if (timerIterations)
710 {
James Feistbe5dfca2020-07-22 08:54:59 -0700711 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700712 self->startDeadline(timerIterations);
713 return;
714 }
715
716 self->close();
717 });
James Feistcb6cb492020-04-03 13:36:17 -0700718
719 if (!timerCancelKey)
720 {
721 close();
722 return;
723 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700724 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000725 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700726 }
727
728 private:
729 Adaptor adaptor;
730 Handler* handler;
731
Ed Tanousa24526d2018-12-10 15:17:59 -0800732 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700733 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800734 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700735 boost::beast::http::request_parser<boost::beast::http::string_body>>
736 parser;
737
Ed Tanous3112a142018-11-29 15:45:10 -0800738 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700739
Ed Tanousa24526d2018-12-10 15:17:59 -0800740 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700741 boost::beast::http::string_body>>
742 serializer;
743
Ed Tanousa24526d2018-12-10 15:17:59 -0800744 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700745 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700746
747 std::weak_ptr<persistent_data::UserSession> session;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700748
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000749 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700750
Ed Tanous1abe55e2018-09-05 08:30:59 -0700751 bool needToCallAfterHandlers{};
752 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700753
Ed Tanous1abe55e2018-09-05 08:30:59 -0700754 std::function<std::string()>& getCachedDateStr;
755 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000756
757 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700758 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800759};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700760} // namespace crow