blob: 679140c7cbee950dbd212f98ec832eeb9afe8d90 [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 Tanouscb13a392020-07-25 19:02:03 +000089 Connection(Handler* handlerIn, const std::string& ServerNameIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070090 std::function<std::string()>& get_cached_date_str_f,
Ed Tanous271584a2019-07-09 16:24:22 -070091 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080092 adaptor(std::move(adaptorIn)),
Ed Tanous271584a2019-07-09 16:24:22 -070093 handler(handlerIn), serverName(ServerNameIn),
Ed Tanous52cc1122020-07-18 13:51:21 -070094 getCachedDateStr(get_cached_date_str_f), timerQueue(timerQueueIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070095 {
96 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070097 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070098 parser->header_limit(httpHeaderLimit);
Ed Tanous1abe55e2018-09-05 08:30:59 -070099 req.emplace(parser->get());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200100
101#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100102 auto ca_available = !std::filesystem::is_empty(
103 std::filesystem::path(ensuressl::trustStorePath));
Ed Tanous52cc1122020-07-18 13:51:21 -0700104 if (ca_available && persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100105 .getAuthMethodsConfig()
106 .tls)
107 {
108 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
109 SSL_set_session_id_context(
110 adaptor.native_handle(),
111 reinterpret_cast<const unsigned char*>(serverName.c_str()),
Zbigniew Kurzynskicac94c52019-11-07 12:55:04 +0100112 static_cast<unsigned int>(serverName.length()));
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100113 BMCWEB_LOG_DEBUG << this << " TLS is enabled on this connection.";
114 }
115
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100116 adaptor.set_verify_callback([this](
117 bool preverified,
118 boost::asio::ssl::verify_context& ctx) {
119 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -0700120 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100121 .getAuthMethodsConfig()
122 .tls)
123 {
124 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200125 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100126 }
127
128 // We always return true to allow full auth flow
129 if (!preverified)
130 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100131 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100132 return true;
133 }
134
135 X509_STORE_CTX* cts = ctx.native_handle();
136 if (cts == nullptr)
137 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100138 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100139 return true;
140 }
141
142 // Get certificate
143 X509* peerCert =
144 X509_STORE_CTX_get_current_cert(ctx.native_handle());
145 if (peerCert == nullptr)
146 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100147 BMCWEB_LOG_DEBUG << this
148 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100149 return true;
150 }
151
152 // Check if certificate is OK
153 int error = X509_STORE_CTX_get_error(cts);
154 if (error != X509_V_OK)
155 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100156 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100157 return true;
158 }
159 // Check that we have reached final certificate in chain
160 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
161 if (depth != 0)
162
163 {
164 BMCWEB_LOG_DEBUG
165 << this << " Certificate verification in progress (depth "
166 << depth << "), waiting to reach final depth";
167 return true;
168 }
169
170 BMCWEB_LOG_DEBUG << this
171 << " Certificate verification of final depth";
172
173 // Verify KeyUsage
174 bool isKeyUsageDigitalSignature = false;
175 bool isKeyUsageKeyAgreement = false;
176
177 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000178 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100179
180 if (usage == nullptr)
181 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100182 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100183 return true;
184 }
185
186 for (int i = 0; i < usage->length; i++)
187 {
188 if (KU_DIGITAL_SIGNATURE & usage->data[i])
189 {
190 isKeyUsageDigitalSignature = true;
191 }
192 if (KU_KEY_AGREEMENT & usage->data[i])
193 {
194 isKeyUsageKeyAgreement = true;
195 }
196 }
197
198 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
199 {
200 BMCWEB_LOG_DEBUG << this
201 << " Certificate ExtendedKeyUsage does "
202 "not allow provided certificate to "
203 "be used for user authentication";
204 return true;
205 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200206 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100207
208 // Determine that ExtendedKeyUsage includes Client Auth
209
Ed Tanous23a21a12020-07-25 04:45:05 +0000210 stack_st_ASN1_OBJECT* extUsage =
211 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
212 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100213
214 if (extUsage == nullptr)
215 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100216 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100217 return true;
218 }
219
220 bool isExKeyUsageClientAuth = false;
221 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
222 {
223 if (NID_client_auth ==
224 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
225 {
226 isExKeyUsageClientAuth = true;
227 break;
228 }
229 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200230 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100231
232 // Certificate has to have proper key usages set
233 if (!isExKeyUsageClientAuth)
234 {
235 BMCWEB_LOG_DEBUG << this
236 << " Certificate ExtendedKeyUsage does "
237 "not allow provided certificate to "
238 "be used for user authentication";
239 return true;
240 }
241 std::string sslUser;
242 // Extract username contained in CommonName
243 sslUser.resize(256, '\0');
244
245 int status = X509_NAME_get_text_by_NID(
246 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
247 static_cast<int>(sslUser.size()));
248
249 if (status == -1)
250 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100251 BMCWEB_LOG_DEBUG
252 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100253 return true;
254 }
255
256 size_t lastChar = sslUser.find('\0');
257 if (lastChar == std::string::npos || lastChar == 0)
258 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100259 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100260 return true;
261 }
262 sslUser.resize(lastChar);
263
Ed Tanous52cc1122020-07-18 13:51:21 -0700264 session =
265 persistent_data::SessionStore::getInstance()
266 .generateUserSession(
267 sslUser, persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100268 if (auto sp = session.lock())
269 {
270 BMCWEB_LOG_DEBUG << this
271 << " Generating TLS session: " << sp->uniqueId;
272 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100273 return true;
274 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200275#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
276
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700277#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700278 connectionCount++;
279 BMCWEB_LOG_DEBUG << this << " Connection open, total "
280 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700281#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700282 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700283
Ed Tanous1abe55e2018-09-05 08:30:59 -0700284 ~Connection()
285 {
286 res.completeRequestHandler = nullptr;
287 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700288#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700289 connectionCount--;
290 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
291 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700292#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700293 }
294
Ed Tanousceac6f72018-12-02 11:58:47 -0800295 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700296 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800297 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700298 }
299
Ed Tanous1abe55e2018-09-05 08:30:59 -0700300 void start()
301 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700302
James Feist3909dc82020-04-03 10:58:55 -0700303 startDeadline(0);
Ed Tanousceac6f72018-12-02 11:58:47 -0800304 // TODO(ed) Abstract this to a more clever class with the idea of an
305 // asynchronous "start"
306 if constexpr (std::is_same_v<Adaptor,
307 boost::beast::ssl_stream<
308 boost::asio::ip::tcp::socket>>)
309 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000310 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
311 [this, self(shared_from_this())](
312 const boost::system::error_code& ec) {
313 if (ec)
314 {
315 return;
316 }
317 doReadHeaders();
318 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800319 }
320 else
321 {
322 doReadHeaders();
323 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700324 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700325
Ed Tanous1abe55e2018-09-05 08:30:59 -0700326 void handle()
327 {
328 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700329
Ed Tanous1abe55e2018-09-05 08:30:59 -0700330 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700331
Ed Tanous1abe55e2018-09-05 08:30:59 -0700332 // Check for HTTP version 1.1.
333 if (req->version() == 11)
334 {
335 if (req->getHeaderValue(boost::beast::http::field::host).empty())
336 {
337 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700338 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700339 }
340 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700341
Ed Tanouse278c182019-03-13 16:23:37 -0700342 BMCWEB_LOG_INFO << "Request: "
343 << " " << this << " HTTP/" << req->version() / 10 << "."
344 << req->version() % 10 << ' ' << req->methodString()
345 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700346
Ed Tanous1abe55e2018-09-05 08:30:59 -0700347 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700348
Ed Tanous1abe55e2018-09-05 08:30:59 -0700349 if (!isInvalidRequest)
350 {
Ed Tanous23a21a12020-07-25 04:45:05 +0000351 req->socket = [self = shared_from_this()]() -> Adaptor& {
raviteja-b4722efe2020-02-03 12:23:18 -0600352 return self->socket();
353 };
354
Ed Tanous1abe55e2018-09-05 08:30:59 -0700355 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700356 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700357
Ed Tanouse278c182019-03-13 16:23:37 -0700358 req->ioService = static_cast<decltype(req->ioService)>(
359 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200360
Ed Tanous1abe55e2018-09-05 08:30:59 -0700361 if (!res.completed)
362 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000363 needToCallAfterHandlers = true;
364 res.completeRequestHandler = [self(shared_from_this())] {
365 self->completeRequest();
366 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700367 if (req->isUpgrade() &&
368 boost::iequals(
369 req->getHeaderValue(boost::beast::http::field::upgrade),
370 "websocket"))
371 {
372 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000373 // delete lambda with self shared_ptr
374 // to enable connection destruction
375 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700376 return;
377 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700378 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700379 }
380 else
381 {
382 completeRequest();
383 }
384 }
385 else
386 {
387 completeRequest();
388 }
389 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700390
Ed Tanouse278c182019-03-13 16:23:37 -0700391 bool isAlive()
392 {
393
394 if constexpr (std::is_same_v<Adaptor,
395 boost::beast::ssl_stream<
396 boost::asio::ip::tcp::socket>>)
397 {
398 return adaptor.next_layer().is_open();
399 }
400 else
401 {
402 return adaptor.is_open();
403 }
404 }
405 void close()
406 {
Ed Tanouse278c182019-03-13 16:23:37 -0700407 if constexpr (std::is_same_v<Adaptor,
408 boost::beast::ssl_stream<
409 boost::asio::ip::tcp::socket>>)
410 {
411 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200412#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
413 if (auto sp = session.lock())
414 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100415 BMCWEB_LOG_DEBUG << this
416 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200417 persistent_data::SessionStore::getInstance().removeSession(sp);
418 }
419#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700420 }
421 else
422 {
423 adaptor.close();
424 }
425 }
426
Ed Tanous1abe55e2018-09-05 08:30:59 -0700427 void completeRequest()
428 {
429 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
430 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700431
Ed Tanous52cc1122020-07-18 13:51:21 -0700432 addSecurityHeaders(res);
433
Ed Tanous1abe55e2018-09-05 08:30:59 -0700434 if (needToCallAfterHandlers)
435 {
James Feist3909dc82020-04-03 10:58:55 -0700436 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700437 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700438
Ed Tanouse278c182019-03-13 16:23:37 -0700439 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700440 {
441 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
442 // isReading
443 // << ' ' << isWriting;
444 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000445
446 // delete lambda with self shared_ptr
447 // to enable connection destruction
448 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700449 return;
450 }
451 if (res.body().empty() && !res.jsonValue.empty())
452 {
453 if (http_helpers::requestPrefersHtml(*req))
454 {
455 prettyPrintJson(res);
456 }
457 else
458 {
459 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700460 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700461 }
462 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700463
Ed Tanous1abe55e2018-09-05 08:30:59 -0700464 if (res.resultInt() >= 400 && res.body().empty())
465 {
466 res.body() = std::string(res.reason());
467 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700468
469 if (res.result() == boost::beast::http::status::no_content)
470 {
471 // Boost beast throws if content is provided on a no-content
472 // response. Ideally, this would never happen, but in the case that
473 // it does, we don't want to throw.
474 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100475 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700476 res.body().clear();
477 }
478
Ed Tanous1abe55e2018-09-05 08:30:59 -0700479 res.addHeader(boost::beast::http::field::server, serverName);
480 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
481
482 res.keepAlive(req->keepAlive());
483
484 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000485
486 // delete lambda with self shared_ptr
487 // to enable connection destruction
488 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700489 }
490
491 private:
492 void doReadHeaders()
493 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700494 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
495
496 // Clean up any previous Connection.
497 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800498 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000499 [this,
500 self(shared_from_this())](const boost::system::error_code& ec,
501 std::size_t bytes_transferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700502 BMCWEB_LOG_ERROR << this << " async_read_header "
503 << bytes_transferred << " Bytes";
504 bool errorWhileReading = false;
505 if (ec)
506 {
507 errorWhileReading = true;
508 BMCWEB_LOG_ERROR
509 << this << " Error while reading: " << ec.message();
510 }
511 else
512 {
513 // if the adaptor isn't open anymore, and wasn't handed to a
514 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700515 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700516 {
517 errorWhileReading = true;
518 }
519 }
520
James Feist3909dc82020-04-03 10:58:55 -0700521 cancelDeadlineTimer();
522
Ed Tanous1abe55e2018-09-05 08:30:59 -0700523 if (errorWhileReading)
524 {
Ed Tanouse278c182019-03-13 16:23:37 -0700525 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700526 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700527 return;
528 }
529
James Feist3909dc82020-04-03 10:58:55 -0700530 if (!req)
531 {
532 close();
533 return;
534 }
535
Ed Tanousdc7a7932020-08-17 15:04:58 -0700536 // Note, despite the bmcweb coding policy on use of exceptions
537 // for error handling, this one particular use of exceptions is
538 // deemed acceptible, as it solved a significant error handling
539 // problem that resulted in seg faults, the exact thing that the
540 // exceptions rule is trying to avoid. If at some point,
541 // boost::urls makes the parser object public (or we port it
542 // into bmcweb locally) this will be replaced with
543 // parser::parse, which returns a status code
James Feist5a7e8772020-07-22 09:08:38 -0700544
Ed Tanousdc7a7932020-08-17 15:04:58 -0700545 try
546 {
547 req->urlView = boost::urls::url_view(req->target());
548 req->url = req->urlView.encoded_path();
549 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700550 catch (std::exception& p)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700551 {
552 BMCWEB_LOG_ERROR << p;
553 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700554
James Feist6964c982020-07-28 16:10:23 -0700555 crow::authorization::authenticate(*req, res, session);
James Feist3909dc82020-04-03 10:58:55 -0700556
557 bool loggedIn = req && req->session;
558 if (loggedIn)
559 {
560 startDeadline(loggedInAttempts);
561 BMCWEB_LOG_DEBUG << "Starting slow deadline";
562
James Feist5a7e8772020-07-22 09:08:38 -0700563 req->urlParams = req->urlView.params();
564
565#ifdef BMCWEB_ENABLE_DEBUG
566 std::string paramList = "";
567 for (const auto param : req->urlParams)
568 {
569 paramList += param->key() + " " + param->value() + " ";
570 }
571 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
572#endif
James Feist3909dc82020-04-03 10:58:55 -0700573 }
574 else
575 {
576 const boost::optional<uint64_t> contentLength =
577 parser->content_length();
578 if (contentLength &&
579 *contentLength > loggedOutPostBodyLimit)
580 {
581 BMCWEB_LOG_DEBUG << "Content length greater than limit "
582 << *contentLength;
583 close();
584 return;
585 }
586
587 startDeadline(loggedOutAttempts);
588 BMCWEB_LOG_DEBUG << "Starting quick deadline";
589 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700590 doRead();
591 });
592 }
593
594 void doRead()
595 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700596 BMCWEB_LOG_DEBUG << this << " doRead";
597
598 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800599 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000600 [this,
601 self(shared_from_this())](const boost::system::error_code& ec,
602 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100603 BMCWEB_LOG_DEBUG << this << " async_read " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700604 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700605
606 bool errorWhileReading = false;
607 if (ec)
608 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100609 BMCWEB_LOG_ERROR
610 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700611 errorWhileReading = true;
612 }
613 else
614 {
James Feist3909dc82020-04-03 10:58:55 -0700615 if (isAlive())
616 {
617 cancelDeadlineTimer();
618 bool loggedIn = req && req->session;
619 if (loggedIn)
620 {
621 startDeadline(loggedInAttempts);
622 }
623 else
624 {
625 startDeadline(loggedOutAttempts);
626 }
627 }
628 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700629 {
630 errorWhileReading = true;
631 }
632 }
633 if (errorWhileReading)
634 {
635 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700636 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700637 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700638 return;
639 }
640 handle();
641 });
642 }
643
644 void doWrite()
645 {
James Feist3909dc82020-04-03 10:58:55 -0700646 bool loggedIn = req && req->session;
647 if (loggedIn)
648 {
649 startDeadline(loggedInAttempts);
650 }
651 else
652 {
653 startDeadline(loggedOutAttempts);
654 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100655 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700656 res.preparePayload();
657 serializer.emplace(*res.stringResponse);
658 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800659 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000660 [this,
661 self(shared_from_this())](const boost::system::error_code& ec,
662 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100663 BMCWEB_LOG_DEBUG << this << " async_write " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700664 << " bytes";
665
James Feist54d8bb12020-07-20 13:28:59 -0700666 cancelDeadlineTimer();
667
Ed Tanous1abe55e2018-09-05 08:30:59 -0700668 if (ec)
669 {
670 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700671 return;
672 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800673 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700674 {
Ed Tanouse278c182019-03-13 16:23:37 -0700675 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700676 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700677 return;
678 }
679
680 serializer.reset();
681 BMCWEB_LOG_DEBUG << this << " Clearing response";
682 res.clear();
683 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500684 parser->body_limit(httpReqBodyLimit); // reset body limit for
685 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700686 buffer.consume(buffer.size());
687
688 req.emplace(parser->get());
689 doReadHeaders();
690 });
691 }
692
Ed Tanous1abe55e2018-09-05 08:30:59 -0700693 void cancelDeadlineTimer()
694 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000695 if (timerCancelKey)
696 {
697 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
698 << ' ' << *timerCancelKey;
699 timerQueue.cancel(*timerCancelKey);
700 timerCancelKey.reset();
701 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700702 }
703
James Feist3909dc82020-04-03 10:58:55 -0700704 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700705 {
706 cancelDeadlineTimer();
707
James Feist3909dc82020-04-03 10:58:55 -0700708 if (timerIterations)
709 {
710 timerIterations--;
711 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100712
James Feist3909dc82020-04-03 10:58:55 -0700713 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700714 timerQueue.add([self(shared_from_this()), timerIterations,
715 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700716 // Mark timer as not active to avoid canceling it during
717 // Connection destructor which leads to double free issue
718 self->timerCancelKey.reset();
719 if (!self->isAlive())
720 {
721 return;
722 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100723
James Feistbe5dfca2020-07-22 08:54:59 -0700724 bool loggedIn = self->req && self->req->session;
725 // allow slow uploads for logged in users
726 if (loggedIn && self->parser->get().body().size() > readCount)
727 {
728 BMCWEB_LOG_DEBUG << self.get()
729 << " restart timer - read in progress";
730 self->startDeadline(timerIterations);
731 return;
732 }
733
James Feist3909dc82020-04-03 10:58:55 -0700734 // Threshold can be used to drop slow connections
735 // to protect against slow-rate DoS attack
736 if (timerIterations)
737 {
James Feistbe5dfca2020-07-22 08:54:59 -0700738 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700739 self->startDeadline(timerIterations);
740 return;
741 }
742
743 self->close();
744 });
James Feistcb6cb492020-04-03 13:36:17 -0700745
746 if (!timerCancelKey)
747 {
748 close();
749 return;
750 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700751 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000752 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700753 }
754
755 private:
756 Adaptor adaptor;
757 Handler* handler;
758
Ed Tanousa24526d2018-12-10 15:17:59 -0800759 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700760 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800761 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700762 boost::beast::http::request_parser<boost::beast::http::string_body>>
763 parser;
764
Ed Tanous3112a142018-11-29 15:45:10 -0800765 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700766
Ed Tanousa24526d2018-12-10 15:17:59 -0800767 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700768 boost::beast::http::string_body>>
769 serializer;
770
Ed Tanousa24526d2018-12-10 15:17:59 -0800771 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700772 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700773
774 std::weak_ptr<persistent_data::UserSession> session;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700775
776 const std::string& serverName;
777
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000778 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700779
Ed Tanous1abe55e2018-09-05 08:30:59 -0700780 bool needToCallAfterHandlers{};
781 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700782
Ed Tanous1abe55e2018-09-05 08:30:59 -0700783 std::function<std::string()>& getCachedDateStr;
784 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000785
786 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700787 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800788};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700789} // namespace crow