xref: /openbmc/bmcweb/http/http_response.hpp (revision d51c61b4)
104e438cbSEd Tanous #pragma once
2b2896149SEd Tanous #include "http_body.hpp"
304e438cbSEd Tanous #include "logging.hpp"
43ccb3adbSEd Tanous #include "utils/hex_utils.hpp"
504e438cbSEd Tanous 
60242baffSEd Tanous #include <fcntl.h>
70242baffSEd Tanous 
804e438cbSEd Tanous #include <boost/beast/http/message.hpp>
9faf100f9SEd Tanous #include <nlohmann/json.hpp>
1004e438cbSEd Tanous 
118a9a25c8SEd Tanous #include <optional>
1204e438cbSEd Tanous #include <string>
138a9a25c8SEd Tanous #include <string_view>
148e3f7032SAbhilash Raju #include <utility>
150242baffSEd Tanous 
1604e438cbSEd Tanous namespace crow
1704e438cbSEd Tanous {
1804e438cbSEd Tanous 
1904e438cbSEd Tanous template <typename Adaptor, typename Handler>
2004e438cbSEd Tanous class Connection;
2104e438cbSEd Tanous 
2227b0cf90SEd Tanous namespace http = boost::beast::http;
2327b0cf90SEd Tanous 
24*d51c61b4SMyung Bae enum class OpenCode
25*d51c61b4SMyung Bae {
26*d51c61b4SMyung Bae     Success,
27*d51c61b4SMyung Bae     FileDoesNotExist,
28*d51c61b4SMyung Bae     InternalError,
29*d51c61b4SMyung Bae };
30*d51c61b4SMyung Bae 
3104e438cbSEd Tanous struct Response
3204e438cbSEd Tanous {
3304e438cbSEd Tanous     template <typename Adaptor, typename Handler>
3404e438cbSEd Tanous     friend class crow::Connection;
3504e438cbSEd Tanous 
36b2896149SEd Tanous     http::response<bmcweb::HttpBody> response;
3704e438cbSEd Tanous 
3804e438cbSEd Tanous     nlohmann::json jsonValue;
3927b0cf90SEd Tanous     using fields_type = http::header<false, http::fields>;
fieldscrow::Response4027b0cf90SEd Tanous     fields_type& fields()
4127b0cf90SEd Tanous     {
4252e31629SEd Tanous         return response.base();
4327b0cf90SEd Tanous     }
4427b0cf90SEd Tanous 
fieldscrow::Response4527b0cf90SEd Tanous     const fields_type& fields() const
4627b0cf90SEd Tanous     {
4752e31629SEd Tanous         return response.base();
4827b0cf90SEd Tanous     }
4904e438cbSEd Tanous 
addHeadercrow::Response5026ccae32SEd Tanous     void addHeader(std::string_view key, std::string_view value)
5104e438cbSEd Tanous     {
5227b0cf90SEd Tanous         fields().insert(key, value);
5304e438cbSEd Tanous     }
5404e438cbSEd Tanous 
addHeadercrow::Response5527b0cf90SEd Tanous     void addHeader(http::field key, std::string_view value)
5604e438cbSEd Tanous     {
5727b0cf90SEd Tanous         fields().insert(key, value);
58994fd86aSEd Tanous     }
59994fd86aSEd Tanous 
clearHeadercrow::Response6027b0cf90SEd Tanous     void clearHeader(http::field key)
61994fd86aSEd Tanous     {
6227b0cf90SEd Tanous         fields().erase(key);
6304e438cbSEd Tanous     }
6404e438cbSEd Tanous 
6552e31629SEd Tanous     Response() = default;
Responsecrow::Response6613548d85SEd Tanous     Response(Response&& res) noexcept :
6727b0cf90SEd Tanous         response(std::move(res.response)), jsonValue(std::move(res.jsonValue)),
6827b0cf90SEd Tanous         completed(res.completed)
6913548d85SEd Tanous     {
7013548d85SEd Tanous         // See note in operator= move handler for why this is needed.
7113548d85SEd Tanous         if (!res.completed)
7213548d85SEd Tanous         {
7313548d85SEd Tanous             completeRequestHandler = std::move(res.completeRequestHandler);
7413548d85SEd Tanous             res.completeRequestHandler = nullptr;
7513548d85SEd Tanous         }
7613548d85SEd Tanous     }
7713548d85SEd Tanous 
78ecd6a3a2SEd Tanous     ~Response() = default;
79ecd6a3a2SEd Tanous 
80ecd6a3a2SEd Tanous     Response(const Response&) = delete;
8104e438cbSEd Tanous     Response& operator=(const Response& r) = delete;
8204e438cbSEd Tanous 
operator =crow::Response8304e438cbSEd Tanous     Response& operator=(Response&& r) noexcept
8404e438cbSEd Tanous     {
8562598e31SEd Tanous         BMCWEB_LOG_DEBUG("Moving response containers; this: {}; other: {}",
8662598e31SEd Tanous                          logPtr(this), logPtr(&r));
8772374eb7SNan Zhou         if (this == &r)
8872374eb7SNan Zhou         {
8972374eb7SNan Zhou             return *this;
9072374eb7SNan Zhou         }
9127b0cf90SEd Tanous         response = std::move(r.response);
9204e438cbSEd Tanous         jsonValue = std::move(r.jsonValue);
93499b5b4dSEd Tanous         expectedHash = std::move(r.expectedHash);
9413548d85SEd Tanous 
9513548d85SEd Tanous         // Only need to move completion handler if not already completed
9613548d85SEd Tanous         // Note, there are cases where we might move out of a Response object
9713548d85SEd Tanous         // while in a completion handler for that response object.  This check
9813548d85SEd Tanous         // is intended to prevent destructing the functor we are currently
9913548d85SEd Tanous         // executing from in that case.
10013548d85SEd Tanous         if (!r.completed)
10113548d85SEd Tanous         {
10272374eb7SNan Zhou             completeRequestHandler = std::move(r.completeRequestHandler);
10372374eb7SNan Zhou             r.completeRequestHandler = nullptr;
10413548d85SEd Tanous         }
10513548d85SEd Tanous         else
10613548d85SEd Tanous         {
10713548d85SEd Tanous             completeRequestHandler = nullptr;
10813548d85SEd Tanous         }
10913548d85SEd Tanous         completed = r.completed;
11004e438cbSEd Tanous         return *this;
11104e438cbSEd Tanous     }
11204e438cbSEd Tanous 
resultcrow::Response1133590bd1dSNan Zhou     void result(unsigned v)
1143590bd1dSNan Zhou     {
11527b0cf90SEd Tanous         fields().result(v);
1163590bd1dSNan Zhou     }
1173590bd1dSNan Zhou 
resultcrow::Response11827b0cf90SEd Tanous     void result(http::status v)
11904e438cbSEd Tanous     {
12027b0cf90SEd Tanous         fields().result(v);
12104e438cbSEd Tanous     }
12204e438cbSEd Tanous 
copyBodycrow::Response12327b0cf90SEd Tanous     void copyBody(const Response& res)
12404e438cbSEd Tanous     {
12552e31629SEd Tanous         response.body() = res.response.body();
12627b0cf90SEd Tanous     }
12727b0cf90SEd Tanous 
resultcrow::Response12827b0cf90SEd Tanous     http::status result() const
12927b0cf90SEd Tanous     {
13027b0cf90SEd Tanous         return fields().result();
13104e438cbSEd Tanous     }
13204e438cbSEd Tanous 
resultIntcrow::Response133039a47e3SCarson Labrado     unsigned resultInt() const
13404e438cbSEd Tanous     {
13527b0cf90SEd Tanous         return fields().result_int();
13604e438cbSEd Tanous     }
13704e438cbSEd Tanous 
reasoncrow::Response138bb60f4deSEd Tanous     std::string_view reason() const
13904e438cbSEd Tanous     {
14027b0cf90SEd Tanous         return fields().reason();
14104e438cbSEd Tanous     }
14204e438cbSEd Tanous 
isCompletedcrow::Response14304e438cbSEd Tanous     bool isCompleted() const noexcept
14404e438cbSEd Tanous     {
14504e438cbSEd Tanous         return completed;
14604e438cbSEd Tanous     }
14704e438cbSEd Tanous 
bodycrow::Response14827b0cf90SEd Tanous     const std::string* body()
14904e438cbSEd Tanous     {
15052e31629SEd Tanous         return &response.body().str();
15104e438cbSEd Tanous     }
15204e438cbSEd Tanous 
getHeaderValuecrow::Response15346a81465SCarson Labrado     std::string_view getHeaderValue(std::string_view key) const
15446a81465SCarson Labrado     {
15527b0cf90SEd Tanous         return fields()[key];
15646a81465SCarson Labrado     }
15746a81465SCarson Labrado 
getHeaderValuecrow::Response158499b5b4dSEd Tanous     std::string_view getHeaderValue(boost::beast::http::field key) const
159499b5b4dSEd Tanous     {
160499b5b4dSEd Tanous         return fields()[key];
161499b5b4dSEd Tanous     }
162499b5b4dSEd Tanous 
keepAlivecrow::Response16304e438cbSEd Tanous     void keepAlive(bool k)
16404e438cbSEd Tanous     {
16552e31629SEd Tanous         response.keep_alive(k);
16604e438cbSEd Tanous     }
16704e438cbSEd Tanous 
keepAlivecrow::Response168bb60f4deSEd Tanous     bool keepAlive() const
16904e438cbSEd Tanous     {
17052e31629SEd Tanous         return response.keep_alive();
17127b0cf90SEd Tanous     }
17227b0cf90SEd Tanous 
sizecrow::Response17352e31629SEd Tanous     std::optional<uint64_t> size()
17452e31629SEd Tanous     {
17552e31629SEd Tanous         return response.body().payloadSize();
17652e31629SEd Tanous     }
17752e31629SEd Tanous 
preparePayloadcrow::Response17852e31629SEd Tanous     void preparePayload()
17927b0cf90SEd Tanous     {
18027b0cf90SEd Tanous         // This code is a throw-free equivalent to
18127b0cf90SEd Tanous         // beast::http::message::prepare_payload
18252e31629SEd Tanous         std::optional<uint64_t> pSize = response.body().payloadSize();
1830242baffSEd Tanous 
18427b0cf90SEd Tanous         using http::status;
18527b0cf90SEd Tanous         using http::status_class;
18627b0cf90SEd Tanous         using http::to_status_class;
18727b0cf90SEd Tanous         bool is1XXReturn = to_status_class(result()) ==
18827b0cf90SEd Tanous                            status_class::informational;
1890242baffSEd Tanous         if (!pSize)
1900242baffSEd Tanous         {
1910242baffSEd Tanous             response.chunked(true);
1920242baffSEd Tanous             return;
1930242baffSEd Tanous         }
1940242baffSEd Tanous         response.content_length(*pSize);
1950242baffSEd Tanous 
1960242baffSEd Tanous         if (is1XXReturn || result() == status::no_content ||
1970242baffSEd Tanous             result() == status::not_modified)
19827b0cf90SEd Tanous         {
19927b0cf90SEd Tanous             BMCWEB_LOG_CRITICAL("{} Response content provided but code was "
20027b0cf90SEd Tanous                                 "no-content or not_modified, which aren't "
20127b0cf90SEd Tanous                                 "allowed to have a body",
20227b0cf90SEd Tanous                                 logPtr(this));
20352e31629SEd Tanous             response.content_length(0);
20452e31629SEd Tanous             return;
20527b0cf90SEd Tanous         }
20604e438cbSEd Tanous     }
20704e438cbSEd Tanous 
clearcrow::Response20804e438cbSEd Tanous     void clear()
20904e438cbSEd Tanous     {
21062598e31SEd Tanous         BMCWEB_LOG_DEBUG("{} Clearing response containers", logPtr(this));
21152e31629SEd Tanous         response.clear();
21206fc9bebSEd Tanous         response.body().clear();
21352e31629SEd Tanous 
214a6695a84SEd Tanous         jsonValue = nullptr;
21504e438cbSEd Tanous         completed = false;
216291d709dSEd Tanous         expectedHash = std::nullopt;
21704e438cbSEd Tanous     }
21804e438cbSEd Tanous 
computeEtagcrow::Response2192d6cb56bSEd Tanous     std::string computeEtag() const
22004e438cbSEd Tanous     {
22189f18008SEd Tanous         // Only set etag if this request succeeded
22227b0cf90SEd Tanous         if (result() != http::status::ok)
22389f18008SEd Tanous         {
2242d6cb56bSEd Tanous             return "";
22589f18008SEd Tanous         }
2262d6cb56bSEd Tanous         // and the json response isn't empty
2272d6cb56bSEd Tanous         if (jsonValue.empty())
2282d6cb56bSEd Tanous         {
2292d6cb56bSEd Tanous             return "";
2302d6cb56bSEd Tanous         }
2312d6cb56bSEd Tanous         size_t hashval = std::hash<nlohmann::json>{}(jsonValue);
2322d6cb56bSEd Tanous         return "\"" + intToHexString(hashval, 8) + "\"";
2332d6cb56bSEd Tanous     }
2342d6cb56bSEd Tanous 
writecrow::Response23527b0cf90SEd Tanous     void write(std::string&& bodyPart)
23627b0cf90SEd Tanous     {
23752e31629SEd Tanous         response.body().str() = std::move(bodyPart);
23827b0cf90SEd Tanous     }
23927b0cf90SEd Tanous 
endcrow::Response2402d6cb56bSEd Tanous     void end()
2412d6cb56bSEd Tanous     {
24204e438cbSEd Tanous         if (completed)
24304e438cbSEd Tanous         {
24462598e31SEd Tanous             BMCWEB_LOG_ERROR("{} Response was ended twice", logPtr(this));
24504e438cbSEd Tanous             return;
24604e438cbSEd Tanous         }
24704e438cbSEd Tanous         completed = true;
24862598e31SEd Tanous         BMCWEB_LOG_DEBUG("{} calling completion handler", logPtr(this));
24904e438cbSEd Tanous         if (completeRequestHandler)
25004e438cbSEd Tanous         {
25162598e31SEd Tanous             BMCWEB_LOG_DEBUG("{} completion handler was valid", logPtr(this));
25272374eb7SNan Zhou             completeRequestHandler(*this);
25304e438cbSEd Tanous         }
25404e438cbSEd Tanous     }
25504e438cbSEd Tanous 
setCompleteRequestHandlercrow::Response25672374eb7SNan Zhou     void setCompleteRequestHandler(std::function<void(Response&)>&& handler)
2574147b8acSJohn Edward Broadbent     {
25862598e31SEd Tanous         BMCWEB_LOG_DEBUG("{} setting completion handler", logPtr(this));
25972374eb7SNan Zhou         completeRequestHandler = std::move(handler);
26013548d85SEd Tanous 
26113548d85SEd Tanous         // Now that we have a new completion handler attached, we're no longer
26213548d85SEd Tanous         // complete
26313548d85SEd Tanous         completed = false;
26472374eb7SNan Zhou     }
26572374eb7SNan Zhou 
releaseCompleteRequestHandlercrow::Response26672374eb7SNan Zhou     std::function<void(Response&)> releaseCompleteRequestHandler()
26772374eb7SNan Zhou     {
26862598e31SEd Tanous         BMCWEB_LOG_DEBUG("{} releasing completion handler{}", logPtr(this),
26962598e31SEd Tanous                          static_cast<bool>(completeRequestHandler));
27072374eb7SNan Zhou         std::function<void(Response&)> ret = completeRequestHandler;
27172374eb7SNan Zhou         completeRequestHandler = nullptr;
27213548d85SEd Tanous         completed = true;
27372374eb7SNan Zhou         return ret;
27472374eb7SNan Zhou     }
27572374eb7SNan Zhou 
setHashAndHandleNotModifiedcrow::Response276291d709dSEd Tanous     void setHashAndHandleNotModified()
277291d709dSEd Tanous     {
278291d709dSEd Tanous         // Can only hash if we have content that's valid
27927b0cf90SEd Tanous         if (jsonValue.empty() || result() != http::status::ok)
280291d709dSEd Tanous         {
281291d709dSEd Tanous             return;
282291d709dSEd Tanous         }
283291d709dSEd Tanous         size_t hashval = std::hash<nlohmann::json>{}(jsonValue);
284291d709dSEd Tanous         std::string hexVal = "\"" + intToHexString(hashval, 8) + "\"";
28527b0cf90SEd Tanous         addHeader(http::field::etag, hexVal);
286291d709dSEd Tanous         if (expectedHash && hexVal == *expectedHash)
287291d709dSEd Tanous         {
288a6695a84SEd Tanous             jsonValue = nullptr;
28927b0cf90SEd Tanous             result(http::status::not_modified);
290291d709dSEd Tanous         }
291291d709dSEd Tanous     }
292291d709dSEd Tanous 
setExpectedHashcrow::Response293291d709dSEd Tanous     void setExpectedHash(std::string_view hash)
294291d709dSEd Tanous     {
295291d709dSEd Tanous         expectedHash = hash;
296291d709dSEd Tanous     }
297291d709dSEd Tanous 
openFilecrow::Response298*d51c61b4SMyung Bae     OpenCode openFile(const std::filesystem::path& path,
299b5f288d2SAbhilash Raju                       bmcweb::EncodingType enc = bmcweb::EncodingType::Raw)
30027b0cf90SEd Tanous     {
30127b0cf90SEd Tanous         boost::beast::error_code ec;
30252e31629SEd Tanous         response.body().open(path.c_str(), boost::beast::file_mode::read, ec);
30352e31629SEd Tanous         response.body().encodingType = enc;
30427b0cf90SEd Tanous         if (ec)
30527b0cf90SEd Tanous         {
306*d51c61b4SMyung Bae             BMCWEB_LOG_ERROR("Failed to open file {}, ec={}", path.c_str(),
307*d51c61b4SMyung Bae                              ec.value());
308*d51c61b4SMyung Bae             if (ec.value() == boost::system::errc::no_such_file_or_directory)
309*d51c61b4SMyung Bae             {
310*d51c61b4SMyung Bae                 return OpenCode::FileDoesNotExist;
31127b0cf90SEd Tanous             }
312*d51c61b4SMyung Bae             return OpenCode::InternalError;
313*d51c61b4SMyung Bae         }
314*d51c61b4SMyung Bae         return OpenCode::Success;
315b5f288d2SAbhilash Raju     }
316b5f288d2SAbhilash Raju 
openFdcrow::Response317b5f288d2SAbhilash Raju     bool openFd(int fd, bmcweb::EncodingType enc = bmcweb::EncodingType::Raw)
318b5f288d2SAbhilash Raju     {
319b5f288d2SAbhilash Raju         boost::beast::error_code ec;
3200242baffSEd Tanous         // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
3210242baffSEd Tanous         int retval = fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
3220242baffSEd Tanous         if (retval == -1)
3230242baffSEd Tanous         {
3240242baffSEd Tanous             BMCWEB_LOG_ERROR("Setting O_NONBLOCK failed");
3250242baffSEd Tanous         }
32652e31629SEd Tanous         response.body().encodingType = enc;
32752e31629SEd Tanous         response.body().setFd(fd, ec);
328b5f288d2SAbhilash Raju         if (ec)
329b5f288d2SAbhilash Raju         {
330b5f288d2SAbhilash Raju             BMCWEB_LOG_ERROR("Failed to set fd");
331b5f288d2SAbhilash Raju             return false;
332b5f288d2SAbhilash Raju         }
333b5f288d2SAbhilash Raju         return true;
334b5f288d2SAbhilash Raju     }
335b5f288d2SAbhilash Raju 
336b5f288d2SAbhilash Raju   private:
337291d709dSEd Tanous     std::optional<std::string> expectedHash;
33872374eb7SNan Zhou     bool completed = false;
33972374eb7SNan Zhou     std::function<void(Response&)> completeRequestHandler;
34004e438cbSEd Tanous };
34104e438cbSEd Tanous } // namespace crow
342