blob: 689b60a20fba9e8bedcb71c9b0b02c68763abb8c [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 Tanous57fce802019-05-21 13:00:34 -070021#include <json_html_serializer.hpp>
Ed Tanous52cc1122020-07-18 13:51:21 -070022#include <security_headers.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050023#include <ssl_key_handler.hpp>
24
Manojkiran Eda44250442020-06-16 12:51:38 +053025#include <atomic>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050026#include <chrono>
27#include <vector>
28
Ed Tanous1abe55e2018-09-05 08:30:59 -070029namespace crow
30{
Ed Tanous257f5792018-03-17 14:40:09 -070031
Ed Tanous1abe55e2018-09-05 08:30:59 -070032inline void prettyPrintJson(crow::Response& res)
33{
Ed Tanous57fce802019-05-21 13:00:34 -070034 json_html_util::dumpHtml(res.body(), res.jsonValue);
35
Ed Tanous93ef5802019-01-03 10:15:41 -080036 res.addHeader("Content-Type", "text/html;charset=UTF-8");
Ed Tanous257f5792018-03-17 14:40:09 -070037}
38
Ed Tanous55c7b7a2018-05-22 15:27:24 -070039#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanouse0d918b2018-03-27 17:41:04 -070040static std::atomic<int> connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -070041#endif
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070042
Adriana Kobylak0e1cf262019-12-05 13:57:57 -060043// request body limit size set by the BMCWEB_HTTP_REQ_BODY_LIMIT_MB option
44constexpr unsigned int httpReqBodyLimit =
45 1024 * 1024 * BMCWEB_HTTP_REQ_BODY_LIMIT_MB;
Jennifer Leeacb7cfb2018-06-07 16:08:15 -070046
James Feist3909dc82020-04-03 10:58:55 -070047constexpr uint64_t loggedOutPostBodyLimit = 4096;
48
49constexpr uint32_t httpHeaderLimit = 8192;
50
51// drop all connections after 1 minute, this time limit was chosen
52// arbitrarily and can be adjusted later if needed
53static constexpr const size_t loggedInAttempts =
54 (60 / timerQueueTimeoutSeconds);
55
56static constexpr const size_t loggedOutAttempts =
57 (15 / timerQueueTimeoutSeconds);
58
Ed Tanous52cc1122020-07-18 13:51:21 -070059template <typename Adaptor, typename Handler>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050060class Connection :
Ed Tanous52cc1122020-07-18 13:51:21 -070061 public std::enable_shared_from_this<Connection<Adaptor, Handler>>
Ed Tanous1abe55e2018-09-05 08:30:59 -070062{
63 public:
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070064 Connection(Handler* handlerIn,
Ed Tanous1abe55e2018-09-05 08:30:59 -070065 std::function<std::string()>& get_cached_date_str_f,
Ed Tanous271584a2019-07-09 16:24:22 -070066 detail::TimerQueue& timerQueueIn, Adaptor adaptorIn) :
Ed Tanousceac6f72018-12-02 11:58:47 -080067 adaptor(std::move(adaptorIn)),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070068 handler(handlerIn), getCachedDateStr(get_cached_date_str_f),
69 timerQueue(timerQueueIn)
Ed Tanous1abe55e2018-09-05 08:30:59 -070070 {
71 parser.emplace(std::piecewise_construct, std::make_tuple());
Ed Tanous1abe55e2018-09-05 08:30:59 -070072 parser->body_limit(httpReqBodyLimit);
James Feist3909dc82020-04-03 10:58:55 -070073 parser->header_limit(httpHeaderLimit);
Ed Tanous1abe55e2018-09-05 08:30:59 -070074 req.emplace(parser->get());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +020075
76#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanous2c70f802020-09-28 14:29:23 -070077 auto caAvailable = !std::filesystem::is_empty(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010078 std::filesystem::path(ensuressl::trustStorePath));
Ed Tanous2c70f802020-09-28 14:29:23 -070079 if (caAvailable && persistent_data::SessionStore::getInstance()
80 .getAuthMethodsConfig()
81 .tls)
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010082 {
83 adaptor.set_verify_mode(boost::asio::ssl::verify_peer);
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070084 std::string id = "bmcweb";
85 int ret = SSL_set_session_id_context(
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010086 adaptor.native_handle(),
Ed Tanouse7d1a1c2020-09-28 09:36:35 -070087 reinterpret_cast<const unsigned char*>(id.c_str()),
88 static_cast<unsigned int>(id.length()));
89 if (ret == 0)
90 {
91 BMCWEB_LOG_ERROR << this << " failed to set SSL id";
92 }
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010093 }
94
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +010095 adaptor.set_verify_callback([this](
96 bool preverified,
97 boost::asio::ssl::verify_context& ctx) {
98 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -070099 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100100 .getAuthMethodsConfig()
101 .tls)
102 {
103 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200104 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100105 }
106
107 // We always return true to allow full auth flow
108 if (!preverified)
109 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100110 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100111 return true;
112 }
113
114 X509_STORE_CTX* cts = ctx.native_handle();
115 if (cts == nullptr)
116 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100117 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100118 return true;
119 }
120
121 // Get certificate
122 X509* peerCert =
123 X509_STORE_CTX_get_current_cert(ctx.native_handle());
124 if (peerCert == nullptr)
125 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100126 BMCWEB_LOG_DEBUG << this
127 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100128 return true;
129 }
130
131 // Check if certificate is OK
132 int error = X509_STORE_CTX_get_error(cts);
133 if (error != X509_V_OK)
134 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100135 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100136 return true;
137 }
138 // Check that we have reached final certificate in chain
139 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
140 if (depth != 0)
141
142 {
143 BMCWEB_LOG_DEBUG
144 << this << " Certificate verification in progress (depth "
145 << depth << "), waiting to reach final depth";
146 return true;
147 }
148
149 BMCWEB_LOG_DEBUG << this
150 << " Certificate verification of final depth";
151
152 // Verify KeyUsage
153 bool isKeyUsageDigitalSignature = false;
154 bool isKeyUsageKeyAgreement = false;
155
156 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000157 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100158
159 if (usage == nullptr)
160 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100161 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100162 return true;
163 }
164
165 for (int i = 0; i < usage->length; i++)
166 {
167 if (KU_DIGITAL_SIGNATURE & usage->data[i])
168 {
169 isKeyUsageDigitalSignature = true;
170 }
171 if (KU_KEY_AGREEMENT & usage->data[i])
172 {
173 isKeyUsageKeyAgreement = true;
174 }
175 }
176
177 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
178 {
179 BMCWEB_LOG_DEBUG << this
180 << " Certificate ExtendedKeyUsage does "
181 "not allow provided certificate to "
182 "be used for user authentication";
183 return true;
184 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200185 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100186
187 // Determine that ExtendedKeyUsage includes Client Auth
188
Ed Tanous23a21a12020-07-25 04:45:05 +0000189 stack_st_ASN1_OBJECT* extUsage =
190 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
191 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100192
193 if (extUsage == nullptr)
194 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100195 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100196 return true;
197 }
198
199 bool isExKeyUsageClientAuth = false;
200 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
201 {
202 if (NID_client_auth ==
203 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
204 {
205 isExKeyUsageClientAuth = true;
206 break;
207 }
208 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200209 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100210
211 // Certificate has to have proper key usages set
212 if (!isExKeyUsageClientAuth)
213 {
214 BMCWEB_LOG_DEBUG << this
215 << " Certificate ExtendedKeyUsage does "
216 "not allow provided certificate to "
217 "be used for user authentication";
218 return true;
219 }
220 std::string sslUser;
221 // Extract username contained in CommonName
222 sslUser.resize(256, '\0');
223
224 int status = X509_NAME_get_text_by_NID(
225 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
226 static_cast<int>(sslUser.size()));
227
228 if (status == -1)
229 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100230 BMCWEB_LOG_DEBUG
231 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100232 return true;
233 }
234
235 size_t lastChar = sslUser.find('\0');
236 if (lastChar == std::string::npos || lastChar == 0)
237 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100238 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100239 return true;
240 }
241 sslUser.resize(lastChar);
242
Ed Tanous52cc1122020-07-18 13:51:21 -0700243 session =
244 persistent_data::SessionStore::getInstance()
245 .generateUserSession(
246 sslUser, persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100247 if (auto sp = session.lock())
248 {
249 BMCWEB_LOG_DEBUG << this
250 << " Generating TLS session: " << sp->uniqueId;
251 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100252 return true;
253 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200254#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
255
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700256#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700257 connectionCount++;
258 BMCWEB_LOG_DEBUG << this << " Connection open, total "
259 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700260#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700261 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700262
Ed Tanous1abe55e2018-09-05 08:30:59 -0700263 ~Connection()
264 {
265 res.completeRequestHandler = nullptr;
266 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700267#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700268 connectionCount--;
269 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
270 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700271#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700272 }
273
Ed Tanousceac6f72018-12-02 11:58:47 -0800274 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700275 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800276 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700277 }
278
Ed Tanous1abe55e2018-09-05 08:30:59 -0700279 void start()
280 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700281
James Feist3909dc82020-04-03 10:58:55 -0700282 startDeadline(0);
Ed Tanousceac6f72018-12-02 11:58:47 -0800283 // TODO(ed) Abstract this to a more clever class with the idea of an
284 // asynchronous "start"
285 if constexpr (std::is_same_v<Adaptor,
286 boost::beast::ssl_stream<
287 boost::asio::ip::tcp::socket>>)
288 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000289 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
290 [this, self(shared_from_this())](
291 const boost::system::error_code& ec) {
292 if (ec)
293 {
294 return;
295 }
296 doReadHeaders();
297 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800298 }
299 else
300 {
301 doReadHeaders();
302 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700303 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700304
Ed Tanous1abe55e2018-09-05 08:30:59 -0700305 void handle()
306 {
307 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700308
Ed Tanous1abe55e2018-09-05 08:30:59 -0700309 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700310
Ed Tanous1abe55e2018-09-05 08:30:59 -0700311 // Check for HTTP version 1.1.
312 if (req->version() == 11)
313 {
314 if (req->getHeaderValue(boost::beast::http::field::host).empty())
315 {
316 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700317 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700318 }
319 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700320
Ed Tanouse278c182019-03-13 16:23:37 -0700321 BMCWEB_LOG_INFO << "Request: "
322 << " " << this << " HTTP/" << req->version() / 10 << "."
323 << req->version() % 10 << ' ' << req->methodString()
324 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700325
Ed Tanous1abe55e2018-09-05 08:30:59 -0700326 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700327
Ed Tanous1abe55e2018-09-05 08:30:59 -0700328 if (!isInvalidRequest)
329 {
330 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700331 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700332
Ed Tanouse278c182019-03-13 16:23:37 -0700333 req->ioService = static_cast<decltype(req->ioService)>(
334 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200335
Ed Tanous1abe55e2018-09-05 08:30:59 -0700336 if (!res.completed)
337 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000338 needToCallAfterHandlers = true;
339 res.completeRequestHandler = [self(shared_from_this())] {
340 self->completeRequest();
341 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700342 if (req->isUpgrade() &&
343 boost::iequals(
344 req->getHeaderValue(boost::beast::http::field::upgrade),
345 "websocket"))
346 {
347 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000348 // delete lambda with self shared_ptr
349 // to enable connection destruction
350 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700351 return;
352 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700353 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700354 }
355 else
356 {
357 completeRequest();
358 }
359 }
360 else
361 {
362 completeRequest();
363 }
364 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700365
Ed Tanouse278c182019-03-13 16:23:37 -0700366 bool isAlive()
367 {
368
369 if constexpr (std::is_same_v<Adaptor,
370 boost::beast::ssl_stream<
371 boost::asio::ip::tcp::socket>>)
372 {
373 return adaptor.next_layer().is_open();
374 }
375 else
376 {
377 return adaptor.is_open();
378 }
379 }
380 void close()
381 {
Ed Tanouse278c182019-03-13 16:23:37 -0700382 if constexpr (std::is_same_v<Adaptor,
383 boost::beast::ssl_stream<
384 boost::asio::ip::tcp::socket>>)
385 {
386 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200387#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
388 if (auto sp = session.lock())
389 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100390 BMCWEB_LOG_DEBUG << this
391 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200392 persistent_data::SessionStore::getInstance().removeSession(sp);
393 }
394#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700395 }
396 else
397 {
398 adaptor.close();
399 }
400 }
401
Ed Tanous1abe55e2018-09-05 08:30:59 -0700402 void completeRequest()
403 {
404 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
405 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700406
Ed Tanous52cc1122020-07-18 13:51:21 -0700407 addSecurityHeaders(res);
408
Ed Tanous1abe55e2018-09-05 08:30:59 -0700409 if (needToCallAfterHandlers)
410 {
James Feist3909dc82020-04-03 10:58:55 -0700411 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700412 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700413
Ed Tanouse278c182019-03-13 16:23:37 -0700414 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700415 {
416 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
417 // isReading
418 // << ' ' << isWriting;
419 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000420
421 // delete lambda with self shared_ptr
422 // to enable connection destruction
423 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700424 return;
425 }
426 if (res.body().empty() && !res.jsonValue.empty())
427 {
428 if (http_helpers::requestPrefersHtml(*req))
429 {
430 prettyPrintJson(res);
431 }
432 else
433 {
434 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700435 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700436 }
437 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700438
Ed Tanous1abe55e2018-09-05 08:30:59 -0700439 if (res.resultInt() >= 400 && res.body().empty())
440 {
441 res.body() = std::string(res.reason());
442 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700443
444 if (res.result() == boost::beast::http::status::no_content)
445 {
446 // Boost beast throws if content is provided on a no-content
447 // response. Ideally, this would never happen, but in the case that
448 // it does, we don't want to throw.
449 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100450 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700451 res.body().clear();
452 }
453
Ed Tanous1abe55e2018-09-05 08:30:59 -0700454 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
455
456 res.keepAlive(req->keepAlive());
457
458 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000459
460 // delete lambda with self shared_ptr
461 // to enable connection destruction
462 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700463 }
464
465 private:
466 void doReadHeaders()
467 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700468 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
469
470 // Clean up any previous Connection.
471 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800472 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000473 [this,
474 self(shared_from_this())](const boost::system::error_code& ec,
475 std::size_t bytes_transferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700476 BMCWEB_LOG_ERROR << this << " async_read_header "
477 << bytes_transferred << " Bytes";
478 bool errorWhileReading = false;
479 if (ec)
480 {
481 errorWhileReading = true;
482 BMCWEB_LOG_ERROR
483 << this << " Error while reading: " << ec.message();
484 }
485 else
486 {
487 // if the adaptor isn't open anymore, and wasn't handed to a
488 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700489 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700490 {
491 errorWhileReading = true;
492 }
493 }
494
James Feist3909dc82020-04-03 10:58:55 -0700495 cancelDeadlineTimer();
496
Ed Tanous1abe55e2018-09-05 08:30:59 -0700497 if (errorWhileReading)
498 {
Ed Tanouse278c182019-03-13 16:23:37 -0700499 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700500 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700501 return;
502 }
503
James Feist3909dc82020-04-03 10:58:55 -0700504 if (!req)
505 {
506 close();
507 return;
508 }
509
Ed Tanousdc7a7932020-08-17 15:04:58 -0700510 // Note, despite the bmcweb coding policy on use of exceptions
511 // for error handling, this one particular use of exceptions is
512 // deemed acceptible, as it solved a significant error handling
513 // problem that resulted in seg faults, the exact thing that the
514 // exceptions rule is trying to avoid. If at some point,
515 // boost::urls makes the parser object public (or we port it
516 // into bmcweb locally) this will be replaced with
517 // parser::parse, which returns a status code
James Feist5a7e8772020-07-22 09:08:38 -0700518
Ed Tanousdc7a7932020-08-17 15:04:58 -0700519 try
520 {
521 req->urlView = boost::urls::url_view(req->target());
522 req->url = req->urlView.encoded_path();
523 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700524 catch (std::exception& p)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700525 {
Ed Tanous3bcc0152020-08-25 07:47:29 -0700526 BMCWEB_LOG_ERROR << p.what();
Ed Tanousdc7a7932020-08-17 15:04:58 -0700527 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700528
James Feist6964c982020-07-28 16:10:23 -0700529 crow::authorization::authenticate(*req, res, session);
James Feist3909dc82020-04-03 10:58:55 -0700530
531 bool loggedIn = req && req->session;
532 if (loggedIn)
533 {
534 startDeadline(loggedInAttempts);
535 BMCWEB_LOG_DEBUG << "Starting slow deadline";
536
James Feist5a7e8772020-07-22 09:08:38 -0700537 req->urlParams = req->urlView.params();
538
539#ifdef BMCWEB_ENABLE_DEBUG
540 std::string paramList = "";
541 for (const auto param : req->urlParams)
542 {
543 paramList += param->key() + " " + param->value() + " ";
544 }
545 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
546#endif
James Feist3909dc82020-04-03 10:58:55 -0700547 }
548 else
549 {
550 const boost::optional<uint64_t> contentLength =
551 parser->content_length();
552 if (contentLength &&
553 *contentLength > loggedOutPostBodyLimit)
554 {
555 BMCWEB_LOG_DEBUG << "Content length greater than limit "
556 << *contentLength;
557 close();
558 return;
559 }
560
561 startDeadline(loggedOutAttempts);
562 BMCWEB_LOG_DEBUG << "Starting quick deadline";
563 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700564 doRead();
565 });
566 }
567
568 void doRead()
569 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700570 BMCWEB_LOG_DEBUG << this << " doRead";
571
572 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800573 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000574 [this,
575 self(shared_from_this())](const boost::system::error_code& ec,
576 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100577 BMCWEB_LOG_DEBUG << this << " async_read " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700578 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700579
580 bool errorWhileReading = false;
581 if (ec)
582 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100583 BMCWEB_LOG_ERROR
584 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700585 errorWhileReading = true;
586 }
587 else
588 {
James Feist3909dc82020-04-03 10:58:55 -0700589 if (isAlive())
590 {
591 cancelDeadlineTimer();
592 bool loggedIn = req && req->session;
593 if (loggedIn)
594 {
595 startDeadline(loggedInAttempts);
596 }
597 else
598 {
599 startDeadline(loggedOutAttempts);
600 }
601 }
602 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700603 {
604 errorWhileReading = true;
605 }
606 }
607 if (errorWhileReading)
608 {
609 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700610 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700611 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700612 return;
613 }
614 handle();
615 });
616 }
617
618 void doWrite()
619 {
James Feist3909dc82020-04-03 10:58:55 -0700620 bool loggedIn = req && req->session;
621 if (loggedIn)
622 {
623 startDeadline(loggedInAttempts);
624 }
625 else
626 {
627 startDeadline(loggedOutAttempts);
628 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100629 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700630 res.preparePayload();
631 serializer.emplace(*res.stringResponse);
632 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800633 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000634 [this,
635 self(shared_from_this())](const boost::system::error_code& ec,
636 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100637 BMCWEB_LOG_DEBUG << this << " async_write " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700638 << " bytes";
639
James Feist54d8bb12020-07-20 13:28:59 -0700640 cancelDeadlineTimer();
641
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642 if (ec)
643 {
644 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 return;
646 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800647 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 {
Ed Tanouse278c182019-03-13 16:23:37 -0700649 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700650 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651 return;
652 }
653
654 serializer.reset();
655 BMCWEB_LOG_DEBUG << this << " Clearing response";
656 res.clear();
657 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500658 parser->body_limit(httpReqBodyLimit); // reset body limit for
659 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700660 buffer.consume(buffer.size());
661
662 req.emplace(parser->get());
663 doReadHeaders();
664 });
665 }
666
Ed Tanous1abe55e2018-09-05 08:30:59 -0700667 void cancelDeadlineTimer()
668 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000669 if (timerCancelKey)
670 {
671 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
672 << ' ' << *timerCancelKey;
673 timerQueue.cancel(*timerCancelKey);
674 timerCancelKey.reset();
675 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700676 }
677
James Feist3909dc82020-04-03 10:58:55 -0700678 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700679 {
680 cancelDeadlineTimer();
681
James Feist3909dc82020-04-03 10:58:55 -0700682 if (timerIterations)
683 {
684 timerIterations--;
685 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100686
James Feist3909dc82020-04-03 10:58:55 -0700687 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700688 timerQueue.add([self(shared_from_this()), timerIterations,
689 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700690 // Mark timer as not active to avoid canceling it during
691 // Connection destructor which leads to double free issue
692 self->timerCancelKey.reset();
693 if (!self->isAlive())
694 {
695 return;
696 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100697
James Feistbe5dfca2020-07-22 08:54:59 -0700698 bool loggedIn = self->req && self->req->session;
699 // allow slow uploads for logged in users
700 if (loggedIn && self->parser->get().body().size() > readCount)
701 {
702 BMCWEB_LOG_DEBUG << self.get()
703 << " restart timer - read in progress";
704 self->startDeadline(timerIterations);
705 return;
706 }
707
James Feist3909dc82020-04-03 10:58:55 -0700708 // Threshold can be used to drop slow connections
709 // to protect against slow-rate DoS attack
710 if (timerIterations)
711 {
James Feistbe5dfca2020-07-22 08:54:59 -0700712 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700713 self->startDeadline(timerIterations);
714 return;
715 }
716
717 self->close();
718 });
James Feistcb6cb492020-04-03 13:36:17 -0700719
720 if (!timerCancelKey)
721 {
722 close();
723 return;
724 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700725 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000726 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700727 }
728
729 private:
730 Adaptor adaptor;
731 Handler* handler;
732
Ed Tanousa24526d2018-12-10 15:17:59 -0800733 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700734 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800735 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700736 boost::beast::http::request_parser<boost::beast::http::string_body>>
737 parser;
738
Ed Tanous3112a142018-11-29 15:45:10 -0800739 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700740
Ed Tanousa24526d2018-12-10 15:17:59 -0800741 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700742 boost::beast::http::string_body>>
743 serializer;
744
Ed Tanousa24526d2018-12-10 15:17:59 -0800745 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700747
748 std::weak_ptr<persistent_data::UserSession> session;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700749
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000750 std::optional<size_t> timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700751
Ed Tanous1abe55e2018-09-05 08:30:59 -0700752 bool needToCallAfterHandlers{};
753 bool needToStartReadAfterComplete{};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700754
Ed Tanous1abe55e2018-09-05 08:30:59 -0700755 std::function<std::string()>& getCachedDateStr;
756 detail::TimerQueue& timerQueue;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000757
758 using std::enable_shared_from_this<
Ed Tanous52cc1122020-07-18 13:51:21 -0700759 Connection<Adaptor, Handler>>::shared_from_this;
Ed Tanous3112a142018-11-29 15:45:10 -0800760};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700761} // namespace crow