blob: 3459d551f7749a50bca48b7cdd0eb431a46aeb7a [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 Tanouscb13a392020-07-25 19:02:03 +000064 Connection(Handler* handlerIn, const std::string& ServerNameIn,
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 Tanous271584a2019-07-09 16:24:22 -070068 handler(handlerIn), serverName(ServerNameIn),
Ed Tanous52cc1122020-07-18 13:51:21 -070069 getCachedDateStr(get_cached_date_str_f), 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);
84 SSL_set_session_id_context(
85 adaptor.native_handle(),
86 reinterpret_cast<const unsigned char*>(serverName.c_str()),
Zbigniew Kurzynskicac94c52019-11-07 12:55:04 +010087 static_cast<unsigned int>(serverName.length()));
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +010088 BMCWEB_LOG_DEBUG << this << " TLS is enabled on this connection.";
89 }
90
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +010091 adaptor.set_verify_callback([this](
92 bool preverified,
93 boost::asio::ssl::verify_context& ctx) {
94 // do nothing if TLS is disabled
Ed Tanous52cc1122020-07-18 13:51:21 -070095 if (!persistent_data::SessionStore::getInstance()
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +010096 .getAuthMethodsConfig()
97 .tls)
98 {
99 BMCWEB_LOG_DEBUG << this << " TLS auth_config is disabled";
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200100 return true;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100101 }
102
103 // We always return true to allow full auth flow
104 if (!preverified)
105 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100106 BMCWEB_LOG_DEBUG << this << " TLS preverification failed.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100107 return true;
108 }
109
110 X509_STORE_CTX* cts = ctx.native_handle();
111 if (cts == nullptr)
112 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100113 BMCWEB_LOG_DEBUG << this << " Cannot get native TLS handle.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100114 return true;
115 }
116
117 // Get certificate
118 X509* peerCert =
119 X509_STORE_CTX_get_current_cert(ctx.native_handle());
120 if (peerCert == nullptr)
121 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100122 BMCWEB_LOG_DEBUG << this
123 << " Cannot get current TLS certificate.";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100124 return true;
125 }
126
127 // Check if certificate is OK
128 int error = X509_STORE_CTX_get_error(cts);
129 if (error != X509_V_OK)
130 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100131 BMCWEB_LOG_INFO << this << " Last TLS error is: " << error;
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100132 return true;
133 }
134 // Check that we have reached final certificate in chain
135 int32_t depth = X509_STORE_CTX_get_error_depth(cts);
136 if (depth != 0)
137
138 {
139 BMCWEB_LOG_DEBUG
140 << this << " Certificate verification in progress (depth "
141 << depth << "), waiting to reach final depth";
142 return true;
143 }
144
145 BMCWEB_LOG_DEBUG << this
146 << " Certificate verification of final depth";
147
148 // Verify KeyUsage
149 bool isKeyUsageDigitalSignature = false;
150 bool isKeyUsageKeyAgreement = false;
151
152 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
Ed Tanous23a21a12020-07-25 04:45:05 +0000153 X509_get_ext_d2i(peerCert, NID_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100154
155 if (usage == nullptr)
156 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100157 BMCWEB_LOG_DEBUG << this << " TLS usage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100158 return true;
159 }
160
161 for (int i = 0; i < usage->length; i++)
162 {
163 if (KU_DIGITAL_SIGNATURE & usage->data[i])
164 {
165 isKeyUsageDigitalSignature = true;
166 }
167 if (KU_KEY_AGREEMENT & usage->data[i])
168 {
169 isKeyUsageKeyAgreement = true;
170 }
171 }
172
173 if (!isKeyUsageDigitalSignature || !isKeyUsageKeyAgreement)
174 {
175 BMCWEB_LOG_DEBUG << this
176 << " Certificate ExtendedKeyUsage does "
177 "not allow provided certificate to "
178 "be used for user authentication";
179 return true;
180 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200181 ASN1_BIT_STRING_free(usage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100182
183 // Determine that ExtendedKeyUsage includes Client Auth
184
Ed Tanous23a21a12020-07-25 04:45:05 +0000185 stack_st_ASN1_OBJECT* extUsage =
186 static_cast<stack_st_ASN1_OBJECT*>(X509_get_ext_d2i(
187 peerCert, NID_ext_key_usage, nullptr, nullptr));
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100188
189 if (extUsage == nullptr)
190 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100191 BMCWEB_LOG_DEBUG << this << " TLS extUsage is null";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100192 return true;
193 }
194
195 bool isExKeyUsageClientAuth = false;
196 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
197 {
198 if (NID_client_auth ==
199 OBJ_obj2nid(sk_ASN1_OBJECT_value(extUsage, i)))
200 {
201 isExKeyUsageClientAuth = true;
202 break;
203 }
204 }
Zbigniew Kurzynski09d02f82020-03-30 13:41:42 +0200205 sk_ASN1_OBJECT_free(extUsage);
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100206
207 // Certificate has to have proper key usages set
208 if (!isExKeyUsageClientAuth)
209 {
210 BMCWEB_LOG_DEBUG << this
211 << " Certificate ExtendedKeyUsage does "
212 "not allow provided certificate to "
213 "be used for user authentication";
214 return true;
215 }
216 std::string sslUser;
217 // Extract username contained in CommonName
218 sslUser.resize(256, '\0');
219
220 int status = X509_NAME_get_text_by_NID(
221 X509_get_subject_name(peerCert), NID_commonName, sslUser.data(),
222 static_cast<int>(sslUser.size()));
223
224 if (status == -1)
225 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100226 BMCWEB_LOG_DEBUG
227 << this << " TLS cannot get username to create session";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100228 return true;
229 }
230
231 size_t lastChar = sslUser.find('\0');
232 if (lastChar == std::string::npos || lastChar == 0)
233 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100234 BMCWEB_LOG_DEBUG << this << " Invalid TLS user name";
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100235 return true;
236 }
237 sslUser.resize(lastChar);
238
Ed Tanous52cc1122020-07-18 13:51:21 -0700239 session =
240 persistent_data::SessionStore::getInstance()
241 .generateUserSession(
242 sslUser, persistent_data::PersistenceType::TIMEOUT);
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100243 if (auto sp = session.lock())
244 {
245 BMCWEB_LOG_DEBUG << this
246 << " Generating TLS session: " << sp->uniqueId;
247 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100248 return true;
249 });
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200250#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
251
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700252#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700253 connectionCount++;
254 BMCWEB_LOG_DEBUG << this << " Connection open, total "
255 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700256#endif
Ed Tanous1abe55e2018-09-05 08:30:59 -0700257 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700258
Ed Tanous1abe55e2018-09-05 08:30:59 -0700259 ~Connection()
260 {
261 res.completeRequestHandler = nullptr;
262 cancelDeadlineTimer();
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700263#ifdef BMCWEB_ENABLE_DEBUG
Ed Tanous1abe55e2018-09-05 08:30:59 -0700264 connectionCount--;
265 BMCWEB_LOG_DEBUG << this << " Connection closed, total "
266 << connectionCount;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700267#endif
Ed Tanous7045c8d2017-04-03 10:04:37 -0700268 }
269
Ed Tanousceac6f72018-12-02 11:58:47 -0800270 Adaptor& socket()
Ed Tanous1abe55e2018-09-05 08:30:59 -0700271 {
Ed Tanousceac6f72018-12-02 11:58:47 -0800272 return adaptor;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700273 }
274
Ed Tanous1abe55e2018-09-05 08:30:59 -0700275 void start()
276 {
Ed Tanous7045c8d2017-04-03 10:04:37 -0700277
James Feist3909dc82020-04-03 10:58:55 -0700278 startDeadline(0);
Ed Tanousceac6f72018-12-02 11:58:47 -0800279 // TODO(ed) Abstract this to a more clever class with the idea of an
280 // asynchronous "start"
281 if constexpr (std::is_same_v<Adaptor,
282 boost::beast::ssl_stream<
283 boost::asio::ip::tcp::socket>>)
284 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000285 adaptor.async_handshake(boost::asio::ssl::stream_base::server,
286 [this, self(shared_from_this())](
287 const boost::system::error_code& ec) {
288 if (ec)
289 {
290 return;
291 }
292 doReadHeaders();
293 });
Ed Tanousceac6f72018-12-02 11:58:47 -0800294 }
295 else
296 {
297 doReadHeaders();
298 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700299 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700300
Ed Tanous1abe55e2018-09-05 08:30:59 -0700301 void handle()
302 {
303 cancelDeadlineTimer();
James Feist3909dc82020-04-03 10:58:55 -0700304
Ed Tanous1abe55e2018-09-05 08:30:59 -0700305 bool isInvalidRequest = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700306
Ed Tanous1abe55e2018-09-05 08:30:59 -0700307 // Check for HTTP version 1.1.
308 if (req->version() == 11)
309 {
310 if (req->getHeaderValue(boost::beast::http::field::host).empty())
311 {
312 isInvalidRequest = true;
Ed Tanousde5c9f32019-03-26 09:17:55 -0700313 res.result(boost::beast::http::status::bad_request);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700314 }
315 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700316
Ed Tanouse278c182019-03-13 16:23:37 -0700317 BMCWEB_LOG_INFO << "Request: "
318 << " " << this << " HTTP/" << req->version() / 10 << "."
319 << req->version() % 10 << ' ' << req->methodString()
320 << " " << req->target();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700321
Ed Tanous1abe55e2018-09-05 08:30:59 -0700322 needToCallAfterHandlers = false;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700323
Ed Tanous1abe55e2018-09-05 08:30:59 -0700324 if (!isInvalidRequest)
325 {
326 res.completeRequestHandler = [] {};
Ed Tanouse278c182019-03-13 16:23:37 -0700327 res.isAliveHelper = [this]() -> bool { return isAlive(); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700328
Ed Tanouse278c182019-03-13 16:23:37 -0700329 req->ioService = static_cast<decltype(req->ioService)>(
330 &adaptor.get_executor().context());
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200331
Ed Tanous1abe55e2018-09-05 08:30:59 -0700332 if (!res.completed)
333 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000334 needToCallAfterHandlers = true;
335 res.completeRequestHandler = [self(shared_from_this())] {
336 self->completeRequest();
337 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700338 if (req->isUpgrade() &&
339 boost::iequals(
340 req->getHeaderValue(boost::beast::http::field::upgrade),
341 "websocket"))
342 {
343 handler->handleUpgrade(*req, res, std::move(adaptor));
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000344 // delete lambda with self shared_ptr
345 // to enable connection destruction
346 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700347 return;
348 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700349 handler->handle(*req, res);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700350 }
351 else
352 {
353 completeRequest();
354 }
355 }
356 else
357 {
358 completeRequest();
359 }
360 }
Ed Tanouse0d918b2018-03-27 17:41:04 -0700361
Ed Tanouse278c182019-03-13 16:23:37 -0700362 bool isAlive()
363 {
364
365 if constexpr (std::is_same_v<Adaptor,
366 boost::beast::ssl_stream<
367 boost::asio::ip::tcp::socket>>)
368 {
369 return adaptor.next_layer().is_open();
370 }
371 else
372 {
373 return adaptor.is_open();
374 }
375 }
376 void close()
377 {
Ed Tanouse278c182019-03-13 16:23:37 -0700378 if constexpr (std::is_same_v<Adaptor,
379 boost::beast::ssl_stream<
380 boost::asio::ip::tcp::socket>>)
381 {
382 adaptor.next_layer().close();
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200383#ifdef BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
384 if (auto sp = session.lock())
385 {
Zbigniew Kurzynski009c2a42019-11-14 13:37:15 +0100386 BMCWEB_LOG_DEBUG << this
387 << " Removing TLS session: " << sp->uniqueId;
Kowalski, Kamil55e43f62019-07-10 13:12:57 +0200388 persistent_data::SessionStore::getInstance().removeSession(sp);
389 }
390#endif // BMCWEB_ENABLE_MUTUAL_TLS_AUTHENTICATION
Ed Tanouse278c182019-03-13 16:23:37 -0700391 }
392 else
393 {
394 adaptor.close();
395 }
396 }
397
Ed Tanous1abe55e2018-09-05 08:30:59 -0700398 void completeRequest()
399 {
400 BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
401 << res.resultInt() << " keepalive=" << req->keepAlive();
Ed Tanous7045c8d2017-04-03 10:04:37 -0700402
Ed Tanous52cc1122020-07-18 13:51:21 -0700403 addSecurityHeaders(res);
404
Ed Tanous1abe55e2018-09-05 08:30:59 -0700405 if (needToCallAfterHandlers)
406 {
James Feist3909dc82020-04-03 10:58:55 -0700407 crow::authorization::cleanupTempSession(*req);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700408 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700409
Ed Tanouse278c182019-03-13 16:23:37 -0700410 if (!isAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700411 {
412 // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " <<
413 // isReading
414 // << ' ' << isWriting;
415 // delete this;
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000416
417 // delete lambda with self shared_ptr
418 // to enable connection destruction
419 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700420 return;
421 }
422 if (res.body().empty() && !res.jsonValue.empty())
423 {
424 if (http_helpers::requestPrefersHtml(*req))
425 {
426 prettyPrintJson(res);
427 }
428 else
429 {
430 res.jsonMode();
Jason M. Bills193ad2f2018-09-26 15:08:52 -0700431 res.body() = res.jsonValue.dump(2, ' ', true);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700432 }
433 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700434
Ed Tanous1abe55e2018-09-05 08:30:59 -0700435 if (res.resultInt() >= 400 && res.body().empty())
436 {
437 res.body() = std::string(res.reason());
438 }
Ed Tanous6295bec2019-09-03 10:11:01 -0700439
440 if (res.result() == boost::beast::http::status::no_content)
441 {
442 // Boost beast throws if content is provided on a no-content
443 // response. Ideally, this would never happen, but in the case that
444 // it does, we don't want to throw.
445 BMCWEB_LOG_CRITICAL
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100446 << this << " Response content provided but code was no-content";
Ed Tanous6295bec2019-09-03 10:11:01 -0700447 res.body().clear();
448 }
449
Ed Tanous1abe55e2018-09-05 08:30:59 -0700450 res.addHeader(boost::beast::http::field::server, serverName);
451 res.addHeader(boost::beast::http::field::date, getCachedDateStr());
452
453 res.keepAlive(req->keepAlive());
454
455 doWrite();
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000456
457 // delete lambda with self shared_ptr
458 // to enable connection destruction
459 res.completeRequestHandler = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700460 }
461
462 private:
463 void doReadHeaders()
464 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700465 BMCWEB_LOG_DEBUG << this << " doReadHeaders";
466
467 // Clean up any previous Connection.
468 boost::beast::http::async_read_header(
Ed Tanousceac6f72018-12-02 11:58:47 -0800469 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000470 [this,
471 self(shared_from_this())](const boost::system::error_code& ec,
472 std::size_t bytes_transferred) {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700473 BMCWEB_LOG_ERROR << this << " async_read_header "
474 << bytes_transferred << " Bytes";
475 bool errorWhileReading = false;
476 if (ec)
477 {
478 errorWhileReading = true;
479 BMCWEB_LOG_ERROR
480 << this << " Error while reading: " << ec.message();
481 }
482 else
483 {
484 // if the adaptor isn't open anymore, and wasn't handed to a
485 // websocket, treat as an error
Ed Tanouse278c182019-03-13 16:23:37 -0700486 if (!isAlive() && !req->isUpgrade())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700487 {
488 errorWhileReading = true;
489 }
490 }
491
James Feist3909dc82020-04-03 10:58:55 -0700492 cancelDeadlineTimer();
493
Ed Tanous1abe55e2018-09-05 08:30:59 -0700494 if (errorWhileReading)
495 {
Ed Tanouse278c182019-03-13 16:23:37 -0700496 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700497 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700498 return;
499 }
500
James Feist3909dc82020-04-03 10:58:55 -0700501 if (!req)
502 {
503 close();
504 return;
505 }
506
Ed Tanousdc7a7932020-08-17 15:04:58 -0700507 // Note, despite the bmcweb coding policy on use of exceptions
508 // for error handling, this one particular use of exceptions is
509 // deemed acceptible, as it solved a significant error handling
510 // problem that resulted in seg faults, the exact thing that the
511 // exceptions rule is trying to avoid. If at some point,
512 // boost::urls makes the parser object public (or we port it
513 // into bmcweb locally) this will be replaced with
514 // parser::parse, which returns a status code
James Feist5a7e8772020-07-22 09:08:38 -0700515
Ed Tanousdc7a7932020-08-17 15:04:58 -0700516 try
517 {
518 req->urlView = boost::urls::url_view(req->target());
519 req->url = req->urlView.encoded_path();
520 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700521 catch (std::exception& p)
Ed Tanousdc7a7932020-08-17 15:04:58 -0700522 {
Ed Tanous3bcc0152020-08-25 07:47:29 -0700523 BMCWEB_LOG_ERROR << p.what();
Ed Tanousdc7a7932020-08-17 15:04:58 -0700524 }
Ed Tanous92ccb882020-08-18 10:36:33 -0700525
James Feist6964c982020-07-28 16:10:23 -0700526 crow::authorization::authenticate(*req, res, session);
James Feist3909dc82020-04-03 10:58:55 -0700527
528 bool loggedIn = req && req->session;
529 if (loggedIn)
530 {
531 startDeadline(loggedInAttempts);
532 BMCWEB_LOG_DEBUG << "Starting slow deadline";
533
James Feist5a7e8772020-07-22 09:08:38 -0700534 req->urlParams = req->urlView.params();
535
536#ifdef BMCWEB_ENABLE_DEBUG
537 std::string paramList = "";
538 for (const auto param : req->urlParams)
539 {
540 paramList += param->key() + " " + param->value() + " ";
541 }
542 BMCWEB_LOG_DEBUG << "QueryParams: " << paramList;
543#endif
James Feist3909dc82020-04-03 10:58:55 -0700544 }
545 else
546 {
547 const boost::optional<uint64_t> contentLength =
548 parser->content_length();
549 if (contentLength &&
550 *contentLength > loggedOutPostBodyLimit)
551 {
552 BMCWEB_LOG_DEBUG << "Content length greater than limit "
553 << *contentLength;
554 close();
555 return;
556 }
557
558 startDeadline(loggedOutAttempts);
559 BMCWEB_LOG_DEBUG << "Starting quick deadline";
560 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700561 doRead();
562 });
563 }
564
565 void doRead()
566 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700567 BMCWEB_LOG_DEBUG << this << " doRead";
568
569 boost::beast::http::async_read(
Ed Tanousceac6f72018-12-02 11:58:47 -0800570 adaptor, buffer, *parser,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000571 [this,
572 self(shared_from_this())](const boost::system::error_code& ec,
573 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100574 BMCWEB_LOG_DEBUG << this << " async_read " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700575 << " Bytes";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700576
577 bool errorWhileReading = false;
578 if (ec)
579 {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100580 BMCWEB_LOG_ERROR
581 << this << " Error while reading: " << ec.message();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700582 errorWhileReading = true;
583 }
584 else
585 {
James Feist3909dc82020-04-03 10:58:55 -0700586 if (isAlive())
587 {
588 cancelDeadlineTimer();
589 bool loggedIn = req && req->session;
590 if (loggedIn)
591 {
592 startDeadline(loggedInAttempts);
593 }
594 else
595 {
596 startDeadline(loggedOutAttempts);
597 }
598 }
599 else
Ed Tanous1abe55e2018-09-05 08:30:59 -0700600 {
601 errorWhileReading = true;
602 }
603 }
604 if (errorWhileReading)
605 {
606 cancelDeadlineTimer();
Ed Tanouse278c182019-03-13 16:23:37 -0700607 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700608 BMCWEB_LOG_DEBUG << this << " from read(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700609 return;
610 }
611 handle();
612 });
613 }
614
615 void doWrite()
616 {
James Feist3909dc82020-04-03 10:58:55 -0700617 bool loggedIn = req && req->session;
618 if (loggedIn)
619 {
620 startDeadline(loggedInAttempts);
621 }
622 else
623 {
624 startDeadline(loggedOutAttempts);
625 }
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100626 BMCWEB_LOG_DEBUG << this << " doWrite";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700627 res.preparePayload();
628 serializer.emplace(*res.stringResponse);
629 boost::beast::http::async_write(
Ed Tanousceac6f72018-12-02 11:58:47 -0800630 adaptor, *serializer,
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000631 [this,
632 self(shared_from_this())](const boost::system::error_code& ec,
633 std::size_t bytes_transferred) {
Zbigniew Kurzynski2658d982019-11-19 18:01:08 +0100634 BMCWEB_LOG_DEBUG << this << " async_write " << bytes_transferred
Ed Tanous1abe55e2018-09-05 08:30:59 -0700635 << " bytes";
636
James Feist54d8bb12020-07-20 13:28:59 -0700637 cancelDeadlineTimer();
638
Ed Tanous1abe55e2018-09-05 08:30:59 -0700639 if (ec)
640 {
641 BMCWEB_LOG_DEBUG << this << " from write(2)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700642 return;
643 }
Ed Tanousceac6f72018-12-02 11:58:47 -0800644 if (!res.keepAlive())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700645 {
Ed Tanouse278c182019-03-13 16:23:37 -0700646 close();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700647 BMCWEB_LOG_DEBUG << this << " from write(1)";
Ed Tanous1abe55e2018-09-05 08:30:59 -0700648 return;
649 }
650
651 serializer.reset();
652 BMCWEB_LOG_DEBUG << this << " Clearing response";
653 res.clear();
654 parser.emplace(std::piecewise_construct, std::make_tuple());
Gunnar Millsded2a1e2020-07-24 09:46:33 -0500655 parser->body_limit(httpReqBodyLimit); // reset body limit for
656 // newly created parser
Ed Tanous1abe55e2018-09-05 08:30:59 -0700657 buffer.consume(buffer.size());
658
659 req.emplace(parser->get());
660 doReadHeaders();
661 });
662 }
663
Ed Tanous1abe55e2018-09-05 08:30:59 -0700664 void cancelDeadlineTimer()
665 {
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000666 if (timerCancelKey)
667 {
668 BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue
669 << ' ' << *timerCancelKey;
670 timerQueue.cancel(*timerCancelKey);
671 timerCancelKey.reset();
672 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700673 }
674
James Feist3909dc82020-04-03 10:58:55 -0700675 void startDeadline(size_t timerIterations)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700676 {
677 cancelDeadlineTimer();
678
James Feist3909dc82020-04-03 10:58:55 -0700679 if (timerIterations)
680 {
681 timerIterations--;
682 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100683
James Feist3909dc82020-04-03 10:58:55 -0700684 timerCancelKey =
James Feistbe5dfca2020-07-22 08:54:59 -0700685 timerQueue.add([self(shared_from_this()), timerIterations,
686 readCount{parser->get().body().size()}] {
James Feist3909dc82020-04-03 10:58:55 -0700687 // Mark timer as not active to avoid canceling it during
688 // Connection destructor which leads to double free issue
689 self->timerCancelKey.reset();
690 if (!self->isAlive())
691 {
692 return;
693 }
Jan Sowinski2b5e08e2020-01-09 17:16:02 +0100694
James Feistbe5dfca2020-07-22 08:54:59 -0700695 bool loggedIn = self->req && self->req->session;
696 // allow slow uploads for logged in users
697 if (loggedIn && self->parser->get().body().size() > readCount)
698 {
699 BMCWEB_LOG_DEBUG << self.get()
700 << " restart timer - read in progress";
701 self->startDeadline(timerIterations);
702 return;
703 }
704
James Feist3909dc82020-04-03 10:58:55 -0700705 // Threshold can be used to drop slow connections
706 // to protect against slow-rate DoS attack
707 if (timerIterations)
708 {
James Feistbe5dfca2020-07-22 08:54:59 -0700709 BMCWEB_LOG_DEBUG << self.get() << " restart timer";
James Feist3909dc82020-04-03 10:58:55 -0700710 self->startDeadline(timerIterations);
711 return;
712 }
713
714 self->close();
715 });
James Feistcb6cb492020-04-03 13:36:17 -0700716
717 if (!timerCancelKey)
718 {
719 close();
720 return;
721 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700722 BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000723 << *timerCancelKey;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700724 }
725
726 private:
727 Adaptor adaptor;
728 Handler* handler;
729
Ed Tanousa24526d2018-12-10 15:17:59 -0800730 // Making this a std::optional allows it to be efficiently destroyed and
Ed Tanous1abe55e2018-09-05 08:30:59 -0700731 // re-created on Connection reset
Ed Tanousa24526d2018-12-10 15:17:59 -0800732 std::optional<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700733 boost::beast::http::request_parser<boost::beast::http::string_body>>
734 parser;
735
Ed Tanous3112a142018-11-29 15:45:10 -0800736 boost::beast::flat_static_buffer<8192> buffer;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700737
Ed Tanousa24526d2018-12-10 15:17:59 -0800738 std::optional<boost::beast::http::response_serializer<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700739 boost::beast::http::string_body>>
740 serializer;
741
Ed Tanousa24526d2018-12-10 15:17:59 -0800742 std::optional<crow::Request> req;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700743 crow::Response res;
Ed Tanous52cc1122020-07-18 13:51:21 -0700744
745 std::weak_ptr<persistent_data::UserSession> session;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746
747 const std::string& serverName;
748
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