blob: 855cc11bcc1b579aac56235a8ae0537dff15f6b6 [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 Tanous2f1ebcd2019-02-13 19:39:07 -080016#include <boost/asio/ssl.hpp>
Ed Tanous3112a142018-11-29 15:45:10 -080017#include <boost/beast/core/flat_static_buffer.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050018#include <boost/beast/http.hpp>
Manojkiran Eda44250442020-06-16 12:51:38 +053019#include <boost/beast/ssl/ssl_stream.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050020#include <boost/beast/websocket.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{
Jason M. Bills193ad2f2018-09-26 15:08:52 -070033 std::string value = res.jsonValue.dump(4, ' ', true);
Ed Tanousa29c9972018-11-29 15:54:32 -080034 utility::escapeHtml(value);
35 utility::convertToLinks(value);
Ed Tanous1abe55e2018-09-05 08:30:59 -070036 res.body() = "<html>\n"
37 "<head>\n"
38 "<title>Redfish API</title>\n"
39 "<link rel=\"stylesheet\" type=\"text/css\" "
40 "href=\"/styles/default.css\">\n"
41 "<script src=\"/highlight.pack.js\"></script>"
42 "<script>hljs.initHighlightingOnLoad();</script>"
43 "</head>\n"
44 "<body>\n"
45 "<div style=\"max-width: 576px;margin:0 auto;\">\n"
46 "<img src=\"/DMTF_Redfish_logo_2017.svg\" alt=\"redfish\" "
47 "height=\"406px\" "
48 "width=\"576px\">\n"
49 "<br>\n"
50 "<pre>\n"
51 "<code class=\"json\">" +
52 value +
53 "</code>\n"
54 "</pre>\n"
55 "</div>\n"
56 "</body>\n"
57 "</html>\n";
Ed Tanous93ef5802019-01-03 10:15:41 -080058 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070059}
60
Ed Tanous7045c8d2017-04-03 10:04:37 -070061using namespace boost;
62using tcp = asio::ip::tcp;
63
Ed Tanous55c7b7a2018-05-22 15:27:24 -070064#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -070065static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -070066#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070067
Adriana Kobylak0e1cf262019-12-05 13:57:57 -060068// request body limit size set by the BMCWEB_HTTP_REQ_BODY_LIMIT_MB option
69constexpr unsigned int httpReqBodyLimit =
70 1024 * 1024 * BMCWEB_HTTP_REQ_BODY_LIMIT_MB;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070071
James Feist3909dc82020-04-03 10:58:55 -070072constexpr uint64_t loggedOutPostBodyLimit = 4096;
73
74constexpr uint32_t httpHeaderLimit = 8192;
75
76// drop all connections after 1 minute, this time limit was chosen
77// arbitrarily and can be adjusted later if needed
78static constexpr const size_t loggedInAttempts =
79 (60 / timerQueueTimeoutSeconds);
80
81static constexpr const size_t loggedOutAttempts =
82 (15 / timerQueueTimeoutSeconds);
83
Ed Tanous52cc1122020-07-18 13:51:21 -070084template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050085class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070086 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070087{
88 public:
Ed Tanous271584a2019-07-09 16:24:22 -070089 Connection(boost::asio::io_context& ioService, Handler* handlerIn,
90 const std::string& ServerNameIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070091 std::function<std::string()>& get_cached_date_str_f,
Ed Tanous271584a2019-07-09 16:24:22 -070092 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080093 adaptor(std::move(adaptorIn)),
Ed Tanous271584a2019-07-09 16:24:22 -070094 handler(handlerIn), serverName(ServerNameIn),
Ed Tanous52cc1122020-07-18 13:51:21 -070095 getCachedDateStr(get_cached_date_str_f), timerQueue(timerQueueIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070096 {
97 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070098 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070099 parser->header_limit(httpHeaderLimit);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700100 req.emplace(parser->get());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200101
102#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100103 auto ca_available = !std::filesystem::is_empty(
104 std::filesystem::path(ensuressl::trustStorePath));
Ed Tanous52cc1122020-07-18 13:51:21 -0700105 if (ca_available && persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100106 .getAuthMethodsConfig()
107 .tls)
108 {
109 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
110 SSL_set_session_id_context(
111 adaptor.native_handle(),
112 reinterpret_cast<const unsigned char*>(serverName.c_str()),
Zbigniew Kurzynskicac94c52019-11-07 12:55:04 +0100113 static_cast<unsigned int>(serverName.length()));
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100114 BMCWEB_LOG_DEBUG << this << " TLS is enabled on this connection.";
115 }
116
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100117 adaptor.set_verify_callback([this](
118 bool preverified,
119 boost::asio::ssl::verify_context& ctx) {
120 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700121 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100122 .getAuthMethodsConfig()
123 .tls)
124 {
125 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200126 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100127 }
128
129 // We always return true to allow full auth flow
130 if (!preverified)
131 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100132 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100133 return true;
134 }
135
136 X509_STORE_CTX* cts = ctx.native_handle();
137 if (cts == nullptr)
138 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100139 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100140 return true;
141 }
142
143 // Get certificate
144 X509* peerCert =
145 X509_STORE_CTX_get_current_cert(ctx.native_handle());
146 if (peerCert == nullptr)
147 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100148 BMCWEB_LOG_DEBUG << this
149 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100150 return true;
151 }
152
153 // Check if certificate is OK
154 int error = X509_STORE_CTX_get_error(cts);
155 if (error != X509_V_OK)
156 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100157 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100158 return true;
159 }
160 // Check that we have reached final certificate in chain
161 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
162 if (depth != 0)
163
164 {
165 BMCWEB_LOG_DEBUG
166 << this << " Certificate verification in progress (depth "
167 << depth << "), waiting to reach final depth";
168 return true;
169 }
170
171 BMCWEB_LOG_DEBUG << this
172 << " Certificate verification of final depth";
173
174 // Verify KeyUsage
175 bool isKeyUsageDigitalSignature = false;
176 bool isKeyUsageKeyAgreement = false;
177
178 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000179 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100180
181 if (usage == nullptr)
182 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100183 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100184 return true;
185 }
186
187 for (int i = 0; i < usage->length; i++)
188 {
189 if (KU_DIGITAL_SIGNATURE & usage->data[i])
190 {
191 isKeyUsageDigitalSignature = true;
192 }
193 if (KU_KEY_AGREEMENT & usage->data[i])
194 {
195 isKeyUsageKeyAgreement = true;
196 }
197 }
198
199 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
200 {
201 BMCWEB_LOG_DEBUG << this
202 << " Certificate ExtendedKeyUsage does "
203 "not allow provided certificate to "
204 "be used for user authentication";
205 return true;
206 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200207 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100208
209 // Determine that ExtendedKeyUsage includes Client Auth
210
Ed Tanous23a21a12020-07-25 04:45:05 +0000211 stack_st_ASN1_OBJECT* extUsage =
212 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
213 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100214
215 if (extUsage == nullptr)
216 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100217 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100218 return true;
219 }
220
221 bool isExKeyUsageClientAuth = false;
222 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
223 {
224 if (NID_client_auth ==
225 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
226 {
227 isExKeyUsageClientAuth = true;
228 break;
229 }
230 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200231 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100232
233 // Certificate has to have proper key usages set
234 if (!isExKeyUsageClientAuth)
235 {
236 BMCWEB_LOG_DEBUG << this
237 << " Certificate ExtendedKeyUsage does "
238 "not allow provided certificate to "
239 "be used for user authentication";
240 return true;
241 }
242 std::string sslUser;
243 // Extract username contained in CommonName
244 sslUser.resize(256, '\0');
245
246 int status = X509_NAME_get_text_by_NID(
247 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
248 static_cast<int>(sslUser.size()));
249
250 if (status == -1)
251 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100252 BMCWEB_LOG_DEBUG
253 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100254 return true;
255 }
256
257 size_t lastChar = sslUser.find('\0');
258 if (lastChar == std::string::npos || lastChar == 0)
259 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100260 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100261 return true;
262 }
263 sslUser.resize(lastChar);
264
Ed Tanous52cc1122020-07-18 13:51:21 -0700265 session =
266 persistent_data::SessionStore::getInstance()
267 .generateUserSession(
268 sslUser, persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100269 if (auto sp = session.lock())
270 {
271 BMCWEB_LOG_DEBUG << this
272 << " Generating TLS session: " << sp->uniqueId;
273 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100274 return true;
275 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200276#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
277
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700278#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700279 connectionCount++;
280 BMCWEB_LOG_DEBUG << this << " Connection open, total "
281 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700282#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700283 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700284
Ed Tanous1abe55e2018-09-05 08:30:59 -0700285 ~Connection()
286 {
287 res.completeRequestHandler = nullptr;
288 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700289#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700290 connectionCount--;
291 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
292 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700293#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700294 }
295
Ed Tanousceac6f72018-12-02 11:58:47 -0800296 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700297 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800298 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700299 }
300
Ed Tanous1abe55e2018-09-05 08:30:59 -0700301 void start()
302 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700303
James Feist3909dc82020-04-03 10:58:55 -0700304 startDeadline(0);
Ed Tanousceac6f72018-12-02 11:58:47 -0800305 // TODO(ed) Abstract this to a more clever class with the idea of an
306 // asynchronous "start"
307 if constexpr (std::is_same_v<Adaptor,
308 boost::beast::ssl_stream<
309 boost::asio::ip::tcp::socket>>)
310 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000311 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
312 [this, self(shared_from_this())](
313 const boost::system::error_code& ec) {
314 if (ec)
315 {
316 return;
317 }
318 doReadHeaders();
319 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800320 }
321 else
322 {
323 doReadHeaders();
324 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700325 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700326
Ed Tanous1abe55e2018-09-05 08:30:59 -0700327 void handle()
328 {
329 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700330
Ed Tanous1abe55e2018-09-05 08:30:59 -0700331 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700332
Ed Tanous1abe55e2018-09-05 08:30:59 -0700333 // Check for HTTP version 1.1.
334 if (req->version() == 11)
335 {
336 if (req->getHeaderValue(boost::beast::http::field::host).empty())
337 {
338 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700339 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700340 }
341 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700342
Ed Tanouse278c182019-03-13 16:23:37 -0700343 BMCWEB_LOG_INFO << "Request: "
344 << " " << this << " HTTP/" << req->version() / 10 << "."
345 << req->version() % 10 << ' ' << req->methodString()
346 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700347
Ed Tanous1abe55e2018-09-05 08:30:59 -0700348 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700349
Ed Tanous1abe55e2018-09-05 08:30:59 -0700350 if (!isInvalidRequest)
351 {
Ed Tanous23a21a12020-07-25 04:45:05 +0000352 req->socket = [self = shared_from_this()]() -> Adaptor& {
raviteja-b4722efe2020-02-03 12:23:18 -0600353 return self->socket();
354 };
355
Ed Tanous1abe55e2018-09-05 08:30:59 -0700356 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700357 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700358
Ed Tanouse278c182019-03-13 16:23:37 -0700359 req->ioService = static_cast<decltype(req->ioService)>(
360 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200361
Ed Tanous1abe55e2018-09-05 08:30:59 -0700362 if (!res.completed)
363 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000364 needToCallAfterHandlers = true;
365 res.completeRequestHandler = [self(shared_from_this())] {
366 self->completeRequest();
367 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700368 if (req->isUpgrade() &&
369 boost::iequals(
370 req->getHeaderValue(boost::beast::http::field::upgrade),
371 "websocket"))
372 {
373 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000374 // delete lambda with self shared_ptr
375 // to enable connection destruction
376 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700377 return;
378 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700379 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700380 }
381 else
382 {
383 completeRequest();
384 }
385 }
386 else
387 {
388 completeRequest();
389 }
390 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700391
Ed Tanouse278c182019-03-13 16:23:37 -0700392 bool isAlive()
393 {
394
395 if constexpr (std::is_same_v<Adaptor,
396 boost::beast::ssl_stream<
397 boost::asio::ip::tcp::socket>>)
398 {
399 return adaptor.next_layer().is_open();
400 }
401 else
402 {
403 return adaptor.is_open();
404 }
405 }
406 void close()
407 {
Ed Tanouse278c182019-03-13 16:23:37 -0700408 if constexpr (std::is_same_v<Adaptor,
409 boost::beast::ssl_stream<
410 boost::asio::ip::tcp::socket>>)
411 {
412 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200413#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
414 if (auto sp = session.lock())
415 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100416 BMCWEB_LOG_DEBUG << this
417 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200418 persistent_data::SessionStore::getInstance().removeSession(sp);
419 }
420#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700421 }
422 else
423 {
424 adaptor.close();
425 }
426 }
427
Ed Tanous1abe55e2018-09-05 08:30:59 -0700428 void completeRequest()
429 {
430 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
431 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700432
Ed Tanous52cc1122020-07-18 13:51:21 -0700433 addSecurityHeaders(res);
434
Ed Tanous1abe55e2018-09-05 08:30:59 -0700435 if (needToCallAfterHandlers)
436 {
James Feist3909dc82020-04-03 10:58:55 -0700437 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700438 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700439
Ed Tanouse278c182019-03-13 16:23:37 -0700440 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700441 {
442 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
443 // isReading
444 // << ' ' << isWriting;
445 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000446
447 // delete lambda with self shared_ptr
448 // to enable connection destruction
449 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700450 return;
451 }
452 if (res.body().empty() && !res.jsonValue.empty())
453 {
454 if (http_helpers::requestPrefersHtml(*req))
455 {
456 prettyPrintJson(res);
457 }
458 else
459 {
460 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700461 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700462 }
463 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700464
Ed Tanous1abe55e2018-09-05 08:30:59 -0700465 if (res.resultInt() >= 400 && res.body().empty())
466 {
467 res.body() = std::string(res.reason());
468 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700469
470 if (res.result() == boost::beast::http::status::no_content)
471 {
472 // Boost beast throws if content is provided on a no-content
473 // response. Ideally, this would never happen, but in the case that
474 // it does, we don't want to throw.
475 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100476 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700477 res.body().clear();
478 }
479
Ed Tanous1abe55e2018-09-05 08:30:59 -0700480 res.addHeader(boost::beast::http::field::server, serverName);
481 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
482
483 res.keepAlive(req->keepAlive());
484
485 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000486
487 // delete lambda with self shared_ptr
488 // to enable connection destruction
489 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700490 }
491
492 private:
493 void doReadHeaders()
494 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700495 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
496
497 // Clean up any previous Connection.
498 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800499 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000500 [this,
501 self(shared_from_this())](const boost::system::error_code& ec,
502 std::size_t bytes_transferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700503 BMCWEB_LOG_ERROR << this << " async_read_header "
504 << bytes_transferred << " Bytes";
505 bool errorWhileReading = false;
506 if (ec)
507 {
508 errorWhileReading = true;
509 BMCWEB_LOG_ERROR
510 << this << " Error while reading: " << ec.message();
511 }
512 else
513 {
514 // if the adaptor isn't open anymore, and wasn't handed to a
515 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700516 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700517 {
518 errorWhileReading = true;
519 }
520 }
521
James Feist3909dc82020-04-03 10:58:55 -0700522 cancelDeadlineTimer();
523
Ed Tanous1abe55e2018-09-05 08:30:59 -0700524 if (errorWhileReading)
525 {
Ed Tanouse278c182019-03-13 16:23:37 -0700526 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700527 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700528 return;
529 }
530
James Feist3909dc82020-04-03 10:58:55 -0700531 if (!req)
532 {
533 close();
534 return;
535 }
536
James Feist5a7e8772020-07-22 09:08:38 -0700537 req->urlView = boost::urls::url_view(req->target());
538 req->url = req->urlView.encoded_path();
539
James Feist6964c982020-07-28 16:10:23 -0700540 crow::authorization::authenticate(*req, res, session);
James Feist3909dc82020-04-03 10:58:55 -0700541
542 bool loggedIn = req && req->session;
543 if (loggedIn)
544 {
545 startDeadline(loggedInAttempts);
546 BMCWEB_LOG_DEBUG << "Starting slow deadline";
547
James Feist5a7e8772020-07-22 09:08:38 -0700548 req->urlParams = req->urlView.params();
549
550#ifdef BMCWEB_ENABLE_DEBUG
551 std::string paramList = "";
552 for (const auto param : req->urlParams)
553 {
554 paramList += param->key() + " " + param->value() + " ";
555 }
556 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
557#endif
James Feist3909dc82020-04-03 10:58:55 -0700558 }
559 else
560 {
561 const boost::optional<uint64_t> contentLength =
562 parser->content_length();
563 if (contentLength &&
564 *contentLength > loggedOutPostBodyLimit)
565 {
566 BMCWEB_LOG_DEBUG << "Content length greater than limit "
567 << *contentLength;
568 close();
569 return;
570 }
571
572 startDeadline(loggedOutAttempts);
573 BMCWEB_LOG_DEBUG << "Starting quick deadline";
574 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700575 doRead();
576 });
577 }
578
579 void doRead()
580 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700581 BMCWEB_LOG_DEBUG << this << " doRead";
582
583 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800584 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000585 [this,
586 self(shared_from_this())](const boost::system::error_code& ec,
587 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100588 BMCWEB_LOG_DEBUG << this << " async_read " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700589 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700590
591 bool errorWhileReading = false;
592 if (ec)
593 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100594 BMCWEB_LOG_ERROR
595 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700596 errorWhileReading = true;
597 }
598 else
599 {
James Feist3909dc82020-04-03 10:58:55 -0700600 if (isAlive())
601 {
602 cancelDeadlineTimer();
603 bool loggedIn = req && req->session;
604 if (loggedIn)
605 {
606 startDeadline(loggedInAttempts);
607 }
608 else
609 {
610 startDeadline(loggedOutAttempts);
611 }
612 }
613 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700614 {
615 errorWhileReading = true;
616 }
617 }
618 if (errorWhileReading)
619 {
620 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700621 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700622 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700623 return;
624 }
625 handle();
626 });
627 }
628
629 void doWrite()
630 {
James Feist3909dc82020-04-03 10:58:55 -0700631 bool loggedIn = req && req->session;
632 if (loggedIn)
633 {
634 startDeadline(loggedInAttempts);
635 }
636 else
637 {
638 startDeadline(loggedOutAttempts);
639 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100640 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700641 res.preparePayload();
642 serializer.emplace(*res.stringResponse);
643 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800644 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000645 [this,
646 self(shared_from_this())](const boost::system::error_code& ec,
647 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100648 BMCWEB_LOG_DEBUG << this << " async_write " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700649 << " bytes";
650
James Feist54d8bb12020-07-20 13:28:59 -0700651 cancelDeadlineTimer();
652
Ed Tanous1abe55e2018-09-05 08:30:59 -0700653 if (ec)
654 {
655 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700656 return;
657 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800658 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700659 {
Ed Tanouse278c182019-03-13 16:23:37 -0700660 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700661 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700662 return;
663 }
664
665 serializer.reset();
666 BMCWEB_LOG_DEBUG << this << " Clearing response";
667 res.clear();
668 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500669 parser->body_limit(httpReqBodyLimit); // reset body limit for
670 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700671 buffer.consume(buffer.size());
672
673 req.emplace(parser->get());
674 doReadHeaders();
675 });
676 }
677
Ed Tanous1abe55e2018-09-05 08:30:59 -0700678 void cancelDeadlineTimer()
679 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000680 if (timerCancelKey)
681 {
682 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
683 << ' ' << *timerCancelKey;
684 timerQueue.cancel(*timerCancelKey);
685 timerCancelKey.reset();
686 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700687 }
688
James Feist3909dc82020-04-03 10:58:55 -0700689 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700690 {
691 cancelDeadlineTimer();
692
James Feist3909dc82020-04-03 10:58:55 -0700693 if (timerIterations)
694 {
695 timerIterations--;
696 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100697
James Feist3909dc82020-04-03 10:58:55 -0700698 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700699 timerQueue.add([self(shared_from_this()), timerIterations,
700 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700701 // Mark timer as not active to avoid canceling it during
702 // Connection destructor which leads to double free issue
703 self->timerCancelKey.reset();
704 if (!self->isAlive())
705 {
706 return;
707 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100708
James Feistbe5dfca2020-07-22 08:54:59 -0700709 bool loggedIn = self->req && self->req->session;
710 // allow slow uploads for logged in users
711 if (loggedIn && self->parser->get().body().size() > readCount)
712 {
713 BMCWEB_LOG_DEBUG << self.get()
714 << " restart timer - read in progress";
715 self->startDeadline(timerIterations);
716 return;
717 }
718
James Feist3909dc82020-04-03 10:58:55 -0700719 // Threshold can be used to drop slow connections
720 // to protect against slow-rate DoS attack
721 if (timerIterations)
722 {
James Feistbe5dfca2020-07-22 08:54:59 -0700723 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700724 self->startDeadline(timerIterations);
725 return;
726 }
727
728 self->close();
729 });
James Feistcb6cb492020-04-03 13:36:17 -0700730
731 if (!timerCancelKey)
732 {
733 close();
734 return;
735 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700736 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000737 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700738 }
739
740 private:
741 Adaptor adaptor;
742 Handler* handler;
743
Ed Tanousa24526d2018-12-10 15:17:59 -0800744 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700745 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800746 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700747 boost::beast::http::request_parser<boost::beast::http::string_body>>
748 parser;
749
Ed Tanous3112a142018-11-29 15:45:10 -0800750 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700751
Ed Tanousa24526d2018-12-10 15:17:59 -0800752 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700753 boost::beast::http::string_body>>
754 serializer;
755
Ed Tanousa24526d2018-12-10 15:17:59 -0800756 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700757 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700758
759 std::weak_ptr<persistent_data::UserSession> session;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700760
761 const std::string& serverName;
762
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000763 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700764
Ed Tanous1abe55e2018-09-05 08:30:59 -0700765 bool needToCallAfterHandlers{};
766 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700767
Ed Tanous1abe55e2018-09-05 08:30:59 -0700768 std::function<std::string()>& getCachedDateStr;
769 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000770
771 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700772 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800773};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700774} // namespace crow