Move over to upstream c++ style
This patchset moves bmcweb over to the upstream style naming
conventions for variables, classes, and functions, as well as imposes
the latest clang-format file.
This changeset was mostly built automatically by the included
.clang-tidy file, which has the ability to autoformat and auto rename
variables. At some point in the future I would like to see this in
greater use, but for now, we will impose it on bmcweb, and see how it
goes.
Tested: Code still compiles, and appears to run, although other issues
are possible and likely.
Change-Id: If422a2e36df924e897736b3feffa89f411d9dac1
Signed-off-by: Ed Tanous <ed.tanous@intel.com>
diff --git a/crow/include/crow/app.h b/crow/include/crow/app.h
index 9abf6bb..f006a78 100644
--- a/crow/include/crow/app.h
+++ b/crow/include/crow/app.h
@@ -15,11 +15,11 @@
#include "crow/routing.h"
#include "crow/utility.h"
-#define CROW_ROUTE(app, url) \
+#define BMCWEB_ROUTE(app, url) \
app.template route<crow::black_magic::get_parameter_tag(url)>(url)
namespace crow {
-#ifdef CROW_ENABLE_SSL
+#ifdef BMCWEB_ENABLE_SSL
using ssl_context_t = boost::asio::ssl::context;
#endif
template <typename... Middlewares>
@@ -27,184 +27,184 @@
public:
using self_t = Crow;
using server_t = Server<Crow, SocketAdaptor, Middlewares...>;
-#ifdef CROW_ENABLE_SSL
+#ifdef BMCWEB_ENABLE_SSL
using ssl_server_t = Server<Crow, SSLAdaptor, Middlewares...>;
#endif
explicit Crow(std::shared_ptr<boost::asio::io_service> io =
std::make_shared<boost::asio::io_service>())
- : io_(std::move(io)) {}
+ : io(std::move(io)) {}
~Crow() { this->stop(); }
template <typename Adaptor>
- void handle_upgrade(const request& req, response& res, Adaptor&& adaptor) {
- router_.handle_upgrade(req, res, adaptor);
+ void handleUpgrade(const Request& req, Response& res, Adaptor&& adaptor) {
+ router.handleUpgrade(req, res, adaptor);
}
- void handle(const request& req, response& res) { router_.handle(req, res); }
+ void handle(const Request& req, Response& res) { router.handle(req, res); }
- DynamicRule& route_dynamic(std::string&& rule) {
- return router_.new_rule_dynamic(rule);
+ DynamicRule& routeDynamic(std::string&& rule) {
+ return router.newRuleDynamic(rule);
}
template <uint64_t Tag>
auto route(std::string&& rule) -> typename std::result_of<
- decltype (&Router::new_rule_tagged<Tag>)(Router, std::string&&)>::type {
- return router_.new_rule_tagged<Tag>(std::move(rule));
+ decltype (&Router::newRuleTagged<Tag>)(Router, std::string&&)>::type {
+ return router.newRuleTagged<Tag>(std::move(rule));
}
self_t& socket(int existing_socket) {
- socket_ = existing_socket;
+ socketFd = existing_socket;
return *this;
}
self_t& port(std::uint16_t port) {
- port_ = port;
+ portUint = port;
return *this;
}
self_t& bindaddr(std::string bindaddr) {
- bindaddr_ = bindaddr;
+ bindaddrStr = bindaddr;
return *this;
}
- void validate() { router_.validate(); }
+ void validate() { router.validate(); }
void run() {
validate();
-#ifdef CROW_ENABLE_SSL
- if (use_ssl_) {
- if (-1 == socket_) {
- ssl_server_ = std::move(std::make_unique<ssl_server_t>(
- this, bindaddr_, port_, &middlewares_, &ssl_context_, io_));
+#ifdef BMCWEB_ENABLE_SSL
+ if (useSsl) {
+ if (-1 == socketFd) {
+ sslServer = std::move(std::make_unique<ssl_server_t>(
+ this, bindaddrStr, portUint, &middlewares, &sslContext, io));
} else {
- ssl_server_ = std::move(std::make_unique<ssl_server_t>(
- this, socket_, &middlewares_, &ssl_context_, io_));
+ sslServer = std::move(std::make_unique<ssl_server_t>(
+ this, socketFd, &middlewares, &sslContext, io));
}
- ssl_server_->set_tick_function(tick_interval_, tick_function_);
- ssl_server_->run();
+ sslServer->setTickFunction(tickInterval, tickFunction);
+ sslServer->run();
} else
#endif
{
- if (-1 == socket_) {
- server_ = std::move(std::make_unique<server_t>(
- this, bindaddr_, port_, &middlewares_, nullptr, io_));
+ if (-1 == socketFd) {
+ server = std::move(std::make_unique<server_t>(
+ this, bindaddrStr, portUint, &middlewares, nullptr, io));
} else {
- server_ = std::move(std::make_unique<server_t>(
- this, socket_, &middlewares_, nullptr, io_));
+ server = std::move(std::make_unique<server_t>(
+ this, socketFd, &middlewares, nullptr, io));
}
- server_->set_tick_function(tick_interval_, tick_function_);
- server_->run();
+ server->setTickFunction(tickInterval, tickFunction);
+ server->run();
}
}
- void stop() { io_->stop(); }
+ void stop() { io->stop(); }
- void debug_print() {
- CROW_LOG_DEBUG << "Routing:";
- router_.debug_print();
+ void debugPrint() {
+ BMCWEB_LOG_DEBUG << "Routing:";
+ router.debugPrint();
}
- std::vector<const std::string*> get_routes() {
+ std::vector<const std::string*> getRoutes() {
// TODO(ed) Should this be /?
const std::string root("");
- return router_.get_routes(root);
+ return router.getRoutes(root);
}
- std::vector<const std::string*> get_routes(const std::string& parent) {
- return router_.get_routes(parent);
+ std::vector<const std::string*> getRoutes(const std::string& parent) {
+ return router.getRoutes(parent);
}
-#ifdef CROW_ENABLE_SSL
- self_t& ssl_file(const std::string& crt_filename,
- const std::string& key_filename) {
- use_ssl_ = true;
- ssl_context_.set_verify_mode(boost::asio::ssl::verify_peer);
- ssl_context_.use_certificate_file(crt_filename, ssl_context_t::pem);
- ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
- ssl_context_.set_options(boost::asio::ssl::context::default_workarounds |
- boost::asio::ssl::context::no_sslv2 |
- boost::asio::ssl::context::no_sslv3);
+#ifdef BMCWEB_ENABLE_SSL
+ self_t& sslFile(const std::string& crt_filename,
+ const std::string& key_filename) {
+ useSsl = true;
+ sslContext.set_verify_mode(boost::asio::ssl::verify_peer);
+ sslContext.use_certificate_file(crt_filename, ssl_context_t::pem);
+ sslContext.use_private_key_file(key_filename, ssl_context_t::pem);
+ sslContext.set_options(boost::asio::ssl::context::default_workarounds |
+ boost::asio::ssl::context::no_sslv2 |
+ boost::asio::ssl::context::no_sslv3);
return *this;
}
- self_t& ssl_file(const std::string& pem_filename) {
- use_ssl_ = true;
- ssl_context_.set_verify_mode(boost::asio::ssl::verify_peer);
- ssl_context_.load_verify_file(pem_filename);
- ssl_context_.set_options(boost::asio::ssl::context::default_workarounds |
- boost::asio::ssl::context::no_sslv2 |
- boost::asio::ssl::context::no_sslv3);
+ self_t& sslFile(const std::string& pem_filename) {
+ useSsl = true;
+ sslContext.set_verify_mode(boost::asio::ssl::verify_peer);
+ sslContext.load_verify_file(pem_filename);
+ sslContext.set_options(boost::asio::ssl::context::default_workarounds |
+ boost::asio::ssl::context::no_sslv2 |
+ boost::asio::ssl::context::no_sslv3);
return *this;
}
self_t& ssl(boost::asio::ssl::context&& ctx) {
- use_ssl_ = true;
- ssl_context_ = std::move(ctx);
+ useSsl = true;
+ sslContext = std::move(ctx);
return *this;
}
- bool use_ssl_{false};
- ssl_context_t ssl_context_{boost::asio::ssl::context::sslv23};
+ bool useSsl{false};
+ ssl_context_t sslContext{boost::asio::ssl::context::sslv23};
#else
template <typename T, typename... Remain>
self_t& ssl_file(T&&, Remain&&...) {
- // We can't call .ssl() member function unless CROW_ENABLE_SSL is defined.
+ // We can't call .ssl() member function unless BMCWEB_ENABLE_SSL is defined.
static_assert(
// make static_assert dependent to T; always false
std::is_base_of<T, void>::value,
- "Define CROW_ENABLE_SSL to enable ssl support.");
+ "Define BMCWEB_ENABLE_SSL to enable ssl support.");
return *this;
}
template <typename T>
self_t& ssl(T&&) {
- // We can't call .ssl() member function unless CROW_ENABLE_SSL is defined.
+ // We can't call .ssl() member function unless BMCWEB_ENABLE_SSL is defined.
static_assert(
// make static_assert dependent to T; always false
std::is_base_of<T, void>::value,
- "Define CROW_ENABLE_SSL to enable ssl support.");
+ "Define BMCWEB_ENABLE_SSL to enable ssl support.");
return *this;
}
#endif
// middleware
- using context_t = detail::context<Middlewares...>;
+ using context_t = detail::Context<Middlewares...>;
template <typename T>
- typename T::context& get_context(const request& req) {
- static_assert(black_magic::contains<T, Middlewares...>::value,
+ typename T::Context& getContext(const Request& req) {
+ static_assert(black_magic::Contains<T, Middlewares...>::value,
"App doesn't have the specified middleware type.");
- auto& ctx = *reinterpret_cast<context_t*>(req.middleware_context);
+ auto& ctx = *reinterpret_cast<context_t*>(req.middlewareContext);
return ctx.template get<T>();
}
template <typename T>
- T& get_middleware() {
- return utility::get_element_by_type<T, Middlewares...>(middlewares_);
+ T& getMiddleware() {
+ return utility::getElementByType<T, Middlewares...>(middlewares);
}
template <typename Duration, typename Func>
self_t& tick(Duration d, Func f) {
- tick_interval_ = std::chrono::duration_cast<std::chrono::milliseconds>(d);
- tick_function_ = f;
+ tickInterval = std::chrono::duration_cast<std::chrono::milliseconds>(d);
+ tickFunction = f;
return *this;
}
private:
- std::shared_ptr<asio::io_service> io_;
- uint16_t port_ = 80;
- std::string bindaddr_ = "::";
- int socket_ = -1;
- Router router_;
+ std::shared_ptr<asio::io_service> io;
+ uint16_t portUint = 80;
+ std::string bindaddrStr = "::";
+ int socketFd = -1;
+ Router router;
- std::chrono::milliseconds tick_interval_{};
- std::function<void()> tick_function_;
+ std::chrono::milliseconds tickInterval{};
+ std::function<void()> tickFunction;
- std::tuple<Middlewares...> middlewares_;
+ std::tuple<Middlewares...> middlewares;
-#ifdef CROW_ENABLE_SSL
- std::unique_ptr<ssl_server_t> ssl_server_;
+#ifdef BMCWEB_ENABLE_SSL
+ std::unique_ptr<ssl_server_t> sslServer;
#endif
- std::unique_ptr<server_t> server_;
+ std::unique_ptr<server_t> server;
};
template <typename... Middlewares>
using App = Crow<Middlewares...>;
diff --git a/crow/include/crow/common.h b/crow/include/crow/common.h
index 63fd002..e155da6 100644
--- a/crow/include/crow/common.h
+++ b/crow/include/crow/common.h
@@ -32,7 +32,7 @@
Patch = 24,
};
-inline std::string method_name(boost::beast::http::verb method) {
+inline std::string methodName(boost::beast::http::verb method) {
switch (method) {
case boost::beast::http::verb::delete_:
return "DELETE";
@@ -66,27 +66,27 @@
MAX
};
-struct routing_params {
- std::vector<int64_t> int_params;
- std::vector<uint64_t> uint_params;
- std::vector<double> double_params;
- std::vector<std::string> string_params;
+struct RoutingParams {
+ std::vector<int64_t> intParams;
+ std::vector<uint64_t> uintParams;
+ std::vector<double> doubleParams;
+ std::vector<std::string> stringParams;
- void debug_print() const {
- std::cerr << "routing_params" << std::endl;
- for (auto i : int_params) {
+ void debugPrint() const {
+ std::cerr << "RoutingParams" << std::endl;
+ for (auto i : intParams) {
std::cerr << i << ", ";
}
std::cerr << std::endl;
- for (auto i : uint_params) {
+ for (auto i : uintParams) {
std::cerr << i << ", ";
}
std::cerr << std::endl;
- for (auto i : double_params) {
+ for (auto i : doubleParams) {
std::cerr << i << ", ";
}
std::cerr << std::endl;
- for (auto& i : string_params) {
+ for (auto& i : stringParams) {
std::cerr << i << ", ";
}
std::cerr << std::endl;
@@ -97,23 +97,23 @@
};
template <>
-inline int64_t routing_params::get<int64_t>(unsigned index) const {
- return int_params[index];
+inline int64_t RoutingParams::get<int64_t>(unsigned index) const {
+ return intParams[index];
}
template <>
-inline uint64_t routing_params::get<uint64_t>(unsigned index) const {
- return uint_params[index];
+inline uint64_t RoutingParams::get<uint64_t>(unsigned index) const {
+ return uintParams[index];
}
template <>
-inline double routing_params::get<double>(unsigned index) const {
- return double_params[index];
+inline double RoutingParams::get<double>(unsigned index) const {
+ return doubleParams[index];
}
template <>
-inline std::string routing_params::get<std::string>(unsigned index) const {
- return string_params[index];
+inline std::string RoutingParams::get<std::string>(unsigned index) const {
+ return stringParams[index];
}
} // namespace crow
@@ -123,16 +123,16 @@
using verb = boost::beast::http::verb;
// clang-format off
return
- crow::black_magic::is_equ_p(str, "GET", 3) ? verb::get :
- crow::black_magic::is_equ_p(str, "DELETE", 6) ? verb::delete_ :
- crow::black_magic::is_equ_p(str, "HEAD", 4) ? verb::head :
- crow::black_magic::is_equ_p(str, "POST", 4) ? verb::post :
- crow::black_magic::is_equ_p(str, "PUT", 3) ? verb::put :
- crow::black_magic::is_equ_p(str, "OPTIONS", 7) ? verb::options :
- crow::black_magic::is_equ_p(str, "CONNECT", 7) ? verb::connect :
- crow::black_magic::is_equ_p(str, "TRACE", 5) ? verb::trace :
- crow::black_magic::is_equ_p(str, "PATCH", 5) ? verb::patch :
- crow::black_magic::is_equ_p(str, "PURGE", 5) ? verb::purge :
+ crow::black_magic::isEquP(str, "GET", 3) ? verb::get :
+ crow::black_magic::isEquP(str, "DELETE", 6) ? verb::delete_ :
+ crow::black_magic::isEquP(str, "HEAD", 4) ? verb::head :
+ crow::black_magic::isEquP(str, "POST", 4) ? verb::post :
+ crow::black_magic::isEquP(str, "PUT", 3) ? verb::put :
+ crow::black_magic::isEquP(str, "OPTIONS", 7) ? verb::options :
+ crow::black_magic::isEquP(str, "CONNECT", 7) ? verb::connect :
+ crow::black_magic::isEquP(str, "TRACE", 5) ? verb::trace :
+ crow::black_magic::isEquP(str, "PATCH", 5) ? verb::patch :
+ crow::black_magic::isEquP(str, "PURGE", 5) ? verb::purge :
throw std::runtime_error("invalid http method");
// clang-format on
}
\ No newline at end of file
diff --git a/crow/include/crow/http_connection.h b/crow/include/crow/http_connection.h
index 43437ef..36c19d0 100644
--- a/crow/include/crow/http_connection.h
+++ b/crow/include/crow/http_connection.h
@@ -17,13 +17,13 @@
#include <boost/beast/http.hpp>
#include <boost/beast/websocket.hpp>
-#ifdef CROW_ENABLE_SSL
+#ifdef BMCWEB_ENABLE_SSL
#include <boost/asio/ssl.hpp>
#endif
namespace crow {
-inline void escape_html(std::string& data) {
+inline void escapeHtml(std::string& data) {
std::string buffer;
// less than 5% of characters should be larger, so reserve a buffer of the
// right size
@@ -53,17 +53,17 @@
data.swap(buffer);
}
-inline void convert_to_links(std::string& s) {
+inline void convertToLinks(std::string& s) {
const static std::regex r{
- "("@odata\\.((id)|(context))"[ \\n]*:[ "
+ "("@odata\\.((id)|(Context))"[ \\n]*:[ "
"\\n]*)("((?!").*)")"};
s = std::regex_replace(s, r, "$1<a href=\"$6\">$5</a>");
}
-inline void pretty_print_json(crow::response& res) {
- std::string value = res.json_value.dump(4);
- escape_html(value);
- convert_to_links(value);
+inline void prettyPrintJson(crow::Response& res) {
+ std::string value = res.jsonValue.dump(4);
+ escapeHtml(value);
+ convertToLinks(value);
res.body() =
"<html>\n"
"<head>\n"
@@ -94,42 +94,42 @@
namespace detail {
template <typename MW>
-struct check_before_handle_arity_3_const {
- template <typename T, void (T::*)(request&, response&, typename MW::context&)
- const = &T::before_handle>
+struct CheckBeforeHandleArity3Const {
+ template <typename T, void (T::*)(Request&, Response&, typename MW::Context&)
+ const = &T::beforeHandle>
struct get {};
};
template <typename MW>
-struct check_before_handle_arity_3 {
- template <typename T, void (T::*)(request&, response&,
- typename MW::context&) = &T::before_handle>
+struct CheckBeforeHandleArity3 {
+ template <typename T, void (T::*)(Request&, Response&,
+ typename MW::Context&) = &T::beforeHandle>
struct get {};
};
template <typename MW>
-struct check_after_handle_arity_3_const {
- template <typename T, void (T::*)(request&, response&, typename MW::context&)
- const = &T::after_handle>
+struct CheckAfterHandleArity3Const {
+ template <typename T, void (T::*)(Request&, Response&, typename MW::Context&)
+ const = &T::afterHandle>
struct get {};
};
template <typename MW>
-struct check_after_handle_arity_3 {
- template <typename T, void (T::*)(request&, response&,
- typename MW::context&) = &T::after_handle>
+struct CheckAfterHandleArity3 {
+ template <typename T, void (T::*)(Request&, Response&,
+ typename MW::Context&) = &T::afterHandle>
struct get {};
};
template <typename T>
-struct is_before_handle_arity_3_impl {
+struct IsBeforeHandleArity3Impl {
template <typename C>
static std::true_type f(
- typename check_before_handle_arity_3_const<T>::template get<C>*);
+ typename CheckBeforeHandleArity3Const<T>::template get<C>*);
template <typename C>
static std::true_type f(
- typename check_before_handle_arity_3<T>::template get<C>*);
+ typename CheckBeforeHandleArity3<T>::template get<C>*);
template <typename C>
static std::false_type f(...);
@@ -139,14 +139,13 @@
};
template <typename T>
-struct is_after_handle_arity_3_impl {
+struct IsAfterHandleArity3Impl {
template <typename C>
static std::true_type f(
- typename check_after_handle_arity_3_const<T>::template get<C>*);
+ typename CheckAfterHandleArity3Const<T>::template get<C>*);
template <typename C>
- static std::true_type f(
- typename check_after_handle_arity_3<T>::template get<C>*);
+ static std::true_type f(typename CheckAfterHandleArity3<T>::template get<C>*);
template <typename C>
static std::false_type f(...);
@@ -156,52 +155,52 @@
};
template <typename MW, typename Context, typename ParentContext>
-typename std::enable_if<!is_before_handle_arity_3_impl<MW>::value>::type
-before_handler_call(MW& mw, request& req, response& res, Context& ctx,
- ParentContext& /*parent_ctx*/) {
- mw.before_handle(req, res, ctx.template get<MW>(), ctx);
+typename std::enable_if<!IsBeforeHandleArity3Impl<MW>::value>::type
+beforeHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
+ ParentContext& /*parent_ctx*/) {
+ mw.beforeHandle(req, res, ctx.template get<MW>(), ctx);
}
template <typename MW, typename Context, typename ParentContext>
-typename std::enable_if<is_before_handle_arity_3_impl<MW>::value>::type
-before_handler_call(MW& mw, request& req, response& res, Context& ctx,
- ParentContext& /*parent_ctx*/) {
- mw.before_handle(req, res, ctx.template get<MW>());
+typename std::enable_if<IsBeforeHandleArity3Impl<MW>::value>::type
+beforeHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
+ ParentContext& /*parent_ctx*/) {
+ mw.beforeHandle(req, res, ctx.template get<MW>());
}
template <typename MW, typename Context, typename ParentContext>
-typename std::enable_if<!is_after_handle_arity_3_impl<MW>::value>::type
-after_handler_call(MW& mw, request& req, response& res, Context& ctx,
- ParentContext& /*parent_ctx*/) {
- mw.after_handle(req, res, ctx.template get<MW>(), ctx);
+typename std::enable_if<!IsAfterHandleArity3Impl<MW>::value>::type
+afterHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
+ ParentContext& /*parent_ctx*/) {
+ mw.afterHandle(req, res, ctx.template get<MW>(), ctx);
}
template <typename MW, typename Context, typename ParentContext>
-typename std::enable_if<is_after_handle_arity_3_impl<MW>::value>::type
-after_handler_call(MW& mw, request& req, response& res, Context& ctx,
- ParentContext& /*parent_ctx*/) {
- mw.after_handle(req, res, ctx.template get<MW>());
+typename std::enable_if<IsAfterHandleArity3Impl<MW>::value>::type
+afterHandlerCall(MW& mw, Request& req, Response& res, Context& ctx,
+ ParentContext& /*parent_ctx*/) {
+ mw.afterHandle(req, res, ctx.template get<MW>());
}
template <int N, typename Context, typename Container, typename CurrentMW,
typename... Middlewares>
-bool middleware_call_helper(Container& middlewares, request& req, response& res,
- Context& ctx) {
+bool middlewareCallHelper(Container& middlewares, Request& req, Response& res,
+ Context& ctx) {
using parent_context_t = typename Context::template partial<N - 1>;
- before_handler_call<CurrentMW, Context, parent_context_t>(
+ beforeHandlerCall<CurrentMW, Context, parent_context_t>(
std::get<N>(middlewares), req, res, ctx,
static_cast<parent_context_t&>(ctx));
- if (res.is_completed()) {
- after_handler_call<CurrentMW, Context, parent_context_t>(
+ if (res.isCompleted()) {
+ afterHandlerCall<CurrentMW, Context, parent_context_t>(
std::get<N>(middlewares), req, res, ctx,
static_cast<parent_context_t&>(ctx));
return true;
}
- if (middleware_call_helper<N + 1, Context, Container, Middlewares...>(
+ if (middlewareCallHelper<N + 1, Context, Container, Middlewares...>(
middlewares, req, res, ctx)) {
- after_handler_call<CurrentMW, Context, parent_context_t>(
+ afterHandlerCall<CurrentMW, Context, parent_context_t>(
std::get<N>(middlewares), req, res, ctx,
static_cast<parent_context_t&>(ctx));
return true;
@@ -211,366 +210,367 @@
}
template <int N, typename Context, typename Container>
-bool middleware_call_helper(Container& /*middlewares*/, request& /*req*/,
- response& /*res*/, Context& /*ctx*/) {
+bool middlewareCallHelper(Container& /*middlewares*/, Request& /*req*/,
+ Response& /*res*/, Context& /*ctx*/) {
return false;
}
template <int N, typename Context, typename Container>
-typename std::enable_if<(N < 0)>::type after_handlers_call_helper(
- Container& /*middlewares*/, Context& /*context*/, request& /*req*/,
- response& /*res*/) {}
+typename std::enable_if<(N < 0)>::type afterHandlersCallHelper(
+ Container& /*middlewares*/, Context& /*Context*/, Request& /*req*/,
+ Response& /*res*/) {}
template <int N, typename Context, typename Container>
-typename std::enable_if<(N == 0)>::type after_handlers_call_helper(
- Container& middlewares, Context& ctx, request& req, response& res) {
+typename std::enable_if<(N == 0)>::type afterHandlersCallHelper(
+ Container& middlewares, Context& ctx, Request& req, Response& res) {
using parent_context_t = typename Context::template partial<N - 1>;
using CurrentMW = typename std::tuple_element<
N, typename std::remove_reference<Container>::type>::type;
- after_handler_call<CurrentMW, Context, parent_context_t>(
+ afterHandlerCall<CurrentMW, Context, parent_context_t>(
std::get<N>(middlewares), req, res, ctx,
static_cast<parent_context_t&>(ctx));
}
template <int N, typename Context, typename Container>
-typename std::enable_if<(N > 0)>::type after_handlers_call_helper(
- Container& middlewares, Context& ctx, request& req, response& res) {
+typename std::enable_if<(N > 0)>::type afterHandlersCallHelper(
+ Container& middlewares, Context& ctx, Request& req, Response& res) {
using parent_context_t = typename Context::template partial<N - 1>;
using CurrentMW = typename std::tuple_element<
N, typename std::remove_reference<Container>::type>::type;
- after_handler_call<CurrentMW, Context, parent_context_t>(
+ afterHandlerCall<CurrentMW, Context, parent_context_t>(
std::get<N>(middlewares), req, res, ctx,
static_cast<parent_context_t&>(ctx));
- after_handlers_call_helper<N - 1, Context, Container>(middlewares, ctx, req,
- res);
+ afterHandlersCallHelper<N - 1, Context, Container>(middlewares, ctx, req,
+ res);
}
} // namespace detail
-#ifdef CROW_ENABLE_DEBUG
+#ifdef BMCWEB_ENABLE_DEBUG
static std::atomic<int> connectionCount;
#endif
template <typename Adaptor, typename Handler, typename... Middlewares>
class Connection {
public:
- Connection(boost::asio::io_service& io_service, Handler* handler,
+ Connection(boost::asio::io_service& ioService, Handler* handler,
const std::string& server_name,
std::tuple<Middlewares...>* middlewares,
std::function<std::string()>& get_cached_date_str_f,
- detail::timer_queue& timer_queue,
- typename Adaptor::context* adaptor_ctx_)
- : adaptor_(io_service, adaptor_ctx_),
- handler_(handler),
- server_name_(server_name),
- middlewares_(middlewares),
- get_cached_date_str(get_cached_date_str_f),
- timer_queue(timer_queue) {
- parser_.emplace(std::piecewise_construct, std::make_tuple());
+ detail::TimerQueue& timerQueue,
+ typename Adaptor::context* adaptorCtx)
+ : adaptor(ioService, adaptorCtx),
+ handler(handler),
+ serverName(server_name),
+ middlewares(middlewares),
+ getCachedDateStr(get_cached_date_str_f),
+ timerQueue(timerQueue) {
+ parser.emplace(std::piecewise_construct, std::make_tuple());
- parser_->body_limit(1024 * 1024 * 1); // 1MB
- req_.emplace(parser_->get());
-#ifdef CROW_ENABLE_DEBUG
+ parser->body_limit(1024 * 1024 * 1); // 1MB
+ req.emplace(parser->get());
+#ifdef BMCWEB_ENABLE_DEBUG
connectionCount++;
- CROW_LOG_DEBUG << this << " Connection open, total " << connectionCount;
+ BMCWEB_LOG_DEBUG << this << " Connection open, total " << connectionCount;
#endif
}
~Connection() {
- res.complete_request_handler_ = nullptr;
- cancel_deadline_timer();
-#ifdef CROW_ENABLE_DEBUG
+ res.completeRequestHandler = nullptr;
+ cancelDeadlineTimer();
+#ifdef BMCWEB_ENABLE_DEBUG
connectionCount--;
- CROW_LOG_DEBUG << this << " Connection closed, total " << connectionCount;
+ BMCWEB_LOG_DEBUG << this << " Connection closed, total " << connectionCount;
#endif
}
- decltype(std::declval<Adaptor>().raw_socket()) & socket() {
- return adaptor_.raw_socket();
+ decltype(std::declval<Adaptor>().rawSocket()) & socket() {
+ return adaptor.rawSocket();
}
void start() {
- adaptor_.start([this](const boost::system::error_code& ec) {
+ adaptor.start([this](const boost::system::error_code& ec) {
if (!ec) {
- start_deadline();
+ startDeadline();
- do_read_headers();
+ doReadHeaders();
} else {
- check_destroy();
+ checkDestroy();
}
});
}
void handle() {
- cancel_deadline_timer();
- bool is_invalid_request = false;
- const boost::string_view connection =
- req_->get_header_value(boost::beast::http::field::connection);
+ cancelDeadlineTimer();
+ bool isInvalidRequest = false;
+ const boost::string_view Connection =
+ req->getHeaderValue(boost::beast::http::field::connection);
// Check for HTTP version 1.1.
- if (req_->version() == 11) {
- if (req_->get_header_value(boost::beast::http::field::host).empty()) {
- is_invalid_request = true;
- res = response(boost::beast::http::status::bad_request);
+ if (req->version() == 11) {
+ if (req->getHeaderValue(boost::beast::http::field::host).empty()) {
+ isInvalidRequest = true;
+ res = Response(boost::beast::http::status::bad_request);
}
}
- CROW_LOG_INFO << "Request: " << adaptor_.remote_endpoint() << " " << this
- << " HTTP/" << req_->version() / 10 << "."
- << req_->version() % 10 << ' ' << req_->method_string() << " "
- << req_->target();
+ BMCWEB_LOG_INFO << "Request: " << adaptor.remoteEndpoint() << " " << this
+ << " HTTP/" << req->version() / 10 << "."
+ << req->version() % 10 << ' ' << req->methodString() << " "
+ << req->target();
- need_to_call_after_handlers_ = false;
+ needToCallAfterHandlers = false;
- if (!is_invalid_request) {
- res.complete_request_handler_ = [] {};
- res.is_alive_helper_ = [this]() -> bool { return adaptor_.is_open(); };
+ if (!isInvalidRequest) {
+ res.completeRequestHandler = [] {};
+ res.isAliveHelper = [this]() -> bool { return adaptor.isOpen(); };
- ctx_ = detail::context<Middlewares...>();
- req_->middleware_context = (void*)&ctx_;
- req_->io_service = &adaptor_.get_io_service();
- detail::middleware_call_helper<0, decltype(ctx_), decltype(*middlewares_),
- Middlewares...>(*middlewares_, *req_, res,
- ctx_);
+ ctx = detail::Context<Middlewares...>();
+ req->middlewareContext = (void*)&ctx;
+ req->ioService = &adaptor.getIoService();
+ detail::middlewareCallHelper<0, decltype(ctx), decltype(*middlewares),
+ Middlewares...>(*middlewares, *req, res,
+ ctx);
- if (!res.completed_) {
- if (req_->is_upgrade() &&
+ if (!res.completed) {
+ if (req->isUpgrade() &&
boost::iequals(
- req_->get_header_value(boost::beast::http::field::upgrade),
+ req->getHeaderValue(boost::beast::http::field::upgrade),
"websocket")) {
- handler_->handle_upgrade(*req_, res, std::move(adaptor_));
+ handler->handleUpgrade(*req, res, std::move(adaptor));
return;
}
- res.complete_request_handler_ = [this] { this->complete_request(); };
- need_to_call_after_handlers_ = true;
- handler_->handle(*req_, res);
- if (req_->keep_alive()) {
- res.add_header("connection", "Keep-Alive");
+ res.completeRequestHandler = [this] { this->completeRequest(); };
+ needToCallAfterHandlers = true;
+ handler->handle(*req, res);
+ if (req->keepAlive()) {
+ res.addHeader("connection", "Keep-Alive");
}
} else {
- complete_request();
+ completeRequest();
}
} else {
- complete_request();
+ completeRequest();
}
}
- void complete_request() {
- CROW_LOG_INFO << "Response: " << this << ' ' << req_->url << ' '
- << res.result_int() << " keepalive=" << req_->keep_alive();
+ void completeRequest() {
+ BMCWEB_LOG_INFO << "Response: " << this << ' ' << req->url << ' '
+ << res.resultInt() << " keepalive=" << req->keepAlive();
- if (need_to_call_after_handlers_) {
- need_to_call_after_handlers_ = false;
+ if (needToCallAfterHandlers) {
+ needToCallAfterHandlers = false;
- // call all after_handler of middlewares
- detail::after_handlers_call_helper<((int)sizeof...(Middlewares) - 1),
- decltype(ctx_),
- decltype(*middlewares_)>(
- *middlewares_, ctx_, *req_, res);
+ // call all afterHandler of middlewares
+ detail::afterHandlersCallHelper<((int)sizeof...(Middlewares) - 1),
+ decltype(ctx), decltype(*middlewares)>(
+ *middlewares, ctx, *req, res);
}
// auto self = this->shared_from_this();
- res.complete_request_handler_ = nullptr;
+ res.completeRequestHandler = nullptr;
- if (!adaptor_.is_open()) {
- // CROW_LOG_DEBUG << this << " delete (socket is closed) " << is_reading
- // << ' ' << is_writing;
+ if (!adaptor.isOpen()) {
+ // BMCWEB_LOG_DEBUG << this << " delete (socket is closed) " << isReading
+ // << ' ' << isWriting;
// delete this;
return;
}
- if (res.body().empty() && !res.json_value.empty()) {
- if (http_helpers::request_prefers_html(*req_)) {
- pretty_print_json(res);
+ if (res.body().empty() && !res.jsonValue.empty()) {
+ if (http_helpers::requestPrefersHtml(*req)) {
+ prettyPrintJson(res);
} else {
- res.json_mode();
- res.body() = res.json_value.dump(2);
+ res.jsonMode();
+ res.body() = res.jsonValue.dump(2);
}
}
- if (res.result_int() >= 400 && res.body().empty()) {
+ if (res.resultInt() >= 400 && res.body().empty()) {
res.body() = std::string(res.reason());
}
- res.add_header(boost::beast::http::field::server, server_name_);
- res.add_header(boost::beast::http::field::date, get_cached_date_str());
+ res.addHeader(boost::beast::http::field::server, serverName);
+ res.addHeader(boost::beast::http::field::date, getCachedDateStr());
- res.keep_alive(req_->keep_alive());
+ res.keepAlive(req->keepAlive());
- do_write();
+ doWrite();
}
private:
- void do_read_headers() {
+ void doReadHeaders() {
// auto self = this->shared_from_this();
- is_reading = true;
- CROW_LOG_DEBUG << this << " do_read_headers";
+ isReading = true;
+ BMCWEB_LOG_DEBUG << this << " doReadHeaders";
- // Clean up any previous connection.
+ // Clean up any previous Connection.
boost::beast::http::async_read_header(
- adaptor_.socket(), buffer_, *parser_,
+ adaptor.socket(), buffer, *parser,
[this](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
- is_reading = false;
- CROW_LOG_ERROR << this << " async_read_header " << bytes_transferred
- << " Bytes";
- bool error_while_reading = false;
+ isReading = false;
+ BMCWEB_LOG_ERROR << this << " async_read_header " << bytes_transferred
+ << " Bytes";
+ bool errorWhileReading = false;
if (ec) {
- error_while_reading = true;
- CROW_LOG_ERROR << this << " Error while reading: " << ec.message();
+ errorWhileReading = true;
+ BMCWEB_LOG_ERROR << this
+ << " Error while reading: " << ec.message();
} else {
// if the adaptor isn't open anymore, and wasn't handed to a
// websocket, treat as an error
- if (!adaptor_.is_open() && !req_->is_upgrade()) {
- error_while_reading = true;
+ if (!adaptor.isOpen() && !req->isUpgrade()) {
+ errorWhileReading = true;
}
}
- if (error_while_reading) {
- cancel_deadline_timer();
- adaptor_.close();
- CROW_LOG_DEBUG << this << " from read(1)";
- check_destroy();
+ if (errorWhileReading) {
+ cancelDeadlineTimer();
+ adaptor.close();
+ BMCWEB_LOG_DEBUG << this << " from read(1)";
+ checkDestroy();
return;
}
// Compute the url parameters for the request
- req_->url = req_->target();
- std::size_t index = req_->url.find("?");
+ req->url = req->target();
+ std::size_t index = req->url.find("?");
if (index != boost::string_view::npos) {
- req_->url = req_->url.substr(0, index - 1);
+ req->url = req->url.substr(0, index - 1);
}
- req_->url_params = query_string(std::string(req_->target()));
- do_read();
+ req->urlParams = QueryString(std::string(req->target()));
+ doRead();
});
}
- void do_read() {
+ void doRead() {
// auto self = this->shared_from_this();
- is_reading = true;
- CROW_LOG_DEBUG << this << " do_read";
+ isReading = true;
+ BMCWEB_LOG_DEBUG << this << " doRead";
boost::beast::http::async_read(
- adaptor_.socket(), buffer_, *parser_,
+ adaptor.socket(), buffer, *parser,
[this](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
- CROW_LOG_ERROR << this << " async_read " << bytes_transferred
- << " Bytes";
- is_reading = false;
+ BMCWEB_LOG_ERROR << this << " async_read " << bytes_transferred
+ << " Bytes";
+ isReading = false;
- bool error_while_reading = false;
+ bool errorWhileReading = false;
if (ec) {
- CROW_LOG_ERROR << "Error while reading: " << ec.message();
- error_while_reading = true;
+ BMCWEB_LOG_ERROR << "Error while reading: " << ec.message();
+ errorWhileReading = true;
} else {
- if (!adaptor_.is_open()) {
- error_while_reading = true;
+ if (!adaptor.isOpen()) {
+ errorWhileReading = true;
}
}
- if (error_while_reading) {
- cancel_deadline_timer();
- adaptor_.close();
- CROW_LOG_DEBUG << this << " from read(1)";
- check_destroy();
+ if (errorWhileReading) {
+ cancelDeadlineTimer();
+ adaptor.close();
+ BMCWEB_LOG_DEBUG << this << " from read(1)";
+ checkDestroy();
return;
}
handle();
});
}
- void do_write() {
+ void doWrite() {
// auto self = this->shared_from_this();
- is_writing = true;
- CROW_LOG_DEBUG << "Doing Write";
- res.prepare_payload();
- serializer_.emplace(*res.string_response);
+ isWriting = true;
+ BMCWEB_LOG_DEBUG << "Doing Write";
+ res.preparePayload();
+ serializer.emplace(*res.stringResponse);
boost::beast::http::async_write(
- adaptor_.socket(), *serializer_,
+ adaptor.socket(), *serializer,
[&](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
- is_writing = false;
- CROW_LOG_DEBUG << this << " Wrote " << bytes_transferred << " bytes";
+ isWriting = false;
+ BMCWEB_LOG_DEBUG << this << " Wrote " << bytes_transferred
+ << " bytes";
if (ec) {
- CROW_LOG_DEBUG << this << " from write(2)";
- check_destroy();
+ BMCWEB_LOG_DEBUG << this << " from write(2)";
+ checkDestroy();
return;
}
- if (!req_->keep_alive()) {
- adaptor_.close();
- CROW_LOG_DEBUG << this << " from write(1)";
- check_destroy();
+ if (!req->keepAlive()) {
+ adaptor.close();
+ BMCWEB_LOG_DEBUG << this << " from write(1)";
+ checkDestroy();
return;
}
- serializer_.reset();
- CROW_LOG_DEBUG << this << " Clearing response";
+ serializer.reset();
+ BMCWEB_LOG_DEBUG << this << " Clearing response";
res.clear();
- parser_.emplace(std::piecewise_construct, std::make_tuple());
- buffer_.consume(buffer_.size());
+ parser.emplace(std::piecewise_construct, std::make_tuple());
+ buffer.consume(buffer.size());
- req_.emplace(parser_->get());
- do_read_headers();
+ req.emplace(parser->get());
+ doReadHeaders();
});
}
- void check_destroy() {
- CROW_LOG_DEBUG << this << " is_reading " << is_reading << " is_writing "
- << is_writing;
- if (!is_reading && !is_writing) {
- CROW_LOG_DEBUG << this << " delete (idle) ";
+ void checkDestroy() {
+ BMCWEB_LOG_DEBUG << this << " isReading " << isReading << " isWriting "
+ << isWriting;
+ if (!isReading && !isWriting) {
+ BMCWEB_LOG_DEBUG << this << " delete (idle) ";
delete this;
}
}
- void cancel_deadline_timer() {
- CROW_LOG_DEBUG << this << " timer cancelled: " << &timer_queue << ' '
- << timer_cancel_key_;
- timer_queue.cancel(timer_cancel_key_);
+ void cancelDeadlineTimer() {
+ BMCWEB_LOG_DEBUG << this << " timer cancelled: " << &timerQueue << ' '
+ << timerCancelKey;
+ timerQueue.cancel(timerCancelKey);
}
- void start_deadline() {
- cancel_deadline_timer();
+ void startDeadline() {
+ cancelDeadlineTimer();
- timer_cancel_key_ = timer_queue.add([this] {
- if (!adaptor_.is_open()) {
+ timerCancelKey = timerQueue.add([this] {
+ if (!adaptor.isOpen()) {
return;
}
- adaptor_.close();
+ adaptor.close();
});
- CROW_LOG_DEBUG << this << " timer added: " << &timer_queue << ' '
- << timer_cancel_key_;
+ BMCWEB_LOG_DEBUG << this << " timer added: " << &timerQueue << ' '
+ << timerCancelKey;
}
private:
- Adaptor adaptor_;
- Handler* handler_;
+ Adaptor adaptor;
+ Handler* handler;
// Making this a boost::optional allows it to be efficiently destroyed and
- // re-created on connection reset
+ // re-created on Connection reset
boost::optional<
boost::beast::http::request_parser<boost::beast::http::string_body>>
- parser_;
+ parser;
- boost::beast::flat_buffer buffer_{8192};
+ boost::beast::flat_buffer buffer{8192};
boost::optional<
boost::beast::http::response_serializer<boost::beast::http::string_body>>
- serializer_;
+ serializer;
- boost::optional<crow::request> req_;
- crow::response res;
+ boost::optional<crow::Request> req;
+ crow::Response res;
- const std::string& server_name_;
+ const std::string& serverName;
- int timer_cancel_key_;
+ int timerCancelKey{-1};
- bool is_reading{};
- bool is_writing{};
- bool need_to_call_after_handlers_{};
- bool need_to_start_read_after_complete_{};
- bool add_keep_alive_{};
+ bool isReading{};
+ bool isWriting{};
+ bool needToCallAfterHandlers{};
+ bool needToStartReadAfterComplete{};
+ bool addKeepAlive{};
- std::tuple<Middlewares...>* middlewares_;
- detail::context<Middlewares...> ctx_;
+ std::tuple<Middlewares...>* middlewares;
+ detail::Context<Middlewares...> ctx;
- std::function<std::string()>& get_cached_date_str;
- detail::timer_queue& timer_queue;
+ std::function<std::string()>& getCachedDateStr;
+ detail::TimerQueue& timerQueue;
}; // namespace crow
} // namespace crow
diff --git a/crow/include/crow/http_request.h b/crow/include/crow/http_request.h
index eb3e01c..301aa59 100644
--- a/crow/include/crow/http_request.h
+++ b/crow/include/crow/http_request.h
@@ -9,42 +9,38 @@
namespace crow {
-struct request {
+struct Request {
boost::string_view url{};
- query_string url_params{};
- bool is_secure{false};
+ QueryString urlParams{};
+ bool isSecure{false};
const std::string& body;
- void* middleware_context{};
- boost::asio::io_service* io_service{};
+ void* middlewareContext{};
+ boost::asio::io_service* ioService{};
- request(boost::beast::http::request<boost::beast::http::string_body>& req)
+ Request(boost::beast::http::request<boost::beast::http::string_body>& req)
: req(req), body(req.body()) {}
const boost::beast::http::verb method() const { return req.method(); }
- const boost::string_view get_header_value(
- boost::string_view key) const {
+ const boost::string_view getHeaderValue(boost::string_view key) const {
return req[key];
}
- const boost::string_view get_header_value(
- boost::beast::http::field key) const {
+ const boost::string_view getHeaderValue(boost::beast::http::field key) const {
return req[key];
}
- const boost::string_view method_string() const {
- return req.method_string();
- }
+ const boost::string_view methodString() const { return req.method_string(); }
const boost::string_view target() const { return req.target(); }
unsigned version() { return req.version(); }
- bool is_upgrade() { return boost::beast::websocket::is_upgrade(req); }
+ bool isUpgrade() { return boost::beast::websocket::is_upgrade(req); }
- bool keep_alive() { return req.keep_alive(); }
+ bool keepAlive() { return req.keep_alive(); }
private:
boost::beast::http::request<boost::beast::http::string_body>& req;
diff --git a/crow/include/crow/http_response.h b/crow/include/crow/http_response.h
index 6c28237..a738687 100644
--- a/crow/include/crow/http_response.h
+++ b/crow/include/crow/http_response.h
@@ -11,98 +11,97 @@
template <typename Adaptor, typename Handler, typename... Middlewares>
class Connection;
-struct response {
+struct Response {
template <typename Adaptor, typename Handler, typename... Middlewares>
friend class crow::Connection;
using response_type =
boost::beast::http::response<boost::beast::http::string_body>;
- boost::optional<response_type> string_response;
+ boost::optional<response_type> stringResponse;
- nlohmann::json json_value;
+ nlohmann::json jsonValue;
- void add_header(const boost::string_view key,
- const boost::string_view value) {
- string_response->set(key, value);
+ void addHeader(const boost::string_view key, const boost::string_view value) {
+ stringResponse->set(key, value);
}
- void add_header(boost::beast::http::field key, boost::string_view value) {
- string_response->set(key, value);
+ void addHeader(boost::beast::http::field key, boost::string_view value) {
+ stringResponse->set(key, value);
}
- response() : string_response(response_type{}) {}
+ Response() : stringResponse(response_type{}) {}
- explicit response(boost::beast::http::status code)
- : string_response(response_type{}) {}
+ explicit Response(boost::beast::http::status code)
+ : stringResponse(response_type{}) {}
- explicit response(boost::string_view body_)
- : string_response(response_type{}) {
- string_response->body() = std::string(body_);
+ explicit Response(boost::string_view body_)
+ : stringResponse(response_type{}) {
+ stringResponse->body() = std::string(body_);
}
- response(boost::beast::http::status code, boost::string_view s)
- : string_response(response_type{}) {
- string_response->result(code);
- string_response->body() = std::string(s);
+ Response(boost::beast::http::status code, boost::string_view s)
+ : stringResponse(response_type{}) {
+ stringResponse->result(code);
+ stringResponse->body() = std::string(s);
}
- response(response&& r) {
- CROW_LOG_DEBUG << "Moving response containers";
+ Response(Response&& r) {
+ BMCWEB_LOG_DEBUG << "Moving response containers";
*this = std::move(r);
}
- ~response() { CROW_LOG_DEBUG << this << " Destroying response"; }
+ ~Response() { BMCWEB_LOG_DEBUG << this << " Destroying response"; }
- response& operator=(const response& r) = delete;
+ Response& operator=(const Response& r) = delete;
- response& operator=(response&& r) noexcept {
- CROW_LOG_DEBUG << "Moving response containers";
- string_response = std::move(r.string_response);
- r.string_response.emplace(response_type{});
- json_value = std::move(r.json_value);
- completed_ = r.completed_;
+ Response& operator=(Response&& r) noexcept {
+ BMCWEB_LOG_DEBUG << "Moving response containers";
+ stringResponse = std::move(r.stringResponse);
+ r.stringResponse.emplace(response_type{});
+ jsonValue = std::move(r.jsonValue);
+ completed = r.completed;
return *this;
}
- void result(boost::beast::http::status v) { string_response->result(v); }
+ void result(boost::beast::http::status v) { stringResponse->result(v); }
- boost::beast::http::status result() { return string_response->result(); }
+ boost::beast::http::status result() { return stringResponse->result(); }
- unsigned result_int() { return string_response->result_int(); }
+ unsigned resultInt() { return stringResponse->result_int(); }
- boost::string_view reason() { return string_response->reason(); }
+ boost::string_view reason() { return stringResponse->reason(); }
- bool is_completed() const noexcept { return completed_; }
+ bool isCompleted() const noexcept { return completed; }
- std::string& body() { return string_response->body(); }
+ std::string& body() { return stringResponse->body(); }
- void keep_alive(bool k) { string_response->keep_alive(k); }
+ void keepAlive(bool k) { stringResponse->keep_alive(k); }
- void prepare_payload() { string_response->prepare_payload(); };
+ void preparePayload() { stringResponse->prepare_payload(); };
void clear() {
- CROW_LOG_DEBUG << this << " Clearing response containers";
- string_response.emplace(response_type{});
- json_value.clear();
- completed_ = false;
+ BMCWEB_LOG_DEBUG << this << " Clearing response containers";
+ stringResponse.emplace(response_type{});
+ jsonValue.clear();
+ completed = false;
}
void write(boost::string_view body_part) {
- string_response->body() += std::string(body_part);
+ stringResponse->body() += std::string(body_part);
}
void end() {
- if (completed_) {
- CROW_LOG_ERROR << "Response was ended twice";
+ if (completed) {
+ BMCWEB_LOG_ERROR << "Response was ended twice";
return;
}
- completed_ = true;
- CROW_LOG_DEBUG << "calling completion handler";
- if (!complete_request_handler_) {
- CROW_LOG_ERROR << "completion handler was invalid";
+ completed = true;
+ BMCWEB_LOG_DEBUG << "calling completion handler";
+ if (!completeRequestHandler) {
+ BMCWEB_LOG_ERROR << "completion handler was invalid";
return;
}
- complete_request_handler_();
+ completeRequestHandler();
}
@@ -111,14 +110,14 @@
end();
}
- bool is_alive() { return is_alive_helper_ && is_alive_helper_(); }
+ bool isAlive() { return isAliveHelper && isAliveHelper(); }
private:
- bool completed_{};
- std::function<void()> complete_request_handler_;
- std::function<bool()> is_alive_helper_;
+ bool completed{};
+ std::function<void()> completeRequestHandler;
+ std::function<bool()> isAliveHelper;
// In case of a JSON object, set the Content-Type header
- void json_mode() { add_header("Content-Type", "application/json"); }
+ void jsonMode() { addHeader("Content-Type", "application/json"); }
};
} // namespace crow
diff --git a/crow/include/crow/http_server.h b/crow/include/crow/http_server.h
index 86bf54b..96b85dc 100644
--- a/crow/include/crow/http_server.h
+++ b/crow/include/crow/http_server.h
@@ -7,12 +7,12 @@
#include <memory>
#include <utility>
#include <vector>
-#include "crow/timer_queue.h"
#include "crow/http_connection.h"
#include "crow/logging.h"
+#include "crow/timer_queue.h"
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
-#ifdef CROW_ENABLE_SSL
+#ifdef BMCWEB_ENABLE_SSL
#include <boost/asio/ssl.hpp>
#endif
@@ -29,13 +29,13 @@
typename Adaptor::context* adaptor_ctx = nullptr,
std::shared_ptr<boost::asio::io_service> io =
std::make_shared<boost::asio::io_service>())
- : io_service_(std::move(io)),
- acceptor_(std::move(acceptor)),
- signals_(*io_service_, SIGINT, SIGTERM),
- tick_timer_(*io_service_),
- handler_(handler),
- middlewares_(middlewares),
- adaptor_ctx_(adaptor_ctx) {}
+ : ioService(std::move(io)),
+ acceptor(std::move(acceptor)),
+ signals(*ioService, SIGINT, SIGTERM),
+ tickTimer(*ioService),
+ handler(handler),
+ middlewares(middlewares),
+ adaptorCtx(adaptor_ctx) {}
Server(Handler* handler, const std::string& bindaddr, uint16_t port,
std::tuple<Middlewares...>* middlewares = nullptr,
@@ -59,53 +59,53 @@
existing_socket),
middlewares, adaptor_ctx, io) {}
- void set_tick_function(std::chrono::milliseconds d, std::function<void()> f) {
- tick_interval_ = d;
- tick_function_ = f;
+ void setTickFunction(std::chrono::milliseconds d, std::function<void()> f) {
+ tickInterval = d;
+ tickFunction = f;
}
- void on_tick() {
- tick_function_();
- tick_timer_.expires_from_now(
- boost::posix_time::milliseconds(tick_interval_.count()));
- tick_timer_.async_wait([this](const boost::system::error_code& ec) {
+ void onTick() {
+ tickFunction();
+ tickTimer.expires_from_now(
+ boost::posix_time::milliseconds(tickInterval.count()));
+ tickTimer.async_wait([this](const boost::system::error_code& ec) {
if (ec) {
return;
}
- on_tick();
+ onTick();
});
}
- void update_date_str() {
- auto last_time_t = time(0);
- tm my_tm{};
+ void updateDateStr() {
+ auto lastTimeT = time(0);
+ tm myTm{};
#ifdef _MSC_VER
gmtime_s(&my_tm, &last_time_t);
#else
- gmtime_r(&last_time_t, &my_tm);
+ gmtime_r(&lastTimeT, &myTm);
#endif
- date_str.resize(100);
- size_t date_str_sz =
- strftime(&date_str[0], 99, "%a, %d %b %Y %H:%M:%S GMT", &my_tm);
- date_str.resize(date_str_sz);
+ dateStr.resize(100);
+ size_t dateStrSz =
+ strftime(&dateStr[0], 99, "%a, %d %b %Y %H:%M:%S GMT", &myTm);
+ dateStr.resize(dateStrSz);
};
void run() {
- update_date_str();
+ updateDateStr();
- get_cached_date_str_ = [this]() -> std::string {
- static std::chrono::time_point<std::chrono::steady_clock>
- last_date_update = std::chrono::steady_clock::now();
- if (std::chrono::steady_clock::now() - last_date_update >=
+ getCachedDateStr = [this]() -> std::string {
+ static std::chrono::time_point<std::chrono::steady_clock> lastDateUpdate =
+ std::chrono::steady_clock::now();
+ if (std::chrono::steady_clock::now() - lastDateUpdate >=
std::chrono::seconds(10)) {
- last_date_update = std::chrono::steady_clock::now();
- update_date_str();
+ lastDateUpdate = std::chrono::steady_clock::now();
+ updateDateStr();
}
- return this->date_str;
+ return this->dateStr;
};
- boost::asio::deadline_timer timer(*io_service_);
+ boost::asio::deadline_timer timer(*ioService);
timer.expires_from_now(boost::posix_time::seconds(1));
std::function<void(const boost::system::error_code& ec)> handler;
@@ -113,71 +113,71 @@
if (ec) {
return;
}
- timer_queue_.process();
+ timerQueue.process();
timer.expires_from_now(boost::posix_time::seconds(1));
timer.async_wait(handler);
};
timer.async_wait(handler);
- if (tick_function_ && tick_interval_.count() > 0) {
- tick_timer_.expires_from_now(
- boost::posix_time::milliseconds(tick_interval_.count()));
- tick_timer_.async_wait([this](const boost::system::error_code& ec) {
+ if (tickFunction && tickInterval.count() > 0) {
+ tickTimer.expires_from_now(
+ boost::posix_time::milliseconds(tickInterval.count()));
+ tickTimer.async_wait([this](const boost::system::error_code& ec) {
if (ec) {
return;
}
- on_tick();
+ onTick();
});
}
- CROW_LOG_INFO << server_name_ << " server is running, local endpoint "
- << acceptor_->local_endpoint();
+ BMCWEB_LOG_INFO << serverName << " server is running, local endpoint "
+ << acceptor->local_endpoint();
- signals_.async_wait([&](const boost::system::error_code& /*error*/,
- int /*signal_number*/) { stop(); });
+ signals.async_wait([&](const boost::system::error_code& /*error*/,
+ int /*signal_number*/) { stop(); });
- do_accept();
+ doAccept();
}
- void stop() { io_service_->stop(); }
+ void stop() { ioService->stop(); }
- void do_accept() {
+ void doAccept() {
auto p = new Connection<Adaptor, Handler, Middlewares...>(
- *io_service_, handler_, server_name_, middlewares_,
- get_cached_date_str_, timer_queue_, adaptor_ctx_);
- acceptor_->async_accept(p->socket(),
- [this, p](boost::system::error_code ec) {
- if (!ec) {
- this->io_service_->post([p] { p->start(); });
- } else {
- delete p;
- }
- do_accept();
- });
+ *ioService, handler, serverName, middlewares, getCachedDateStr,
+ timerQueue, adaptorCtx);
+ acceptor->async_accept(p->socket(),
+ [this, p](boost::system::error_code ec) {
+ if (!ec) {
+ this->ioService->post([p] { p->start(); });
+ } else {
+ delete p;
+ }
+ doAccept();
+ });
}
private:
- std::shared_ptr<asio::io_service> io_service_;
- detail::timer_queue timer_queue_;
- std::function<std::string()> get_cached_date_str_;
- std::unique_ptr<tcp::acceptor> acceptor_;
- boost::asio::signal_set signals_;
- boost::asio::deadline_timer tick_timer_;
+ std::shared_ptr<asio::io_service> ioService;
+ detail::TimerQueue timerQueue;
+ std::function<std::string()> getCachedDateStr;
+ std::unique_ptr<tcp::acceptor> acceptor;
+ boost::asio::signal_set signals;
+ boost::asio::deadline_timer tickTimer;
- std::string date_str;
+ std::string dateStr;
- Handler* handler_;
- std::string server_name_ = "iBMC";
+ Handler* handler;
+ std::string serverName = "iBMC";
- std::chrono::milliseconds tick_interval_{};
- std::function<void()> tick_function_;
+ std::chrono::milliseconds tickInterval{};
+ std::function<void()> tickFunction;
- std::tuple<Middlewares...>* middlewares_;
+ std::tuple<Middlewares...>* middlewares;
-#ifdef CROW_ENABLE_SSL
- bool use_ssl_{false};
- boost::asio::ssl::context ssl_context_{boost::asio::ssl::context::sslv23};
+#ifdef BMCWEB_ENABLE_SSL
+ bool useSsl{false};
+ boost::asio::ssl::context sslContext{boost::asio::ssl::context::sslv23};
#endif
- typename Adaptor::context* adaptor_ctx_;
+ typename Adaptor::context* adaptorCtx;
}; // namespace crow
} // namespace crow
diff --git a/crow/include/crow/logging.h b/crow/include/crow/logging.h
index 390f80f..4a68df3 100644
--- a/crow/include/crow/logging.h
+++ b/crow/include/crow/logging.h
@@ -43,29 +43,29 @@
char date[32];
time_t t = time(0);
- tm my_tm{};
+ tm myTm{};
#ifdef _MSC_VER
gmtime_s(&my_tm, &t);
#else
- gmtime_r(&t, &my_tm);
+ gmtime_r(&t, &myTm);
#endif
- size_t sz = strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", &my_tm);
+ size_t sz = strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", &myTm);
return std::string(date, date + sz);
}
public:
- logger(const std::string& prefix, LogLevel level) : level_(level) {
-#ifdef CROW_ENABLE_LOGGING
- stringstream_ << "(" << timestamp() << ") [" << prefix << "] ";
+ logger(const std::string& prefix, LogLevel level) : level(level) {
+#ifdef BMCWEB_ENABLE_LOGGING
+ stringstream << "(" << timestamp() << ") [" << prefix << "] ";
#endif
}
~logger() {
-#ifdef CROW_ENABLE_LOGGING
- if (level_ >= get_current_log_level()) {
- stringstream_ << std::endl;
- get_handler_ref()->log(stringstream_.str(), level_);
+#ifdef BMCWEB_ENABLE_LOGGING
+ if (level >= get_current_log_level()) {
+ stringstream << std::endl;
+ getHandlerRef()->log(stringstream.str(), level);
}
#endif
}
@@ -73,51 +73,51 @@
//
template <typename T>
logger& operator<<(T const& value) {
-#ifdef CROW_ENABLE_LOGGING
- if (level_ >= get_current_log_level()) {
- stringstream_ << value;
+#ifdef BMCWEB_ENABLE_LOGGING
+ if (level >= get_current_log_level()) {
+ stringstream << value;
}
#endif
return *this;
}
//
- static void setLogLevel(LogLevel level) { get_log_level_ref() = level; }
+ static void setLogLevel(LogLevel level) { getLogLevelRef() = level; }
- static void setHandler(ILogHandler* handler) { get_handler_ref() = handler; }
+ static void setHandler(ILogHandler* handler) { getHandlerRef() = handler; }
- static LogLevel get_current_log_level() { return get_log_level_ref(); }
+ static LogLevel get_current_log_level() { return getLogLevelRef(); }
private:
//
- static LogLevel& get_log_level_ref() {
- static auto current_level = static_cast<LogLevel>(1);
- return current_level;
+ static LogLevel& getLogLevelRef() {
+ static auto currentLevel = static_cast<LogLevel>(1);
+ return currentLevel;
}
- static ILogHandler*& get_handler_ref() {
- static CerrLogHandler default_handler;
- static ILogHandler* current_handler = &default_handler;
- return current_handler;
+ static ILogHandler*& getHandlerRef() {
+ static CerrLogHandler defaultHandler;
+ static ILogHandler* currentHandler = &defaultHandler;
+ return currentHandler;
}
//
- std::ostringstream stringstream_;
- LogLevel level_;
+ std::ostringstream stringstream;
+ LogLevel level;
};
} // namespace crow
-#define CROW_LOG_CRITICAL \
+#define BMCWEB_LOG_CRITICAL \
if (crow::logger::get_current_log_level() <= crow::LogLevel::Critical) \
crow::logger("CRITICAL", crow::LogLevel::Critical)
-#define CROW_LOG_ERROR \
+#define BMCWEB_LOG_ERROR \
if (crow::logger::get_current_log_level() <= crow::LogLevel::Error) \
crow::logger("ERROR ", crow::LogLevel::Error)
-#define CROW_LOG_WARNING \
+#define BMCWEB_LOG_WARNING \
if (crow::logger::get_current_log_level() <= crow::LogLevel::Warning) \
crow::logger("WARNING ", crow::LogLevel::Warning)
-#define CROW_LOG_INFO \
+#define BMCWEB_LOG_INFO \
if (crow::logger::get_current_log_level() <= crow::LogLevel::Info) \
crow::logger("INFO ", crow::LogLevel::Info)
-#define CROW_LOG_DEBUG \
+#define BMCWEB_LOG_DEBUG \
if (crow::logger::get_current_log_level() <= crow::LogLevel::Debug) \
crow::logger("DEBUG ", crow::LogLevel::Debug)
diff --git a/crow/include/crow/middleware_context.h b/crow/include/crow/middleware_context.h
index 7b2f8d5..03309f6 100644
--- a/crow/include/crow/middleware_context.h
+++ b/crow/include/crow/middleware_context.h
@@ -7,57 +7,57 @@
namespace crow {
namespace detail {
template <typename... Middlewares>
-struct partial_context
- : public black_magic::pop_back<Middlewares...>::template rebind<
- partial_context>,
- public black_magic::last_element_type<Middlewares...>::type::context {
- using parent_context = typename black_magic::pop_back<
- Middlewares...>::template rebind<::crow::detail::partial_context>;
+struct PartialContext
+ : public black_magic::PopBack<Middlewares...>::template rebind<
+ PartialContext>,
+ public black_magic::LastElementType<Middlewares...>::type::Context {
+ using parent_context = typename black_magic::PopBack<
+ Middlewares...>::template rebind<::crow::detail::PartialContext>;
template <int N>
using partial = typename std::conditional<
- N == sizeof...(Middlewares)-1, partial_context,
+ N == sizeof...(Middlewares) - 1, PartialContext,
typename parent_context::template partial<N>>::type;
template <typename T>
- typename T::context& get() {
- return static_cast<typename T::context&>(*this);
+ typename T::Context& get() {
+ return static_cast<typename T::Context&>(*this);
}
};
template <>
-struct partial_context<> {
+struct PartialContext<> {
template <int>
- using partial = partial_context;
+ using partial = PartialContext;
};
template <int N, typename Context, typename Container, typename CurrentMW,
typename... Middlewares>
-bool middleware_call_helper(Container& middlewares, request& req, response& res,
- Context& ctx);
+bool middlewareCallHelper(Container& middlewares, Request& req, Response& res,
+ Context& ctx);
template <typename... Middlewares>
-struct context : private partial_context<Middlewares...>
-// struct context : private Middlewares::context... // simple but less type-safe
+struct Context : private PartialContext<Middlewares...>
+// struct Context : private Middlewares::context... // simple but less type-safe
{
template <int N, typename Context, typename Container>
- friend typename std::enable_if<(N == 0)>::type after_handlers_call_helper(
- Container& middlewares, Context& ctx, request& req, response& res);
+ friend typename std::enable_if<(N == 0)>::type afterHandlersCallHelper(
+ Container& middlewares, Context& ctx, Request& req, Response& res);
template <int N, typename Context, typename Container>
- friend typename std::enable_if<(N > 0)>::type after_handlers_call_helper(
- Container& middlewares, Context& ctx, request& req, response& res);
+ friend typename std::enable_if<(N > 0)>::type afterHandlersCallHelper(
+ Container& middlewares, Context& ctx, Request& req, Response& res);
template <int N, typename Context, typename Container, typename CurrentMW,
typename... Middlewares2>
- friend bool middleware_call_helper(Container& middlewares, request& req,
- response& res, Context& ctx);
+ friend bool middlewareCallHelper(Container& middlewares, Request& req,
+ Response& res, Context& ctx);
template <typename T>
- typename T::context& get() {
- return static_cast<typename T::context&>(*this);
+ typename T::Context& get() {
+ return static_cast<typename T::Context&>(*this);
}
template <int N>
- using partial = typename partial_context<Middlewares...>::template partial<N>;
+ using partial = typename PartialContext<Middlewares...>::template partial<N>;
};
-} // namespace detail
-} // namespace crow
+} // namespace detail
+} // namespace crow
diff --git a/crow/include/crow/query_string.h b/crow/include/crow/query_string.h
index 5e28e18..0606994 100644
--- a/crow/include/crow/query_string.h
+++ b/crow/include/crow/query_string.h
@@ -12,45 +12,45 @@
// https://github.com/bartgrantham/qs_parse
// ----------------------------------------------------------------------------
/* Similar to strncmp, but handles URL-encoding for either string */
-int qs_strncmp(const char* s, const char* qs, size_t n);
+int qsStrncmp(const char* s, const char* qs, size_t n);
/* Finds the beginning of each key/value pair and stores a pointer in qs_kv.
* Also decodes the value portion of the k/v pair *in-place*. In a future
* enhancement it will also have a compile-time option of sorting qs_kv
* alphabetically by key. */
-int qs_parse(char* qs, char* qs_kv[], int qs_kv_size);
+int qsParse(char* qs, char* qs_kv[], int qs_kv_size);
/* Used by qs_parse to decode the value portion of a k/v pair */
-int qs_decode(char* qs);
+int qsDecode(char* qs);
/* Looks up the value according to the key on a pre-processed query string
* A future enhancement will be a compile-time option to look up the key
* in a pre-sorted qs_kv array via a binary search. */
// char * qs_k2v(const char * key, char * qs_kv[], int qs_kv_size);
-char* qs_k2v(const char* key, char* const* qs_kv, int qs_kv_size, int nth);
+char* qsK2v(const char* key, char* const* qs_kv, int qs_kv_size, int nth);
/* Non-destructive lookup of value, based on key. User provides the
* destinaton string and length. */
-char* qs_scanvalue(const char* key, const char* qs, char* val, size_t val_len);
+char* qsScanvalue(const char* key, const char* qs, char* val, size_t val_len);
// TODO: implement sorting of the qs_kv array; for now ensure it's not compiled
#undef _qsSORTING
// isxdigit _is_ available in <ctype.h>, but let's avoid another header instead
-#define CROW_QS_ISHEX(x) \
+#define BMCWEB_QS_ISHEX(x) \
((((x) >= '0' && (x) <= '9') || ((x) >= 'A' && (x) <= 'F') || \
((x) >= 'a' && (x) <= 'f')) \
? 1 \
: 0)
-#define CROW_QS_HEX2DEC(x) \
+#define BMCWEB_QS_HEX2DEC(x) \
(((x) >= '0' && (x) <= '9') \
? (x)-48 \
: ((x) >= 'A' && (x) <= 'F') ? (x)-55 \
: ((x) >= 'a' && (x) <= 'f') ? (x)-87 : 0)
-#define CROW_QS_ISQSCHR(x) \
+#define BMCWEB_QS_ISQSCHR(x) \
((((x) == '=') || ((x) == '#') || ((x) == '&') || ((x) == '\0')) ? 0 : 1)
-inline int qs_strncmp(const char* s, const char* qs, size_t n) {
+inline int qsStrncmp(const char* s, const char* qs, size_t n) {
int i = 0;
unsigned char u1, u2, unyb, lnyb;
@@ -58,10 +58,10 @@
u1 = static_cast<unsigned char>(*s++);
u2 = static_cast<unsigned char>(*qs++);
- if (!CROW_QS_ISQSCHR(u1)) {
+ if (!BMCWEB_QS_ISQSCHR(u1)) {
u1 = '\0';
}
- if (!CROW_QS_ISQSCHR(u2)) {
+ if (!BMCWEB_QS_ISQSCHR(u2)) {
u2 = '\0';
}
@@ -72,8 +72,8 @@
{
unyb = static_cast<unsigned char>(*s++);
lnyb = static_cast<unsigned char>(*s++);
- if (CROW_QS_ISHEX(unyb) && CROW_QS_ISHEX(lnyb)) {
- u1 = (CROW_QS_HEX2DEC(unyb) * 16) + CROW_QS_HEX2DEC(lnyb);
+ if (BMCWEB_QS_ISHEX(unyb) && BMCWEB_QS_ISHEX(lnyb)) {
+ u1 = (BMCWEB_QS_HEX2DEC(unyb) * 16) + BMCWEB_QS_HEX2DEC(lnyb);
} else {
u1 = '\0';
}
@@ -86,8 +86,8 @@
{
unyb = static_cast<unsigned char>(*qs++);
lnyb = static_cast<unsigned char>(*qs++);
- if (CROW_QS_ISHEX(unyb) && CROW_QS_ISHEX(lnyb)) {
- u2 = (CROW_QS_HEX2DEC(unyb) * 16) + CROW_QS_HEX2DEC(lnyb);
+ if (BMCWEB_QS_ISHEX(unyb) && BMCWEB_QS_ISHEX(lnyb)) {
+ u2 = (BMCWEB_QS_HEX2DEC(unyb) * 16) + BMCWEB_QS_HEX2DEC(lnyb);
} else {
u2 = '\0';
}
@@ -101,37 +101,37 @@
}
i++;
}
- if (CROW_QS_ISQSCHR(*qs)) {
+ if (BMCWEB_QS_ISQSCHR(*qs)) {
return -1;
} else {
return 0;
}
}
-inline int qs_parse(char* qs, char* qs_kv[], int qs_kv_size) {
+inline int qsParse(char* qs, char* qs_kv[], int qs_kv_size) {
int i, j;
- char* substr_ptr;
+ char* substrPtr;
for (i = 0; i < qs_kv_size; i++) {
qs_kv[i] = NULL;
}
// find the beginning of the k/v substrings or the fragment
- substr_ptr = qs + strcspn(qs, "?#");
- if (substr_ptr[0] != '\0') {
- substr_ptr++;
+ substrPtr = qs + strcspn(qs, "?#");
+ if (substrPtr[0] != '\0') {
+ substrPtr++;
} else {
return 0; // no query or fragment
}
i = 0;
while (i < qs_kv_size) {
- qs_kv[i] = substr_ptr;
- j = strcspn(substr_ptr, "&");
- if (substr_ptr[j] == '\0') {
+ qs_kv[i] = substrPtr;
+ j = strcspn(substrPtr, "&");
+ if (substrPtr[j] == '\0') {
break;
}
- substr_ptr += j + 1;
+ substrPtr += j + 1;
i++;
}
i++; // x &'s -> means x iterations of this loop -> means *x+1* k/v pairs
@@ -139,12 +139,12 @@
// we only decode the values in place, the keys could have '='s in them
// which will hose our ability to distinguish keys from values later
for (j = 0; j < i; j++) {
- substr_ptr = qs_kv[j] + strcspn(qs_kv[j], "=&#");
- if (substr_ptr[0] == '&' ||
- substr_ptr[0] == '\0') { // blank value: skip decoding
- substr_ptr[0] = '\0';
+ substrPtr = qs_kv[j] + strcspn(qs_kv[j], "=&#");
+ if (substrPtr[0] == '&' ||
+ substrPtr[0] == '\0') { // blank value: skip decoding
+ substrPtr[0] = '\0';
} else {
- qs_decode(++substr_ptr);
+ qsDecode(++substrPtr);
}
}
@@ -155,19 +155,20 @@
return i;
}
-inline int qs_decode(char* qs) {
+inline int qsDecode(char* qs) {
int i = 0, j = 0;
- while (CROW_QS_ISQSCHR(qs[j])) {
+ while (BMCWEB_QS_ISQSCHR(qs[j])) {
if (qs[j] == '+') {
qs[i] = ' ';
} else if (qs[j] == '%') // easier/safer than scanf
{
- if (!CROW_QS_ISHEX(qs[j + 1]) || !CROW_QS_ISHEX(qs[j + 2])) {
+ if (!BMCWEB_QS_ISHEX(qs[j + 1]) || !BMCWEB_QS_ISHEX(qs[j + 2])) {
qs[i] = '\0';
return i;
}
- qs[i] = (CROW_QS_HEX2DEC(qs[j + 1]) * 16) + CROW_QS_HEX2DEC(qs[j + 2]);
+ qs[i] =
+ (BMCWEB_QS_HEX2DEC(qs[j + 1]) * 16) + BMCWEB_QS_HEX2DEC(qs[j + 2]);
j += 2;
} else {
qs[i] = qs[j];
@@ -180,19 +181,19 @@
return i;
}
-inline char* qs_k2v(const char* key, char* const* qs_kv, int qs_kv_size,
- int nth = 0) {
+inline char* qsK2v(const char* key, char* const* qs_kv, int qs_kv_size,
+ int nth = 0) {
int i;
- size_t key_len, skip;
+ size_t keyLen, skip;
- key_len = strlen(key);
+ keyLen = strlen(key);
#ifdef _qsSORTING
// TODO: binary search for key in the sorted qs_kv
#else // _qsSORTING
for (i = 0; i < qs_kv_size; i++) {
// we rely on the unambiguous '=' to find the value in our k/v pair
- if (qs_strncmp(key, qs_kv[i], key_len) == 0) {
+ if (qsStrncmp(key, qs_kv[i], keyLen) == 0) {
skip = strcspn(qs_kv[i], "=");
if (qs_kv[i][skip] == '=') {
skip++;
@@ -210,9 +211,9 @@
return NULL;
}
-inline char* qs_scanvalue(const char* key, const char* qs, char* val,
- size_t val_len) {
- size_t i, key_len;
+inline char* qsScanvalue(const char* key, const char* qs, char* val,
+ size_t val_len) {
+ size_t i, keyLen;
const char* tmp;
// find the beginning of the k/v substrings
@@ -220,9 +221,9 @@
qs = tmp + 1;
}
- key_len = strlen(key);
+ keyLen = strlen(key);
while (qs[0] != '#' && qs[0] != '\0') {
- if (qs_strncmp(key, qs, key_len) == 0) {
+ if (qsStrncmp(key, qs, keyLen) == 0) {
break;
}
qs += strcspn(qs, "&") + 1;
@@ -237,7 +238,7 @@
qs++;
i = strcspn(qs, "&=#");
strncpy(val, qs, (val_len - 1) < (i + 1) ? (val_len - 1) : (i + 1));
- qs_decode(val);
+ qsDecode(val);
} else {
if (val_len > 0) {
val[0] = '\0';
@@ -250,83 +251,81 @@
// ----------------------------------------------------------------------------
namespace crow {
-class query_string {
+class QueryString {
public:
- static const int MAX_KEY_VALUE_PAIRS_COUNT = 256;
+ static const int maxKeyValuePairsCount = 256;
- query_string() = default;
+ QueryString() = default;
- query_string(const query_string& qs) : url_(qs.url_) {
- for (auto p : qs.key_value_pairs_) {
- key_value_pairs_.push_back(
- const_cast<char*>(p - qs.url_.c_str() + url_.c_str()));
+ QueryString(const QueryString& qs) : url(qs.url) {
+ for (auto p : qs.keyValuePairs) {
+ keyValuePairs.push_back(
+ const_cast<char*>(p - qs.url.c_str() + url.c_str()));
}
}
- query_string& operator=(const query_string& qs) {
- url_ = qs.url_;
- key_value_pairs_.clear();
- for (auto p : qs.key_value_pairs_) {
- key_value_pairs_.push_back(
- const_cast<char*>(p - qs.url_.c_str() + url_.c_str()));
+ QueryString& operator=(const QueryString& qs) {
+ url = qs.url;
+ keyValuePairs.clear();
+ for (auto p : qs.keyValuePairs) {
+ keyValuePairs.push_back(
+ const_cast<char*>(p - qs.url.c_str() + url.c_str()));
}
return *this;
}
- query_string& operator=(query_string&& qs) {
- key_value_pairs_ = std::move(qs.key_value_pairs_);
- auto* old_data = const_cast<char*>(qs.url_.c_str());
- url_ = std::move(qs.url_);
- for (auto& p : key_value_pairs_) {
- p += const_cast<char*>(url_.c_str()) - old_data;
+ QueryString& operator=(QueryString&& qs) {
+ keyValuePairs = std::move(qs.keyValuePairs);
+ auto* oldData = const_cast<char*>(qs.url.c_str());
+ url = std::move(qs.url);
+ for (auto& p : keyValuePairs) {
+ p += const_cast<char*>(url.c_str()) - oldData;
}
return *this;
}
- explicit query_string(std::string url) : url_(std::move(url)) {
- if (url_.empty()) {
+ explicit QueryString(std::string url) : url(std::move(url)) {
+ if (url.empty()) {
return;
}
- key_value_pairs_.resize(MAX_KEY_VALUE_PAIRS_COUNT);
+ keyValuePairs.resize(maxKeyValuePairsCount);
- int count =
- qs_parse(&url_[0], &key_value_pairs_[0], MAX_KEY_VALUE_PAIRS_COUNT);
- key_value_pairs_.resize(count);
+ int count = qsParse(&url[0], &keyValuePairs[0], maxKeyValuePairsCount);
+ keyValuePairs.resize(count);
}
void clear() {
- key_value_pairs_.clear();
- url_.clear();
+ keyValuePairs.clear();
+ url.clear();
}
- friend std::ostream& operator<<(std::ostream& os, const query_string& qs) {
+ friend std::ostream& operator<<(std::ostream& os, const QueryString& qs) {
os << "[ ";
- for (size_t i = 0; i < qs.key_value_pairs_.size(); ++i) {
+ for (size_t i = 0; i < qs.keyValuePairs.size(); ++i) {
if (i != 0u) {
os << ", ";
}
- os << qs.key_value_pairs_[i];
+ os << qs.keyValuePairs[i];
}
os << " ]";
return os;
}
char* get(const std::string& name) const {
- char* ret =
- qs_k2v(name.c_str(), key_value_pairs_.data(), key_value_pairs_.size());
+ char* ret = qsK2v(name.c_str(), keyValuePairs.data(), keyValuePairs.size());
return ret;
}
- std::vector<char*> get_list(const std::string& name) const {
+ std::vector<char*> getList(const std::string& name) const {
std::vector<char*> ret;
std::string plus = name + "[]";
char* element = nullptr;
int count = 0;
while (1) {
- element = qs_k2v(plus.c_str(), key_value_pairs_.data(),
- key_value_pairs_.size(), count++);
+ element = qsK2v(plus.c_str(), keyValuePairs.data(), keyValuePairs.size(),
+ count++);
if (element == nullptr) {
break;
}
@@ -336,8 +335,8 @@
}
private:
- std::string url_;
- std::vector<char*> key_value_pairs_;
+ std::string url;
+ std::vector<char*> keyValuePairs;
};
} // namespace crow
diff --git a/crow/include/crow/routing.h b/crow/include/crow/routing.h
index f3fedd8..12daeb4 100644
--- a/crow/include/crow/routing.h
+++ b/crow/include/crow/routing.h
@@ -22,37 +22,37 @@
namespace crow {
class BaseRule {
public:
- BaseRule(std::string rule) : rule_(std::move(rule)) {}
+ BaseRule(std::string rule) : rule(std::move(rule)) {}
virtual ~BaseRule() {}
virtual void validate() = 0;
std::unique_ptr<BaseRule> upgrade() {
- if (rule_to_upgrade_) return std::move(rule_to_upgrade_);
+ if (ruleToUpgrade) return std::move(ruleToUpgrade);
return {};
}
- virtual void handle(const request&, response&, const routing_params&) = 0;
- virtual void handle_upgrade(const request&, response& res, SocketAdaptor&&) {
- res = response(boost::beast::http::status::not_found);
+ virtual void handle(const Request&, Response&, const RoutingParams&) = 0;
+ virtual void handleUpgrade(const Request&, Response& res, SocketAdaptor&&) {
+ res = Response(boost::beast::http::status::not_found);
res.end();
}
-#ifdef CROW_ENABLE_SSL
- virtual void handle_upgrade(const request&, response& res, SSLAdaptor&&) {
- res = response(boost::beast::http::status::not_found);
+#ifdef BMCWEB_ENABLE_SSL
+ virtual void handleUpgrade(const Request&, Response& res, SSLAdaptor&&) {
+ res = Response(boost::beast::http::status::not_found);
res.end();
}
#endif
- uint32_t get_methods() { return methods_; }
+ uint32_t getMethods() { return methodsBitfield; }
protected:
- uint32_t methods_{1 << (int)boost::beast::http::verb::get};
+ uint32_t methodsBitfield{1 << (int)boost::beast::http::verb::get};
- std::string rule_;
- std::string name_;
+ std::string rule;
+ std::string nameStr;
- std::unique_ptr<BaseRule> rule_to_upgrade_;
+ std::unique_ptr<BaseRule> ruleToUpgrade;
friend class Router;
template <typename T>
@@ -62,74 +62,74 @@
namespace detail {
namespace routing_handler_call_helper {
template <typename T, int Pos>
-struct call_pair {
+struct CallPair {
using type = T;
static const int pos = Pos;
};
template <typename H1>
-struct call_params {
+struct CallParams {
H1& handler;
- const routing_params& params;
- const request& req;
- response& res;
+ const RoutingParams& params;
+ const Request& req;
+ Response& res;
};
template <typename F, int NInt, int NUint, int NDouble, int NString,
typename S1, typename S2>
-struct call {};
+struct Call {};
template <typename F, int NInt, int NUint, int NDouble, int NString,
typename... Args1, typename... Args2>
-struct call<F, NInt, NUint, NDouble, NString, black_magic::S<int64_t, Args1...>,
+struct Call<F, NInt, NUint, NDouble, NString, black_magic::S<int64_t, Args1...>,
black_magic::S<Args2...>> {
void operator()(F cparams) {
using pushed = typename black_magic::S<Args2...>::template push_back<
- call_pair<int64_t, NInt>>;
- call<F, NInt + 1, NUint, NDouble, NString, black_magic::S<Args1...>,
+ CallPair<int64_t, NInt>>;
+ Call<F, NInt + 1, NUint, NDouble, NString, black_magic::S<Args1...>,
pushed>()(cparams);
}
};
template <typename F, int NInt, int NUint, int NDouble, int NString,
typename... Args1, typename... Args2>
-struct call<F, NInt, NUint, NDouble, NString,
+struct Call<F, NInt, NUint, NDouble, NString,
black_magic::S<uint64_t, Args1...>, black_magic::S<Args2...>> {
void operator()(F cparams) {
using pushed = typename black_magic::S<Args2...>::template push_back<
- call_pair<uint64_t, NUint>>;
- call<F, NInt, NUint + 1, NDouble, NString, black_magic::S<Args1...>,
+ CallPair<uint64_t, NUint>>;
+ Call<F, NInt, NUint + 1, NDouble, NString, black_magic::S<Args1...>,
pushed>()(cparams);
}
};
template <typename F, int NInt, int NUint, int NDouble, int NString,
typename... Args1, typename... Args2>
-struct call<F, NInt, NUint, NDouble, NString, black_magic::S<double, Args1...>,
+struct Call<F, NInt, NUint, NDouble, NString, black_magic::S<double, Args1...>,
black_magic::S<Args2...>> {
void operator()(F cparams) {
using pushed = typename black_magic::S<Args2...>::template push_back<
- call_pair<double, NDouble>>;
- call<F, NInt, NUint, NDouble + 1, NString, black_magic::S<Args1...>,
+ CallPair<double, NDouble>>;
+ Call<F, NInt, NUint, NDouble + 1, NString, black_magic::S<Args1...>,
pushed>()(cparams);
}
};
template <typename F, int NInt, int NUint, int NDouble, int NString,
typename... Args1, typename... Args2>
-struct call<F, NInt, NUint, NDouble, NString,
+struct Call<F, NInt, NUint, NDouble, NString,
black_magic::S<std::string, Args1...>, black_magic::S<Args2...>> {
void operator()(F cparams) {
using pushed = typename black_magic::S<Args2...>::template push_back<
- call_pair<std::string, NString>>;
- call<F, NInt, NUint, NDouble, NString + 1, black_magic::S<Args1...>,
+ CallPair<std::string, NString>>;
+ Call<F, NInt, NUint, NDouble, NString + 1, black_magic::S<Args1...>,
pushed>()(cparams);
}
};
template <typename F, int NInt, int NUint, int NDouble, int NString,
typename... Args1>
-struct call<F, NInt, NUint, NDouble, NString, black_magic::S<>,
+struct Call<F, NInt, NUint, NDouble, NString, black_magic::S<>,
black_magic::S<Args1...>> {
void operator()(F cparams) {
cparams.handler(
@@ -146,26 +146,26 @@
typename std::enable_if<
!std::is_same<
typename std::tuple_element<0, std::tuple<Args..., void>>::type,
- const request&>::value,
+ const Request&>::value,
int>::type = 0) {
- handler_ = (
-#ifdef CROW_CAN_USE_CPP14
+ handler = (
+#ifdef BMCWEB_CAN_USE_CPP14
[f = std::move(f)]
#else
[f]
#endif
- (const request&, response& res, Args... args) {
- res = response(f(args...));
+ (const Request&, Response& res, Args... args) {
+ res = Response(f(args...));
res.end();
});
}
template <typename Req, typename... Args>
- struct req_handler_wrapper {
- req_handler_wrapper(Func f) : f(std::move(f)) {}
+ struct ReqHandlerWrapper {
+ ReqHandlerWrapper(Func f) : f(std::move(f)) {}
- void operator()(const request& req, response& res, Args... args) {
- res = response(f(req, args...));
+ void operator()(const Request& req, Response& res, Args... args) {
+ res = Response(f(req, args...));
res.end();
}
@@ -178,16 +178,16 @@
typename std::enable_if<
std::is_same<
typename std::tuple_element<0, std::tuple<Args..., void>>::type,
- const request&>::value &&
+ const Request&>::value &&
!std::is_same<typename std::tuple_element<
1, std::tuple<Args..., void, void>>::type,
- response&>::value,
+ Response&>::value,
int>::type = 0) {
- handler_ = req_handler_wrapper<Args...>(std::move(f));
- /*handler_ = (
+ handler = ReqHandlerWrapper<Args...>(std::move(f));
+ /*handler = (
[f = std::move(f)]
- (const request& req, response& res, Args... args){
- res = response(f(req, args...));
+ (const Request& req, Response& res, Args... args){
+ res = Response(f(req, args...));
res.end();
});*/
}
@@ -198,45 +198,45 @@
typename std::enable_if<
std::is_same<
typename std::tuple_element<0, std::tuple<Args..., void>>::type,
- const request&>::value &&
+ const Request&>::value &&
std::is_same<typename std::tuple_element<
1, std::tuple<Args..., void, void>>::type,
- response&>::value,
+ Response&>::value,
int>::type = 0) {
- handler_ = std::move(f);
+ handler = std::move(f);
}
template <typename... Args>
- struct handler_type_helper {
+ struct HandlerTypeHelper {
using type =
- std::function<void(const crow::request&, crow::response&, Args...)>;
+ std::function<void(const crow::Request&, crow::Response&, Args...)>;
using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
};
template <typename... Args>
- struct handler_type_helper<const request&, Args...> {
+ struct HandlerTypeHelper<const Request&, Args...> {
using type =
- std::function<void(const crow::request&, crow::response&, Args...)>;
+ std::function<void(const crow::Request&, crow::Response&, Args...)>;
using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
};
template <typename... Args>
- struct handler_type_helper<const request&, response&, Args...> {
+ struct HandlerTypeHelper<const Request&, Response&, Args...> {
using type =
- std::function<void(const crow::request&, crow::response&, Args...)>;
+ std::function<void(const crow::Request&, crow::Response&, Args...)>;
using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
};
- typename handler_type_helper<ArgsWrapped...>::type handler_;
+ typename HandlerTypeHelper<ArgsWrapped...>::type handler;
- void operator()(const request& req, response& res,
- const routing_params& params) {
- detail::routing_handler_call_helper::call<
- detail::routing_handler_call_helper::call_params<decltype(handler_)>, 0,
- 0, 0, 0, typename handler_type_helper<ArgsWrapped...>::args_type,
+ void operator()(const Request& req, Response& res,
+ const RoutingParams& params) {
+ detail::routing_handler_call_helper::Call<
+ detail::routing_handler_call_helper::CallParams<decltype(handler)>, 0,
+ 0, 0, 0, typename HandlerTypeHelper<ArgsWrapped...>::args_type,
black_magic::S<>>()(
- detail::routing_handler_call_helper::call_params<decltype(handler_)>{
- handler_, params, req, res});
+ detail::routing_handler_call_helper::CallParams<decltype(handler)>{
+ handler, params, req, res});
}
};
} // namespace routing_handler_call_helper
@@ -250,82 +250,82 @@
void validate() override {}
- void handle(const request&, response& res, const routing_params&) override {
- res = response(boost::beast::http::status::not_found);
+ void handle(const Request&, Response& res, const RoutingParams&) override {
+ res = Response(boost::beast::http::status::not_found);
res.end();
}
- void handle_upgrade(const request& req, response&,
- SocketAdaptor&& adaptor) override {
- new crow::websocket::Connection<SocketAdaptor>(
- req, std::move(adaptor), open_handler_, message_handler_,
- close_handler_, error_handler_);
+ void handleUpgrade(const Request& req, Response&,
+ SocketAdaptor&& adaptor) override {
+ new crow::websocket::ConnectionImpl<SocketAdaptor>(
+ req, std::move(adaptor), openHandler, messageHandler, closeHandler,
+ errorHandler);
}
-#ifdef CROW_ENABLE_SSL
- void handle_upgrade(const request& req, response&,
- SSLAdaptor&& adaptor) override {
- new crow::websocket::Connection<SSLAdaptor>(req, std::move(adaptor),
- open_handler_, message_handler_,
- close_handler_, error_handler_);
+#ifdef BMCWEB_ENABLE_SSL
+ void handleUpgrade(const Request& req, Response&,
+ SSLAdaptor&& adaptor) override {
+ new crow::websocket::ConnectionImpl<SSLAdaptor>(req, std::move(adaptor),
+ openHandler, messageHandler,
+ closeHandler, errorHandler);
}
#endif
template <typename Func>
self_t& onopen(Func f) {
- open_handler_ = f;
+ openHandler = f;
return *this;
}
template <typename Func>
self_t& onmessage(Func f) {
- message_handler_ = f;
+ messageHandler = f;
return *this;
}
template <typename Func>
self_t& onclose(Func f) {
- close_handler_ = f;
+ closeHandler = f;
return *this;
}
template <typename Func>
self_t& onerror(Func f) {
- error_handler_ = f;
+ errorHandler = f;
return *this;
}
protected:
- std::function<void(crow::websocket::connection&)> open_handler_;
- std::function<void(crow::websocket::connection&, const std::string&, bool)>
- message_handler_;
- std::function<void(crow::websocket::connection&, const std::string&)>
- close_handler_;
- std::function<void(crow::websocket::connection&)> error_handler_;
+ std::function<void(crow::websocket::Connection&)> openHandler;
+ std::function<void(crow::websocket::Connection&, const std::string&, bool)>
+ messageHandler;
+ std::function<void(crow::websocket::Connection&, const std::string&)>
+ closeHandler;
+ std::function<void(crow::websocket::Connection&)> errorHandler;
};
template <typename T>
struct RuleParameterTraits {
using self_t = T;
WebSocketRule& websocket() {
- auto p = new WebSocketRule(((self_t*)this)->rule_);
- ((self_t*)this)->rule_to_upgrade_.reset(p);
+ auto p = new WebSocketRule(((self_t*)this)->rule);
+ ((self_t*)this)->ruleToUpgrade.reset(p);
return *p;
}
self_t& name(std::string name) noexcept {
- ((self_t*)this)->name_ = std::move(name);
+ ((self_t*)this)->nameStr = std::move(name);
return (self_t&)*this;
}
self_t& methods(boost::beast::http::verb method) {
- ((self_t*)this)->methods_ = 1 << (int)method;
+ ((self_t*)this)->methodsBitfield = 1 << (int)method;
return (self_t&)*this;
}
template <typename... MethodArgs>
self_t& methods(boost::beast::http::verb method, MethodArgs... args_method) {
methods(args_method...);
- ((self_t*)this)->methods_ |= 1 << (int)method;
+ ((self_t*)this)->methodsBitfield |= 1 << (int)method;
return (self_t&)*this;
}
};
@@ -335,42 +335,42 @@
DynamicRule(std::string rule) : BaseRule(std::move(rule)) {}
void validate() override {
- if (!erased_handler_) {
- throw std::runtime_error(name_ + (!name_.empty() ? ": " : "") +
- "no handler for url " + rule_);
+ if (!erasedHandler) {
+ throw std::runtime_error(nameStr + (!nameStr.empty() ? ": " : "") +
+ "no handler for url " + rule);
}
}
- void handle(const request& req, response& res,
- const routing_params& params) override {
- erased_handler_(req, res, params);
+ void handle(const Request& req, Response& res,
+ const RoutingParams& params) override {
+ erasedHandler(req, res, params);
}
template <typename Func>
void operator()(Func f) {
using function_t = utility::function_traits<Func>;
- erased_handler_ =
+ erasedHandler =
wrap(std::move(f), black_magic::gen_seq<function_t::arity>());
}
- // enable_if Arg1 == request && Arg2 == response
+ // enable_if Arg1 == request && Arg2 == Response
// enable_if Arg1 == request && Arg2 != resposne
// enable_if Arg1 != request
template <typename Func, unsigned... Indices>
- std::function<void(const request&, response&, const routing_params&)> wrap(
- Func f, black_magic::seq<Indices...>) {
+ std::function<void(const Request&, Response&, const RoutingParams&)> wrap(
+ Func f, black_magic::Seq<Indices...>) {
using function_t = utility::function_traits<Func>;
- if (!black_magic::is_parameter_tag_compatible(
- black_magic::get_parameter_tag_runtime(rule_.c_str()),
+ if (!black_magic::isParameterTagCompatible(
+ black_magic::getParameterTagRuntime(rule.c_str()),
black_magic::compute_parameter_tag_from_args_list<
typename function_t::template arg<Indices>...>::value)) {
throw std::runtime_error(
- "route_dynamic: Handler type is mismatched with URL parameters: " +
- rule_);
+ "routeDynamic: Handler type is mismatched with URL parameters: " +
+ rule);
}
auto ret = detail::routing_handler_call_helper::Wrapped<
Func, typename function_t::template arg<Indices>...>();
@@ -381,13 +381,13 @@
template <typename Func>
void operator()(std::string name, Func&& f) {
- name_ = std::move(name);
+ nameStr = std::move(name);
(*this).template operator()<Func>(std::forward(f));
}
private:
- std::function<void(const request&, response&, const routing_params&)>
- erased_handler_;
+ std::function<void(const Request&, Response&, const RoutingParams&)>
+ erasedHandler;
};
template <typename... Args>
@@ -399,9 +399,9 @@
TaggedRule(std::string rule) : BaseRule(std::move(rule)) {}
void validate() override {
- if (!handler_) {
- throw std::runtime_error(name_ + (!name_.empty() ? ": " : "") +
- "no handler for url " + rule_);
+ if (!handler) {
+ throw std::runtime_error(nameStr + (!nameStr.empty() ? ": " : "") +
+ "no handler for url " + rule);
}
}
@@ -412,15 +412,15 @@
static_assert(
black_magic::CallHelper<Func, black_magic::S<Args...>>::value ||
black_magic::CallHelper<
- Func, black_magic::S<crow::request, Args...>>::value,
+ Func, black_magic::S<crow::Request, Args...>>::value,
"Handler type is mismatched with URL parameters");
static_assert(
!std::is_same<void, decltype(f(std::declval<Args>()...))>::value,
"Handler function cannot have void return type; valid return types: "
"string, int, crow::resposne, nlohmann::json");
- handler_ = [f = std::move(f)](const request&, response& res, Args... args) {
- res = response(f(args...));
+ handler = [f = std::move(f)](const Request&, Response& res, Args... args) {
+ res = Response(f(args...));
res.end();
};
}
@@ -429,23 +429,23 @@
typename std::enable_if<
!black_magic::CallHelper<Func, black_magic::S<Args...>>::value &&
black_magic::CallHelper<
- Func, black_magic::S<crow::request, Args...>>::value,
+ Func, black_magic::S<crow::Request, Args...>>::value,
void>::type
operator()(Func&& f) {
static_assert(
black_magic::CallHelper<Func, black_magic::S<Args...>>::value ||
black_magic::CallHelper<
- Func, black_magic::S<crow::request, Args...>>::value,
+ Func, black_magic::S<crow::Request, Args...>>::value,
"Handler type is mismatched with URL parameters");
static_assert(
- !std::is_same<void, decltype(f(std::declval<crow::request>(),
+ !std::is_same<void, decltype(f(std::declval<crow::Request>(),
std::declval<Args>()...))>::value,
"Handler function cannot have void return type; valid return types: "
"string, int, crow::resposne,nlohmann::json");
- handler_ = [f = std::move(f)](const crow::request& req, crow::response& res,
- Args... args) {
- res = response(f(req, args...));
+ handler = [f = std::move(f)](const crow::Request& req, crow::Response& res,
+ Args... args) {
+ res = Response(f(req, args...));
res.end();
};
}
@@ -454,75 +454,75 @@
typename std::enable_if<
!black_magic::CallHelper<Func, black_magic::S<Args...>>::value &&
!black_magic::CallHelper<
- Func, black_magic::S<crow::request, Args...>>::value,
+ Func, black_magic::S<crow::Request, Args...>>::value,
void>::type
operator()(Func&& f) {
static_assert(
black_magic::CallHelper<Func, black_magic::S<Args...>>::value ||
black_magic::CallHelper<
- Func, black_magic::S<crow::request, Args...>>::value ||
+ Func, black_magic::S<crow::Request, Args...>>::value ||
black_magic::CallHelper<
Func,
- black_magic::S<crow::request, crow::response&, Args...>>::value,
+ black_magic::S<crow::Request, crow::Response&, Args...>>::value,
"Handler type is mismatched with URL parameters");
static_assert(
- std::is_same<void, decltype(f(std::declval<crow::request>(),
- std::declval<crow::response&>(),
+ std::is_same<void, decltype(f(std::declval<crow::Request>(),
+ std::declval<crow::Response&>(),
std::declval<Args>()...))>::value,
"Handler function with response argument should have void return type");
- handler_ = std::move(f);
+ handler = std::move(f);
}
template <typename Func>
void operator()(std::string name, Func&& f) {
- name_ = std::move(name);
+ nameStr = std::move(name);
(*this).template operator()<Func>(std::forward(f));
}
- void handle(const request& req, response& res,
- const routing_params& params) override {
- detail::routing_handler_call_helper::call<
- detail::routing_handler_call_helper::call_params<decltype(handler_)>, 0,
+ void handle(const Request& req, Response& res,
+ const RoutingParams& params) override {
+ detail::routing_handler_call_helper::Call<
+ detail::routing_handler_call_helper::CallParams<decltype(handler)>, 0,
0, 0, 0, black_magic::S<Args...>, black_magic::S<>>()(
- detail::routing_handler_call_helper::call_params<decltype(handler_)>{
- handler_, params, req, res});
+ detail::routing_handler_call_helper::CallParams<decltype(handler)>{
+ handler, params, req, res});
}
private:
- std::function<void(const crow::request&, crow::response&, Args...)> handler_;
+ std::function<void(const crow::Request&, crow::Response&, Args...)> handler;
};
-const int RULE_SPECIAL_REDIRECT_SLASH = 1;
+const int ruleSpecialRedirectSlash = 1;
class Trie {
public:
struct Node {
- unsigned rule_index{};
- std::array<unsigned, (int)ParamType::MAX> param_childrens{};
+ unsigned ruleIndex{};
+ std::array<unsigned, (int)ParamType::MAX> paramChildrens{};
boost::container::flat_map<std::string, unsigned> children;
- bool IsSimpleNode() const {
- return !rule_index &&
- std::all_of(std::begin(param_childrens), std::end(param_childrens),
+ bool isSimpleNode() const {
+ return !ruleIndex &&
+ std::all_of(std::begin(paramChildrens), std::end(paramChildrens),
[](unsigned x) { return !x; });
}
};
- Trie() : nodes_(1) {}
+ Trie() : nodes(1) {}
private:
void optimizeNode(Node* node) {
- for (auto x : node->param_childrens) {
+ for (auto x : node->paramChildrens) {
if (!x) continue;
- Node* child = &nodes_[x];
+ Node* child = &nodes[x];
optimizeNode(child);
}
if (node->children.empty()) return;
bool mergeWithChild = true;
for (auto& kv : node->children) {
- Node* child = &nodes_[kv.second];
- if (!child->IsSimpleNode()) {
+ Node* child = &nodes[kv.second];
+ if (!child->isSimpleNode()) {
mergeWithChild = false;
break;
}
@@ -530,16 +530,16 @@
if (mergeWithChild) {
decltype(node->children) merged;
for (auto& kv : node->children) {
- Node* child = &nodes_[kv.second];
- for (auto& child_kv : child->children) {
- merged[kv.first + child_kv.first] = child_kv.second;
+ Node* child = &nodes[kv.second];
+ for (auto& childKv : child->children) {
+ merged[kv.first + childKv.first] = childKv.second;
}
}
node->children = std::move(merged);
optimizeNode(node);
} else {
for (auto& kv : node->children) {
- Node* child = &nodes_[kv.second];
+ Node* child = &nodes[kv.second];
optimizeNode(child);
}
}
@@ -549,73 +549,72 @@
public:
void validate() {
- if (!head()->IsSimpleNode())
+ if (!head()->isSimpleNode())
throw std::runtime_error("Internal error: Trie header should be simple!");
optimize();
}
- void find_route_indexes(const std::string& req_url,
- std::vector<unsigned>& route_indexes,
- const Node* node = nullptr, unsigned pos = 0) {
+ void findRouteIndexes(const std::string& req_url,
+ std::vector<unsigned>& route_indexes,
+ const Node* node = nullptr, unsigned pos = 0) {
if (node == nullptr) {
node = head();
}
for (auto& kv : node->children) {
const std::string& fragment = kv.first;
- const Node* child = &nodes_[kv.second];
+ const Node* child = &nodes[kv.second];
if (pos >= req_url.size()) {
- if (child->rule_index != 0 && fragment != "/") {
- route_indexes.push_back(child->rule_index);
+ if (child->ruleIndex != 0 && fragment != "/") {
+ route_indexes.push_back(child->ruleIndex);
}
- find_route_indexes(req_url, route_indexes, child,
- pos + fragment.size());
+ findRouteIndexes(req_url, route_indexes, child, pos + fragment.size());
} else {
if (req_url.compare(pos, fragment.size(), fragment) == 0) {
- find_route_indexes(req_url, route_indexes, child,
- pos + fragment.size());
+ findRouteIndexes(req_url, route_indexes, child,
+ pos + fragment.size());
}
}
}
}
- std::pair<unsigned, routing_params> find(
+ std::pair<unsigned, RoutingParams> find(
const boost::string_view req_url, const Node* node = nullptr,
- unsigned pos = 0, routing_params* params = nullptr) const {
- routing_params empty;
+ unsigned pos = 0, RoutingParams* params = nullptr) const {
+ RoutingParams empty;
if (params == nullptr) params = ∅
unsigned found{};
- routing_params match_params;
+ RoutingParams matchParams;
if (node == nullptr) node = head();
- if (pos == req_url.size()) return {node->rule_index, *params};
+ if (pos == req_url.size()) return {node->ruleIndex, *params};
- auto update_found =
- [&found, &match_params](std::pair<unsigned, routing_params>& ret) {
- if (ret.first && (!found || found > ret.first)) {
- found = ret.first;
- match_params = std::move(ret.second);
- }
- };
+ auto updateFound = [&found,
+ &matchParams](std::pair<unsigned, RoutingParams>& ret) {
+ if (ret.first && (!found || found > ret.first)) {
+ found = ret.first;
+ matchParams = std::move(ret.second);
+ }
+ };
- if (node->param_childrens[(int)ParamType::INT]) {
+ if (node->paramChildrens[(int)ParamType::INT]) {
char c = req_url[pos];
if ((c >= '0' && c <= '9') || c == '+' || c == '-') {
char* eptr;
errno = 0;
long long int value = std::strtoll(req_url.data() + pos, &eptr, 10);
if (errno != ERANGE && eptr != req_url.data() + pos) {
- params->int_params.push_back(value);
+ params->intParams.push_back(value);
auto ret =
- find(req_url, &nodes_[node->param_childrens[(int)ParamType::INT]],
+ find(req_url, &nodes[node->paramChildrens[(int)ParamType::INT]],
eptr - req_url.data(), params);
- update_found(ret);
- params->int_params.pop_back();
+ updateFound(ret);
+ params->intParams.pop_back();
}
}
}
- if (node->param_childrens[(int)ParamType::UINT]) {
+ if (node->paramChildrens[(int)ParamType::UINT]) {
char c = req_url[pos];
if ((c >= '0' && c <= '9') || c == '+') {
char* eptr;
@@ -623,76 +622,76 @@
unsigned long long int value =
std::strtoull(req_url.data() + pos, &eptr, 10);
if (errno != ERANGE && eptr != req_url.data() + pos) {
- params->uint_params.push_back(value);
- auto ret = find(req_url,
- &nodes_[node->param_childrens[(int)ParamType::UINT]],
- eptr - req_url.data(), params);
- update_found(ret);
- params->uint_params.pop_back();
+ params->uintParams.push_back(value);
+ auto ret =
+ find(req_url, &nodes[node->paramChildrens[(int)ParamType::UINT]],
+ eptr - req_url.data(), params);
+ updateFound(ret);
+ params->uintParams.pop_back();
}
}
}
- if (node->param_childrens[(int)ParamType::DOUBLE]) {
+ if (node->paramChildrens[(int)ParamType::DOUBLE]) {
char c = req_url[pos];
if ((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.') {
char* eptr;
errno = 0;
double value = std::strtod(req_url.data() + pos, &eptr);
if (errno != ERANGE && eptr != req_url.data() + pos) {
- params->double_params.push_back(value);
- auto ret = find(
- req_url, &nodes_[node->param_childrens[(int)ParamType::DOUBLE]],
- eptr - req_url.data(), params);
- update_found(ret);
- params->double_params.pop_back();
+ params->doubleParams.push_back(value);
+ auto ret = find(req_url,
+ &nodes[node->paramChildrens[(int)ParamType::DOUBLE]],
+ eptr - req_url.data(), params);
+ updateFound(ret);
+ params->doubleParams.pop_back();
}
}
}
- if (node->param_childrens[(int)ParamType::STRING]) {
+ if (node->paramChildrens[(int)ParamType::STRING]) {
size_t epos = pos;
for (; epos < req_url.size(); epos++) {
if (req_url[epos] == '/') break;
}
if (epos != pos) {
- params->string_params.emplace_back(req_url.substr(pos, epos - pos));
- auto ret = find(req_url,
- &nodes_[node->param_childrens[(int)ParamType::STRING]],
- epos, params);
- update_found(ret);
- params->string_params.pop_back();
+ params->stringParams.emplace_back(req_url.substr(pos, epos - pos));
+ auto ret =
+ find(req_url, &nodes[node->paramChildrens[(int)ParamType::STRING]],
+ epos, params);
+ updateFound(ret);
+ params->stringParams.pop_back();
}
}
- if (node->param_childrens[(int)ParamType::PATH]) {
+ if (node->paramChildrens[(int)ParamType::PATH]) {
size_t epos = req_url.size();
if (epos != pos) {
- params->string_params.emplace_back(req_url.substr(pos, epos - pos));
+ params->stringParams.emplace_back(req_url.substr(pos, epos - pos));
auto ret =
- find(req_url, &nodes_[node->param_childrens[(int)ParamType::PATH]],
+ find(req_url, &nodes[node->paramChildrens[(int)ParamType::PATH]],
epos, params);
- update_found(ret);
- params->string_params.pop_back();
+ updateFound(ret);
+ params->stringParams.pop_back();
}
}
for (auto& kv : node->children) {
const std::string& fragment = kv.first;
- const Node* child = &nodes_[kv.second];
+ const Node* child = &nodes[kv.second];
if (req_url.compare(pos, fragment.size(), fragment) == 0) {
auto ret = find(req_url, child, pos + fragment.size(), params);
- update_found(ret);
+ updateFound(ret);
}
}
- return {found, match_params};
+ return {found, matchParams};
}
- void add(const std::string& url, unsigned rule_index) {
+ void add(const std::string& url, unsigned ruleIndex) {
unsigned idx{0};
for (unsigned i = 0; i < url.size(); i++) {
@@ -710,11 +709,11 @@
for (auto& x : paramTraits) {
if (url.compare(i, x.name.size(), x.name) == 0) {
- if (!nodes_[idx].param_childrens[(int)x.type]) {
- auto new_node_idx = new_node();
- nodes_[idx].param_childrens[(int)x.type] = new_node_idx;
+ if (!nodes[idx].paramChildrens[(int)x.type]) {
+ auto newNodeIdx = newNode();
+ nodes[idx].paramChildrens[(int)x.type] = newNodeIdx;
}
- idx = nodes_[idx].param_childrens[(int)x.type];
+ idx = nodes[idx].paramChildrens[(int)x.type];
i += x.name.size();
break;
}
@@ -723,113 +722,113 @@
i--;
} else {
std::string piece(&c, 1);
- if (!nodes_[idx].children.count(piece)) {
- auto new_node_idx = new_node();
- nodes_[idx].children.emplace(piece, new_node_idx);
+ if (!nodes[idx].children.count(piece)) {
+ auto newNodeIdx = newNode();
+ nodes[idx].children.emplace(piece, newNodeIdx);
}
- idx = nodes_[idx].children[piece];
+ idx = nodes[idx].children[piece];
}
}
- if (nodes_[idx].rule_index)
+ if (nodes[idx].ruleIndex)
throw std::runtime_error("handler already exists for " + url);
- nodes_[idx].rule_index = rule_index;
+ nodes[idx].ruleIndex = ruleIndex;
}
private:
- void debug_node_print(Node* n, int level) {
+ void debugNodePrint(Node* n, int level) {
for (int i = 0; i < (int)ParamType::MAX; i++) {
- if (n->param_childrens[i]) {
- CROW_LOG_DEBUG << std::string(
- 2 * level, ' ') /*<< "("<<n->param_childrens[i]<<") "*/;
+ if (n->paramChildrens[i]) {
+ BMCWEB_LOG_DEBUG << std::string(
+ 2 * level, ' ') /*<< "("<<n->paramChildrens[i]<<") "*/;
switch ((ParamType)i) {
case ParamType::INT:
- CROW_LOG_DEBUG << "<int>";
+ BMCWEB_LOG_DEBUG << "<int>";
break;
case ParamType::UINT:
- CROW_LOG_DEBUG << "<uint>";
+ BMCWEB_LOG_DEBUG << "<uint>";
break;
case ParamType::DOUBLE:
- CROW_LOG_DEBUG << "<float>";
+ BMCWEB_LOG_DEBUG << "<float>";
break;
case ParamType::STRING:
- CROW_LOG_DEBUG << "<str>";
+ BMCWEB_LOG_DEBUG << "<str>";
break;
case ParamType::PATH:
- CROW_LOG_DEBUG << "<path>";
+ BMCWEB_LOG_DEBUG << "<path>";
break;
default:
- CROW_LOG_DEBUG << "<ERROR>";
+ BMCWEB_LOG_DEBUG << "<ERROR>";
break;
}
- debug_node_print(&nodes_[n->param_childrens[i]], level + 1);
+ debugNodePrint(&nodes[n->paramChildrens[i]], level + 1);
}
}
for (auto& kv : n->children) {
- CROW_LOG_DEBUG << std::string(2 * level,
- ' ') /*<< "(" << kv.second << ") "*/
- << kv.first;
- debug_node_print(&nodes_[kv.second], level + 1);
+ BMCWEB_LOG_DEBUG << std::string(2 * level,
+ ' ') /*<< "(" << kv.second << ") "*/
+ << kv.first;
+ debugNodePrint(&nodes[kv.second], level + 1);
}
}
public:
- void debug_print() { debug_node_print(head(), 0); }
+ void debugPrint() { debugNodePrint(head(), 0); }
private:
- const Node* head() const { return &nodes_.front(); }
+ const Node* head() const { return &nodes.front(); }
- Node* head() { return &nodes_.front(); }
+ Node* head() { return &nodes.front(); }
- unsigned new_node() {
- nodes_.resize(nodes_.size() + 1);
- return nodes_.size() - 1;
+ unsigned newNode() {
+ nodes.resize(nodes.size() + 1);
+ return nodes.size() - 1;
}
- std::vector<Node> nodes_;
+ std::vector<Node> nodes;
};
class Router {
public:
- Router() : rules_(2) {}
+ Router() : rules(2) {}
- DynamicRule& new_rule_dynamic(const std::string& rule) {
+ DynamicRule& newRuleDynamic(const std::string& rule) {
std::unique_ptr<DynamicRule> ruleObject =
std::make_unique<DynamicRule>(rule);
DynamicRule* ptr = ruleObject.get();
- internal_add_rule_object(rule, std::move(ruleObject));
+ internalAddRuleObject(rule, std::move(ruleObject));
return *ptr;
}
template <uint64_t N>
- typename black_magic::arguments<N>::type::template rebind<TaggedRule>&
- new_rule_tagged(const std::string& rule) {
+ typename black_magic::Arguments<N>::type::template rebind<TaggedRule>&
+ newRuleTagged(const std::string& rule) {
using RuleT =
- typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
+ typename black_magic::Arguments<N>::type::template rebind<TaggedRule>;
std::unique_ptr<RuleT> ruleObject = std::make_unique<RuleT>(rule);
RuleT* ptr = ruleObject.get();
- internal_add_rule_object(rule, std::move(ruleObject));
+ internalAddRuleObject(rule, std::move(ruleObject));
return *ptr;
}
- void internal_add_rule_object(const std::string& rule,
- std::unique_ptr<BaseRule> ruleObject) {
- rules_.emplace_back(std::move(ruleObject));
- trie_.add(rule, rules_.size() - 1);
+ void internalAddRuleObject(const std::string& rule,
+ std::unique_ptr<BaseRule> ruleObject) {
+ rules.emplace_back(std::move(ruleObject));
+ trie.add(rule, rules.size() - 1);
// directory case:
// request to `/about' url matches `/about/' rule
if (rule.size() > 2 && rule.back() == '/') {
- trie_.add(rule.substr(0, rule.size() - 1), rules_.size() - 1);
+ trie.add(rule.substr(0, rule.size() - 1), rules.size() - 1);
}
}
void validate() {
- trie_.validate();
- for (auto& rule : rules_) {
+ trie.validate();
+ for (auto& rule : rules) {
if (rule) {
auto upgraded = rule->upgrade();
if (upgraded) rule = std::move(upgraded);
@@ -839,148 +838,148 @@
}
template <typename Adaptor>
- void handle_upgrade(const request& req, response& res, Adaptor&& adaptor) {
- auto found = trie_.find(req.url);
- unsigned rule_index = found.first;
- if (!rule_index) {
- CROW_LOG_DEBUG << "Cannot match rules " << req.url;
- res = response(boost::beast::http::status::not_found);
+ void handleUpgrade(const Request& req, Response& res, Adaptor&& adaptor) {
+ auto found = trie.find(req.url);
+ unsigned ruleIndex = found.first;
+ if (!ruleIndex) {
+ BMCWEB_LOG_DEBUG << "Cannot match rules " << req.url;
+ res = Response(boost::beast::http::status::not_found);
res.end();
return;
}
- if (rule_index >= rules_.size())
+ if (ruleIndex >= rules.size())
throw std::runtime_error("Trie internal structure corrupted!");
- if (rule_index == RULE_SPECIAL_REDIRECT_SLASH) {
- CROW_LOG_INFO << "Redirecting to a url with trailing slash: " << req.url;
- res = response(boost::beast::http::status::moved_permanently);
+ if (ruleIndex == ruleSpecialRedirectSlash) {
+ BMCWEB_LOG_INFO << "Redirecting to a url with trailing slash: "
+ << req.url;
+ res = Response(boost::beast::http::status::moved_permanently);
// TODO absolute url building
- if (req.get_header_value("Host").empty()) {
- res.add_header("Location", std::string(req.url) + "/");
+ if (req.getHeaderValue("Host").empty()) {
+ res.addHeader("Location", std::string(req.url) + "/");
} else {
- res.add_header("Location",
- req.is_secure
- ? "https://"
- : "http://" +
- std::string(req.get_header_value("Host")) +
- std::string(req.url) + "/");
+ res.addHeader(
+ "Location",
+ req.isSecure ? "https://"
+ : "http://" + std::string(req.getHeaderValue("Host")) +
+ std::string(req.url) + "/");
}
res.end();
return;
}
- if ((rules_[rule_index]->get_methods() & (1 << (uint32_t)req.method())) ==
- 0) {
- CROW_LOG_DEBUG << "Rule found but method mismatch: " << req.url
- << " with " << req.method_string() << "("
- << (uint32_t)req.method() << ") / "
- << rules_[rule_index]->get_methods();
- res = response(boost::beast::http::status::not_found);
+ if ((rules[ruleIndex]->getMethods() & (1 << (uint32_t)req.method())) == 0) {
+ BMCWEB_LOG_DEBUG << "Rule found but method mismatch: " << req.url
+ << " with " << req.methodString() << "("
+ << (uint32_t)req.method() << ") / "
+ << rules[ruleIndex]->getMethods();
+ res = Response(boost::beast::http::status::not_found);
res.end();
return;
}
- CROW_LOG_DEBUG << "Matched rule (upgrade) '" << rules_[rule_index]->rule_
- << "' " << (uint32_t)req.method() << " / "
- << rules_[rule_index]->get_methods();
+ BMCWEB_LOG_DEBUG << "Matched rule (upgrade) '" << rules[ruleIndex]->rule
+ << "' " << (uint32_t)req.method() << " / "
+ << rules[ruleIndex]->getMethods();
// any uncaught exceptions become 500s
try {
- rules_[rule_index]->handle_upgrade(req, res, std::move(adaptor));
+ rules[ruleIndex]->handleUpgrade(req, res, std::move(adaptor));
} catch (std::exception& e) {
- CROW_LOG_ERROR << "An uncaught exception occurred: " << e.what();
- res = response(boost::beast::http::status::internal_server_error);
+ BMCWEB_LOG_ERROR << "An uncaught exception occurred: " << e.what();
+ res = Response(boost::beast::http::status::internal_server_error);
res.end();
return;
} catch (...) {
- CROW_LOG_ERROR << "An uncaught exception occurred. The type was unknown "
- "so no information was available.";
- res = response(boost::beast::http::status::internal_server_error);
+ BMCWEB_LOG_ERROR
+ << "An uncaught exception occurred. The type was unknown "
+ "so no information was available.";
+ res = Response(boost::beast::http::status::internal_server_error);
res.end();
return;
}
}
- void handle(const request& req, response& res) {
- auto found = trie_.find(req.url);
+ void handle(const Request& req, Response& res) {
+ auto found = trie.find(req.url);
- unsigned rule_index = found.first;
+ unsigned ruleIndex = found.first;
- if (!rule_index) {
- CROW_LOG_DEBUG << "Cannot match rules " << req.url;
+ if (!ruleIndex) {
+ BMCWEB_LOG_DEBUG << "Cannot match rules " << req.url;
res.result(boost::beast::http::status::not_found);
res.end();
return;
}
- if (rule_index >= rules_.size())
+ if (ruleIndex >= rules.size())
throw std::runtime_error("Trie internal structure corrupted!");
- if (rule_index == RULE_SPECIAL_REDIRECT_SLASH) {
- CROW_LOG_INFO << "Redirecting to a url with trailing slash: " << req.url;
- res = response(boost::beast::http::status::moved_permanently);
+ if (ruleIndex == ruleSpecialRedirectSlash) {
+ BMCWEB_LOG_INFO << "Redirecting to a url with trailing slash: "
+ << req.url;
+ res = Response(boost::beast::http::status::moved_permanently);
// TODO absolute url building
- if (req.get_header_value("Host").empty()) {
- res.add_header("Location", std::string(req.url) + "/");
+ if (req.getHeaderValue("Host").empty()) {
+ res.addHeader("Location", std::string(req.url) + "/");
} else {
- res.add_header("Location",
- (req.is_secure ? "https://" : "http://") +
- std::string(req.get_header_value("Host")) +
- std::string(req.url) + "/");
+ res.addHeader("Location", (req.isSecure ? "https://" : "http://") +
+ std::string(req.getHeaderValue("Host")) +
+ std::string(req.url) + "/");
}
res.end();
return;
}
- if ((rules_[rule_index]->get_methods() & (1 << (uint32_t)req.method())) ==
- 0) {
- CROW_LOG_DEBUG << "Rule found but method mismatch: " << req.url
- << " with " << req.method_string() << "("
- << (uint32_t)req.method() << ") / "
- << rules_[rule_index]->get_methods();
- res = response(boost::beast::http::status::not_found);
+ if ((rules[ruleIndex]->getMethods() & (1 << (uint32_t)req.method())) == 0) {
+ BMCWEB_LOG_DEBUG << "Rule found but method mismatch: " << req.url
+ << " with " << req.methodString() << "("
+ << (uint32_t)req.method() << ") / "
+ << rules[ruleIndex]->getMethods();
+ res = Response(boost::beast::http::status::not_found);
res.end();
return;
}
- CROW_LOG_DEBUG << "Matched rule '" << rules_[rule_index]->rule_ << "' "
- << (uint32_t)req.method() << " / "
- << rules_[rule_index]->get_methods();
+ BMCWEB_LOG_DEBUG << "Matched rule '" << rules[ruleIndex]->rule << "' "
+ << (uint32_t)req.method() << " / "
+ << rules[ruleIndex]->getMethods();
// any uncaught exceptions become 500s
try {
- rules_[rule_index]->handle(req, res, found.second);
+ rules[ruleIndex]->handle(req, res, found.second);
} catch (std::exception& e) {
- CROW_LOG_ERROR << "An uncaught exception occurred: " << e.what();
- res = response(boost::beast::http::status::internal_server_error);
+ BMCWEB_LOG_ERROR << "An uncaught exception occurred: " << e.what();
+ res = Response(boost::beast::http::status::internal_server_error);
res.end();
return;
} catch (...) {
- CROW_LOG_ERROR << "An uncaught exception occurred. The type was unknown "
- "so no information was available.";
- res = response(boost::beast::http::status::internal_server_error);
+ BMCWEB_LOG_ERROR
+ << "An uncaught exception occurred. The type was unknown "
+ "so no information was available.";
+ res = Response(boost::beast::http::status::internal_server_error);
res.end();
return;
}
}
- void debug_print() { trie_.debug_print(); }
+ void debugPrint() { trie.debugPrint(); }
- std::vector<const std::string*> get_routes(const std::string& parent) {
+ std::vector<const std::string*> getRoutes(const std::string& parent) {
std::vector<unsigned> x;
std::vector<const std::string*> ret;
- trie_.find_route_indexes(parent, x);
+ trie.findRouteIndexes(parent, x);
for (unsigned index : x) {
- ret.push_back(&rules_[index]->rule_);
+ ret.push_back(&rules[index]->rule);
}
return ret;
}
private:
- std::vector<std::unique_ptr<BaseRule>> rules_;
- Trie trie_;
+ std::vector<std::unique_ptr<BaseRule>> rules;
+ Trie trie;
};
} // namespace crow
diff --git a/crow/include/crow/settings.h b/crow/include/crow/settings.h
index 8dbd516..8cb1219 100644
--- a/crow/include/crow/settings.h
+++ b/crow/include/crow/settings.h
@@ -3,13 +3,13 @@
// TODO - replace with runtime config. libucl?
/* #ifdef - enables debug mode */
-//#define CROW_ENABLE_DEBUG
+//#define BMCWEB_ENABLE_DEBUG
/* #ifdef - enables logging */
-//#define CROW_ENABLE_LOGGING
+//#define BMCWEB_ENABLE_LOGGING
/* #ifdef - enables ssl */
-//#define CROW_ENABLE_SSL
+//#define BMCWEB_ENABLE_SSL
/* #define - specifies log level */
/*
@@ -21,11 +21,11 @@
default to INFO
*/
-#define CROW_LOG_LEVEL 1
+#define BMCWEB_LOG_LEVEL 1
// compiler flags
#if __cplusplus >= 201402L
-#define CROW_CAN_USE_CPP14
+#define BMCWEB_CAN_USE_CPP14
#endif
#if defined(_MSC_VER)
diff --git a/crow/include/crow/socket_adaptors.h b/crow/include/crow/socket_adaptors.h
index e3d0081..4b379db 100644
--- a/crow/include/crow/socket_adaptors.h
+++ b/crow/include/crow/socket_adaptors.h
@@ -4,7 +4,7 @@
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
-#ifdef CROW_ENABLE_SSL
+#ifdef BMCWEB_ENABLE_SSL
#include <boost/asio/ssl.hpp>
#endif
namespace crow {
@@ -14,128 +14,128 @@
struct SocketAdaptor {
using secure = std::false_type;
using context = void;
- SocketAdaptor(boost::asio::io_service& io_service, context* /*unused*/)
- : socket_(io_service) {}
+ SocketAdaptor(boost::asio::io_service& ioService, context* /*unused*/)
+ : socketCls(ioService) {}
- boost::asio::io_service& get_io_service() { return socket_.get_io_service(); }
+ boost::asio::io_service& getIoService() { return socketCls.get_io_service(); }
- tcp::socket& raw_socket() { return socket_; }
+ tcp::socket& rawSocket() { return socketCls; }
- tcp::socket& socket() { return socket_; }
+ tcp::socket& socket() { return socketCls; }
- std::string remote_endpoint() {
+ std::string remoteEndpoint() {
boost::system::error_code ec;
- tcp::endpoint ep = socket_.remote_endpoint(ec);
+ tcp::endpoint ep = socketCls.remote_endpoint(ec);
if (ec) {
return "";
}
return boost::lexical_cast<std::string>(ep);
}
- bool is_open() { return socket_.is_open(); }
+ bool isOpen() { return socketCls.is_open(); }
- void close() { socket_.close(); }
+ void close() { socketCls.close(); }
template <typename F>
void start(F f) {
f(boost::system::error_code());
}
- tcp::socket socket_;
+ tcp::socket socketCls;
};
struct TestSocketAdaptor {
using secure = std::false_type;
using context = void;
- TestSocketAdaptor(boost::asio::io_service& io_service, context* /*unused*/)
- : socket_(io_service) {}
+ TestSocketAdaptor(boost::asio::io_service& ioService, context* /*unused*/)
+ : socketCls(ioService) {}
- boost::asio::io_service& get_io_service() { return socket_.get_io_service(); }
+ boost::asio::io_service& getIoService() { return socketCls.get_io_service(); }
- tcp::socket& raw_socket() { return socket_; }
+ tcp::socket& rawSocket() { return socketCls; }
- tcp::socket& socket() { return socket_; }
+ tcp::socket& socket() { return socketCls; }
- std::string remote_endpoint() { return "Testhost"; }
+ std::string remoteEndpoint() { return "Testhost"; }
- bool is_open() { return socket_.is_open(); }
+ bool isOpen() { return socketCls.is_open(); }
- void close() { socket_.close(); }
+ void close() { socketCls.close(); }
template <typename F>
void start(F f) {
f(boost::system::error_code());
}
- tcp::socket socket_;
+ tcp::socket socketCls;
};
-#ifdef CROW_ENABLE_SSL
+#ifdef BMCWEB_ENABLE_SSL
struct SSLAdaptor {
using secure = std::true_type;
using context = boost::asio::ssl::context;
using ssl_socket_t = boost::asio::ssl::stream<tcp::socket>;
- SSLAdaptor(boost::asio::io_service& io_service, context* ctx)
- : ssl_socket_(new ssl_socket_t(io_service, *ctx)) {}
+ SSLAdaptor(boost::asio::io_service& ioService, context* ctx)
+ : sslSocket(new ssl_socket_t(ioService, *ctx)) {}
- boost::asio::ssl::stream<tcp::socket>& socket() { return *ssl_socket_; }
+ boost::asio::ssl::stream<tcp::socket>& socket() { return *sslSocket; }
- tcp::socket::lowest_layer_type& raw_socket() {
- return ssl_socket_->lowest_layer();
+ tcp::socket::lowest_layer_type& rawSocket() {
+ return sslSocket->lowest_layer();
}
- std::string remote_endpoint() {
+ std::string remoteEndpoint() {
boost::system::error_code ec;
- tcp::endpoint ep = raw_socket().remote_endpoint(ec);
+ tcp::endpoint ep = rawSocket().remote_endpoint(ec);
if (ec) {
return "";
}
return boost::lexical_cast<std::string>(ep);
}
- bool is_open() {
+ bool isOpen() {
/*TODO(ed) this is a bit of a cheat.
- There are cases when running a websocket where ssl_socket_ might have
+ There are cases when running a websocket where sslSocket might have
std::move() called on it (to transfer ownership to websocket::Connection)
and be empty. This (and the check on close()) is a cheat to do something
sane in this scenario. the correct fix would likely involve changing the
http parser to return a specific code meaning "has been upgraded" so that
- the do_read function knows not to try to close the connection which would
- fail, because the adapter is gone. As is, do_read believes the parse
- failed, because is_open now returns False (which could also mean the client
+ the doRead function knows not to try to close the Connection which would
+ fail, because the adapter is gone. As is, doRead believes the parse
+ failed, because isOpen now returns False (which could also mean the client
disconnected during parse)
- UPdate: The parser does in fact have an "is_upgrade" method that is intended
- for exactly this purpose. Todo is now to make do_read obey the flag
+ UPdate: The parser does in fact have an "isUpgrade" method that is intended
+ for exactly this purpose. Todo is now to make doRead obey the flag
appropriately so this code can be changed back.
*/
- if (ssl_socket_ != nullptr) {
- return ssl_socket_->lowest_layer().is_open();
+ if (sslSocket != nullptr) {
+ return sslSocket->lowest_layer().is_open();
}
return false;
}
void close() {
- if (ssl_socket_ == nullptr) {
+ if (sslSocket == nullptr) {
return;
}
boost::system::error_code ec;
// Shut it down
- this->ssl_socket_->lowest_layer().close();
+ this->sslSocket->lowest_layer().close();
}
- boost::asio::io_service& get_io_service() {
- return raw_socket().get_io_service();
+ boost::asio::io_service& getIoService() {
+ return rawSocket().get_io_service();
}
template <typename F>
void start(F f) {
- ssl_socket_->async_handshake(
+ sslSocket->async_handshake(
boost::asio::ssl::stream_base::server,
[f](const boost::system::error_code& ec) { f(ec); });
}
- std::unique_ptr<boost::asio::ssl::stream<tcp::socket>> ssl_socket_;
+ std::unique_ptr<boost::asio::ssl::stream<tcp::socket>> sslSocket;
};
#endif
} // namespace crow
diff --git a/crow/include/crow/timer_queue.h b/crow/include/crow/timer_queue.h
index d886a63..f5bb467 100644
--- a/crow/include/crow/timer_queue.h
+++ b/crow/include/crow/timer_queue.h
@@ -9,40 +9,40 @@
namespace crow {
namespace detail {
// fast timer queue for fixed tick value.
-class timer_queue {
+class TimerQueue {
public:
- timer_queue() { dq_.set_capacity(100); }
+ TimerQueue() { dq.set_capacity(100); }
void cancel(int k) {
- unsigned int index = static_cast<unsigned int>(k - step_);
- if (index < dq_.size()) {
- dq_[index].second = nullptr;
+ unsigned int index = static_cast<unsigned int>(k - step);
+ if (index < dq.size()) {
+ dq[index].second = nullptr;
}
}
int add(std::function<void()> f) {
- dq_.push_back(
+ dq.push_back(
std::make_pair(std::chrono::steady_clock::now(), std::move(f)));
- int ret = step_ + dq_.size() - 1;
+ int ret = step + dq.size() - 1;
- CROW_LOG_DEBUG << "timer add inside: " << this << ' ' << ret;
+ BMCWEB_LOG_DEBUG << "timer add inside: " << this << ' ' << ret;
return ret;
}
void process() {
auto now = std::chrono::steady_clock::now();
- while (!dq_.empty()) {
- auto& x = dq_.front();
+ while (!dq.empty()) {
+ auto& x = dq.front();
if (now - x.first < std::chrono::seconds(5)) {
break;
}
if (x.second) {
- CROW_LOG_DEBUG << "timer call: " << this << ' ' << step_;
+ BMCWEB_LOG_DEBUG << "timer call: " << this << ' ' << step;
// we know that timer handlers are very simple currenty; call here
x.second();
}
- dq_.pop_front();
- step_++;
+ dq.pop_front();
+ step++;
}
}
@@ -53,11 +53,11 @@
boost::circular_buffer_space_optimized<storage_type,
std::allocator<storage_type>>
- dq_{};
+ dq{};
- // boost::circular_buffer<storage_type> dq_{20};
- // std::deque<storage_type> dq_{};
- int step_{};
+ // boost::circular_buffer<storage_type> dq{20};
+ // std::deque<storage_type> dq{};
+ int step{};
};
} // namespace detail
} // namespace crow
diff --git a/crow/include/crow/utility.h b/crow/include/crow/utility.h
index 98b6534..d2557b0 100644
--- a/crow/include/crow/utility.h
+++ b/crow/include/crow/utility.h
@@ -14,105 +14,105 @@
struct OutOfRange {
OutOfRange(unsigned /*pos*/, unsigned /*length*/) {}
};
-constexpr unsigned requires_in_range(unsigned i, unsigned len) {
+constexpr unsigned requiresInRange(unsigned i, unsigned len) {
return i >= len ? throw OutOfRange(i, len) : i;
}
-class const_str {
- const char* const begin_;
- unsigned size_;
+class ConstStr {
+ const char* const beginPtr;
+ unsigned sizeUint;
public:
template <unsigned N>
- constexpr const_str(const char (&arr)[N]) : begin_(arr), size_(N - 1) {
+ constexpr ConstStr(const char (&arr)[N]) : beginPtr(arr), sizeUint(N - 1) {
static_assert(N >= 1, "not a string literal");
}
constexpr char operator[](unsigned i) const {
- return requires_in_range(i, size_), begin_[i];
+ return requiresInRange(i, sizeUint), beginPtr[i];
}
- constexpr operator const char*() const { return begin_; }
+ constexpr operator const char*() const { return beginPtr; }
- constexpr const char* begin() const { return begin_; }
- constexpr const char* end() const { return begin_ + size_; }
+ constexpr const char* begin() const { return beginPtr; }
+ constexpr const char* end() const { return beginPtr + sizeUint; }
- constexpr unsigned size() const { return size_; }
+ constexpr unsigned size() const { return sizeUint; }
};
-constexpr unsigned find_closing_tag(const_str s, unsigned p) {
- return s[p] == '>' ? p : find_closing_tag(s, p + 1);
+constexpr unsigned findClosingTag(ConstStr s, unsigned p) {
+ return s[p] == '>' ? p : findClosingTag(s, p + 1);
}
-constexpr bool is_valid(const_str s, unsigned i = 0, int f = 0) {
+constexpr bool isValid(ConstStr s, unsigned i = 0, int f = 0) {
return i == s.size()
? f == 0
: f < 0 || f >= 2
? false
- : s[i] == '<' ? is_valid(s, i + 1, f + 1)
- : s[i] == '>' ? is_valid(s, i + 1, f - 1)
- : is_valid(s, i + 1, f);
+ : s[i] == '<' ? isValid(s, i + 1, f + 1)
+ : s[i] == '>' ? isValid(s, i + 1, f - 1)
+ : isValid(s, i + 1, f);
}
-constexpr bool is_equ_p(const char* a, const char* b, unsigned n) {
+constexpr bool isEquP(const char* a, const char* b, unsigned n) {
return *a == 0 && *b == 0 && n == 0
? true
: (*a == 0 || *b == 0)
? false
: n == 0 ? true
- : *a != *b ? false : is_equ_p(a + 1, b + 1, n - 1);
+ : *a != *b ? false : isEquP(a + 1, b + 1, n - 1);
}
-constexpr bool is_equ_n(const_str a, unsigned ai, const_str b, unsigned bi,
- unsigned n) {
+constexpr bool isEquN(ConstStr a, unsigned ai, ConstStr b, unsigned bi,
+ unsigned n) {
return ai + n > a.size() || bi + n > b.size()
? false
: n == 0 ? true
: a[ai] != b[bi] ? false
- : is_equ_n(a, ai + 1, b, bi + 1, n - 1);
+ : isEquN(a, ai + 1, b, bi + 1, n - 1);
}
-constexpr bool is_int(const_str s, unsigned i) {
- return is_equ_n(s, i, "<int>", 0, 5);
+constexpr bool isInt(ConstStr s, unsigned i) {
+ return isEquN(s, i, "<int>", 0, 5);
}
-constexpr bool is_uint(const_str s, unsigned i) {
- return is_equ_n(s, i, "<uint>", 0, 6);
+constexpr bool isUint(ConstStr s, unsigned i) {
+ return isEquN(s, i, "<uint>", 0, 6);
}
-constexpr bool is_float(const_str s, unsigned i) {
- return is_equ_n(s, i, "<float>", 0, 7) || is_equ_n(s, i, "<double>", 0, 8);
+constexpr bool isFloat(ConstStr s, unsigned i) {
+ return isEquN(s, i, "<float>", 0, 7) || isEquN(s, i, "<double>", 0, 8);
}
-constexpr bool is_str(const_str s, unsigned i) {
- return is_equ_n(s, i, "<str>", 0, 5) || is_equ_n(s, i, "<string>", 0, 8);
+constexpr bool isStr(ConstStr s, unsigned i) {
+ return isEquN(s, i, "<str>", 0, 5) || isEquN(s, i, "<string>", 0, 8);
}
-constexpr bool is_path(const_str s, unsigned i) {
- return is_equ_n(s, i, "<path>", 0, 6);
+constexpr bool isPath(ConstStr s, unsigned i) {
+ return isEquN(s, i, "<path>", 0, 6);
}
template <typename T>
struct parameter_tag {
static const int value = 0;
};
-#define CROW_INTERNAL_PARAMETER_TAG(t, i) \
- template <> \
- struct parameter_tag<t> { \
- static const int value = i; \
+#define BMCWEB_INTERNAL_PARAMETER_TAG(t, i) \
+ template <> \
+ struct parameter_tag<t> { \
+ static const int value = i; \
}
-CROW_INTERNAL_PARAMETER_TAG(int, 1);
-CROW_INTERNAL_PARAMETER_TAG(char, 1);
-CROW_INTERNAL_PARAMETER_TAG(short, 1);
-CROW_INTERNAL_PARAMETER_TAG(long, 1);
-CROW_INTERNAL_PARAMETER_TAG(long long, 1);
-CROW_INTERNAL_PARAMETER_TAG(unsigned int, 2);
-CROW_INTERNAL_PARAMETER_TAG(unsigned char, 2);
-CROW_INTERNAL_PARAMETER_TAG(unsigned short, 2);
-CROW_INTERNAL_PARAMETER_TAG(unsigned long, 2);
-CROW_INTERNAL_PARAMETER_TAG(unsigned long long, 2);
-CROW_INTERNAL_PARAMETER_TAG(double, 3);
-CROW_INTERNAL_PARAMETER_TAG(std::string, 4);
-#undef CROW_INTERNAL_PARAMETER_TAG
+BMCWEB_INTERNAL_PARAMETER_TAG(int, 1);
+BMCWEB_INTERNAL_PARAMETER_TAG(char, 1);
+BMCWEB_INTERNAL_PARAMETER_TAG(short, 1);
+BMCWEB_INTERNAL_PARAMETER_TAG(long, 1);
+BMCWEB_INTERNAL_PARAMETER_TAG(long long, 1);
+BMCWEB_INTERNAL_PARAMETER_TAG(unsigned int, 2);
+BMCWEB_INTERNAL_PARAMETER_TAG(unsigned char, 2);
+BMCWEB_INTERNAL_PARAMETER_TAG(unsigned short, 2);
+BMCWEB_INTERNAL_PARAMETER_TAG(unsigned long, 2);
+BMCWEB_INTERNAL_PARAMETER_TAG(unsigned long long, 2);
+BMCWEB_INTERNAL_PARAMETER_TAG(double, 3);
+BMCWEB_INTERNAL_PARAMETER_TAG(std::string, 4);
+#undef BMCWEB_INTERNAL_PARAMETER_TAG
template <typename... Args>
struct compute_parameter_tag_from_args_list;
@@ -123,15 +123,15 @@
template <typename Arg, typename... Args>
struct compute_parameter_tag_from_args_list<Arg, Args...> {
- static const int sub_value =
+ static const int subValue =
compute_parameter_tag_from_args_list<Args...>::value;
static const int value =
parameter_tag<typename std::decay<Arg>::type>::value
- ? sub_value * 6 + parameter_tag<typename std::decay<Arg>::type>::value
- : sub_value;
+ ? subValue * 6 + parameter_tag<typename std::decay<Arg>::type>::value
+ : subValue;
};
-static inline bool is_parameter_tag_compatible(uint64_t a, uint64_t b) {
+static inline bool isParameterTagCompatible(uint64_t a, uint64_t b) {
if (a == 0) {
return b == 0;
}
@@ -149,81 +149,80 @@
if (sa != sb) {
return false;
}
- return is_parameter_tag_compatible(a / 6, b / 6);
+ return isParameterTagCompatible(a / 6, b / 6);
}
-static inline unsigned find_closing_tag_runtime(const char* s, unsigned p) {
+static inline unsigned findClosingTagRuntime(const char* s, unsigned p) {
return s[p] == 0 ? throw std::runtime_error("unmatched tag <")
- : s[p] == '>' ? p : find_closing_tag_runtime(s, p + 1);
+ : s[p] == '>' ? p : findClosingTagRuntime(s, p + 1);
}
-static inline uint64_t get_parameter_tag_runtime(const char* s,
- unsigned p = 0) {
+static inline uint64_t getParameterTagRuntime(const char* s, unsigned p = 0) {
return s[p] == 0
? 0
: s[p] == '<'
? (std::strncmp(s + p, "<int>", 5) == 0
- ? get_parameter_tag_runtime(
- s, find_closing_tag_runtime(s, p)) *
+ ? getParameterTagRuntime(
+ s, findClosingTagRuntime(s, p)) *
6 +
1
: std::strncmp(s + p, "<uint>", 6) == 0
- ? get_parameter_tag_runtime(
- s, find_closing_tag_runtime(s, p)) *
+ ? getParameterTagRuntime(
+ s, findClosingTagRuntime(s, p)) *
6 +
2
: (std::strncmp(s + p, "<float>", 7) == 0 ||
std::strncmp(s + p, "<double>", 8) == 0)
- ? get_parameter_tag_runtime(
- s, find_closing_tag_runtime(s, p)) *
+ ? getParameterTagRuntime(
+ s, findClosingTagRuntime(s, p)) *
6 +
3
: (std::strncmp(s + p, "<str>", 5) == 0 ||
std::strncmp(s + p, "<string>", 8) ==
0)
- ? get_parameter_tag_runtime(
- s, find_closing_tag_runtime(
- s, p)) *
+ ? getParameterTagRuntime(
+ s,
+ findClosingTagRuntime(s, p)) *
6 +
4
: std::strncmp(s + p, "<path>",
6) == 0
- ? get_parameter_tag_runtime(
+ ? getParameterTagRuntime(
s,
- find_closing_tag_runtime(
+ findClosingTagRuntime(
s, p)) *
6 +
5
: throw std::runtime_error(
"invalid parameter "
"type"))
- : get_parameter_tag_runtime(s, p + 1);
+ : getParameterTagRuntime(s, p + 1);
}
-constexpr uint64_t get_parameter_tag(const_str s, unsigned p = 0) {
+constexpr uint64_t get_parameter_tag(ConstStr s, unsigned p = 0) {
return p == s.size()
? 0
: s[p] == '<'
- ? (is_int(s, p)
- ? get_parameter_tag(s, find_closing_tag(s, p)) * 6 + 1
- : is_uint(s, p)
- ? get_parameter_tag(s, find_closing_tag(s, p)) *
+ ? (isInt(s, p)
+ ? get_parameter_tag(s, findClosingTag(s, p)) * 6 + 1
+ : isUint(s, p)
+ ? get_parameter_tag(s, findClosingTag(s, p)) *
6 +
2
- : is_float(s, p)
+ : isFloat(s, p)
? get_parameter_tag(
- s, find_closing_tag(s, p)) *
+ s, findClosingTag(s, p)) *
6 +
3
- : is_str(s, p)
+ : isStr(s, p)
? get_parameter_tag(
- s, find_closing_tag(s, p)) *
+ s, findClosingTag(s, p)) *
6 +
4
- : is_path(s, p)
+ : isPath(s, p)
? get_parameter_tag(
- s, find_closing_tag(
- s, p)) *
+ s,
+ findClosingTag(s, p)) *
6 +
5
: throw std::runtime_error(
@@ -256,53 +255,53 @@
};
template <int N>
-struct single_tag_to_type {};
+struct SingleTagToType {};
template <>
-struct single_tag_to_type<1> {
+struct SingleTagToType<1> {
using type = int64_t;
};
template <>
-struct single_tag_to_type<2> {
+struct SingleTagToType<2> {
using type = uint64_t;
};
template <>
-struct single_tag_to_type<3> {
+struct SingleTagToType<3> {
using type = double;
};
template <>
-struct single_tag_to_type<4> {
+struct SingleTagToType<4> {
using type = std::string;
};
template <>
-struct single_tag_to_type<5> {
+struct SingleTagToType<5> {
using type = std::string;
};
template <uint64_t Tag>
-struct arguments {
- using subarguments = typename arguments<Tag / 6>::type;
+struct Arguments {
+ using subarguments = typename Arguments<Tag / 6>::type;
using type = typename subarguments::template push<
- typename single_tag_to_type<Tag % 6>::type>;
+ typename SingleTagToType<Tag % 6>::type>;
};
template <>
-struct arguments<0> {
+struct Arguments<0> {
using type = S<>;
};
template <typename... T>
-struct last_element_type {
+struct LastElementType {
using type =
typename std::tuple_element<sizeof...(T) - 1, std::tuple<T...>>::type;
};
template <>
-struct last_element_type<> {};
+struct LastElementType<> {};
// from
// http://stackoverflow.com/questions/13072359/c11-compile-time-array-with-logarithmic-evaluation-depth
@@ -310,15 +309,15 @@
using Invoke = typename T::type;
template <unsigned...>
-struct seq {
- using type = seq;
+struct Seq {
+ using type = Seq;
};
template <class S1, class S2>
struct concat;
template <unsigned... I1, unsigned... I2>
-struct concat<seq<I1...>, seq<I2...>> : seq<I1..., (sizeof...(I1) + I2)...> {};
+struct concat<Seq<I1...>, Seq<I2...>> : Seq<I1..., (sizeof...(I1) + I2)...> {};
template <class S1, class S2>
using Concat = Invoke<concat<S1, S2>>;
@@ -332,31 +331,31 @@
struct gen_seq : Concat<GenSeq<N / 2>, GenSeq<N - N / 2>> {};
template <>
-struct gen_seq<0> : seq<> {};
+struct gen_seq<0> : Seq<> {};
template <>
-struct gen_seq<1> : seq<0> {};
+struct gen_seq<1> : Seq<0> {};
template <typename Seq, typename Tuple>
-struct pop_back_helper;
+struct PopBackHelper;
template <unsigned... N, typename Tuple>
-struct pop_back_helper<seq<N...>, Tuple> {
+struct PopBackHelper<Seq<N...>, Tuple> {
template <template <typename... Args> class U>
using rebind = U<typename std::tuple_element<N, Tuple>::type...>;
};
template <typename... T>
-struct pop_back //: public pop_back_helper<typename
- // gen_seq<sizeof...(T)-1>::type, std::tuple<T...>>
+struct PopBack //: public PopBackHelper<typename
+ // gen_seq<sizeof...(T)-1>::type, std::tuple<T...>>
{
template <template <typename... Args> class U>
using rebind =
- typename pop_back_helper<typename gen_seq<sizeof...(T) - 1>::type,
- std::tuple<T...>>::template rebind<U>;
+ typename PopBackHelper<typename gen_seq<sizeof...(T) - 1>::type,
+ std::tuple<T...>>::template rebind<U>;
};
template <>
-struct pop_back<> {
+struct PopBack<> {
template <template <typename... Args> class U>
using rebind = U<>;
};
@@ -364,42 +363,42 @@
// from
// http://stackoverflow.com/questions/2118541/check-if-c0x-parameter-pack-contains-a-type
template <typename Tp, typename... List>
-struct contains : std::true_type {};
+struct Contains : std::true_type {};
template <typename Tp, typename Head, typename... Rest>
-struct contains<Tp, Head, Rest...>
+struct Contains<Tp, Head, Rest...>
: std::conditional<std::is_same<Tp, Head>::value, std::true_type,
- contains<Tp, Rest...>>::type {};
+ Contains<Tp, Rest...>>::type {};
template <typename Tp>
-struct contains<Tp> : std::false_type {};
+struct Contains<Tp> : std::false_type {};
template <typename T>
-struct empty_context {};
+struct EmptyContext {};
template <typename T>
struct promote {
using type = T;
};
-#define CROW_INTERNAL_PROMOTE_TYPE(t1, t2) \
- template <> \
- struct promote<t1> { \
- using type = t2; \
+#define BMCWEB_INTERNAL_PROMOTE_TYPE(t1, t2) \
+ template <> \
+ struct promote<t1> { \
+ using type = t2; \
}
-CROW_INTERNAL_PROMOTE_TYPE(char, int64_t);
-CROW_INTERNAL_PROMOTE_TYPE(short, int64_t);
-CROW_INTERNAL_PROMOTE_TYPE(int, int64_t);
-CROW_INTERNAL_PROMOTE_TYPE(long, int64_t);
-CROW_INTERNAL_PROMOTE_TYPE(long long, int64_t);
-CROW_INTERNAL_PROMOTE_TYPE(unsigned char, uint64_t);
-CROW_INTERNAL_PROMOTE_TYPE(unsigned short, uint64_t);
-CROW_INTERNAL_PROMOTE_TYPE(unsigned int, uint64_t);
-CROW_INTERNAL_PROMOTE_TYPE(unsigned long, uint64_t);
-CROW_INTERNAL_PROMOTE_TYPE(unsigned long long, uint64_t);
-CROW_INTERNAL_PROMOTE_TYPE(float, double);
-#undef CROW_INTERNAL_PROMOTE_TYPE
+BMCWEB_INTERNAL_PROMOTE_TYPE(char, int64_t);
+BMCWEB_INTERNAL_PROMOTE_TYPE(short, int64_t);
+BMCWEB_INTERNAL_PROMOTE_TYPE(int, int64_t);
+BMCWEB_INTERNAL_PROMOTE_TYPE(long, int64_t);
+BMCWEB_INTERNAL_PROMOTE_TYPE(long long, int64_t);
+BMCWEB_INTERNAL_PROMOTE_TYPE(unsigned char, uint64_t);
+BMCWEB_INTERNAL_PROMOTE_TYPE(unsigned short, uint64_t);
+BMCWEB_INTERNAL_PROMOTE_TYPE(unsigned int, uint64_t);
+BMCWEB_INTERNAL_PROMOTE_TYPE(unsigned long, uint64_t);
+BMCWEB_INTERNAL_PROMOTE_TYPE(unsigned long long, uint64_t);
+BMCWEB_INTERNAL_PROMOTE_TYPE(float, double);
+#undef BMCWEB_INTERNAL_PROMOTE_TYPE
template <typename T>
using promote_t = typename promote<T>::type;
@@ -409,28 +408,28 @@
namespace detail {
template <class T, std::size_t N, class... Args>
-struct get_index_of_element_from_tuple_by_type_impl {
+struct GetIndexOfElementFromTupleByTypeImpl {
static constexpr auto value = N;
};
template <class T, std::size_t N, class... Args>
-struct get_index_of_element_from_tuple_by_type_impl<T, N, T, Args...> {
+struct GetIndexOfElementFromTupleByTypeImpl<T, N, T, Args...> {
static constexpr auto value = N;
};
template <class T, std::size_t N, class U, class... Args>
-struct get_index_of_element_from_tuple_by_type_impl<T, N, U, Args...> {
+struct GetIndexOfElementFromTupleByTypeImpl<T, N, U, Args...> {
static constexpr auto value =
- get_index_of_element_from_tuple_by_type_impl<T, N + 1, Args...>::value;
+ GetIndexOfElementFromTupleByTypeImpl<T, N + 1, Args...>::value;
};
} // namespace detail
namespace utility {
template <class T, class... Args>
-T& get_element_by_type(std::tuple<Args...>& t) {
- return std::get<detail::get_index_of_element_from_tuple_by_type_impl<
- T, 0, Args...>::value>(t);
+T& getElementByType(std::tuple<Args...>& t) {
+ return std::get<
+ detail::GetIndexOfElementFromTupleByTypeImpl<T, 0, Args...>::value>(t);
}
template <typename T>
@@ -445,31 +444,31 @@
using arg = typename parent_t::template arg<i>;
};
-template <typename ClassType, typename R, typename... Args>
-struct function_traits<R (ClassType::*)(Args...) const> {
+template <typename ClassType, typename r, typename... Args>
+struct function_traits<r (ClassType::*)(Args...) const> {
static const size_t arity = sizeof...(Args);
- using result_type = R;
+ using result_type = r;
template <size_t i>
using arg = typename std::tuple_element<i, std::tuple<Args...>>::type;
};
-template <typename ClassType, typename R, typename... Args>
-struct function_traits<R (ClassType::*)(Args...)> {
+template <typename ClassType, typename r, typename... Args>
+struct function_traits<r (ClassType::*)(Args...)> {
static const size_t arity = sizeof...(Args);
- using result_type = R;
+ using result_type = r;
template <size_t i>
using arg = typename std::tuple_element<i, std::tuple<Args...>>::type;
};
-template <typename R, typename... Args>
-struct function_traits<std::function<R(Args...)>> {
+template <typename r, typename... Args>
+struct function_traits<std::function<r(Args...)>> {
static const size_t arity = sizeof...(Args);
- using result_type = R;
+ using result_type = r;
template <size_t i>
using arg = typename std::tuple_element<i, std::tuple<Args...>>::type;
@@ -509,7 +508,7 @@
return ret;
}
-inline static std::string base64encode_urlsafe(const char* data, size_t size) {
+inline static std::string base64encodeUrlsafe(const char* data, size_t size) {
return base64encode(
data, size,
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_");
@@ -517,10 +516,10 @@
// TODO this is temporary and should be deleted once base64 is refactored out of
// crow
-inline bool base64_decode(const boost::string_view input, std::string& output) {
+inline bool base64Decode(const boost::string_view input, std::string& output) {
static const char nop = -1;
// See note on encoding_data[] in above function
- static const char decoding_data[] = {
+ static const char decodingData[] = {
nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop,
nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop,
nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, 62, nop,
@@ -540,43 +539,43 @@
nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop, nop,
nop};
- size_t input_length = input.size();
+ size_t inputLength = input.size();
// allocate space for output string
output.clear();
- output.reserve(((input_length + 2) / 3) * 4);
+ output.reserve(((inputLength + 2) / 3) * 4);
// for each 4-bytes sequence from the input, extract 4 6-bits sequences by
// droping first two bits
// and regenerate into 3 8-bits sequences
- for (size_t i = 0; i < input_length; i++) {
+ for (size_t i = 0; i < inputLength; i++) {
char base64code0;
char base64code1;
char base64code2 = 0; // initialized to 0 to suppress warnings
char base64code3;
- base64code0 = decoding_data[static_cast<int>(input[i])]; // NOLINT
+ base64code0 = decodingData[static_cast<int>(input[i])]; // NOLINT
if (base64code0 == nop) { // non base64 character
return false;
}
- if (!(++i < input_length)) { // we need at least two input bytes for first
- // byte output
+ if (!(++i < inputLength)) { // we need at least two input bytes for first
+ // byte output
return false;
}
- base64code1 = decoding_data[static_cast<int>(input[i])]; // NOLINT
+ base64code1 = decodingData[static_cast<int>(input[i])]; // NOLINT
if (base64code1 == nop) { // non base64 character
return false;
}
output +=
static_cast<char>((base64code0 << 2) | ((base64code1 >> 4) & 0x3));
- if (++i < input_length) {
+ if (++i < inputLength) {
char c = input[i];
if (c == '=') { // padding , end of input
return (base64code1 & 0x0f) == 0;
}
- base64code2 = decoding_data[static_cast<int>(input[i])]; // NOLINT
+ base64code2 = decodingData[static_cast<int>(input[i])]; // NOLINT
if (base64code2 == nop) { // non base64 character
return false;
}
@@ -584,12 +583,12 @@
((base64code2 >> 2) & 0x0f));
}
- if (++i < input_length) {
+ if (++i < inputLength) {
char c = input[i];
if (c == '=') { // padding , end of input
return (base64code2 & 0x03) == 0;
}
- base64code3 = decoding_data[static_cast<int>(input[i])]; // NOLINT
+ base64code3 = decodingData[static_cast<int>(input[i])]; // NOLINT
if (base64code3 == nop) { // non base64 character
return false;
}
diff --git a/crow/include/crow/websocket.h b/crow/include/crow/websocket.h
index 7cd48ef..2272500 100644
--- a/crow/include/crow/websocket.h
+++ b/crow/include/crow/websocket.h
@@ -15,49 +15,50 @@
Payload,
};
-struct connection {
+struct Connection {
public:
- explicit connection(const crow::request& req)
- : req(req), userdata_(nullptr){};
+ explicit Connection(const crow::Request& req)
+ : req(req), userdataPtr(nullptr){};
- virtual void send_binary(const std::string& msg) = 0;
- virtual void send_text(const std::string& msg) = 0;
+ virtual void sendBinary(const std::string& msg) = 0;
+ virtual void sendText(const std::string& msg) = 0;
virtual void close(const std::string& msg = "quit") = 0;
- virtual boost::asio::io_service& get_io_service() = 0;
- virtual ~connection() = default;
+ virtual boost::asio::io_service& getIoService() = 0;
+ virtual ~Connection() = default;
- void userdata(void* u) { userdata_ = u; }
- void* userdata() { return userdata_; }
+ void userdata(void* u) { userdataPtr = u; }
+ void* userdata() { return userdataPtr; }
- crow::request req;
+ crow::Request req;
private:
- void* userdata_;
+ void* userdataPtr;
};
template <typename Adaptor>
-class Connection : public connection {
+class ConnectionImpl : public Connection {
public:
- Connection(const crow::request& req, Adaptor&& adaptor,
- std::function<void(connection&)> open_handler,
- std::function<void(connection&, const std::string&, bool)>
- message_handler,
- std::function<void(connection&, const std::string&)> close_handler,
- std::function<void(connection&)> error_handler)
- : adaptor_(std::move(adaptor)),
- connection(req),
- open_handler_(std::move(open_handler)),
- message_handler_(std::move(message_handler)),
- close_handler_(std::move(close_handler)),
- error_handler_(std::move(error_handler)) {
- if (!boost::iequals(req.get_header_value("upgrade"), "websocket")) {
+ ConnectionImpl(
+ const crow::Request& req, Adaptor&& adaptor,
+ std::function<void(Connection&)> open_handler,
+ std::function<void(Connection&, const std::string&, bool)>
+ message_handler,
+ std::function<void(Connection&, const std::string&)> close_handler,
+ std::function<void(Connection&)> error_handler)
+ : adaptor(std::move(adaptor)),
+ Connection(req),
+ openHandler(std::move(open_handler)),
+ messageHandler(std::move(message_handler)),
+ closeHandler(std::move(close_handler)),
+ errorHandler(std::move(error_handler)) {
+ if (!boost::iequals(req.getHeaderValue("upgrade"), "websocket")) {
adaptor.close();
delete this;
return;
}
// Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
// Sec-WebSocket-Version: 13
- std::string magic(req.get_header_value("Sec-WebSocket-Key"));
+ std::string magic(req.getHeaderValue("Sec-WebSocket-Key"));
magic += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
boost::uuids::detail::sha1 s;
s.process_bytes(magic.data(), magic.size());
@@ -73,64 +74,64 @@
template <typename CompletionHandler>
void dispatch(CompletionHandler handler) {
- adaptor_.get_io_service().dispatch(handler);
+ adaptor.getIoService().dispatch(handler);
}
template <typename CompletionHandler>
void post(CompletionHandler handler) {
- adaptor_.get_io_service().post(handler);
+ adaptor.getIoService().post(handler);
}
- boost::asio::io_service& get_io_service() override {
- return adaptor_.get_io_service();
+ boost::asio::io_service& getIoService() override {
+ return adaptor.getIoService();
}
- void send_pong(const std::string& msg) {
+ void sendPong(const std::string& msg) {
dispatch([this, msg] {
char buf[3] = "\x8A\x00";
buf[1] += msg.size();
- write_buffers_.emplace_back(buf, buf + 2);
- write_buffers_.emplace_back(msg);
- do_write();
+ writeBuffers.emplace_back(buf, buf + 2);
+ writeBuffers.emplace_back(msg);
+ doWrite();
});
}
- void send_binary(const std::string& msg) override {
+ void sendBinary(const std::string& msg) override {
dispatch([this, msg] {
- auto header = build_header(2, msg.size());
- write_buffers_.emplace_back(std::move(header));
- write_buffers_.emplace_back(msg);
- do_write();
+ auto header = buildHeader(2, msg.size());
+ writeBuffers.emplace_back(std::move(header));
+ writeBuffers.emplace_back(msg);
+ doWrite();
});
}
- void send_text(const std::string& msg) override {
+ void sendText(const std::string& msg) override {
dispatch([this, msg] {
- auto header = build_header(1, msg.size());
- write_buffers_.emplace_back(std::move(header));
- write_buffers_.emplace_back(msg);
- do_write();
+ auto header = buildHeader(1, msg.size());
+ writeBuffers.emplace_back(std::move(header));
+ writeBuffers.emplace_back(msg);
+ doWrite();
});
}
void close(const std::string& msg) override {
dispatch([this, msg] {
- has_sent_close_ = true;
- if (has_recv_close_ && !is_close_handler_called_) {
- is_close_handler_called_ = true;
- if (close_handler_) {
- close_handler_(*this, msg);
+ hasSentClose = true;
+ if (hasRecvClose && !isCloseHandlerCalled) {
+ isCloseHandlerCalled = true;
+ if (closeHandler) {
+ closeHandler(*this, msg);
}
}
- auto header = build_header(0x8, msg.size());
- write_buffers_.emplace_back(std::move(header));
- write_buffers_.emplace_back(msg);
- do_write();
+ auto header = buildHeader(0x8, msg.size());
+ writeBuffers.emplace_back(std::move(header));
+ writeBuffers.emplace_back(msg);
+ doWrite();
});
}
protected:
- std::string build_header(int opcode, uint64_t size) {
+ std::string buildHeader(int opcode, uint64_t size) {
char buf[2 + 8] = "\x80\x00";
buf[0] += opcode;
if (size < 126) {
@@ -158,34 +159,33 @@
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
//"Sec-WebSocket-Protocol: binary\r\n" // TODO(ed): this hardcodes
- // binary mode
- // find a better way
+ // binary mode find a better way
"Sec-WebSocket-Accept: ";
static std::string crlf = "\r\n";
- write_buffers_.emplace_back(header);
- write_buffers_.emplace_back(std::move(hello));
- write_buffers_.emplace_back(crlf);
- write_buffers_.emplace_back(crlf);
- do_write();
- if (open_handler_) {
- open_handler_(*this);
+ writeBuffers.emplace_back(header);
+ writeBuffers.emplace_back(std::move(hello));
+ writeBuffers.emplace_back(crlf);
+ writeBuffers.emplace_back(crlf);
+ doWrite();
+ if (openHandler) {
+ openHandler(*this);
}
- do_read();
+ doRead();
}
- void do_read() {
- is_reading = true;
- switch (state_) {
+ void doRead() {
+ isReading = true;
+ switch (state) {
case WebSocketReadState::MiniHeader: {
- // boost::asio::async_read(adaptor_.socket(),
- // boost::asio::buffer(&mini_header_, 1),
- adaptor_.socket().async_read_some(
- boost::asio::buffer(&mini_header_, 2),
+ // boost::asio::async_read(adaptor.socket(),
+ // boost::asio::buffer(&miniHeader, 1),
+ adaptor.socket().async_read_some(
+ boost::asio::buffer(&miniHeader, 2),
[this](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
- is_reading = false;
- mini_header_ = htons(mini_header_);
-#ifdef CROW_ENABLE_DEBUG
+ isReading = false;
+ miniHeader = htons(miniHeader);
+#ifdef BMCWEB_ENABLE_DEBUG
if (!ec && bytes_transferred != 2) {
throw std::runtime_error(
@@ -193,35 +193,35 @@
}
#endif
- if (!ec && ((mini_header_ & 0x80) == 0x80)) {
- if ((mini_header_ & 0x7f) == 127) {
- state_ = WebSocketReadState::Len64;
- } else if ((mini_header_ & 0x7f) == 126) {
- state_ = WebSocketReadState::Len16;
+ if (!ec && ((miniHeader & 0x80) == 0x80)) {
+ if ((miniHeader & 0x7f) == 127) {
+ state = WebSocketReadState::Len64;
+ } else if ((miniHeader & 0x7f) == 126) {
+ state = WebSocketReadState::Len16;
} else {
- remaining_length_ = mini_header_ & 0x7f;
- state_ = WebSocketReadState::Mask;
+ remainingLength = miniHeader & 0x7f;
+ state = WebSocketReadState::Mask;
}
- do_read();
+ doRead();
} else {
- close_connection_ = true;
- adaptor_.close();
- if (error_handler_) {
- error_handler_(*this);
+ closeConnection = true;
+ adaptor.close();
+ if (errorHandler) {
+ errorHandler(*this);
}
- check_destroy();
+ checkDestroy();
}
});
} break;
case WebSocketReadState::Len16: {
- remaining_length_ = 0;
+ remainingLength = 0;
boost::asio::async_read(
- adaptor_.socket(), boost::asio::buffer(&remaining_length_, 2),
+ adaptor.socket(), boost::asio::buffer(&remainingLength, 2),
[this](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
- is_reading = false;
- remaining_length_ = ntohs(*(uint16_t*)&remaining_length_);
-#ifdef CROW_ENABLE_DEBUG
+ isReading = false;
+ remainingLength = ntohs(*(uint16_t*)&remainingLength);
+#ifdef BMCWEB_ENABLE_DEBUG
if (!ec && bytes_transferred != 2) {
throw std::runtime_error(
"WebSocket:Len16:async_read fail:asio bug?");
@@ -229,31 +229,30 @@
#endif
if (!ec) {
- state_ = WebSocketReadState::Mask;
- do_read();
+ state = WebSocketReadState::Mask;
+ doRead();
} else {
- close_connection_ = true;
- adaptor_.close();
- if (error_handler_) {
- error_handler_(*this);
+ closeConnection = true;
+ adaptor.close();
+ if (errorHandler) {
+ errorHandler(*this);
}
- check_destroy();
+ checkDestroy();
}
});
} break;
case WebSocketReadState::Len64: {
boost::asio::async_read(
- adaptor_.socket(), boost::asio::buffer(&remaining_length_, 8),
+ adaptor.socket(), boost::asio::buffer(&remainingLength, 8),
[this](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
- is_reading = false;
- remaining_length_ =
+ isReading = false;
+ remainingLength =
((1 == ntohl(1))
- ? (remaining_length_)
- : ((uint64_t)ntohl((remaining_length_)&0xFFFFFFFF)
- << 32) |
- ntohl((remaining_length_) >> 32));
-#ifdef CROW_ENABLE_DEBUG
+ ? (remainingLength)
+ : ((uint64_t)ntohl((remainingLength)&0xFFFFFFFF) << 32) |
+ ntohl((remainingLength) >> 32));
+#ifdef BMCWEB_ENABLE_DEBUG
if (!ec && bytes_transferred != 8) {
throw std::runtime_error(
"WebSocket:Len16:async_read fail:asio bug?");
@@ -261,25 +260,25 @@
#endif
if (!ec) {
- state_ = WebSocketReadState::Mask;
- do_read();
+ state = WebSocketReadState::Mask;
+ doRead();
} else {
- close_connection_ = true;
- adaptor_.close();
- if (error_handler_) {
- error_handler_(*this);
+ closeConnection = true;
+ adaptor.close();
+ if (errorHandler) {
+ errorHandler(*this);
}
- check_destroy();
+ checkDestroy();
}
});
} break;
case WebSocketReadState::Mask:
boost::asio::async_read(
- adaptor_.socket(), boost::asio::buffer((char*)&mask_, 4),
+ adaptor.socket(), boost::asio::buffer((char*)&mask, 4),
[this](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
- is_reading = false;
-#ifdef CROW_ENABLE_DEBUG
+ isReading = false;
+#ifdef BMCWEB_ENABLE_DEBUG
if (!ec && bytes_transferred != 4) {
throw std::runtime_error(
"WebSocket:Mask:async_read fail:asio bug?");
@@ -287,185 +286,185 @@
#endif
if (!ec) {
- state_ = WebSocketReadState::Payload;
- do_read();
+ state = WebSocketReadState::Payload;
+ doRead();
} else {
- close_connection_ = true;
- if (error_handler_) {
- error_handler_(*this);
+ closeConnection = true;
+ if (errorHandler) {
+ errorHandler(*this);
}
- adaptor_.close();
+ adaptor.close();
}
});
break;
case WebSocketReadState::Payload: {
- size_t to_read = buffer_.size();
- if (remaining_length_ < to_read) {
- to_read = remaining_length_;
+ size_t toRead = buffer.size();
+ if (remainingLength < toRead) {
+ toRead = remainingLength;
}
- adaptor_.socket().async_read_some(
- boost::asio::buffer(buffer_, to_read),
+ adaptor.socket().async_read_some(
+ boost::asio::buffer(buffer, toRead),
[this](const boost::system::error_code& ec,
std::size_t bytes_transferred) {
- is_reading = false;
+ isReading = false;
if (!ec) {
- fragment_.insert(fragment_.end(), buffer_.begin(),
- buffer_.begin() + bytes_transferred);
- remaining_length_ -= bytes_transferred;
- if (remaining_length_ == 0) {
- handle_fragment();
- state_ = WebSocketReadState::MiniHeader;
- do_read();
+ fragment.insert(fragment.end(), buffer.begin(),
+ buffer.begin() + bytes_transferred);
+ remainingLength -= bytes_transferred;
+ if (remainingLength == 0) {
+ handleFragment();
+ state = WebSocketReadState::MiniHeader;
+ doRead();
}
} else {
- close_connection_ = true;
- if (error_handler_) {
- error_handler_(*this);
+ closeConnection = true;
+ if (errorHandler) {
+ errorHandler(*this);
}
- adaptor_.close();
+ adaptor.close();
}
});
} break;
}
}
- bool is_FIN() { return mini_header_ & 0x8000; }
+ bool isFin() { return miniHeader & 0x8000; }
- int opcode() { return (mini_header_ & 0x0f00) >> 8; }
+ int opcode() { return (miniHeader & 0x0f00) >> 8; }
- void handle_fragment() {
- for (decltype(fragment_.length()) i = 0; i < fragment_.length(); i++) {
- fragment_[i] ^= ((char*)&mask_)[i % 4];
+ void handleFragment() {
+ for (decltype(fragment.length()) i = 0; i < fragment.length(); i++) {
+ fragment[i] ^= ((char*)&mask)[i % 4];
}
switch (opcode()) {
case 0: // Continuation
{
- message_ += fragment_;
- if (is_FIN()) {
- if (message_handler_) {
- message_handler_(*this, message_, is_binary_);
+ message += fragment;
+ if (isFin()) {
+ if (messageHandler) {
+ messageHandler(*this, message, isBinary);
}
- message_.clear();
+ message.clear();
}
}
case 1: // Text
{
- is_binary_ = false;
- message_ += fragment_;
- if (is_FIN()) {
- if (message_handler_) {
- message_handler_(*this, message_, is_binary_);
+ isBinary = false;
+ message += fragment;
+ if (isFin()) {
+ if (messageHandler) {
+ messageHandler(*this, message, isBinary);
}
- message_.clear();
+ message.clear();
}
} break;
case 2: // Binary
{
- is_binary_ = true;
- message_ += fragment_;
- if (is_FIN()) {
- if (message_handler_) {
- message_handler_(*this, message_, is_binary_);
+ isBinary = true;
+ message += fragment;
+ if (isFin()) {
+ if (messageHandler) {
+ messageHandler(*this, message, isBinary);
}
- message_.clear();
+ message.clear();
}
} break;
case 0x8: // Close
{
- has_recv_close_ = true;
- if (!has_sent_close_) {
- close(fragment_);
+ hasRecvClose = true;
+ if (!hasSentClose) {
+ close(fragment);
} else {
- adaptor_.close();
- close_connection_ = true;
- if (!is_close_handler_called_) {
- if (close_handler_) {
- close_handler_(*this, fragment_);
+ adaptor.close();
+ closeConnection = true;
+ if (!isCloseHandlerCalled) {
+ if (closeHandler) {
+ closeHandler(*this, fragment);
}
- is_close_handler_called_ = true;
+ isCloseHandlerCalled = true;
}
- check_destroy();
+ checkDestroy();
}
} break;
case 0x9: // Ping
{
- send_pong(fragment_);
+ sendPong(fragment);
} break;
case 0xA: // Pong
{
- pong_received_ = true;
+ pongReceived = true;
} break;
}
- fragment_.clear();
+ fragment.clear();
}
- void do_write() {
- if (sending_buffers_.empty()) {
- sending_buffers_.swap(write_buffers_);
+ void doWrite() {
+ if (sendingBuffers.empty()) {
+ sendingBuffers.swap(writeBuffers);
std::vector<boost::asio::const_buffer> buffers;
- buffers.reserve(sending_buffers_.size());
- for (auto& s : sending_buffers_) {
+ buffers.reserve(sendingBuffers.size());
+ for (auto& s : sendingBuffers) {
buffers.emplace_back(boost::asio::buffer(s));
}
- boost::asio::async_write(adaptor_.socket(), buffers,
+ boost::asio::async_write(adaptor.socket(), buffers,
[&](const boost::system::error_code& ec,
std::size_t /*bytes_transferred*/) {
- sending_buffers_.clear();
- if (!ec && !close_connection_) {
- if (!write_buffers_.empty()) {
- do_write();
+ sendingBuffers.clear();
+ if (!ec && !closeConnection) {
+ if (!writeBuffers.empty()) {
+ doWrite();
}
- if (has_sent_close_) {
- close_connection_ = true;
+ if (hasSentClose) {
+ closeConnection = true;
}
} else {
- close_connection_ = true;
- check_destroy();
+ closeConnection = true;
+ checkDestroy();
}
});
}
}
- void check_destroy() {
- // if (has_sent_close_ && has_recv_close_)
- if (!is_close_handler_called_) {
- if (close_handler_) {
- close_handler_(*this, "uncleanly");
+ void checkDestroy() {
+ // if (hasSentClose && hasRecvClose)
+ if (!isCloseHandlerCalled) {
+ if (closeHandler) {
+ closeHandler(*this, "uncleanly");
}
}
- if (sending_buffers_.empty() && !is_reading) {
+ if (sendingBuffers.empty() && !isReading) {
delete this;
}
}
private:
- Adaptor adaptor_;
+ Adaptor adaptor;
- std::vector<std::string> sending_buffers_;
- std::vector<std::string> write_buffers_;
+ std::vector<std::string> sendingBuffers;
+ std::vector<std::string> writeBuffers;
- std::array<char, 4096> buffer_{};
- bool is_binary_{};
- std::string message_;
- std::string fragment_;
- WebSocketReadState state_{WebSocketReadState::MiniHeader};
- uint64_t remaining_length_{0};
- bool close_connection_{false};
- bool is_reading{false};
- uint32_t mask_{};
- uint16_t mini_header_{};
- bool has_sent_close_{false};
- bool has_recv_close_{false};
- bool error_occured_{false};
- bool pong_received_{false};
- bool is_close_handler_called_{false};
+ std::array<char, 4096> buffer{};
+ bool isBinary{};
+ std::string message;
+ std::string fragment;
+ WebSocketReadState state{WebSocketReadState::MiniHeader};
+ uint64_t remainingLength{0};
+ bool closeConnection{false};
+ bool isReading{false};
+ uint32_t mask{};
+ uint16_t miniHeader{};
+ bool hasSentClose{false};
+ bool hasRecvClose{false};
+ bool errorOccured{false};
+ bool pongReceived{false};
+ bool isCloseHandlerCalled{false};
- std::function<void(connection&)> open_handler_;
- std::function<void(connection&, const std::string&, bool)> message_handler_;
- std::function<void(connection&, const std::string&)> close_handler_;
- std::function<void(connection&)> error_handler_;
+ std::function<void(Connection&)> openHandler;
+ std::function<void(Connection&, const std::string&, bool)> messageHandler;
+ std::function<void(Connection&, const std::string&)> closeHandler;
+ std::function<void(Connection&)> errorHandler;
};
} // namespace websocket
} // namespace crow