xref: /openbmc/bmcweb/http/http_connection.hpp (revision e777eff2b67c7884ae485861f256dacddedb3c48)
1 // SPDX-License-Identifier: Apache-2.0
2 // SPDX-FileCopyrightText: Copyright OpenBMC Authors
3 #pragma once
4 #include "bmcweb_config.h"
5 
6 #include "async_resp.hpp"
7 #include "authentication.hpp"
8 #include "complete_response_fields.hpp"
9 #include "forward_unauthorized.hpp"
10 #include "http2_connection.hpp"
11 #include "http_body.hpp"
12 #include "http_connect_types.hpp"
13 #include "http_request.hpp"
14 #include "http_response.hpp"
15 #include "http_utility.hpp"
16 #include "logging.hpp"
17 #include "mutual_tls.hpp"
18 #include "sessions.hpp"
19 #include "str_utility.hpp"
20 #include "utility.hpp"
21 
22 #include <boost/asio/error.hpp>
23 #include <boost/asio/ip/tcp.hpp>
24 #include <boost/asio/ssl/error.hpp>
25 #include <boost/asio/ssl/stream.hpp>
26 #include <boost/asio/ssl/stream_base.hpp>
27 #include <boost/asio/ssl/verify_context.hpp>
28 #include <boost/asio/steady_timer.hpp>
29 #include <boost/beast/_experimental/test/stream.hpp>
30 #include <boost/beast/core/buffers_generator.hpp>
31 #include <boost/beast/core/detect_ssl.hpp>
32 #include <boost/beast/core/error.hpp>
33 #include <boost/beast/core/flat_static_buffer.hpp>
34 #include <boost/beast/http/error.hpp>
35 #include <boost/beast/http/field.hpp>
36 #include <boost/beast/http/message_generator.hpp>
37 #include <boost/beast/http/parser.hpp>
38 #include <boost/beast/http/read.hpp>
39 #include <boost/beast/http/rfc7230.hpp>
40 #include <boost/beast/http/status.hpp>
41 #include <boost/beast/http/verb.hpp>
42 #include <boost/none.hpp>
43 #include <boost/optional/optional.hpp>
44 #include <boost/url/url_view.hpp>
45 
46 #include <bit>
47 #include <chrono>
48 #include <cstddef>
49 #include <cstdint>
50 #include <functional>
51 #include <memory>
52 #include <optional>
53 #include <string>
54 #include <string_view>
55 #include <system_error>
56 #include <type_traits>
57 #include <utility>
58 
59 namespace crow
60 {
61 
62 // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables)
63 static int connectionCount = 0;
64 
65 // request body limit size set by the BMCWEB_HTTP_BODY_LIMIT option
66 constexpr uint64_t httpReqBodyLimit = 1024UL * 1024UL * BMCWEB_HTTP_BODY_LIMIT;
67 
68 constexpr uint64_t loggedOutPostBodyLimit = 4096U;
69 
70 constexpr uint32_t httpHeaderLimit = 8192U;
71 
72 enum class DeadlineTimerType
73 {
74     Default,
75     Keepalive,
76 };
77 
78 template <typename Adaptor, typename Handler>
79 class Connection :
80     public std::enable_shared_from_this<Connection<Adaptor, Handler>>
81 {
82     using self_type = Connection<Adaptor, Handler>;
83 
84   public:
Connection(Handler * handlerIn,HttpType httpTypeIn,boost::asio::steady_timer && timerIn,std::function<std::string ()> & getCachedDateStrF,boost::asio::ssl::stream<Adaptor> && adaptorIn)85     Connection(Handler* handlerIn, HttpType httpTypeIn,
86                boost::asio::steady_timer&& timerIn,
87                std::function<std::string()>& getCachedDateStrF,
88                boost::asio::ssl::stream<Adaptor>&& adaptorIn) :
89         httpType(httpTypeIn), adaptor(std::move(adaptorIn)), handler(handlerIn),
90         timer(std::move(timerIn)), getCachedDateStr(getCachedDateStrF)
91     {
92         initParser();
93 
94         connectionCount++;
95 
96         BMCWEB_LOG_DEBUG("{} Connection created, total {}", logPtr(this),
97                          connectionCount);
98     }
99 
~Connection()100     ~Connection()
101     {
102         res.releaseCompleteRequestHandler();
103         cancelDeadlineTimer();
104 
105         connectionCount--;
106         BMCWEB_LOG_DEBUG("{} Connection closed, total {}", logPtr(this),
107                          connectionCount);
108     }
109 
110     Connection(const Connection&) = delete;
111     Connection(Connection&&) = delete;
112     Connection& operator=(const Connection&) = delete;
113     Connection& operator=(Connection&&) = delete;
114 
tlsVerifyCallback(bool preverified,boost::asio::ssl::verify_context & ctx)115     bool tlsVerifyCallback(bool preverified,
116                            boost::asio::ssl::verify_context& ctx)
117     {
118         BMCWEB_LOG_DEBUG("{} tlsVerifyCallback called with preverified {}",
119                          logPtr(this), preverified);
120         if (preverified)
121         {
122             mtlsSession = verifyMtlsUser(ip, ctx);
123             if (mtlsSession)
124             {
125                 BMCWEB_LOG_DEBUG("{} Generated TLS session: {}", logPtr(this),
126                                  mtlsSession->uniqueId);
127             }
128         }
129         const persistent_data::AuthConfigMethods& c =
130             persistent_data::SessionStore::getInstance().getAuthMethodsConfig();
131         if (c.tlsStrict)
132         {
133             BMCWEB_LOG_DEBUG(
134                 "{} TLS is in strict mode, returning preverified as is.",
135                 logPtr(this));
136             return preverified;
137         }
138         // If tls strict mode is disabled
139         // We always return true to allow full auth flow for resources that
140         // don't require auth
141         return true;
142     }
143 
prepareMutualTls()144     bool prepareMutualTls()
145     {
146         BMCWEB_LOG_DEBUG("prepareMutualTls");
147 
148         constexpr std::string_view id = "bmcweb";
149 
150         const char* idPtr = id.data();
151         const auto* idCPtr = std::bit_cast<const unsigned char*>(idPtr);
152         auto idLen = static_cast<unsigned int>(id.length());
153         int ret =
154             SSL_set_session_id_context(adaptor.native_handle(), idCPtr, idLen);
155         if (ret == 0)
156         {
157             BMCWEB_LOG_ERROR("{} failed to set SSL id", logPtr(this));
158             return false;
159         }
160 
161         BMCWEB_LOG_DEBUG("set_verify_callback");
162 
163         boost::system::error_code ec;
164         adaptor.set_verify_callback(
165             std::bind_front(&self_type::tlsVerifyCallback, this), ec);
166         if (ec)
167         {
168             BMCWEB_LOG_ERROR("Failed to set verify callback {}", ec);
169             return false;
170         }
171 
172         return true;
173     }
174 
afterDetectSsl(const std::shared_ptr<self_type> &,boost::beast::error_code ec,bool isTls)175     void afterDetectSsl(const std::shared_ptr<self_type>& /*self*/,
176                         boost::beast::error_code ec, bool isTls)
177     {
178         if (ec)
179         {
180             BMCWEB_LOG_ERROR("Couldn't detect ssl ", ec);
181             return;
182         }
183         BMCWEB_LOG_DEBUG("{} TLS was detected as {}", logPtr(this), isTls);
184         if (isTls)
185         {
186             if (httpType != HttpType::HTTPS && httpType != HttpType::BOTH)
187             {
188                 BMCWEB_LOG_WARNING(
189                     "{} Connection closed due to incompatible type",
190                     logPtr(this));
191                 return;
192             }
193             httpType = HttpType::HTTPS;
194             adaptor.async_handshake(
195                 boost::asio::ssl::stream_base::server, buffer.data(),
196                 std::bind_front(&self_type::afterSslHandshake, this,
197                                 shared_from_this()));
198         }
199         else
200         {
201             if (httpType != HttpType::HTTP && httpType != HttpType::BOTH)
202             {
203                 BMCWEB_LOG_WARNING(
204                     "{} Connection closed due to incompatible type",
205                     logPtr(this));
206                 return;
207             }
208 
209             httpType = HttpType::HTTP;
210             BMCWEB_LOG_INFO("Starting non-SSL session");
211             doReadHeaders();
212         }
213     }
214 
start()215     void start()
216     {
217         BMCWEB_LOG_DEBUG("{} Connection started, total {}", logPtr(this),
218                          connectionCount);
219         if (connectionCount >= 200)
220         {
221             BMCWEB_LOG_CRITICAL("{} Max connection count exceeded.",
222                                 logPtr(this));
223             return;
224         }
225 
226         if constexpr (BMCWEB_MUTUAL_TLS_AUTH)
227         {
228             if (!prepareMutualTls())
229             {
230                 BMCWEB_LOG_ERROR("{} Failed to prepare mTLS", logPtr(this));
231                 return;
232             }
233         }
234 
235         startDeadline(DeadlineTimerType::Default);
236 
237         readClientIp();
238         boost::beast::async_detect_ssl(
239             adaptor.next_layer(), buffer,
240             std::bind_front(&self_type::afterDetectSsl, this,
241                             shared_from_this()));
242     }
243 
afterSslHandshake(const std::shared_ptr<self_type> &,const boost::system::error_code & ec,size_t bytesParsed)244     void afterSslHandshake(const std::shared_ptr<self_type>& /*self*/,
245                            const boost::system::error_code& ec,
246                            size_t bytesParsed)
247     {
248         buffer.consume(bytesParsed);
249         if (ec)
250         {
251             BMCWEB_LOG_ERROR("{} SSL handshake failed", logPtr(this));
252             return;
253         }
254         BMCWEB_LOG_DEBUG("{} SSL handshake succeeded", logPtr(this));
255         // If http2 is enabled, negotiate the protocol
256         if constexpr (BMCWEB_HTTP2)
257         {
258             const unsigned char* alpn = nullptr;
259             unsigned int alpnlen = 0;
260             SSL_get0_alpn_selected(adaptor.native_handle(), &alpn, &alpnlen);
261             if (alpn != nullptr)
262             {
263                 std::string_view selectedProtocol(
264                     std::bit_cast<const char*>(alpn), alpnlen);
265                 BMCWEB_LOG_DEBUG("ALPN selected protocol \"{}\" len: {}",
266                                  selectedProtocol, alpnlen);
267                 if (selectedProtocol == "h2")
268                 {
269                     upgradeToHttp2();
270                     return;
271                 }
272             }
273         }
274 
275         doReadHeaders();
276     }
277 
initParser()278     void initParser()
279     {
280         boost::beast::http::request_parser<bmcweb::HttpBody>& instance =
281             parser.emplace();
282 
283         // reset header limit for newly created parser
284         instance.header_limit(httpHeaderLimit);
285 
286         // Initially set no body limit. We don't yet know if the user is
287         // authenticated.
288         instance.body_limit(boost::none);
289     }
290 
upgradeToHttp2()291     void upgradeToHttp2()
292     {
293         auto http2 = std::make_shared<HTTP2Connection<Adaptor, Handler>>(
294             std::move(adaptor), handler, getCachedDateStr, httpType,
295             mtlsSession);
296         if (http2settings.empty())
297         {
298             http2->start();
299         }
300         else
301         {
302             http2->startFromSettings(http2settings);
303         }
304     }
305 
306     // returns whether connection was upgraded
doUpgrade(const std::shared_ptr<bmcweb::AsyncResp> & asyncResp)307     bool doUpgrade(const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
308     {
309         using boost::beast::http::field;
310         using boost::beast::http::token_list;
311 
312         bool isSse =
313             isContentTypeAllowed(req->getHeaderValue("Accept"),
314                                  http_helpers::ContentType::EventStream, false);
315 
316         bool isWebsocket = false;
317         bool isH2c = false;
318         // Check connection header is upgrade
319         if (token_list{req->req[field::connection]}.exists("upgrade"))
320         {
321             BMCWEB_LOG_DEBUG("{} Connection: Upgrade header was present",
322                              logPtr(this));
323             // Parse if upgrade is h2c or websocket
324             token_list upgrade{req->req[field::upgrade]};
325             isWebsocket = upgrade.exists("websocket");
326             isH2c = upgrade.exists("h2c");
327             BMCWEB_LOG_DEBUG("{} Upgrade isWebsocket: {} isH2c: {}",
328                              logPtr(this), isWebsocket, isH2c);
329         }
330 
331         if (BMCWEB_HTTP2 && isH2c)
332         {
333             std::string_view base64settings = req->req[field::http2_settings];
334             if (utility::base64Decode<true>(base64settings, http2settings))
335             {
336                 res.result(boost::beast::http::status::switching_protocols);
337                 res.addHeader(boost::beast::http::field::connection, "Upgrade");
338                 res.addHeader(boost::beast::http::field::upgrade, "h2c");
339             }
340         }
341 
342         // websocket and SSE are only allowed on GET
343         if (req->req.method() == boost::beast::http::verb::get)
344         {
345             if (isWebsocket || isSse)
346             {
347                 asyncResp->res.setCompleteRequestHandler(
348                     [self(shared_from_this())](crow::Response& thisRes) {
349                         if (thisRes.result() != boost::beast::http::status::ok)
350                         {
351                             // When any error occurs before handle upgradation,
352                             // the result in response will be set to respective
353                             // error. By default the Result will be OK (200),
354                             // which implies successful handle upgrade. Response
355                             // needs to be sent over this connection only on
356                             // failure.
357                             self->completeRequest(thisRes);
358                             return;
359                         }
360                     });
361                 BMCWEB_LOG_INFO("{} Upgrading socket", logPtr(this));
362                 if (httpType == HttpType::HTTP)
363                 {
364                     handler->handleUpgrade(req, asyncResp,
365                                            std::move(adaptor.next_layer()));
366                 }
367                 else
368                 {
369                     handler->handleUpgrade(req, asyncResp, std::move(adaptor));
370                 }
371 
372                 return true;
373             }
374         }
375         return false;
376     }
377 
handle()378     void handle()
379     {
380         std::error_code reqEc;
381         if (!parser)
382         {
383             return;
384         }
385         req = std::make_shared<Request>(parser->release(), reqEc);
386         if (reqEc)
387         {
388             BMCWEB_LOG_DEBUG("Request failed to construct{}", reqEc.message());
389             res.result(boost::beast::http::status::bad_request);
390             completeRequest(res);
391             return;
392         }
393         req->session = userSession;
394         using boost::beast::http::field;
395         accept = req->getHeaderValue(field::accept);
396         acceptEncoding = req->getHeaderValue(field::accept_encoding);
397         // Fetch the client IP address
398         req->ipAddress = ip;
399 
400         // Check for HTTP version 1.1.
401         if (req->version() == 11)
402         {
403             if (req->getHeaderValue(field::host).empty())
404             {
405                 res.result(boost::beast::http::status::bad_request);
406                 completeRequest(res);
407                 return;
408             }
409         }
410 
411         BMCWEB_LOG_INFO("Request:  {} HTTP/{}.{} {} {} {}", logPtr(this),
412                         req->version() / 10, req->version() % 10,
413                         req->methodString(), req->target(),
414                         req->ipAddress.to_string());
415 
416         if (res.completed)
417         {
418             completeRequest(res);
419             return;
420         }
421         keepAlive = req->keepAlive();
422 
423         if (authenticationEnabled)
424         {
425             if (!authentication::isOnAllowlist(req->url().path(),
426                                                req->method()) &&
427                 req->session == nullptr)
428             {
429                 BMCWEB_LOG_WARNING("Authentication failed");
430                 forward_unauthorized::sendUnauthorized(
431                     req->url().encoded_path(),
432                     req->getHeaderValue("X-Requested-With"),
433                     req->getHeaderValue("Accept"), res);
434                 completeRequest(res);
435                 return;
436             }
437         }
438 
439         auto asyncResp = std::make_shared<bmcweb::AsyncResp>();
440         BMCWEB_LOG_DEBUG("Setting completion handler");
441         asyncResp->res.setCompleteRequestHandler(
442             [self(shared_from_this())](Response& thisRes) {
443                 self->completeRequest(thisRes);
444             });
445         if (doUpgrade(asyncResp))
446         {
447             return;
448         }
449         std::string_view expectedEtag =
450             req->getHeaderValue(boost::beast::http::field::if_none_match);
451         if (!expectedEtag.empty())
452         {
453             asyncResp->res.setExpectedEtag(expectedEtag);
454         }
455         handler->handle(req, asyncResp);
456     }
457 
hardClose()458     void hardClose()
459     {
460         BMCWEB_LOG_DEBUG("{} Closing socket", logPtr(this));
461         adaptor.next_layer().close();
462     }
463 
tlsShutdownComplete(const std::shared_ptr<self_type> & self,const boost::system::error_code & ec)464     void tlsShutdownComplete(const std::shared_ptr<self_type>& self,
465                              const boost::system::error_code& ec)
466     {
467         if (ec)
468         {
469             BMCWEB_LOG_WARNING("{} Failed to shut down TLS cleanly {}",
470                                logPtr(self.get()), ec);
471         }
472         self->hardClose();
473     }
474 
gracefulClose()475     void gracefulClose()
476     {
477         BMCWEB_LOG_DEBUG("{} Socket close requested", logPtr(this));
478 
479         if (httpType == HttpType::HTTPS)
480         {
481             if (mtlsSession != nullptr)
482             {
483                 BMCWEB_LOG_DEBUG("{} Removing TLS session: {}", logPtr(this),
484                                  mtlsSession->uniqueId);
485                 persistent_data::SessionStore::getInstance().removeSession(
486                     mtlsSession);
487             }
488 
489             adaptor.async_shutdown(std::bind_front(
490                 &self_type::tlsShutdownComplete, this, shared_from_this()));
491         }
492         else
493         {
494             hardClose();
495         }
496     }
497 
completeRequest(Response & thisRes)498     void completeRequest(Response& thisRes)
499     {
500         res = std::move(thisRes);
501         res.keepAlive(keepAlive);
502 
503         completeResponseFields(accept, acceptEncoding, res);
504         res.addHeader(boost::beast::http::field::date, getCachedDateStr());
505 
506         doWrite();
507 
508         // delete lambda with self shared_ptr
509         // to enable connection destruction
510         res.setCompleteRequestHandler(nullptr);
511     }
512 
readClientIp()513     void readClientIp()
514     {
515         boost::system::error_code ec;
516 
517         boost::asio::ip::tcp::endpoint endpoint =
518             boost::beast::get_lowest_layer(adaptor).remote_endpoint(ec);
519 
520         if (ec)
521         {
522             // If remote endpoint fails keep going. "ClientOriginIPAddress"
523             // will be empty.
524             BMCWEB_LOG_ERROR("Failed to get the client's IP Address. ec : {}",
525                              ec);
526             return;
527         }
528         ip = endpoint.address();
529     }
530 
disableAuth()531     void disableAuth()
532     {
533         authenticationEnabled = false;
534     }
535 
536   private:
getContentLengthLimit()537     uint64_t getContentLengthLimit()
538     {
539         if constexpr (!BMCWEB_INSECURE_DISABLE_AUTH)
540         {
541             if (userSession == nullptr)
542             {
543                 return loggedOutPostBodyLimit;
544             }
545         }
546 
547         return httpReqBodyLimit;
548     }
549 
550     // Returns true if content length was within limits
551     // Returns false if content length error has been returned
handleContentLengthError()552     bool handleContentLengthError()
553     {
554         if (!parser)
555         {
556             BMCWEB_LOG_CRITICAL("Parser was null");
557             return false;
558         }
559         const boost::optional<uint64_t> contentLength =
560             parser->content_length();
561         if (!contentLength)
562         {
563             BMCWEB_LOG_DEBUG("{} No content length available", logPtr(this));
564             return true;
565         }
566 
567         uint64_t maxAllowedContentLength = getContentLengthLimit();
568 
569         if (*contentLength > maxAllowedContentLength)
570         {
571             // If the users content limit is between the logged in
572             // and logged out limits They probably just didn't log
573             // in
574             if (*contentLength > loggedOutPostBodyLimit &&
575                 *contentLength < httpReqBodyLimit)
576             {
577                 BMCWEB_LOG_DEBUG(
578                     "{} Content length {} valid, but greater than logged out"
579                     " limit of {}. Setting unauthorized",
580                     logPtr(this), *contentLength, loggedOutPostBodyLimit);
581                 res.result(boost::beast::http::status::unauthorized);
582             }
583             else
584             {
585                 // Otherwise they're over both limits, so inform
586                 // them
587                 BMCWEB_LOG_DEBUG(
588                     "{} Content length {} was greater than global limit {}."
589                     " Setting payload too large",
590                     logPtr(this), *contentLength, httpReqBodyLimit);
591                 res.result(boost::beast::http::status::payload_too_large);
592             }
593 
594             keepAlive = false;
595             doWrite();
596             return false;
597         }
598 
599         return true;
600     }
601 
afterReadHeaders(const std::shared_ptr<self_type> &,const boost::system::error_code & ec,std::size_t bytesTransferred)602     void afterReadHeaders(const std::shared_ptr<self_type>& /*self*/,
603                           const boost::system::error_code& ec,
604                           std::size_t bytesTransferred)
605     {
606         BMCWEB_LOG_DEBUG("{} async_read_header {} Bytes", logPtr(this),
607                          bytesTransferred);
608 
609         if (ec)
610         {
611             cancelDeadlineTimer();
612 
613             if (ec == boost::beast::http::error::header_limit)
614             {
615                 BMCWEB_LOG_ERROR("{} Header field too large, closing",
616                                  logPtr(this), ec.message());
617 
618                 res.result(boost::beast::http::status::
619                                request_header_fields_too_large);
620                 keepAlive = false;
621                 doWrite();
622                 return;
623             }
624             BMCWEB_LOG_WARNING("{} End of stream, closing {}", logPtr(this),
625                                ec);
626             hardClose();
627             return;
628         }
629 
630         if (!parser)
631         {
632             BMCWEB_LOG_ERROR("Parser was unexpectedly null");
633             return;
634         }
635         auto& parse = *parser;
636         const auto& value = parser->get();
637 
638         if (authenticationEnabled)
639         {
640             boost::beast::http::verb method = value.method();
641             userSession = authentication::authenticate(
642                 ip, res, method, value.base(), mtlsSession);
643         }
644 
645         std::string_view expect = value[boost::beast::http::field::expect];
646         if (bmcweb::asciiIEquals(expect, "100-continue"))
647         {
648             res.result(boost::beast::http::status::continue_);
649             doWrite();
650             return;
651         }
652 
653         if (!handleContentLengthError())
654         {
655             return;
656         }
657 
658         parse.body_limit(getContentLengthLimit());
659 
660         if (parse.is_done())
661         {
662             handle();
663             return;
664         }
665 
666         doRead();
667     }
668 
doReadHeaders()669     void doReadHeaders()
670     {
671         BMCWEB_LOG_DEBUG("{} doReadHeaders", logPtr(this));
672 
673         startDeadline(DeadlineTimerType::Keepalive);
674 
675         if (!parser)
676         {
677             BMCWEB_LOG_CRITICAL("Parser was not initialized.");
678             return;
679         }
680 
681         if (httpType == HttpType::HTTP)
682         {
683             boost::beast::http::async_read_header(
684                 adaptor.next_layer(), buffer, *parser,
685                 std::bind_front(&self_type::afterReadHeaders, this,
686                                 shared_from_this()));
687         }
688         else
689         {
690             boost::beast::http::async_read_header(
691                 adaptor, buffer, *parser,
692                 std::bind_front(&self_type::afterReadHeaders, this,
693                                 shared_from_this()));
694         }
695     }
696 
afterRead(const std::shared_ptr<self_type> &,const boost::system::error_code & ec,std::size_t bytesTransferred)697     void afterRead(const std::shared_ptr<self_type>& /*self*/,
698                    const boost::system::error_code& ec,
699                    std::size_t bytesTransferred)
700     {
701         BMCWEB_LOG_DEBUG("{} async_read_some {} Bytes", logPtr(this),
702                          bytesTransferred);
703 
704         if (ec)
705         {
706             BMCWEB_LOG_ERROR("{} Error while reading: {}", logPtr(this),
707                              ec.message());
708             if (ec == boost::beast::http::error::body_limit)
709             {
710                 if (handleContentLengthError())
711                 {
712                     BMCWEB_LOG_CRITICAL("Body length limit reached, "
713                                         "but no content-length "
714                                         "available?  Should never happen");
715                     res.result(
716                         boost::beast::http::status::internal_server_error);
717                     keepAlive = false;
718                     doWrite();
719                 }
720                 return;
721             }
722             BMCWEB_LOG_WARNING("{} End of stream, closing {}", logPtr(this),
723                                ec);
724             hardClose();
725 
726             return;
727         }
728 
729         // If the user is logged in, allow them to send files
730         // incrementally one piece at a time. If authentication is
731         // disabled then there is no user session hence always allow to
732         // send one piece at a time.
733         if (userSession != nullptr)
734         {
735             cancelDeadlineTimer();
736         }
737 
738         if (!parser)
739         {
740             BMCWEB_LOG_ERROR("Parser was unexpectedly null");
741             return;
742         }
743         if (!parser->is_done())
744         {
745             doRead();
746             return;
747         }
748 
749         cancelDeadlineTimer();
750         handle();
751     }
752 
doRead()753     void doRead()
754     {
755         BMCWEB_LOG_DEBUG("{} doRead", logPtr(this));
756         if (!parser)
757         {
758             return;
759         }
760         auto& parse = *parser;
761         startDeadline(DeadlineTimerType::Default);
762         if (httpType == HttpType::HTTP)
763         {
764             boost::beast::http::async_read_some(
765                 adaptor.next_layer(), buffer, parse,
766                 std::bind_front(&self_type::afterRead, this,
767                                 shared_from_this()));
768         }
769         else
770         {
771             boost::beast::http::async_read_some(
772                 adaptor, buffer, parse,
773                 std::bind_front(&self_type::afterRead, this,
774                                 shared_from_this()));
775         }
776     }
777 
afterDoWrite(const std::shared_ptr<self_type> &,const boost::system::error_code & ec,std::size_t bytesTransferred)778     void afterDoWrite(const std::shared_ptr<self_type>& /*self*/,
779                       const boost::system::error_code& ec,
780                       std::size_t bytesTransferred)
781     {
782         BMCWEB_LOG_DEBUG("{} async_write wrote {} bytes, ec={}", logPtr(this),
783                          bytesTransferred, ec);
784 
785         cancelDeadlineTimer();
786 
787         if (ec == boost::system::errc::operation_would_block ||
788             ec == boost::system::errc::resource_unavailable_try_again)
789         {
790             doWrite();
791             return;
792         }
793 
794         if (ec == boost::beast::http::error::end_of_stream ||
795             ec == boost::asio::ssl::error::stream_truncated)
796         {
797             BMCWEB_LOG_WARNING("{} End of stream, closing {}", logPtr(this),
798                                ec);
799             hardClose();
800             return;
801         }
802 
803         if (ec)
804         {
805             BMCWEB_LOG_DEBUG("{} from write(2)", logPtr(this));
806             return;
807         }
808 
809         if (res.result() == boost::beast::http::status::switching_protocols)
810         {
811             upgradeToHttp2();
812             return;
813         }
814 
815         if (res.result() == boost::beast::http::status::continue_)
816         {
817             // Reset the result to ok
818             res.result(boost::beast::http::status::ok);
819             doRead();
820             return;
821         }
822 
823         if (!keepAlive)
824         {
825             BMCWEB_LOG_DEBUG("{} keepalive not set.  Closing socket",
826                              logPtr(this));
827 
828             gracefulClose();
829             return;
830         }
831 
832         BMCWEB_LOG_DEBUG("{} Clearing response", logPtr(this));
833         res.clear();
834         initParser();
835 
836         userSession = nullptr;
837 
838         req->clear();
839         doReadHeaders();
840     }
841 
doWrite()842     void doWrite()
843     {
844         BMCWEB_LOG_DEBUG("{} doWrite", logPtr(this));
845 
846         boost::urls::url_view urlView;
847         if (req != nullptr)
848         {
849             urlView = req->url();
850         }
851         res.preparePayload(urlView);
852 
853         startDeadline(DeadlineTimerType::Default);
854         if (httpType == HttpType::HTTP)
855         {
856             boost::beast::async_write(
857                 adaptor.next_layer(),
858                 boost::beast::http::message_generator(std::move(res.response)),
859                 std::bind_front(&self_type::afterDoWrite, this,
860                                 shared_from_this()));
861         }
862         else
863         {
864             boost::beast::async_write(
865                 adaptor,
866                 boost::beast::http::message_generator(std::move(res.response)),
867                 std::bind_front(&self_type::afterDoWrite, this,
868                                 shared_from_this()));
869         }
870     }
871 
cancelDeadlineTimer()872     void cancelDeadlineTimer()
873     {
874         timer.cancel();
875         timerStarted = false;
876     }
877 
afterTimerWait(const std::weak_ptr<self_type> & weakSelf,const boost::system::error_code & ec)878     void afterTimerWait(const std::weak_ptr<self_type>& weakSelf,
879                         const boost::system::error_code& ec)
880     {
881         // Note, we are ignoring other types of errors here;  If the timer
882         // failed for any reason, we should still close the connection
883         std::shared_ptr<Connection<Adaptor, Handler>> self = weakSelf.lock();
884         if (!self)
885         {
886             if (ec == boost::asio::error::operation_aborted)
887             {
888                 BMCWEB_LOG_DEBUG(
889                     "{} Timer canceled on connection being destroyed",
890                     logPtr(self.get()));
891             }
892             else
893             {
894                 BMCWEB_LOG_CRITICAL("{} Failed to capture connection",
895                                     logPtr(self.get()));
896             }
897             return;
898         }
899 
900         self->timerStarted = false;
901 
902         if (ec)
903         {
904             if (ec == boost::asio::error::operation_aborted)
905             {
906                 BMCWEB_LOG_DEBUG("{} Timer canceled", logPtr(self.get()));
907                 return;
908             }
909             BMCWEB_LOG_CRITICAL("{} Timer failed {}", logPtr(self.get()), ec);
910         }
911 
912         BMCWEB_LOG_WARNING("{} Connection timed out, hard closing",
913                            logPtr(self.get()));
914 
915         self->hardClose();
916     }
917 
startDeadline(DeadlineTimerType timerType)918     void startDeadline(DeadlineTimerType timerType)
919     {
920         // Timer is already started so no further action is required.
921         if (timerStarted)
922         {
923             return;
924         }
925 
926         int timeoutDurationSeconds = 15;
927         if (timerType == DeadlineTimerType::Keepalive)
928         {
929             // if we're waiting for future requests while idle in keepalive,
930             // allow up to 15 minutes of delay
931             timeoutDurationSeconds = 15 * 60;
932         }
933 
934         std::chrono::seconds timeout(timeoutDurationSeconds);
935 
936         std::weak_ptr<Connection<Adaptor, Handler>> weakSelf = weak_from_this();
937         timer.expires_after(timeout);
938         timer.async_wait(std::bind_front(&self_type::afterTimerWait, this,
939                                          weak_from_this()));
940 
941         timerStarted = true;
942         BMCWEB_LOG_DEBUG("{} timer started", logPtr(this));
943     }
944 
945     bool authenticationEnabled = !BMCWEB_INSECURE_DISABLE_AUTH;
946     HttpType httpType = HttpType::BOTH;
947 
948     boost::asio::ssl::stream<Adaptor> adaptor;
949     Handler* handler;
950 
951     boost::asio::ip::address ip;
952 
953     // Making this a std::optional allows it to be efficiently destroyed and
954     // re-created on Connection reset
955     std::optional<boost::beast::http::request_parser<bmcweb::HttpBody>> parser;
956 
957     boost::beast::flat_static_buffer<8192> buffer;
958 
959     std::shared_ptr<Request> req;
960     std::string accept;
961     std::string http2settings;
962     std::string acceptEncoding;
963 
964     Response res;
965 
966     std::shared_ptr<persistent_data::UserSession> userSession;
967     std::shared_ptr<persistent_data::UserSession> mtlsSession;
968 
969     boost::asio::steady_timer timer;
970 
971     bool keepAlive = true;
972 
973     bool timerStarted = false;
974 
975     std::function<std::string()>& getCachedDateStr;
976 
977     using std::enable_shared_from_this<
978         Connection<Adaptor, Handler>>::shared_from_this;
979 
980     using std::enable_shared_from_this<
981         Connection<Adaptor, Handler>>::weak_from_this;
982 };
983 } // namespace crow
984