summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEd Tanous <ed.tanous@intel.com>2018-05-23 01:27:24 +0300
committerEd Tanous <ed.tanous@intel.com>2018-07-27 01:54:37 +0300
commit55c7b7a2e58779580f33046d2dd8649243776700 (patch)
treeeed2d032dff3e18c4a8d4778e8f52ae5864620ee
parent1752c9657b56a6e1950d8725f44f4298c9872c63 (diff)
downloadbmcweb-55c7b7a2e58779580f33046d2dd8649243776700.tar.xz
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>
-rw-r--r--.clang-format5
-rw-r--r--.clang-tidy31
-rw-r--r--CMakeLists.txt10
-rw-r--r--CMakeLists.txt.in100
-rw-r--r--README.md8
-rw-r--r--crow/README.md26
-rw-r--r--crow/include/crow/app.h172
-rw-r--r--crow/include/crow/common.h60
-rw-r--r--crow/include/crow/http_connection.h482
-rw-r--r--crow/include/crow/http_request.h26
-rw-r--r--crow/include/crow/http_response.h105
-rw-r--r--crow/include/crow/http_server.h150
-rw-r--r--crow/include/crow/logging.h60
-rw-r--r--crow/include/crow/middleware_context.h52
-rw-r--r--crow/include/crow/query_string.h163
-rw-r--r--crow/include/crow/routing.h649
-rw-r--r--crow/include/crow/settings.h10
-rw-r--r--crow/include/crow/socket_adaptors.h86
-rw-r--r--crow/include/crow/timer_queue.h34
-rw-r--r--crow/include/crow/utility.h311
-rw-r--r--crow/include/crow/websocket.h439
-rw-r--r--include/aspeed/JTABLES.H72
-rw-r--r--include/ast_jpeg_decoder.hpp1051
-rw-r--r--include/ast_video_puller.hpp141
-rw-r--r--include/ast_video_types.hpp8
-rw-r--r--include/dbus_monitor.hpp43
-rw-r--r--include/dbus_singleton.hpp4
-rw-r--r--include/gzip_helper.hpp4
-rw-r--r--include/http_utility.hpp4
-rw-r--r--include/image_upload.hpp34
-rw-r--r--include/openbmc_dbus_rest.hpp367
-rw-r--r--include/pam_authenticate.hpp47
-rw-r--r--include/persistent_data_middleware.hpp80
-rw-r--r--include/redfish_v1.hpp58
-rw-r--r--include/security_headers_middleware.hpp49
-rw-r--r--include/sessions.hpp160
-rw-r--r--include/ssl_key_handler.hpp102
-rw-r--r--include/token_authorization_middleware.hpp259
-rw-r--r--include/web_kvm.hpp241
-rw-r--r--include/webassets.hpp60
-rw-r--r--include/webserver_common.hpp4
-rw-r--r--redfish-core/include/error_messages.hpp12
-rw-r--r--redfish-core/include/node.hpp30
-rw-r--r--redfish-core/include/privileges.hpp32
-rw-r--r--redfish-core/include/utils/json_utils.hpp2
-rw-r--r--redfish-core/lib/account_service.hpp4
-rw-r--r--redfish-core/lib/chassis.hpp80
-rw-r--r--redfish-core/lib/ethernet.hpp616
-rw-r--r--redfish-core/lib/managers.hpp22
-rw-r--r--redfish-core/lib/network_protocol.hpp4
-rw-r--r--redfish-core/lib/redfish_sessions.hpp91
-rw-r--r--redfish-core/lib/roles.hpp36
-rw-r--r--redfish-core/lib/sensors.hpp162
-rw-r--r--redfish-core/lib/service_root.hpp8
-rw-r--r--redfish-core/lib/systems.hpp174
-rw-r--r--redfish-core/lib/thermal.hpp8
-rw-r--r--redfish-core/lib/update_service.hpp74
-rw-r--r--redfish-core/scripts/error_messages/error_messages.cpp.in16
-rw-r--r--redfish-core/scripts/error_messages/error_messages.hpp.in4
-rw-r--r--redfish-core/src/error_messages.cpp24
-rw-r--r--redfish-core/src/utils/json_utils.cpp4
-rw-r--r--src/ast_jpeg_decoder_test.cpp106
-rw-r--r--src/ast_video_puller_test.cpp18
-rw-r--r--src/base64.cpp6
-rw-r--r--src/crow_getroutes_test.cpp32
-rw-r--r--src/crow_test.cpp340
-rw-r--r--src/getvideo_main.cpp26
-rw-r--r--src/gtest_main.cpp2
-rw-r--r--src/kvm_websocket_test.cpp14
-rw-r--r--src/security_headers_middleware_test.cpp4
-rw-r--r--src/token_authorization_middleware_test.cpp20
-rw-r--r--src/webassets_test.cpp10
-rw-r--r--src/webserver_main.cpp50
73 files changed, 3875 insertions, 3923 deletions
diff --git a/.clang-format b/.clang-format
index 6f1017fdb3..b98e24fe47 100644
--- a/.clang-format
+++ b/.clang-format
@@ -19,7 +19,7 @@ AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
-BraceWrapping:
+BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
@@ -45,8 +45,7 @@ DerivePointerAlignment: true
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
-IncludeCategories:
-
+IncludeCategories:
- Regex: '^[<"](crow)'
Priority: 5
- Regex: '^[<"](boost)'
diff --git a/.clang-tidy b/.clang-tidy
index 2265e4f1e4..9a314f1941 100644
--- a/.clang-tidy
+++ b/.clang-tidy
@@ -1,28 +1,15 @@
---
-Checks: '*,-modernize-raw-string-literal,-modernize-use-nullptr,-cert-err58-cpp,-misc-unused-parameters,-google-runtime-references,-cppcoreguidelines-special-member-functions,-llvm-header-guard,-google-readability-todo,-llvm-include-order,-google-build-using-namespace,-clang-analyzer-alpha.clone.CloneChecker,-google-runtime-int,-cppcoreguidelines-pro-bounds-array-to-pointer-decay,-clang-analyzer-alpha.deadcode.UnreachableCode,-misc-use-after-move,-cppcoreguidelines-pro-type-vararg,-modernize-use-emplace,-cert-err60-cpp'
+Checks: '-*,readability-identifier-naming'
WarningsAsErrors: ''
-HeaderFilterRegex: '(?!gtest)'
+HeaderFilterRegex: '.*'
AnalyzeTemporaryDtors: false
CheckOptions:
- - key: google-readability-braces-around-statements.ShortStatementLines
- value: '1'
- - key: google-readability-function-size.StatementThreshold
- value: '800'
- - key: google-readability-namespace-comments.ShortNamespaceLines
- value: '10'
- - key: google-readability-namespace-comments.SpacesBeforeComments
- value: '2'
- - key: modernize-loop-convert.MaxCopySize
- value: '16'
- - key: modernize-loop-convert.MinConfidence
- value: reasonable
- - key: modernize-loop-convert.NamingStyle
- value: CamelCase
- - key: modernize-pass-by-value.IncludeStyle
- value: llvm
- - key: modernize-replace-auto-ptr.IncludeStyle
- value: llvm
- - key: modernize-use-nullptr.NullMacros
- value: 'NULL'
+ - { key: readability-identifier-naming.NamespaceCase, value: lower_case}
+ - { key: readability-identifier-naming.ClassCase, value: CamelCase }
+ - { key: readability-identifier-naming.StructCase, value: CamelCase }
+ - { key: readability-identifier-naming.FunctionCase, value: camelBack }
+ - { key: readability-identifier-naming.VariableCase, value: camelBack }
+ - { key: readability-identifier-naming.GlobalConstantCase, value: camelBack }
+ - { key: readability-identifier-naming.MemberCase, value: camelBack }
...
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 0b724cfb31..5aebc9e3f1 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -135,18 +135,18 @@ find_package (OpenSSL REQUIRED)
include_directories (${OPENSSL_INCLUDE_DIR})
message ("OPENSSL_INCLUDE_DIR ${OPENSSL_INCLUDE_DIR}")
-# Crow
+# bmcweb
message ("CMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}")
if (CMAKE_BUILD_TYPE MATCHES Debug)
message ("Logging disabled")
- add_definitions (-DCROW_ENABLE_LOGGING)
- add_definitions (-DCROW_ENABLE_DEBUG)
+ add_definitions (-DBMCWEB_ENABLE_LOGGING)
+ add_definitions (-DBMCWEB_ENABLE_DEBUG)
endif (CMAKE_BUILD_TYPE MATCHES Debug)
if (NOT "${BMCWEB_INSECURE_DISABLE_SSL}")
- add_definitions(-DCROW_ENABLE_SSL)
+ add_definitions(-DBMCWEB_ENABLE_SSL)
endif (NOT "${BMCWEB_INSECURE_DISABLE_SSL}")
-include_directories(${CMAKE_CURRENT_SOURCE_DIR}/crow/include)
+include_directories (${CMAKE_CURRENT_SOURCE_DIR}/crow/include)
# Zlib
find_package (ZLIB REQUIRED)
diff --git a/CMakeLists.txt.in b/CMakeLists.txt.in
index 8e39d9b4e9..627b6efe87 100644
--- a/CMakeLists.txt.in
+++ b/CMakeLists.txt.in
@@ -1,63 +1,43 @@
-cmake_minimum_required(VERSION 3.5)
-
-include(ExternalProject)
-
-file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/prefix)
-file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/prefix/include)
-
-
-# add back GIT_TAG in with the correct SHA1 once
-# https://gerrit.openbmc-project.xyz/#/c/10278/ is merged
-#GIT_TAG
-#2a3af936625bc66cfc6bae1952b57138f141377e
-ExternalProject_Add(
- sdbusplus
- GIT_REPOSITORY
- "https://gerrit.openbmc-project.xyz/openbmc/sdbusplus"
- GIT_TAG
- fce038ad5ac9f458b03d55b441253a9c05dadc3e
- SOURCE_DIR "${CMAKE_BINARY_DIR}/sdbusplus-src"
- BINARY_DIR "${CMAKE_BINARY_DIR}/sdbusplus-build"
- CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/prefix
- CONFIGURE_COMMAND ""
- BUILD_COMMAND ""
- INSTALL_COMMAND cp -r "${CMAKE_BINARY_DIR}/sdbusplus-src/sdbusplus"
- "${CMAKE_BINARY_DIR}/prefix/include"
-)
-
-ExternalProject_Add(
- tinyxml2
- GIT_REPOSITORY
- "https://github.com/leethomason/tinyxml2.git"
- GIT_TAG
- 8c8293ba8969a46947606a93ff0cb5a083aab47a
- CMAKE_ARGS
- SOURCE_DIR "${CMAKE_BINARY_DIR}/tinyxml2-src"
- BINARY_DIR "${CMAKE_BINARY_DIR}/tinyxml2-build"
- CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/prefix
-)
-
-ExternalProject_Add(
- Boost
- URL https://dl.bintray.com/boostorg/release/1.66.0/source/boost_1_66_0.tar.gz
- URL_MD5 d275cd85b00022313c171f602db59fc5
- SOURCE_DIR "${CMAKE_BINARY_DIR}/boost-src"
- BINARY_DIR "${CMAKE_BINARY_DIR}/boost-build"
- CONFIGURE_COMMAND ""
- BUILD_COMMAND ""
- INSTALL_COMMAND mkdir -p "${CMAKE_BINARY_DIR}/prefix/include/" && cp -R ${CMAKE_BINARY_DIR}/boost-src/boost ${CMAKE_BINARY_DIR}/prefix/include
-)
-
-ExternalProject_Add(
- gtest
- GIT_REPOSITORY
- "https://github.com/google/googletest.git"
- GIT_TAG
- dfa853b63d17c787914b663b50c2095a0c5b706e
- CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/googletest-build
- SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src"
- BINARY_DIR "${CMAKE_BINARY_DIR}/googletest-build"
- CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/prefix
+cmake_minimum_required (VERSION 3.5)
+
+include (ExternalProject)
+
+file (MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/prefix)
+file (MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/prefix/include)
+
+externalproject_add (sdbusplus GIT_REPOSITORY
+ ssh://git-amr-2.devtools.intel.com:29418/openbmc-sdbusplus
+ GIT_TAG ce4a3cbfe89d1a30e982899bc336029f730f394e
+ SOURCE_DIR "${CMAKE_BINARY_DIR}/sdbusplus-src" BINARY_DIR
+ "${CMAKE_BINARY_DIR}/sdbusplus-build" CMAKE_ARGS
+ -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/prefix
+ CONFIGURE_COMMAND "" BUILD_COMMAND "" INSTALL_COMMAND cp
+ -r "${CMAKE_BINARY_DIR}/sdbusplus-src/sdbusplus"
+ "${CMAKE_BINARY_DIR}/prefix/include")
+
+externalproject_add (tinyxml2 GIT_REPOSITORY
+ https://github.com/leethomason/tinyxml2.git GIT_TAG
+ 8c8293ba8969a46947606a93ff0cb5a083aab47a CMAKE_ARGS
+ SOURCE_DIR "${CMAKE_BINARY_DIR}/tinyxml2-src" BINARY_DIR
+ "${CMAKE_BINARY_DIR}/tinyxml2-build" CMAKE_ARGS
+ -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/prefix)
+
+externalproject_add (gtest GIT_REPOSITORY
+ "https://github.com/google/googletest.git" GIT_TAG
+ dfa853b63d17c787914b663b50c2095a0c5b706e CMAKE_ARGS
+ -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/googletest-build
+ SOURCE_DIR "${CMAKE_BINARY_DIR}/googletest-src" BINARY_DIR
+ "${CMAKE_BINARY_DIR}/googletest-build" CMAKE_ARGS
+ -DCMAKE_INSTALL_PREFIX=${CMAKE_BINARY_DIR}/prefix)
+
+externalproject_add (
+ Boost URL
+ https://dl.bintray.com/boostorg/release/1.66.0/source/boost_1_66_0.tar.gz
+ URL_MD5 d275cd85b00022313c171f602db59fc5 SOURCE_DIR
+ "${CMAKE_BINARY_DIR}/boost-src" BINARY_DIR
+ "${CMAKE_BINARY_DIR}/boost-build" CONFIGURE_COMMAND "" BUILD_COMMAND ""
+ INSTALL_COMMAND mkdir -p "${CMAKE_BINARY_DIR}/prefix/include/" && cp -R
+ ${CMAKE_BINARY_DIR}/boost-src/boost ${CMAKE_BINARY_DIR}/prefix/include
)
ExternalProject_Add(
diff --git a/README.md b/README.md
index f5e937de92..080e85a374 100644
--- a/README.md
+++ b/README.md
@@ -21,17 +21,17 @@ The crow project has had a number of additions to make it more useful for use in
+ Crow server now calls stop before destruction of the Crow app object.
+ Fixed a bug where timed out websockets would seg fault the system by accessing a destroyed socket object without null checks when in SSL mode.
+ Added a TestSocketAdapter class that could be used to unit test server behavior without utilizing a socket.
-+ Added the "get_routes" call to both the app and the routing Trie class that allows consumers to poll the server for all (or a subset of) registered web routes in the system.
++ Added the "getRoutes" call to both the app and the routing Trie class that allows consumers to poll the server for all (or a subset of) registered web routes in the system.
+ Hardcoded the websocket implementation for binary mode, instead of leaving protocol unspecified.
+ Move most uses of std::unordered_map to boost::flat_map to lower memory consumption, and (in some cases) to improve memory locality.
-+ Adjust the add_headers mechanism to use a fixed string instead of a full map implementation to avoid unnecessary mallocs and reduce the number of scatter gather buffers on an http response.
++ Adjust the addHeaders mechanism to use a fixed string instead of a full map implementation to avoid unnecessary mallocs and reduce the number of scatter gather buffers on an http response.
+ Change server name header from Crow/0.1 to iBMC
+ Starts the http server io_service inside the main thread, instead of creating a new thread.
-+ Removes all CROW_MSVC_WORKAROUND flags.
++ Removes all BMCWEB_MSVC_WORKAROUND flags.
+ Removes the behavior that causes a 301 redirect for paths that end in "/", and simply returns the endpoint requested. This was done for redfish compatibility.
+ Removes the built in crow/json.hpp package and adds nlohmann json package as the first class json package for crow.
+ Move uses of boost::array to std::array where possible.
-+ Add the ability to get a reference to the crow::request object on websocket connection to allow checking header values.
++ Add the ability to get a reference to the crow::Request object on websocket connection to allow checking header values.
+ Patch http handler to call middlewares on websocket connections to allow authentication to be applied appropriately.
+ Adds an is_secure flag to provide information about whether or not the payload was delivered over ssl.
diff --git a/crow/README.md b/crow/README.md
index bea6c50913..4fd449240a 100644
--- a/crow/README.md
+++ b/crow/README.md
@@ -12,7 +12,7 @@ int main()
{
crow::SimpleApp app;
- CROW_ROUTE(app, "/")([](){
+ BMCWEB_ROUTE(app, "/")([](){
return "Hello world";
});
@@ -32,7 +32,7 @@ int main()
- You can also use [json11](https://github.com/dropbox/json11) or [rapidjson](https://github.com/miloyip/rapidjson) for better speed or readability
- [Mustache](http://mustache.github.io/) based templating library (crow::mustache)
- Header only
- - Provide an amalgamated header file `crow_all.h' with every features
+ - Provide an amalgamated header file `BMCWEB_all.h' with every features
- Middleware support
- Websocket support
@@ -44,7 +44,7 @@ int main()
#### JSON Response
```c++
-CROW_ROUTE(app, "/json")
+BMCWEB_ROUTE(app, "/json")
([]{
crow::json::wvalue x;
x["message"] = "Hello, World!";
@@ -54,42 +54,42 @@ CROW_ROUTE(app, "/json")
#### Arguments
```c++
-CROW_ROUTE(app,"/hello/<int>")
+BMCWEB_ROUTE(app,"/hello/<int>")
([](int count){
if (count > 100)
- return crow::response(400);
+ return crow::Response(400);
std::ostringstream os;
os << count << " bottles of beer!";
- return crow::response(os.str());
+ return crow::Response(os.str());
});
```
Handler arguments type check at compile time
```c++
// Compile error with message "Handler type is mismatched with URL paramters"
-CROW_ROUTE(app,"/another/<int>")
+BMCWEB_ROUTE(app,"/another/<int>")
([](int a, int b){
- return crow::response(500);
+ return crow::Response(500);
});
```
#### Handling JSON Requests
```c++
-CROW_ROUTE(app, "/add_json")
+BMCWEB_ROUTE(app, "/add_json")
.methods("POST"_method)
-([](const crow::request& req){
+([](const crow::Request& req){
auto x = crow::json::load(req.body);
if (!x)
- return crow::response(400);
+ return crow::Response(400);
int sum = x["a"].i()+x["b"].i();
std::ostringstream os;
os << sum;
- return crow::response{os.str()};
+ return crow::Response{os.str()};
});
```
## How to Build
-If you just want to use crow, copy amalgamate/crow_all.h and include it.
+If you just want to use crow, copy amalgamate/BMCWEB_all.h and include it.
### Requirements
diff --git a/crow/include/crow/app.h b/crow/include/crow/app.h
index 9abf6bbe9e..f006a78724 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 @@ class Crow {
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);
- }
- std::vector<const std::string*> get_routes(const std::string& parent) {
- return router_.get_routes(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);
+ return router.getRoutes(root);
+ }
+ std::vector<const std::string*> getRoutes(const std::string& parent) {
+ return router.getRoutes(parent);
+ }
+
+#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 63fd002fac..e155da6da9 100644
--- a/crow/include/crow/common.h
+++ b/crow/include/crow/common.h
@@ -32,7 +32,7 @@ enum class HTTPMethod {
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 @@ enum class ParamType {
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 @@ struct routing_params {
};
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 @@ constexpr boost::beast::http::verb operator"" _method(const char* str,
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 43437ef7aa..36c19d0c60 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 @@ inline void escape_html(std::string& data) {
data.swap(buffer);
}
-inline void convert_to_links(std::string& s) {
+inline void convertToLinks(std::string& s) {
const static std::regex r{
- "(&quot;@odata\\.((id)|(context))&quot;[ \\n]*:[ "
+ "(&quot;@odata\\.((id)|(Context))&quot;[ \\n]*:[ "
"\\n]*)(&quot;((?!&quot;).*)&quot;)"};
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 @@ using tcp = asio::ip::tcp;
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 @@ struct is_before_handle_arity_3_impl {
};
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 @@ struct is_after_handle_arity_3_impl {
};
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 @@ bool middleware_call_helper(Container& middlewares, request& req, response& res,
}
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());
-
- parser_->body_limit(1024 * 1024 * 1); // 1MB
- req_.emplace(parser_->get());
-#ifdef CROW_ENABLE_DEBUG
+ 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 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 eb3e01c667..301aa59435 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 6c28237843..a7386872a2 100644
--- a/crow/include/crow/http_response.h
+++ b/crow/include/crow/http_response.h
@@ -11,98 +11,97 @@ namespace crow {
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 @@ struct response {
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 86bf54b427..96b85dc264 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 @@ class Server {
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 @@ class Server {
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 @@ class Server {
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 390f80fd45..4a68df38ce 100644
--- a/crow/include/crow/logging.h
+++ b/crow/include/crow/logging.h
@@ -43,29 +43,29 @@ class logger {
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 @@ class logger {
//
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 7b2f8d589b..03309f67c5 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 5e28e186d0..060699477c 100644
--- a/crow/include/crow/query_string.h
+++ b/crow/include/crow/query_string.h
@@ -12,45 +12,45 @@ namespace crow {
// 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 @@ inline int qs_strncmp(const char* s, const char* qs, size_t n) {
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 @@ inline int qs_strncmp(const char* s, const char* qs, size_t n) {
{
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 @@ inline int qs_strncmp(const char* s, const char* qs, size_t n) {
{
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 @@ inline int qs_strncmp(const char* s, const char* qs, size_t n) {
}
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 @@ inline int qs_parse(char* qs, char* qs_kv[], int qs_kv_size) {
// 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 @@ inline int qs_parse(char* qs, char* qs_kv[], int qs_kv_size) {
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 @@ inline int qs_decode(char* qs) {
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 @@ inline char* qs_k2v(const char* key, char* const* qs_kv, int qs_kv_size,
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 @@ inline char* qs_scanvalue(const char* key, const char* qs, char* val,
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 @@ inline char* qs_scanvalue(const char* key, const char* qs, char* val,
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 @@ inline char* qs_scanvalue(const char* key, const char* qs, char* val,
// ----------------------------------------------------------------------------
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 @@ class query_string {
}
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 f3fedd815f..12daeb46a4 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 @@ class BaseRule {
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 @@ struct Wrapped {
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 @@ struct Wrapped {
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 @@ struct Wrapped {
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 @@ class WebSocketRule : public BaseRule {
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 @@ class DynamicRule : public BaseRule, public RuleParameterTraits<DynamicRule> {
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 @@ class DynamicRule : public BaseRule, public RuleParameterTraits<DynamicRule> {
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 @@ class TaggedRule : public BaseRule,
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 @@ class TaggedRule : public BaseRule,
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 @@ class TaggedRule : public BaseRule,
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 @@ class TaggedRule : public BaseRule,
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 @@ class Trie {
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 @@ class Trie {
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 = &empty;
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 @@ class Trie {
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 @@ class Trie {
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 @@ class Trie {
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 @@ class Router {
}
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 8dbd516d12..8cb121974a 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 e3d00816f4..4b379db457 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 @@ using tcp = asio::ip::tcp;
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 d886a6360d..f5bb467a1f 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 @@ class timer_queue {
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 98b6534a16..d2557b0af5 100644
--- a/crow/include/crow/utility.h
+++ b/crow/include/crow/utility.h
@@ -14,105 +14,105 @@ namespace black_magic {
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 @@ struct compute_parameter_tag_from_args_list<> {
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 @@ static inline bool is_parameter_tag_compatible(uint64_t a, uint64_t b) {
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 @@ struct CallHelper<F, S<Args...>> {
};
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 @@ template <class T>
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 @@ template <unsigned N>
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 @@ struct pop_back<> {
// 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 @@ using promote_t = typename promote<T>::type;
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 @@ struct function_traits : public function_traits<decltype(&T::operator())> {
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 @@ inline static std::string base64encode(
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 @@ inline static std::string base64encode_urlsafe(const char* data, size_t size) {
// 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 @@ inline bool base64_decode(const boost::string_view input, std::string& output) {
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 @@ inline bool base64_decode(const boost::string_view input, std::string& output) {
((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 7cd48ef016..2272500356 100644
--- a/crow/include/crow/websocket.h
+++ b/crow/include/crow/websocket.h
@@ -15,49 +15,50 @@ enum class WebSocketReadState {
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 @@ class Connection : public connection {
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 @@ class Connection : public connection {
"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 @@ class Connection : public connection {
}
#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 @@ class Connection : public connection {
#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 @@ class Connection : public connection {
#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 @@ class Connection : public connection {
#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_;
-
- std::vector<std::string> sending_buffers_;
- std::vector<std::string> write_buffers_;
-
- 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::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 adaptor;
+
+ std::vector<std::string> sendingBuffers;
+ std::vector<std::string> writeBuffers;
+
+ 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&)> 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
diff --git a/include/aspeed/JTABLES.H b/include/aspeed/JTABLES.H
index 8f2d9f3c6f..641fcfb76a 100644
--- a/include/aspeed/JTABLES.H
+++ b/include/aspeed/JTABLES.H
@@ -13,24 +13,24 @@ static const unsigned char dezigzag[64 + 15] = {
// let corrupt input sample past end
63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63};
-static const unsigned char *std_luminance_qt;
-static const unsigned char *std_chrominance_qt;
+static const unsigned char *stdLuminanceQt;
+static const unsigned char *stdChrominanceQt;
// Standard Huffman tables (cf. JPEG standard section K.3) */
-static const unsigned char std_dc_luminance_nrcodes[17] = {
+static const unsigned char stdDcLuminanceNrcodes[17] = {
0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0};
-static const unsigned char std_dc_luminance_values[12] = {0, 1, 2, 3, 4, 5,
+static const unsigned char stdDcLuminanceValues[12] = {0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11};
-static const unsigned char std_dc_chrominance_nrcodes[17] = {
+static const unsigned char stdDcChrominanceNrcodes[17] = {
0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0};
-static const unsigned char std_dc_chrominance_values[12] = {0, 1, 2, 3, 4, 5,
+static const unsigned char stdDcChrominanceValues[12] = {0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11};
-static const unsigned char std_ac_luminance_nrcodes[17] = {
+static const unsigned char stdAcLuminanceNrcodes[17] = {
0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d};
-static const unsigned char std_ac_luminance_values[162] = {
+static const unsigned char stdAcLuminanceValues[162] = {
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06,
0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72,
@@ -46,9 +46,9 @@ static const unsigned char std_ac_luminance_values[162] = {
0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4,
0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa};
-static const unsigned char std_ac_chrominance_nrcodes[17] = {
+static const unsigned char stdAcChrominanceNrcodes[17] = {
0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77};
-static const unsigned char std_ac_chrominance_values[162] = {
+static const unsigned char stdAcChrominanceValues[162] = {
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41,
0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1,
@@ -64,7 +64,7 @@ static const unsigned char std_ac_chrominance_values[162] = {
0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4,
0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa};
-static const unsigned short int DC_LUMINANCE_HUFFMANCODE[13 * 2] = {
+static const unsigned short int dcLuminanceHuffmancode[13 * 2] = {
/* 0 */ 0x0000, 0,
/* 1 */ 0x4000, 2,
/* 2 */ 0x6000, 3,
@@ -80,7 +80,7 @@ static const unsigned short int DC_LUMINANCE_HUFFMANCODE[13 * 2] = {
/* 12 */ 0xFFFF, 9,
};
-static const unsigned short int DC_CHROMINANCE_HUFFMANCODE[13 * 2] = {
+static const unsigned short int dcChrominanceHuffmancode[13 * 2] = {
/* 0 */ 0x0000, 0,
/* 1 */ 0x4000, 2,
/* 2 */ 0x8000, 2,
@@ -96,7 +96,7 @@ static const unsigned short int DC_CHROMINANCE_HUFFMANCODE[13 * 2] = {
/* 12 */ 0xFFFF, 11,
};
-static const unsigned short int AC_LUMINANCE_HUFFMANCODE[39 * 2] = {
+static const unsigned short int acLuminanceHuffmancode[39 * 2] = {
/* 0 */ 0x0000, 0,
/* 1 */ 0x4000, 2,
/* 2 */ 0x8000, 2,
@@ -138,7 +138,7 @@ static const unsigned short int AC_LUMINANCE_HUFFMANCODE[39 * 2] = {
/* 38 */ 0xFFFF, 16,
};
-static const unsigned short int AC_CHROMINANCE_HUFFMANCODE[45 * 2] = {
+static const unsigned short int acChrominanceHuffmancode[45 * 2] = {
/* 0 */ 0x0000, 0,
/* 1 */ 0x4000, 2,
/* 2 */ 0x8000, 2,
@@ -187,59 +187,59 @@ static const unsigned short int AC_CHROMINANCE_HUFFMANCODE[45 * 2] = {
};
//[100]=========================
-static const unsigned char Tbl_100Y[64] = {
+static const unsigned char tbl100Y[64] = {
2, 1, 1, 2, 3, 5, 6, 7, 1, 1, 1, 2, 3, 7, 7, 6,
1, 1, 2, 3, 5, 7, 8, 7, 1, 2, 2, 3, 6, 10, 10, 7,
2, 2, 4, 7, 8, 13, 12, 9, 3, 4, 6, 8, 10, 13, 14, 11,
6, 8, 9, 10, 12, 15, 15, 12, 9, 11, 11, 12, 14, 12, 12, 12};
-static const unsigned char Tbl_100UV[64] = {
+static const unsigned char tbl100Uv[64] = {
3, 3, 4, 8, 18, 18, 18, 18, 3, 3, 4, 12, 18, 18, 18, 18,
4, 4, 10, 18, 18, 18, 18, 18, 8, 12, 18, 18, 18, 18, 18, 18,
18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18,
18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18};
//[086]=========================
-static const unsigned char Tbl_086Y[64] = {
+static const unsigned char tbl086Y[64] = {
3, 2, 1, 3, 4, 7, 9, 11, 2, 2, 2, 3, 4, 10, 11, 10,
2, 2, 3, 4, 7, 10, 12, 10, 2, 3, 4, 5, 9, 16, 15, 11,
3, 4, 6, 10, 12, 20, 19, 14, 4, 6, 10, 12, 15, 19, 21, 17,
9, 12, 14, 16, 19, 22, 22, 18, 13, 17, 17, 18, 21, 18, 19, 18};
-static const unsigned char Tbl_086UV[64] = {
+static const unsigned char tbl086Uv[64] = {
4, 5, 6, 13, 27, 27, 27, 27, 5, 5, 7, 18, 27, 27, 27, 27,
6, 7, 15, 27, 27, 27, 27, 27, 13, 18, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27};
//[071]=========================
-static const unsigned char Tbl_071Y[64] = {
+static const unsigned char tbl071Y[64] = {
6, 4, 3, 6, 9, 15, 19, 22, 4, 4, 5, 7, 9, 21, 22, 20,
5, 4, 6, 9, 15, 21, 25, 21, 5, 6, 8, 10, 19, 32, 30, 23,
6, 8, 13, 21, 25, 40, 38, 28, 9, 13, 20, 24, 30, 39, 42, 34,
18, 24, 29, 32, 38, 45, 45, 37, 27, 34, 35, 36, 42, 37, 38, 37};
-static const unsigned char Tbl_071UV[64] = {
+static const unsigned char tbl071Uv[64] = {
9, 10, 13, 26, 55, 55, 55, 55, 10, 11, 14, 37, 55, 55, 55, 55,
13, 14, 31, 55, 55, 55, 55, 55, 26, 37, 55, 55, 55, 55, 55, 55,
55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55,
55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55};
//[057]=========================
-static const unsigned char Tbl_057Y[64] = {
+static const unsigned char tbl057Y[64] = {
9, 6, 5, 9, 13, 22, 28, 34, 6, 6, 7, 10, 14, 32, 33, 30,
7, 7, 9, 13, 22, 32, 38, 31, 7, 9, 12, 16, 28, 48, 45, 34,
10, 12, 20, 31, 38, 61, 57, 43, 13, 19, 30, 36, 45, 58, 63, 51,
27, 36, 43, 48, 57, 68, 67, 56, 40, 51, 53, 55, 63, 56, 57, 55};
-static const unsigned char Tbl_057UV[64] = {
+static const unsigned char tbl057Uv[64] = {
13, 14, 19, 38, 80, 80, 80, 80, 14, 17, 21, 53, 80, 80, 80, 80,
19, 21, 45, 80, 80, 80, 80, 80, 38, 53, 80, 80, 80, 80, 80, 80,
80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80,
80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80};
//[043]=========================
-static const unsigned char Tbl_043Y[64] = {
+static const unsigned char tbl043Y[64] = {
11, 7, 7, 11, 17, 28, 36, 43, 8, 8, 10, 13, 18, 41, 43, 39,
10, 9, 11, 17, 28, 40, 49, 40, 10, 12, 15, 20, 36, 62, 57, 44,
12, 15, 26, 40, 48, 78, 74, 55, 17, 25, 39, 46, 58, 74, 81, 66,
35, 46, 56, 62, 74, 86, 86, 72, 51, 66, 68, 70, 80, 71, 74, 71};
-static const unsigned char Tbl_043UV[64] = {
+static const unsigned char tbl043Uv[64] = {
18, 19, 26, 51, 108, 108, 108, 108, 19, 22, 28, 72, 108,
108, 108, 108, 26, 28, 61, 108, 108, 108, 108, 108, 51, 72,
108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108,
@@ -247,12 +247,12 @@ static const unsigned char Tbl_043UV[64] = {
108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108, 108};
//[029]=========================
-static const unsigned char Tbl_029Y[64] = {
+static const unsigned char tbl029Y[64] = {
14, 9, 9, 14, 21, 36, 46, 55, 10, 10, 12, 17, 23, 52, 54, 49,
12, 11, 14, 21, 36, 51, 62, 50, 12, 15, 19, 26, 46, 78, 72, 56,
16, 19, 33, 50, 61, 98, 93, 69, 21, 31, 49, 58, 73, 94, 102, 83,
44, 58, 70, 78, 93, 109, 108, 91, 65, 83, 86, 88, 101, 90, 93, 89};
-static const unsigned char Tbl_029UV[64] = {
+static const unsigned char tbl029Uv[64] = {
22, 24, 32, 63, 133, 133, 133, 133, 24, 28, 34, 88, 133,
133, 133, 133, 32, 34, 75, 133, 133, 133, 133, 133, 63, 88,
133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133,
@@ -260,40 +260,40 @@ static const unsigned char Tbl_029UV[64] = {
133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133, 133};
//[014]=========================
-static const unsigned char Tbl_014Y[64] = {
+static const unsigned char tbl014Y[64] = {
17, 12, 10, 17, 26, 43, 55, 66, 13, 13, 15, 20, 28, 63, 65, 60,
15, 14, 17, 26, 43, 62, 75, 61, 15, 18, 24, 31, 55, 95, 87, 67,
19, 24, 40, 61, 74, 119, 112, 84, 26, 38, 60, 70, 88, 113, 123, 100,
53, 70, 85, 95, 112, 132, 131, 110, 78, 100, 103, 107, 122, 109, 112, 108};
-static const unsigned char Tbl_014UV[64] = {
+static const unsigned char tbl014Uv[64] = {
27, 29, 39, 76, 160, 160, 160, 160, 29, 34, 42, 107, 160,
160, 160, 160, 39, 42, 91, 160, 160, 160, 160, 160, 76, 107,
160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160,
160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160, 160};
//[000]=========================
-static const unsigned char Tbl_000Y[64] = {
+static const unsigned char tbl000Y[64] = {
20, 13, 12, 20, 30, 50, 63, 76, 15, 15, 17, 23, 32, 72, 75, 68,
17, 16, 20, 30, 50, 71, 86, 70, 17, 21, 27, 36, 63, 108, 100, 77,
22, 27, 46, 70, 85, 136, 128, 96, 30, 43, 68, 80, 101, 130, 141, 115,
61, 80, 97, 108, 128, 151, 150, 126, 90, 115, 118, 122, 140, 125, 128, 123};
-static const unsigned char Tbl_000UV[64] = {
+static const unsigned char tbl000Uv[64] = {
31, 33, 45, 88, 185, 185, 185, 185, 33, 39, 48, 123, 185,
185, 185, 185, 45, 48, 105, 185, 185, 185, 185, 185, 88, 123,
185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185,
185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185,
185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185, 185};
-struct Huffman_table {
- unsigned char Length[17]; // k =1-16 ; L[k] indicates the number of Huffman
+struct HuffmanTable {
+ unsigned char length[17]; // k =1-16 ; L[k] indicates the number of Huffman
// codes of length k
- unsigned short int minor_code[17]; // indicates the value of the smallest
+ unsigned short int minorCode[17]; // indicates the value of the smallest
// Huffman code of length k
- unsigned short int major_code[17]; // similar, but the highest code
- unsigned char V[65536]; // V[k][j] = Value associated to the j-th Huffman
+ unsigned short int majorCode[17]; // similar, but the highest code
+ unsigned char v[65536]; // V[k][j] = Value associated to the j-th Huffman
// code of length k
// High nibble = nr of previous 0 coefficients
// Low nibble = size (in bits) of the coefficient which will be taken from the
// data stream
- unsigned char Len[65536];
+ unsigned char len[65536];
};
diff --git a/include/ast_jpeg_decoder.hpp b/include/ast_jpeg_decoder.hpp
index d2a482ab74..99e60054c5 100644
--- a/include/ast_jpeg_decoder.hpp
+++ b/include/ast_jpeg_decoder.hpp
@@ -1,30 +1,30 @@
#pragma once
+#include <aspeed/JTABLES.H>
#include <ast_video_types.hpp>
#include <array>
-#include <aspeed/JTABLES.H>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <vector>
-namespace AstVideo {
+namespace ast_video {
-struct COLOR_CACHE {
- COLOR_CACHE()
- : Color{0x008080, 0xFF8080, 0x808080, 0xC08080}, Index{0, 1, 2, 3} {}
+struct ColorCache {
+ ColorCache()
+ : color{0x008080, 0xFF8080, 0x808080, 0xC08080}, index{0, 1, 2, 3} {}
- unsigned long Color[4];
- unsigned char Index[4];
- unsigned char BitMapBits{};
+ unsigned long color[4];
+ unsigned char index[4];
+ unsigned char bitMapBits{};
};
struct RGB {
- unsigned char B;
- unsigned char G;
- unsigned char R;
- unsigned char Reserved;
+ unsigned char b;
+ unsigned char g;
+ unsigned char r;
+ unsigned char reserved;
};
enum class JpgBlock {
@@ -54,61 +54,60 @@ class AstJpegDecoder {
public:
AstJpegDecoder() {
// TODO(ed) figure out how to init this in the constructor
- YUVBuffer.resize(1920 * 1200);
- OutBuffer.resize(1920 * 1200);
- for (auto &r : OutBuffer) {
- r.R = 0x00;
- r.G = 0x00;
- r.B = 0x00;
- r.Reserved = 0xAA;
+ yuvBuffer.resize(1920 * 1200);
+ outBuffer.resize(1920 * 1200);
+ for (auto &r : outBuffer) {
+ r.r = 0x00;
+ r.g = 0x00;
+ r.b = 0x00;
+ r.reserved = 0xAA;
}
int qfactor = 16;
- SCALEFACTOR = qfactor;
- SCALEFACTORUV = qfactor;
- ADVANCESCALEFACTOR = 16;
- ADVANCESCALEFACTORUV = 16;
- init_jpg_table();
+ scalefactor = qfactor;
+ scalefactoruv = qfactor;
+ advancescalefactor = 16;
+ advancescalefactoruv = 16;
+ initJpgTable();
}
- void load_quant_table(std::array<long, 64> &quant_table) {
- float scalefactor[8] = {1.0f, 1.387039845f, 1.306562965f, 1.175875602f,
- 1.0f, 0.785694958f, 0.541196100f, 0.275899379f};
+ void loadQuantTable(std::array<long, 64> &quant_table) {
+ float scalefactor_f[8] = {1.0f, 1.387039845f, 1.306562965f, 1.175875602f,
+ 1.0f, 0.785694958f, 0.541196100f, 0.275899379f};
uint8_t j, row, col;
std::array<uint8_t, 64> tempQT{};
// Load quantization coefficients from JPG file, scale them for DCT and
// reorder
// from zig-zag order
- switch (Y_selector) {
+ switch (ySelector) {
case 0:
- std_luminance_qt = Tbl_000Y;
+ stdLuminanceQt = tbl000Y;
break;
case 1:
- std_luminance_qt = Tbl_014Y;
+ stdLuminanceQt = tbl014Y;
break;
case 2:
- std_luminance_qt = Tbl_029Y;
+ stdLuminanceQt = tbl029Y;
break;
case 3:
- std_luminance_qt = Tbl_043Y;
+ stdLuminanceQt = tbl043Y;
break;
case 4:
- std_luminance_qt = Tbl_057Y;
+ stdLuminanceQt = tbl057Y;
break;
case 5:
- std_luminance_qt = Tbl_071Y;
+ stdLuminanceQt = tbl071Y;
break;
case 6:
- std_luminance_qt = Tbl_086Y;
+ stdLuminanceQt = tbl086Y;
break;
case 7:
- std_luminance_qt = Tbl_100Y;
+ stdLuminanceQt = tbl100Y;
break;
}
- set_quant_table(std_luminance_qt, static_cast<uint8_t>(SCALEFACTOR),
- tempQT);
+ setQuantTable(stdLuminanceQt, static_cast<uint8_t>(scalefactor), tempQT);
for (j = 0; j <= 63; j++) {
quant_table[j] = tempQT[zigzag[j]];
@@ -117,14 +116,14 @@ class AstJpegDecoder {
for (row = 0; row <= 7; row++) {
for (col = 0; col <= 7; col++) {
quant_table[j] = static_cast<long>(
- (quant_table[j] * scalefactor[row] * scalefactor[col]) * 65536);
+ (quant_table[j] * scalefactor_f[row] * scalefactor_f[col]) * 65536);
j++;
}
}
- byte_pos += 64;
+ bytePos += 64;
}
- void load_quant_tableCb(std::array<long, 64> &quant_table) {
+ void loadQuantTableCb(std::array<long, 64> &quant_table) {
float scalefactor[8] = {1.0f, 1.387039845f, 1.306562965f, 1.175875602f,
1.0f, 0.785694958f, 0.541196100f, 0.275899379f};
uint8_t j, row, col;
@@ -132,63 +131,63 @@ class AstJpegDecoder {
// Load quantization coefficients from JPG file, scale them for DCT and
// reorder from zig-zag order
- if (Mapping == 0) {
- switch (UV_selector) {
+ if (mapping == 0) {
+ switch (uvSelector) {
case 0:
- std_chrominance_qt = Tbl_000Y;
+ stdChrominanceQt = tbl000Y;
break;
case 1:
- std_chrominance_qt = Tbl_014Y;
+ stdChrominanceQt = tbl014Y;
break;
case 2:
- std_chrominance_qt = Tbl_029Y;
+ stdChrominanceQt = tbl029Y;
break;
case 3:
- std_chrominance_qt = Tbl_043Y;
+ stdChrominanceQt = tbl043Y;
break;
case 4:
- std_chrominance_qt = Tbl_057Y;
+ stdChrominanceQt = tbl057Y;
break;
case 5:
- std_chrominance_qt = Tbl_071Y;
+ stdChrominanceQt = tbl071Y;
break;
case 6:
- std_chrominance_qt = Tbl_086Y;
+ stdChrominanceQt = tbl086Y;
break;
case 7:
- std_chrominance_qt = Tbl_100Y;
+ stdChrominanceQt = tbl100Y;
break;
}
} else {
- switch (UV_selector) {
+ switch (uvSelector) {
case 0:
- std_chrominance_qt = Tbl_000UV;
+ stdChrominanceQt = tbl000Uv;
break;
case 1:
- std_chrominance_qt = Tbl_014UV;
+ stdChrominanceQt = tbl014Uv;
break;
case 2:
- std_chrominance_qt = Tbl_029UV;
+ stdChrominanceQt = tbl029Uv;
break;
case 3:
- std_chrominance_qt = Tbl_043UV;
+ stdChrominanceQt = tbl043Uv;
break;
case 4:
- std_chrominance_qt = Tbl_057UV;
+ stdChrominanceQt = tbl057Uv;
break;
case 5:
- std_chrominance_qt = Tbl_071UV;
+ stdChrominanceQt = tbl071Uv;
break;
case 6:
- std_chrominance_qt = Tbl_086UV;
+ stdChrominanceQt = tbl086Uv;
break;
case 7:
- std_chrominance_qt = Tbl_100UV;
+ stdChrominanceQt = tbl100Uv;
break;
}
}
- set_quant_table(std_chrominance_qt, static_cast<uint8_t>(SCALEFACTORUV),
- tempQT);
+ setQuantTable(stdChrominanceQt, static_cast<uint8_t>(scalefactoruv),
+ tempQT);
for (j = 0; j <= 63; j++) {
quant_table[j] = tempQT[zigzag[j]];
@@ -201,10 +200,10 @@ class AstJpegDecoder {
j++;
}
}
- byte_pos += 64;
+ bytePos += 64;
}
// Note: Added for Dual_JPEG
- void load_advance_quant_table(std::array<long, 64> &quant_table) {
+ void loadAdvanceQuantTable(std::array<long, 64> &quant_table) {
float scalefactor[8] = {1.0f, 1.387039845f, 1.306562965f, 1.175875602f,
1.0f, 0.785694958f, 0.541196100f, 0.275899379f};
uint8_t j, row, col;
@@ -213,35 +212,35 @@ class AstJpegDecoder {
// Load quantization coefficients from JPG file, scale them for DCT and
// reorder
// from zig-zag order
- switch (advance_selector) {
+ switch (advanceSelector) {
case 0:
- std_luminance_qt = Tbl_000Y;
+ stdLuminanceQt = tbl000Y;
break;
case 1:
- std_luminance_qt = Tbl_014Y;
+ stdLuminanceQt = tbl014Y;
break;
case 2:
- std_luminance_qt = Tbl_029Y;
+ stdLuminanceQt = tbl029Y;
break;
case 3:
- std_luminance_qt = Tbl_043Y;
+ stdLuminanceQt = tbl043Y;
break;
case 4:
- std_luminance_qt = Tbl_057Y;
+ stdLuminanceQt = tbl057Y;
break;
case 5:
- std_luminance_qt = Tbl_071Y;
+ stdLuminanceQt = tbl071Y;
break;
case 6:
- std_luminance_qt = Tbl_086Y;
+ stdLuminanceQt = tbl086Y;
break;
case 7:
- std_luminance_qt = Tbl_100Y;
+ stdLuminanceQt = tbl100Y;
break;
}
// Note: pass ADVANCE SCALE FACTOR to sub-function in Dual-JPEG
- set_quant_table(std_luminance_qt, static_cast<uint8_t>(ADVANCESCALEFACTOR),
- tempQT);
+ setQuantTable(stdLuminanceQt, static_cast<uint8_t>(advancescalefactor),
+ tempQT);
for (j = 0; j <= 63; j++) {
quant_table[j] = tempQT[zigzag[j]];
@@ -254,11 +253,11 @@ class AstJpegDecoder {
j++;
}
}
- byte_pos += 64;
+ bytePos += 64;
}
// Note: Added for Dual-JPEG
- void load_advance_quant_tableCb(std::array<long, 64> &quant_table) {
+ void loadAdvanceQuantTableCb(std::array<long, 64> &quant_table) {
float scalefactor[8] = {1.0f, 1.387039845f, 1.306562965f, 1.175875602f,
1.0f, 0.785694958f, 0.541196100f, 0.275899379f};
uint8_t j, row, col;
@@ -267,64 +266,64 @@ class AstJpegDecoder {
// Load quantization coefficients from JPG file, scale them for DCT and
// reorder
// from zig-zag order
- if (Mapping == 1) {
- switch (advance_selector) {
+ if (mapping == 1) {
+ switch (advanceSelector) {
case 0:
- std_chrominance_qt = Tbl_000Y;
+ stdChrominanceQt = tbl000Y;
break;
case 1:
- std_chrominance_qt = Tbl_014Y;
+ stdChrominanceQt = tbl014Y;
break;
case 2:
- std_chrominance_qt = Tbl_029Y;
+ stdChrominanceQt = tbl029Y;
break;
case 3:
- std_chrominance_qt = Tbl_043Y;
+ stdChrominanceQt = tbl043Y;
break;
case 4:
- std_chrominance_qt = Tbl_057Y;
+ stdChrominanceQt = tbl057Y;
break;
case 5:
- std_chrominance_qt = Tbl_071Y;
+ stdChrominanceQt = tbl071Y;
break;
case 6:
- std_chrominance_qt = Tbl_086Y;
+ stdChrominanceQt = tbl086Y;
break;
case 7:
- std_chrominance_qt = Tbl_100Y;
+ stdChrominanceQt = tbl100Y;
break;
}
} else {
- switch (advance_selector) {
+ switch (advanceSelector) {
case 0:
- std_chrominance_qt = Tbl_000UV;
+ stdChrominanceQt = tbl000Uv;
break;
case 1:
- std_chrominance_qt = Tbl_014UV;
+ stdChrominanceQt = tbl014Uv;
break;
case 2:
- std_chrominance_qt = Tbl_029UV;
+ stdChrominanceQt = tbl029Uv;
break;
case 3:
- std_chrominance_qt = Tbl_043UV;
+ stdChrominanceQt = tbl043Uv;
break;
case 4:
- std_chrominance_qt = Tbl_057UV;
+ stdChrominanceQt = tbl057Uv;
break;
case 5:
- std_chrominance_qt = Tbl_071UV;
+ stdChrominanceQt = tbl071Uv;
break;
case 6:
- std_chrominance_qt = Tbl_086UV;
+ stdChrominanceQt = tbl086Uv;
break;
case 7:
- std_chrominance_qt = Tbl_100UV;
+ stdChrominanceQt = tbl100Uv;
break;
}
}
// Note: pass ADVANCE SCALE FACTOR to sub-function in Dual-JPEG
- set_quant_table(std_chrominance_qt,
- static_cast<uint8_t>(ADVANCESCALEFACTORUV), tempQT);
+ setQuantTable(stdChrominanceQt, static_cast<uint8_t>(advancescalefactoruv),
+ tempQT);
for (j = 0; j <= 63; j++) {
quant_table[j] = tempQT[zigzag[j]];
@@ -337,10 +336,10 @@ class AstJpegDecoder {
j++;
}
}
- byte_pos += 64;
+ bytePos += 64;
}
- void IDCT_transform(short *coef, uint8_t *data, uint8_t nBlock) {
+ void idctTransform(short *coef, uint8_t *data, uint8_t nBlock) {
#define FIX_1_082392200 ((int)277) /* FIX(1.082392200) */
#define FIX_1_414213562 ((int)362) /* FIX(1.414213562) */
#define FIX_1_847759065 ((int)473) /* FIX(1.847759065) */
@@ -357,38 +356,38 @@ class AstJpegDecoder {
long *quantptr;
int *wsptr = workspace;
unsigned char *outptr;
- unsigned char *r_limit = rlimit_table + 128;
- int ctr, dcval, DCTSIZE = 8;
+ unsigned char *rLimit = rlimitTable + 128;
+ int ctr, dcval, dctsize = 8;
- quantptr = &QT[nBlock][0];
+ quantptr = &qt[nBlock][0];
// Pass 1: process columns from input (inptr), store into work array(wsptr)
for (ctr = 8; ctr > 0; ctr--) {
/* Due to quantization, we will usually find that many of the input
- * coefficients are zero, especially the AC terms. We can exploit this
- * by short-circuiting the IDCT calculation for any column in which all
- * the AC terms are zero. In that case each output is equal to the
- * DC coefficient (with scale factor as needed).
- * With typical images and quantization tables, half or more of the
- * column DCT calculations can be simplified this way.
- */
-
- if ((inptr[DCTSIZE * 1] | inptr[DCTSIZE * 2] | inptr[DCTSIZE * 3] |
- inptr[DCTSIZE * 4] | inptr[DCTSIZE * 5] | inptr[DCTSIZE * 6] |
- inptr[DCTSIZE * 7]) == 0) {
+ * coefficients are zero, especially the AC terms. We can exploit this
+ * by short-circuiting the IDCT calculation for any column in which all
+ * the AC terms are zero. In that case each output is equal to the
+ * DC coefficient (with scale factor as needed).
+ * With typical images and quantization tables, half or more of the
+ * column DCT calculations can be simplified this way.
+ */
+
+ if ((inptr[dctsize * 1] | inptr[dctsize * 2] | inptr[dctsize * 3] |
+ inptr[dctsize * 4] | inptr[dctsize * 5] | inptr[dctsize * 6] |
+ inptr[dctsize * 7]) == 0) {
/* AC terms all zero */
- dcval = static_cast<int>((inptr[DCTSIZE * 0] * quantptr[DCTSIZE * 0]) >>
+ dcval = static_cast<int>((inptr[dctsize * 0] * quantptr[dctsize * 0]) >>
16);
- wsptr[DCTSIZE * 0] = dcval;
- wsptr[DCTSIZE * 1] = dcval;
- wsptr[DCTSIZE * 2] = dcval;
- wsptr[DCTSIZE * 3] = dcval;
- wsptr[DCTSIZE * 4] = dcval;
- wsptr[DCTSIZE * 5] = dcval;
- wsptr[DCTSIZE * 6] = dcval;
- wsptr[DCTSIZE * 7] = dcval;
+ wsptr[dctsize * 0] = dcval;
+ wsptr[dctsize * 1] = dcval;
+ wsptr[dctsize * 2] = dcval;
+ wsptr[dctsize * 3] = dcval;
+ wsptr[dctsize * 4] = dcval;
+ wsptr[dctsize * 5] = dcval;
+ wsptr[dctsize * 6] = dcval;
+ wsptr[dctsize * 7] = dcval;
inptr++; /* advance pointers to next column */
quantptr++;
@@ -398,10 +397,10 @@ class AstJpegDecoder {
/* Even part */
- tmp0 = (inptr[DCTSIZE * 0] * quantptr[DCTSIZE * 0]) >> 16;
- tmp1 = (inptr[DCTSIZE * 2] * quantptr[DCTSIZE * 2]) >> 16;
- tmp2 = (inptr[DCTSIZE * 4] * quantptr[DCTSIZE * 4]) >> 16;
- tmp3 = (inptr[DCTSIZE * 6] * quantptr[DCTSIZE * 6]) >> 16;
+ tmp0 = (inptr[dctsize * 0] * quantptr[dctsize * 0]) >> 16;
+ tmp1 = (inptr[dctsize * 2] * quantptr[dctsize * 2]) >> 16;
+ tmp2 = (inptr[dctsize * 4] * quantptr[dctsize * 4]) >> 16;
+ tmp3 = (inptr[dctsize * 6] * quantptr[dctsize * 6]) >> 16;
tmp10 = tmp0 + tmp2; /* phase 3 */
tmp11 = tmp0 - tmp2;
@@ -416,10 +415,10 @@ class AstJpegDecoder {
/* Odd part */
- tmp4 = (inptr[DCTSIZE * 1] * quantptr[DCTSIZE * 1]) >> 16;
- tmp5 = (inptr[DCTSIZE * 3] * quantptr[DCTSIZE * 3]) >> 16;
- tmp6 = (inptr[DCTSIZE * 5] * quantptr[DCTSIZE * 5]) >> 16;
- tmp7 = (inptr[DCTSIZE * 7] * quantptr[DCTSIZE * 7]) >> 16;
+ tmp4 = (inptr[dctsize * 1] * quantptr[dctsize * 1]) >> 16;
+ tmp5 = (inptr[dctsize * 3] * quantptr[dctsize * 3]) >> 16;
+ tmp6 = (inptr[dctsize * 5] * quantptr[dctsize * 5]) >> 16;
+ tmp7 = (inptr[dctsize * 7] * quantptr[dctsize * 7]) >> 16;
z13 = tmp6 + tmp5; /* phase 6 */
z10 = tmp6 - tmp5;
@@ -437,14 +436,14 @@ class AstJpegDecoder {
tmp5 = tmp11 - tmp6;
tmp4 = tmp10 + tmp5;
- wsptr[DCTSIZE * 0] = (tmp0 + tmp7);
- wsptr[DCTSIZE * 7] = (tmp0 - tmp7);
- wsptr[DCTSIZE * 1] = (tmp1 + tmp6);
- wsptr[DCTSIZE * 6] = (tmp1 - tmp6);
- wsptr[DCTSIZE * 2] = (tmp2 + tmp5);
- wsptr[DCTSIZE * 5] = (tmp2 - tmp5);
- wsptr[DCTSIZE * 4] = (tmp3 + tmp4);
- wsptr[DCTSIZE * 3] = (tmp3 - tmp4);
+ wsptr[dctsize * 0] = (tmp0 + tmp7);
+ wsptr[dctsize * 7] = (tmp0 - tmp7);
+ wsptr[dctsize * 1] = (tmp1 + tmp6);
+ wsptr[dctsize * 6] = (tmp1 - tmp6);
+ wsptr[dctsize * 2] = (tmp2 + tmp5);
+ wsptr[dctsize * 5] = (tmp2 - tmp5);
+ wsptr[dctsize * 4] = (tmp3 + tmp4);
+ wsptr[dctsize * 3] = (tmp3 - tmp4);
inptr++; /* advance pointers to next column */
quantptr++;
@@ -460,16 +459,16 @@ class AstJpegDecoder {
#define IDESCALE(x, n) ((int)((x) >> (n)))
wsptr = workspace;
- for (ctr = 0; ctr < DCTSIZE; ctr++) {
+ for (ctr = 0; ctr < dctsize; ctr++) {
outptr = data + ctr * 8;
/* Rows of zeroes can be exploited in the same way as we did with columns.
- * However, the column calculation has created many nonzero AC terms, so
- * the simplification applies less often (typically 5% to 10% of the time).
- * On machines with very fast multiplication, it's possible that the
- * test takes more time than it's worth. In that case this section
- * may be commented out.
- */
+ * However, the column calculation has created many nonzero AC terms, so
+ * the simplification applies less often (typically 5% to 10% of the
+ * time). On machines with very fast multiplication, it's possible that
+ * the test takes more time than it's worth. In that case this section
+ * may be commented out.
+ */
/* Even part */
tmp10 = (wsptr[0] + wsptr[4]);
@@ -503,32 +502,32 @@ class AstJpegDecoder {
/* Final output stage: scale down by a factor of 8 and range-limit */
- outptr[0] = r_limit[IDESCALE((tmp0 + tmp7), (PASS1_BITS + 3)) & 1023L];
- outptr[7] = r_limit[IDESCALE((tmp0 - tmp7), (PASS1_BITS + 3)) & 1023L];
- outptr[1] = r_limit[IDESCALE((tmp1 + tmp6), (PASS1_BITS + 3)) & 1023L];
- outptr[6] = r_limit[IDESCALE((tmp1 - tmp6), (PASS1_BITS + 3)) & 1023L];
- outptr[2] = r_limit[IDESCALE((tmp2 + tmp5), (PASS1_BITS + 3)) & 1023L];
- outptr[5] = r_limit[IDESCALE((tmp2 - tmp5), (PASS1_BITS + 3)) & 1023L];
- outptr[4] = r_limit[IDESCALE((tmp3 + tmp4), (PASS1_BITS + 3)) & 1023L];
- outptr[3] = r_limit[IDESCALE((tmp3 - tmp4), (PASS1_BITS + 3)) & 1023L];
+ outptr[0] = rLimit[IDESCALE((tmp0 + tmp7), (PASS1_BITS + 3)) & 1023L];
+ outptr[7] = rLimit[IDESCALE((tmp0 - tmp7), (PASS1_BITS + 3)) & 1023L];
+ outptr[1] = rLimit[IDESCALE((tmp1 + tmp6), (PASS1_BITS + 3)) & 1023L];
+ outptr[6] = rLimit[IDESCALE((tmp1 - tmp6), (PASS1_BITS + 3)) & 1023L];
+ outptr[2] = rLimit[IDESCALE((tmp2 + tmp5), (PASS1_BITS + 3)) & 1023L];
+ outptr[5] = rLimit[IDESCALE((tmp2 - tmp5), (PASS1_BITS + 3)) & 1023L];
+ outptr[4] = rLimit[IDESCALE((tmp3 + tmp4), (PASS1_BITS + 3)) & 1023L];
+ outptr[3] = rLimit[IDESCALE((tmp3 - tmp4), (PASS1_BITS + 3)) & 1023L];
- wsptr += DCTSIZE; /* advance pointer to next row */
+ wsptr += dctsize; /* advance pointer to next row */
}
}
- void YUVToRGB(
+ void yuvToRgb(
int txb, int tyb,
unsigned char
*pYCbCr, // in, Y: 256 or 64 bytes; Cb: 64 bytes; Cr: 64 bytes
struct RGB *pYUV, // in, Y: 256 or 64 bytes; Cb: 64 bytes; Cr: 64 bytes
unsigned char
*pBgr // out, BGR format, 16*16*3 = 768 bytes; or 8*8*3=192 bytes
- ) {
+ ) {
int i, j, pos, m, n;
unsigned char cb, cr, *py, *pcb, *pcr, *py420[4];
int y;
struct RGB *pByte;
int nBlocksInMcu = 6;
- unsigned int pixel_x, pixel_y;
+ unsigned int pixelX, pixelY;
pByte = reinterpret_cast<struct RGB *>(pBgr);
if (yuvmode == YuvMode::YUV444) {
@@ -536,9 +535,9 @@ class AstJpegDecoder {
pcb = pYCbCr + 64;
pcr = pcb + 64;
- pixel_x = txb * 8;
- pixel_y = tyb * 8;
- pos = (pixel_y * WIDTH) + pixel_x;
+ pixelX = txb * 8;
+ pixelY = tyb * 8;
+ pos = (pixelY * width) + pixelX;
for (j = 0; j < 8; j++) {
for (i = 0; i < 8; i++) {
@@ -548,14 +547,14 @@ class AstJpegDecoder {
cr = pcr[m];
n = pos + i;
// For 2Pass. Save the YUV value
- pYUV[n].B = cb;
- pYUV[n].G = y;
- pYUV[n].R = cr;
- pByte[n].B = rlimit_table[m_Y[y] + m_CbToB[cb]];
- pByte[n].G = rlimit_table[m_Y[y] + m_CbToG[cb] + m_CrToG[cr]];
- pByte[n].R = rlimit_table[m_Y[y] + m_CrToR[cr]];
+ pYUV[n].b = cb;
+ pYUV[n].g = y;
+ pYUV[n].r = cr;
+ pByte[n].b = rlimitTable[mY[y] + mCbToB[cb]];
+ pByte[n].g = rlimitTable[mY[y] + mCbToG[cb] + mCrToG[cr]];
+ pByte[n].r = rlimitTable[mY[y] + mCrToR[cr]];
}
- pos += WIDTH;
+ pos += width;
}
} else {
for (i = 0; i < nBlocksInMcu - 2; i++) {
@@ -564,9 +563,9 @@ class AstJpegDecoder {
pcb = pYCbCr + (nBlocksInMcu - 2) * 64;
pcr = pcb + 64;
- pixel_x = txb * 16;
- pixel_y = tyb * 16;
- pos = (pixel_y * WIDTH) + pixel_x;
+ pixelX = txb * 16;
+ pixelY = tyb * 16;
+ pos = (pixelY * width) + pixelX;
for (j = 0; j < 16; j++) {
for (i = 0; i < 16; i++) {
@@ -576,15 +575,15 @@ class AstJpegDecoder {
cb = pcb[m];
cr = pcr[m];
n = pos + i;
- pByte[n].B = rlimit_table[m_Y[y] + m_CbToB[cb]];
- pByte[n].G = rlimit_table[m_Y[y] + m_CbToG[cb] + m_CrToG[cr]];
- pByte[n].R = rlimit_table[m_Y[y] + m_CrToR[cr]];
+ pByte[n].b = rlimitTable[mY[y] + mCbToB[cb]];
+ pByte[n].g = rlimitTable[mY[y] + mCbToG[cb] + mCrToG[cr]];
+ pByte[n].r = rlimitTable[mY[y] + mCrToR[cr]];
}
- pos += WIDTH;
+ pos += width;
}
}
}
- void YUVToBuffer(
+ void yuvToBuffer(
int txb, int tyb,
unsigned char
*pYCbCr, // in, Y: 256 or 64 bytes; Cb: 64 bytes; Cr: 64 bytes
@@ -592,13 +591,13 @@ class AstJpegDecoder {
*pYUV, // out, BGR format, 16*16*3 = 768 bytes; or 8*8*3=192 bytes
unsigned char
*pBgr // out, BGR format, 16*16*3 = 768 bytes; or 8*8*3=192 bytes
- ) {
+ ) {
int i, j, pos, m, n;
unsigned char cb, cr, *py, *pcb, *pcr, *py420[4];
int y;
struct RGB *pByte;
int nBlocksInMcu = 6;
- unsigned int pixel_x, pixel_y;
+ unsigned int pixelX, pixelY;
pByte = reinterpret_cast<struct RGB *>(pBgr);
if (yuvmode == YuvMode::YUV444) {
@@ -606,25 +605,25 @@ class AstJpegDecoder {
pcb = pYCbCr + 64;
pcr = pcb + 64;
- pixel_x = txb * 8;
- pixel_y = tyb * 8;
- pos = (pixel_y * WIDTH) + pixel_x;
+ pixelX = txb * 8;
+ pixelY = tyb * 8;
+ pos = (pixelY * width) + pixelX;
for (j = 0; j < 8; j++) {
for (i = 0; i < 8; i++) {
m = ((j << 3) + i);
n = pos + i;
- y = pYUV[n].G + (py[m] - 128);
- cb = pYUV[n].B + (pcb[m] - 128);
- cr = pYUV[n].R + (pcr[m] - 128);
- pYUV[n].B = cb;
- pYUV[n].G = y;
- pYUV[n].R = cr;
- pByte[n].B = rlimit_table[m_Y[y] + m_CbToB[cb]];
- pByte[n].G = rlimit_table[m_Y[y] + m_CbToG[cb] + m_CrToG[cr]];
- pByte[n].R = rlimit_table[m_Y[y] + m_CrToR[cr]];
+ y = pYUV[n].g + (py[m] - 128);
+ cb = pYUV[n].b + (pcb[m] - 128);
+ cr = pYUV[n].r + (pcr[m] - 128);
+ pYUV[n].b = cb;
+ pYUV[n].g = y;
+ pYUV[n].r = cr;
+ pByte[n].b = rlimitTable[mY[y] + mCbToB[cb]];
+ pByte[n].g = rlimitTable[mY[y] + mCbToG[cb] + mCrToG[cr]];
+ pByte[n].r = rlimitTable[mY[y] + mCrToR[cr]];
}
- pos += WIDTH;
+ pos += width;
}
} else {
for (i = 0; i < nBlocksInMcu - 2; i++) {
@@ -633,9 +632,9 @@ class AstJpegDecoder {
pcb = pYCbCr + (nBlocksInMcu - 2) * 64;
pcr = pcb + 64;
- pixel_x = txb * 16;
- pixel_y = tyb * 16;
- pos = (pixel_y * WIDTH) + pixel_x;
+ pixelX = txb * 16;
+ pixelY = tyb * 16;
+ pos = (pixelY * width) + pixelX;
for (j = 0; j < 16; j++) {
for (i = 0; i < 16; i++) {
@@ -645,125 +644,125 @@ class AstJpegDecoder {
cb = pcb[m];
cr = pcr[m];
n = pos + i;
- pByte[n].B = rlimit_table[m_Y[y] + m_CbToB[cb]];
- pByte[n].G = rlimit_table[m_Y[y] + m_CbToG[cb] + m_CrToG[cr]];
- pByte[n].R = rlimit_table[m_Y[y] + m_CrToR[cr]];
+ pByte[n].b = rlimitTable[mY[y] + mCbToB[cb]];
+ pByte[n].g = rlimitTable[mY[y] + mCbToG[cb] + mCrToG[cr]];
+ pByte[n].r = rlimitTable[mY[y] + mCrToR[cr]];
}
- pos += WIDTH;
+ pos += width;
}
}
}
- void Decompress(int txb, int tyb, char *outBuf, uint8_t QT_TableSelection) {
+ void decompress(int txb, int tyb, char *outBuf, uint8_t QT_TableSelection) {
unsigned char *ptr;
unsigned char byTileYuv[768] = {};
- memset(DCT_coeff, 0, 384 * 2);
+ memset(dctCoeff, 0, 384 * 2);
ptr = byTileYuv;
- process_Huffman_data_unit(YDC_nr, YAC_nr, &DCY, 0);
- IDCT_transform(DCT_coeff, ptr, QT_TableSelection);
+ processHuffmanDataUnit(ydcNr, yacNr, &dcy, 0);
+ idctTransform(dctCoeff, ptr, QT_TableSelection);
ptr += 64;
if (yuvmode == YuvMode::YUV420) {
- process_Huffman_data_unit(YDC_nr, YAC_nr, &DCY, 64);
- IDCT_transform(DCT_coeff + 64, ptr, QT_TableSelection);
+ processHuffmanDataUnit(ydcNr, yacNr, &dcy, 64);
+ idctTransform(dctCoeff + 64, ptr, QT_TableSelection);
ptr += 64;
- process_Huffman_data_unit(YDC_nr, YAC_nr, &DCY, 128);
- IDCT_transform(DCT_coeff + 128, ptr, QT_TableSelection);
+ processHuffmanDataUnit(ydcNr, yacNr, &dcy, 128);
+ idctTransform(dctCoeff + 128, ptr, QT_TableSelection);
ptr += 64;
- process_Huffman_data_unit(YDC_nr, YAC_nr, &DCY, 192);
- IDCT_transform(DCT_coeff + 192, ptr, QT_TableSelection);
+ processHuffmanDataUnit(ydcNr, yacNr, &dcy, 192);
+ idctTransform(dctCoeff + 192, ptr, QT_TableSelection);
ptr += 64;
- process_Huffman_data_unit(CbDC_nr, CbAC_nr, &DCCb, 256);
- IDCT_transform(DCT_coeff + 256, ptr, QT_TableSelection + 1);
+ processHuffmanDataUnit(cbDcNr, cbAcNr, &dcCb, 256);
+ idctTransform(dctCoeff + 256, ptr, QT_TableSelection + 1);
ptr += 64;
- process_Huffman_data_unit(CrDC_nr, CrAC_nr, &DCCr, 320);
- IDCT_transform(DCT_coeff + 320, ptr, QT_TableSelection + 1);
+ processHuffmanDataUnit(crDcNr, crAcNr, &dcCr, 320);
+ idctTransform(dctCoeff + 320, ptr, QT_TableSelection + 1);
} else {
- process_Huffman_data_unit(CbDC_nr, CbAC_nr, &DCCb, 64);
- IDCT_transform(DCT_coeff + 64, ptr, QT_TableSelection + 1);
+ processHuffmanDataUnit(cbDcNr, cbAcNr, &dcCb, 64);
+ idctTransform(dctCoeff + 64, ptr, QT_TableSelection + 1);
ptr += 64;
- process_Huffman_data_unit(CrDC_nr, CrAC_nr, &DCCr, 128);
- IDCT_transform(DCT_coeff + 128, ptr, QT_TableSelection + 1);
+ processHuffmanDataUnit(crDcNr, crAcNr, &dcCr, 128);
+ idctTransform(dctCoeff + 128, ptr, QT_TableSelection + 1);
}
- // YUVToRGB (txb, tyb, byTileYuv, (unsigned char *)outBuf);
- // YUVBuffer for YUV record
- YUVToRGB(txb, tyb, byTileYuv, YUVBuffer.data(),
+ // yuvToRgb (txb, tyb, byTileYuv, (unsigned char *)outBuf);
+ // yuvBuffer for YUV record
+ yuvToRgb(txb, tyb, byTileYuv, yuvBuffer.data(),
reinterpret_cast<unsigned char *>(outBuf));
}
- void Decompress_2PASS(int txb, int tyb, char *outBuf,
- uint8_t QT_TableSelection) {
+ void decompress2Pass(int txb, int tyb, char *outBuf,
+ uint8_t QT_TableSelection) {
unsigned char *ptr;
unsigned char byTileYuv[768];
- memset(DCT_coeff, 0, 384 * 2);
+ memset(dctCoeff, 0, 384 * 2);
ptr = byTileYuv;
- process_Huffman_data_unit(YDC_nr, YAC_nr, &DCY, 0);
- IDCT_transform(DCT_coeff, ptr, QT_TableSelection);
+ processHuffmanDataUnit(ydcNr, yacNr, &dcy, 0);
+ idctTransform(dctCoeff, ptr, QT_TableSelection);
ptr += 64;
- process_Huffman_data_unit(CbDC_nr, CbAC_nr, &DCCb, 64);
- IDCT_transform(DCT_coeff + 64, ptr, QT_TableSelection + 1);
+ processHuffmanDataUnit(cbDcNr, cbAcNr, &dcCb, 64);
+ idctTransform(dctCoeff + 64, ptr, QT_TableSelection + 1);
ptr += 64;
- process_Huffman_data_unit(CrDC_nr, CrAC_nr, &DCCr, 128);
- IDCT_transform(DCT_coeff + 128, ptr, QT_TableSelection + 1);
+ processHuffmanDataUnit(crDcNr, crAcNr, &dcCr, 128);
+ idctTransform(dctCoeff + 128, ptr, QT_TableSelection + 1);
- YUVToBuffer(txb, tyb, byTileYuv, YUVBuffer.data(),
+ yuvToBuffer(txb, tyb, byTileYuv, yuvBuffer.data(),
reinterpret_cast<unsigned char *>(outBuf));
- // YUVToRGB (txb, tyb, byTileYuv, (unsigned char *)outBuf);
+ // yuvToRgb (txb, tyb, byTileYuv, (unsigned char *)outBuf);
}
- void VQ_Decompress(int txb, int tyb, char *outBuf, uint8_t QT_TableSelection,
- struct COLOR_CACHE *VQ) {
+ void vqDecompress(int txb, int tyb, char *outBuf, uint8_t QT_TableSelection,
+ struct ColorCache *VQ) {
unsigned char *ptr, i;
unsigned char byTileYuv[192];
- int Data;
+ int data;
ptr = byTileYuv;
- if (VQ->BitMapBits == 0) {
+ if (VQ->bitMapBits == 0) {
for (i = 0; i < 64; i++) {
- ptr[0] = (VQ->Color[VQ->Index[0]] & 0xFF0000) >> 16;
- ptr[64] = (VQ->Color[VQ->Index[0]] & 0x00FF00) >> 8;
- ptr[128] = VQ->Color[VQ->Index[0]] & 0x0000FF;
+ ptr[0] = (VQ->color[VQ->index[0]] & 0xFF0000) >> 16;
+ ptr[64] = (VQ->color[VQ->index[0]] & 0x00FF00) >> 8;
+ ptr[128] = VQ->color[VQ->index[0]] & 0x0000FF;
ptr += 1;
}
} else {
for (i = 0; i < 64; i++) {
- Data = static_cast<int>(lookKbits(VQ->BitMapBits));
- ptr[0] = (VQ->Color[VQ->Index[Data]] & 0xFF0000) >> 16;
- ptr[64] = (VQ->Color[VQ->Index[Data]] & 0x00FF00) >> 8;
- ptr[128] = VQ->Color[VQ->Index[Data]] & 0x0000FF;
+ data = static_cast<int>(lookKbits(VQ->bitMapBits));
+ ptr[0] = (VQ->color[VQ->index[data]] & 0xFF0000) >> 16;
+ ptr[64] = (VQ->color[VQ->index[data]] & 0x00FF00) >> 8;
+ ptr[128] = VQ->color[VQ->index[data]] & 0x0000FF;
ptr += 1;
- skipKbits(VQ->BitMapBits);
+ skipKbits(VQ->bitMapBits);
}
}
- // YUVToRGB (txb, tyb, byTileYuv, (unsigned char *)outBuf);
- YUVToRGB(txb, tyb, byTileYuv, YUVBuffer.data(),
+ // yuvToRgb (txb, tyb, byTileYuv, (unsigned char *)outBuf);
+ yuvToRgb(txb, tyb, byTileYuv, yuvBuffer.data(),
reinterpret_cast<unsigned char *>(outBuf));
}
- void MoveBlockIndex() {
+ void moveBlockIndex() {
if (yuvmode == YuvMode::YUV444) {
txb++;
- if (txb >= static_cast<int>(WIDTH / 8)) {
+ if (txb >= static_cast<int>(width / 8)) {
tyb++;
- if (tyb >= static_cast<int>(HEIGHT / 8)) {
+ if (tyb >= static_cast<int>(height / 8)) {
tyb = 0;
}
txb = 0;
}
} else {
txb++;
- if (txb >= static_cast<int>(WIDTH / 16)) {
+ if (txb >= static_cast<int>(width / 16)) {
tyb++;
- if (tyb >= static_cast<int>(HEIGHT / 16)) {
+ if (tyb >= static_cast<int>(height / 16)) {
tyb = 0;
}
txb = 0;
@@ -771,7 +770,7 @@ class AstJpegDecoder {
}
}
- void Init_Color_Table() {
+ void initColorTable() {
int i, x;
int nScale = 1L << 16; // equal to power(2,16)
int nHalf = nScale >> 1;
@@ -780,180 +779,180 @@ class AstJpegDecoder {
/* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
/* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
- /* Cr=>R value is nearest int to 1.597656 * x */
- /* Cb=>B value is nearest int to 2.015625 * x */
- /* Cr=>G value is scaled-up -0.8125 * x */
- /* Cb=>G value is scaled-up -0.390625 * x */
+ /* Cr=>r value is nearest int to 1.597656 * x */
+ /* Cb=>b value is nearest int to 2.015625 * x */
+ /* Cr=>g value is scaled-up -0.8125 * x */
+ /* Cb=>g value is scaled-up -0.390625 * x */
for (i = 0, x = -128; i < 256; i++, x++) {
- m_CrToR[i] = (FIX(1.597656) * x + nHalf) >> 16;
- m_CbToB[i] = (FIX(2.015625) * x + nHalf) >> 16;
- m_CrToG[i] = (-FIX(0.8125) * x + nHalf) >> 16;
- m_CbToG[i] = (-FIX(0.390625) * x + nHalf) >> 16;
+ mCrToR[i] = (FIX(1.597656) * x + nHalf) >> 16;
+ mCbToB[i] = (FIX(2.015625) * x + nHalf) >> 16;
+ mCrToG[i] = (-FIX(0.8125) * x + nHalf) >> 16;
+ mCbToG[i] = (-FIX(0.390625) * x + nHalf) >> 16;
}
for (i = 0, x = -16; i < 256; i++, x++) {
- m_Y[i] = (FIX(1.164) * x + nHalf) >> 16;
+ mY[i] = (FIX(1.164) * x + nHalf) >> 16;
}
- // For Color Text Enchance Y Re-map. Recommend to disable in default
+ // For color Text Enchance Y Re-map. Recommend to disable in default
/*
for (i = 0; i < (VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate);
i++) {
temp = (double)i /
VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate;
temp1 = 1.0 / VideoEngineInfo->INFData.Gamma1Parameter;
- m_Y[i] =
+ mY[i] =
(BYTE)(VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate * pow (temp,
temp1));
- if (m_Y[i] > 255) m_Y[i] = 255;
+ if (mY[i] > 255) mY[i] = 255;
}
for (i = (VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate); i < 256;
i++) {
- m_Y[i] =
+ mY[i] =
(BYTE)((VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate) + (256 -
VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate) * ( pow((double)((i -
VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate) / (256 -
(VideoEngineInfo->INFData.Gamma1_Gamma2_Seperate))), (1.0 /
VideoEngineInfo->INFData.Gamma2Parameter)) ));
- if (m_Y[i] > 255) m_Y[i] = 255;
+ if (mY[i] > 255) mY[i] = 255;
}
*/
}
- void load_Huffman_table(Huffman_table *HT, const unsigned char *nrcode,
- const unsigned char *value,
- const unsigned short int *Huff_code) {
+ void loadHuffmanTable(HuffmanTable *HT, const unsigned char *nrcode,
+ const unsigned char *value,
+ const unsigned short int *Huff_code) {
unsigned char k, j, i;
- unsigned int code, code_index;
+ unsigned int code, codeIndex;
for (j = 1; j <= 16; j++) {
- HT->Length[j] = nrcode[j];
+ HT->length[j] = nrcode[j];
}
for (i = 0, k = 1; k <= 16; k++) {
- for (j = 0; j < HT->Length[k]; j++) {
- HT->V[WORD_hi_lo(k, j)] = value[i];
+ for (j = 0; j < HT->length[k]; j++) {
+ HT->v[wordHiLo(k, j)] = value[i];
i++;
}
}
code = 0;
for (k = 1; k <= 16; k++) {
- HT->minor_code[k] = static_cast<unsigned short int>(code);
- for (j = 1; j <= HT->Length[k]; j++) {
+ HT->minorCode[k] = static_cast<unsigned short int>(code);
+ for (j = 1; j <= HT->length[k]; j++) {
code++;
}
- HT->major_code[k] = static_cast<unsigned short int>(code - 1);
+ HT->majorCode[k] = static_cast<unsigned short int>(code - 1);
code *= 2;
- if (HT->Length[k] == 0) {
- HT->minor_code[k] = 0xFFFF;
- HT->major_code[k] = 0;
+ if (HT->length[k] == 0) {
+ HT->minorCode[k] = 0xFFFF;
+ HT->majorCode[k] = 0;
}
}
- HT->Len[0] = 2;
+ HT->len[0] = 2;
i = 2;
- for (code_index = 1; code_index < 65535; code_index++) {
- if (code_index < Huff_code[i]) {
- HT->Len[code_index] = static_cast<unsigned char>(Huff_code[i + 1]);
+ for (codeIndex = 1; codeIndex < 65535; codeIndex++) {
+ if (codeIndex < Huff_code[i]) {
+ HT->len[codeIndex] = static_cast<unsigned char>(Huff_code[i + 1]);
} else {
i = i + 2;
- HT->Len[code_index] = static_cast<unsigned char>(Huff_code[i + 1]);
+ HT->len[codeIndex] = static_cast<unsigned char>(Huff_code[i + 1]);
}
}
}
- void init_jpg_table() {
- Init_Color_Table();
- prepare_range_limit_table();
- load_Huffman_table(&HTDC[0], std_dc_luminance_nrcodes,
- std_dc_luminance_values, DC_LUMINANCE_HUFFMANCODE);
- load_Huffman_table(&HTAC[0], std_ac_luminance_nrcodes,
- std_ac_luminance_values, AC_LUMINANCE_HUFFMANCODE);
- load_Huffman_table(&HTDC[1], std_dc_chrominance_nrcodes,
- std_dc_chrominance_values, DC_CHROMINANCE_HUFFMANCODE);
- load_Huffman_table(&HTAC[1], std_ac_chrominance_nrcodes,
- std_ac_chrominance_values, AC_CHROMINANCE_HUFFMANCODE);
+ void initJpgTable() {
+ initColorTable();
+ prepareRangeLimitTable();
+ loadHuffmanTable(&htdc[0], stdDcLuminanceNrcodes, stdDcLuminanceValues,
+ dcLuminanceHuffmancode);
+ loadHuffmanTable(&htac[0], stdAcLuminanceNrcodes, stdAcLuminanceValues,
+ acLuminanceHuffmancode);
+ loadHuffmanTable(&htdc[1], stdDcChrominanceNrcodes, stdDcChrominanceValues,
+ dcChrominanceHuffmancode);
+ loadHuffmanTable(&htac[1], stdAcChrominanceNrcodes, stdAcChrominanceValues,
+ acChrominanceHuffmancode);
}
- void prepare_range_limit_table()
+ void prepareRangeLimitTable()
/* Allocate and fill in the sample_range_limit table */
{
int j;
- rlimit_table = reinterpret_cast<unsigned char *>(malloc(5 * 256L + 128));
+ rlimitTable = reinterpret_cast<unsigned char *>(malloc(5 * 256L + 128));
/* First segment of "simple" table: limit[x] = 0 for x < 0 */
- memset((void *)rlimit_table, 0, 256);
- rlimit_table += 256; /* allow negative subscripts of simple table */
+ memset((void *)rlimitTable, 0, 256);
+ rlimitTable += 256; /* allow negative subscripts of simple table */
/* Main part of "simple" table: limit[x] = x */
for (j = 0; j < 256; j++) {
- rlimit_table[j] = j;
+ rlimitTable[j] = j;
}
/* End of simple table, rest of first half of post-IDCT table */
for (j = 256; j < 640; j++) {
- rlimit_table[j] = 255;
+ rlimitTable[j] = 255;
}
/* Second half of post-IDCT table */
- memset((void *)(rlimit_table + 640), 0, 384);
+ memset((void *)(rlimitTable + 640), 0, 384);
for (j = 0; j < 128; j++) {
- rlimit_table[j + 1024] = j;
+ rlimitTable[j + 1024] = j;
}
}
- inline unsigned short int WORD_hi_lo(uint8_t byte_high, uint8_t byte_low) {
+ inline unsigned short int wordHiLo(uint8_t byte_high, uint8_t byte_low) {
return (byte_high << 8) + byte_low;
}
// river
- void process_Huffman_data_unit(uint8_t DC_nr, uint8_t AC_nr,
- signed short int *previous_DC,
- unsigned short int position) {
+ void processHuffmanDataUnit(uint8_t DC_nr, uint8_t AC_nr,
+ signed short int *previous_DC,
+ unsigned short int position) {
uint8_t nr = 0;
uint8_t k;
- unsigned short int tmp_Hcode;
- uint8_t size_val, count_0;
- unsigned short int *min_code;
- uint8_t *huff_values;
- uint8_t byte_temp;
+ unsigned short int tmpHcode;
+ uint8_t sizeVal, count0;
+ unsigned short int *minCode;
+ uint8_t *huffValues;
+ uint8_t byteTemp;
- min_code = HTDC[DC_nr].minor_code;
- // maj_code=HTDC[DC_nr].major_code;
- huff_values = HTDC[DC_nr].V;
+ minCode = htdc[DC_nr].minorCode;
+ // maj_code=htdc[DC_nr].majorCode;
+ huffValues = htdc[DC_nr].v;
// DC
- k = HTDC[DC_nr].Len[static_cast<unsigned short int>(codebuf >> 16)];
+ k = htdc[DC_nr].len[static_cast<unsigned short int>(codebuf >> 16)];
// river
// tmp_Hcode=lookKbits(k);
- tmp_Hcode = static_cast<unsigned short int>(codebuf >> (32 - k));
+ tmpHcode = static_cast<unsigned short int>(codebuf >> (32 - k));
skipKbits(k);
- size_val = huff_values[WORD_hi_lo(
- k, static_cast<uint8_t>(tmp_Hcode - min_code[k]))];
- if (size_val == 0) {
- DCT_coeff[position + 0] = *previous_DC;
+ sizeVal =
+ huffValues[wordHiLo(k, static_cast<uint8_t>(tmpHcode - minCode[k]))];
+ if (sizeVal == 0) {
+ dctCoeff[position + 0] = *previous_DC;
} else {
- DCT_coeff[position + 0] = *previous_DC + getKbits(size_val);
- *previous_DC = DCT_coeff[position + 0];
+ dctCoeff[position + 0] = *previous_DC + getKbits(sizeVal);
+ *previous_DC = dctCoeff[position + 0];
}
// Second, AC coefficient decoding
- min_code = HTAC[AC_nr].minor_code;
- // maj_code=HTAC[AC_nr].major_code;
- huff_values = HTAC[AC_nr].V;
+ minCode = htac[AC_nr].minorCode;
+ // maj_code=htac[AC_nr].majorCode;
+ huffValues = htac[AC_nr].v;
nr = 1; // AC coefficient
do {
- k = HTAC[AC_nr].Len[static_cast<unsigned short int>(codebuf >> 16)];
- tmp_Hcode = static_cast<unsigned short int>(codebuf >> (32 - k));
+ k = htac[AC_nr].len[static_cast<unsigned short int>(codebuf >> 16)];
+ tmpHcode = static_cast<unsigned short int>(codebuf >> (32 - k));
skipKbits(k);
- byte_temp = huff_values[WORD_hi_lo(
- k, static_cast<uint8_t>(tmp_Hcode - min_code[k]))];
- size_val = byte_temp & 0xF;
- count_0 = byte_temp >> 4;
- if (size_val == 0) {
- if (count_0 != 0xF) {
+ byteTemp =
+ huffValues[wordHiLo(k, static_cast<uint8_t>(tmpHcode - minCode[k]))];
+ sizeVal = byteTemp & 0xF;
+ count0 = byteTemp >> 4;
+ if (sizeVal == 0) {
+ if (count0 != 0xF) {
break;
}
nr += 16;
} else {
- nr += count_0; // skip count_0 zeroes
- DCT_coeff[position + dezigzag[nr++]] = getKbits(size_val);
+ nr += count0; // skip count_0 zeroes
+ dctCoeff[position + dezigzag[nr++]] = getKbits(sizeVal);
}
} while (nr < 64);
}
@@ -970,8 +969,8 @@ class AstJpegDecoder {
unsigned long readbuf;
if ((newbits - k) <= 0) {
- readbuf = Buffer[buffer_index];
- buffer_index++;
+ readbuf = buffer[bufferIndex];
+ bufferIndex++;
codebuf =
(codebuf << k) | ((newbuf | (readbuf >> (newbits))) >> (32 - k));
newbuf = readbuf << (k - newbits);
@@ -984,38 +983,38 @@ class AstJpegDecoder {
}
signed short int getKbits(uint8_t k) {
- signed short int signed_wordvalue;
+ signed short int signedWordvalue;
// river
// signed_wordvalue=lookKbits(k);
- signed_wordvalue = static_cast<unsigned short int>(codebuf >> (32 - k));
- if (((1L << (k - 1)) & signed_wordvalue) == 0) {
+ signedWordvalue = static_cast<unsigned short int>(codebuf >> (32 - k));
+ if (((1L << (k - 1)) & signedWordvalue) == 0) {
// neg_pow2 was previously defined as the below. It seemed silly to keep
// a table of values around for something
// THat's relatively easy to compute, so it was replaced with the
// appropriate math
// signed_wordvalue = signed_wordvalue - (0xFFFF >> (16 - k));
- std::array<signed short int, 17> neg_pow2 = {
+ std::array<signed short int, 17> negPow2 = {
0, -1, -3, -7, -15, -31, -63, -127,
-255, -511, -1023, -2047, -4095, -8191, -16383, -32767};
- signed_wordvalue = signed_wordvalue + neg_pow2[k];
+ signedWordvalue = signedWordvalue + negPow2[k];
}
skipKbits(k);
- return signed_wordvalue;
+ return signedWordvalue;
}
- int init_JPG_decoding() {
- byte_pos = 0;
- load_quant_table(QT[0]);
- load_quant_tableCb(QT[1]);
+ int initJpgDecoding() {
+ bytePos = 0;
+ loadQuantTable(qt[0]);
+ loadQuantTableCb(qt[1]);
// Note: Added for Dual-JPEG
- load_advance_quant_table(QT[2]);
- load_advance_quant_tableCb(QT[3]);
+ loadAdvanceQuantTable(qt[2]);
+ loadAdvanceQuantTableCb(qt[3]);
return 1;
}
- void set_quant_table(const uint8_t *basic_table, uint8_t scale_factor,
- std::array<uint8_t, 64>& newtable)
+ void setQuantTable(const uint8_t *basic_table, uint8_t scale_factor,
+ std::array<uint8_t, 64> &newtable)
// Set quantization table and zigzag reorder it
{
uint8_t i;
@@ -1034,12 +1033,12 @@ class AstJpegDecoder {
}
void updatereadbuf(uint32_t *codebuf, uint32_t *newbuf, int walks,
- int *newbits, std::vector<uint32_t> &Buffer) {
+ int *newbits, std::vector<uint32_t> &buffer) {
unsigned long readbuf;
if ((*newbits - walks) <= 0) {
- readbuf = Buffer[buffer_index];
- buffer_index++;
+ readbuf = buffer[bufferIndex];
+ bufferIndex++;
*codebuf = (*codebuf << walks) |
((*newbuf | (readbuf >> (*newbits))) >> (32 - walks));
*newbuf = readbuf << (walks - *newbits);
@@ -1051,71 +1050,71 @@ class AstJpegDecoder {
}
}
- uint32_t decode(std::vector<uint32_t> &buffer, unsigned long width,
- unsigned long height, YuvMode yuvmode_in, int y_selector,
- int uv_selector) {
- COLOR_CACHE Decode_Color;
- if (width != USER_WIDTH || height != USER_HEIGHT || yuvmode_in != yuvmode ||
- y_selector != Y_selector || uv_selector != UV_selector) {
+ uint32_t decode(std::vector<uint32_t> &bufferVector, unsigned long width,
+ unsigned long height, YuvMode yuvmode_in, int ySelector,
+ int uvSelector) {
+ ColorCache decodeColor;
+ if (width != userWidth || height != userHeight || yuvmode_in != yuvmode ||
+ ySelector != ySelector || uvSelector != uvSelector) {
yuvmode = yuvmode_in;
- Y_selector = y_selector; // 0-7
- UV_selector = uv_selector; // 0-7
- USER_HEIGHT = height;
- USER_WIDTH = width;
- WIDTH = width;
- HEIGHT = height;
+ ySelector = ySelector; // 0-7
+ uvSelector = uvSelector; // 0-7
+ userHeight = height;
+ userWidth = width;
+ width = width;
+ height = height;
// TODO(ed) Magic number section. Document appropriately
- advance_selector = 0; // 0-7
- Mapping = 0; // 0 or 1
+ advanceSelector = 0; // 0-7
+ mapping = 0; // 0 or 1
if (yuvmode == YuvMode::YUV420) {
- if ((WIDTH % 16) != 0u) {
- WIDTH = WIDTH + 16 - (WIDTH % 16);
+ if ((width % 16) != 0u) {
+ width = width + 16 - (width % 16);
}
- if ((HEIGHT % 16) != 0u) {
- HEIGHT = HEIGHT + 16 - (HEIGHT % 16);
+ if ((height % 16) != 0u) {
+ height = height + 16 - (height % 16);
}
} else {
- if ((WIDTH % 8) != 0u) {
- WIDTH = WIDTH + 8 - (WIDTH % 8);
+ if ((width % 8) != 0u) {
+ width = width + 8 - (width % 8);
}
- if ((HEIGHT % 8) != 0u) {
- HEIGHT = HEIGHT + 8 - (HEIGHT % 8);
+ if ((height % 8) != 0u) {
+ height = height + 8 - (height % 8);
}
}
- init_JPG_decoding();
+ initJpgDecoding();
}
// TODO(ed) cleanup cruft
- Buffer = buffer.data();
+ buffer = bufferVector.data();
- codebuf = buffer[0];
- newbuf = buffer[1];
- buffer_index = 2;
+ codebuf = bufferVector[0];
+ newbuf = bufferVector[1];
+ bufferIndex = 2;
txb = tyb = 0;
newbits = 32;
- DCY = DCCb = DCCr = 0;
+ dcy = dcCb = dcCr = 0;
- static const uint32_t VQ_HEADER_MASK = 0x01;
- static const uint32_t VQ_NO_UPDATE_HEADER = 0x00;
- static const uint32_t VQ_UPDATE_HEADER = 0x01;
- static const int VQ_NO_UPDATE_LENGTH = 0x03;
- static const int VQ_UPDATE_LENGTH = 0x1B;
- static const uint32_t VQ_INDEX_MASK = 0x03;
- static const uint32_t VQ_COLOR_MASK = 0xFFFFFF;
+ static const uint32_t vqHeaderMask = 0x01;
+ static const uint32_t vqNoUpdateHeader = 0x00;
+ static const uint32_t vqUpdateHeader = 0x01;
+ static const int vqNoUpdateLength = 0x03;
+ static const int vqUpdateLength = 0x1B;
+ static const uint32_t vqIndexMask = 0x03;
+ static const uint32_t vqColorMask = 0xFFFFFF;
- static const int BLOCK_AST2100_START_LENGTH = 0x04;
- static const int BLOCK_AST2100_SKIP_LENGTH = 20; // S:1 H:3 X:8 Y:8
+ static const int blockAsT2100StartLength = 0x04;
+ static const int blockAsT2100SkipLength = 20; // S:1 H:3 X:8 Y:8
do {
- auto block_header = static_cast<JpgBlock>((codebuf >> 28) & 0xFF);
- switch (block_header) {
+ auto blockHeader = static_cast<JpgBlock>((codebuf >> 28) & 0xFF);
+ switch (blockHeader) {
case JpgBlock::JPEG_NO_SKIP_CODE:
- updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_START_LENGTH, &newbits,
- buffer);
- Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0);
+ updatereadbuf(&codebuf, &newbuf, blockAsT2100StartLength, &newbits,
+ bufferVector);
+ decompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0);
break;
case JpgBlock::FRAME_END_CODE:
return 0;
@@ -1125,116 +1124,116 @@ class AstJpegDecoder {
txb = (codebuf & 0x0FF00000) >> 20;
tyb = (codebuf & 0x0FF000) >> 12;
- updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_SKIP_LENGTH, &newbits,
- buffer);
- Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0);
+ updatereadbuf(&codebuf, &newbuf, blockAsT2100SkipLength, &newbits,
+ bufferVector);
+ decompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0);
break;
case JpgBlock::VQ_NO_SKIP_1_COLOR_CODE:
- updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_START_LENGTH, &newbits,
- buffer);
- Decode_Color.BitMapBits = 0;
+ updatereadbuf(&codebuf, &newbuf, blockAsT2100StartLength, &newbits,
+ bufferVector);
+ decodeColor.bitMapBits = 0;
for (int i = 0; i < 1; i++) {
- Decode_Color.Index[i] = ((codebuf >> 29) & VQ_INDEX_MASK);
- if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) {
- updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits,
- buffer);
+ decodeColor.index[i] = ((codebuf >> 29) & vqIndexMask);
+ if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) {
+ updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits,
+ bufferVector);
} else {
- Decode_Color.Color[Decode_Color.Index[i]] =
- ((codebuf >> 5) & VQ_COLOR_MASK);
- updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits,
- buffer);
+ decodeColor.color[decodeColor.index[i]] =
+ ((codebuf >> 5) & vqColorMask);
+ updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits,
+ bufferVector);
}
}
- VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0,
- &Decode_Color);
+ vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0,
+ &decodeColor);
break;
case JpgBlock::VQ_SKIP_1_COLOR_CODE:
txb = (codebuf & 0x0FF00000) >> 20;
tyb = (codebuf & 0x0FF000) >> 12;
- updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_SKIP_LENGTH, &newbits,
- buffer);
- Decode_Color.BitMapBits = 0;
+ updatereadbuf(&codebuf, &newbuf, blockAsT2100SkipLength, &newbits,
+ bufferVector);
+ decodeColor.bitMapBits = 0;
for (int i = 0; i < 1; i++) {
- Decode_Color.Index[i] = ((codebuf >> 29) & VQ_INDEX_MASK);
- if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) {
- updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits,
- buffer);
+ decodeColor.index[i] = ((codebuf >> 29) & vqIndexMask);
+ if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) {
+ updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits,
+ bufferVector);
} else {
- Decode_Color.Color[Decode_Color.Index[i]] =
- ((codebuf >> 5) & VQ_COLOR_MASK);
- updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits,
- buffer);
+ decodeColor.color[decodeColor.index[i]] =
+ ((codebuf >> 5) & vqColorMask);
+ updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits,
+ bufferVector);
}
}
- VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0,
- &Decode_Color);
+ vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0,
+ &decodeColor);
break;
case JpgBlock::VQ_NO_SKIP_2_COLOR_CODE:
- updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_START_LENGTH, &newbits,
- buffer);
- Decode_Color.BitMapBits = 1;
+ updatereadbuf(&codebuf, &newbuf, blockAsT2100StartLength, &newbits,
+ bufferVector);
+ decodeColor.bitMapBits = 1;
for (int i = 0; i < 2; i++) {
- Decode_Color.Index[i] = ((codebuf >> 29) & VQ_INDEX_MASK);
- if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) {
- updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits,
- buffer);
+ decodeColor.index[i] = ((codebuf >> 29) & vqIndexMask);
+ if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) {
+ updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits,
+ bufferVector);
} else {
- Decode_Color.Color[Decode_Color.Index[i]] =
- ((codebuf >> 5) & VQ_COLOR_MASK);
- updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits,
- buffer);
+ decodeColor.color[decodeColor.index[i]] =
+ ((codebuf >> 5) & vqColorMask);
+ updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits,
+ bufferVector);
}
}
- VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0,
- &Decode_Color);
+ vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0,
+ &decodeColor);
break;
case JpgBlock::VQ_SKIP_2_COLOR_CODE:
txb = (codebuf & 0x0FF00000) >> 20;
tyb = (codebuf & 0x0FF000) >> 12;
- updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_SKIP_LENGTH, &newbits,
- buffer);
- Decode_Color.BitMapBits = 1;
+ updatereadbuf(&codebuf, &newbuf, blockAsT2100SkipLength, &newbits,
+ bufferVector);
+ decodeColor.bitMapBits = 1;
for (int i = 0; i < 2; i++) {
- Decode_Color.Index[i] = ((codebuf >> 29) & VQ_INDEX_MASK);
- if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) {
- updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits,
- buffer);
+ decodeColor.index[i] = ((codebuf >> 29) & vqIndexMask);
+ if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) {
+ updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits,
+ bufferVector);
} else {
- Decode_Color.Color[Decode_Color.Index[i]] =
- ((codebuf >> 5) & VQ_COLOR_MASK);
- updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits,
- buffer);
+ decodeColor.color[decodeColor.index[i]] =
+ ((codebuf >> 5) & vqColorMask);
+ updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits,
+ bufferVector);
}
}
- VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0,
- &Decode_Color);
+ vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0,
+ &decodeColor);
break;
case JpgBlock::VQ_NO_SKIP_4_COLOR_CODE:
- updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_START_LENGTH, &newbits,
- buffer);
- Decode_Color.BitMapBits = 2;
-
- for (unsigned char &i : Decode_Color.Index) {
- i = ((codebuf >> 29) & VQ_INDEX_MASK);
- if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) {
- updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits,
- buffer);
+ updatereadbuf(&codebuf, &newbuf, blockAsT2100StartLength, &newbits,
+ bufferVector);
+ decodeColor.bitMapBits = 2;
+
+ for (unsigned char &i : decodeColor.index) {
+ i = ((codebuf >> 29) & vqIndexMask);
+ if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) {
+ updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits,
+ bufferVector);
} else {
- Decode_Color.Color[i] = ((codebuf >> 5) & VQ_COLOR_MASK);
- updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits,
- buffer);
+ decodeColor.color[i] = ((codebuf >> 5) & vqColorMask);
+ updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits,
+ bufferVector);
}
}
- VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0,
- &Decode_Color);
+ vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0,
+ &decodeColor);
break;
@@ -1242,33 +1241,33 @@ class AstJpegDecoder {
txb = (codebuf & 0x0FF00000) >> 20;
tyb = (codebuf & 0x0FF000) >> 12;
- updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_SKIP_LENGTH, &newbits,
- buffer);
- Decode_Color.BitMapBits = 2;
+ updatereadbuf(&codebuf, &newbuf, blockAsT2100SkipLength, &newbits,
+ bufferVector);
+ decodeColor.bitMapBits = 2;
- for (unsigned char &i : Decode_Color.Index) {
- i = ((codebuf >> 29) & VQ_INDEX_MASK);
- if (((codebuf >> 31) & VQ_HEADER_MASK) == VQ_NO_UPDATE_HEADER) {
- updatereadbuf(&codebuf, &newbuf, VQ_NO_UPDATE_LENGTH, &newbits,
- buffer);
+ for (unsigned char &i : decodeColor.index) {
+ i = ((codebuf >> 29) & vqIndexMask);
+ if (((codebuf >> 31) & vqHeaderMask) == vqNoUpdateHeader) {
+ updatereadbuf(&codebuf, &newbuf, vqNoUpdateLength, &newbits,
+ bufferVector);
} else {
- Decode_Color.Color[i] = ((codebuf >> 5) & VQ_COLOR_MASK);
- updatereadbuf(&codebuf, &newbuf, VQ_UPDATE_LENGTH, &newbits,
- buffer);
+ decodeColor.color[i] = ((codebuf >> 5) & vqColorMask);
+ updatereadbuf(&codebuf, &newbuf, vqUpdateLength, &newbits,
+ bufferVector);
}
}
- VQ_Decompress(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()), 0,
- &Decode_Color);
+ vqDecompress(txb, tyb, reinterpret_cast<char *>(outBuffer.data()), 0,
+ &decodeColor);
break;
case JpgBlock::JPEG_SKIP_PASS2_CODE:
txb = (codebuf & 0x0FF00000) >> 20;
tyb = (codebuf & 0x0FF000) >> 12;
- updatereadbuf(&codebuf, &newbuf, BLOCK_AST2100_SKIP_LENGTH, &newbits,
- buffer);
- Decompress_2PASS(txb, tyb, reinterpret_cast<char *>(OutBuffer.data()),
- 2);
+ updatereadbuf(&codebuf, &newbuf, blockAsT2100SkipLength, &newbits,
+ bufferVector);
+ decompress2Pass(txb, tyb, reinterpret_cast<char *>(outBuffer.data()),
+ 2);
break;
default:
@@ -1276,22 +1275,22 @@ class AstJpegDecoder {
return -1;
break;
}
- MoveBlockIndex();
+ moveBlockIndex();
- } while (buffer_index <= buffer.size());
+ } while (bufferIndex <= bufferVector.size());
return -1;
}
#ifdef cimg_version
void dump_to_bitmap_file() {
- cimg_library::CImg<unsigned char> image(WIDTH, HEIGHT, 1, 3);
- for (int y = 0; y < WIDTH; y++) {
- for (int x = 0; x < HEIGHT; x++) {
- auto pixel = OutBuffer[x + (y * WIDTH)];
- image(x, y, 0) = pixel.R;
- image(x, y, 1) = pixel.G;
- image(x, y, 2) = pixel.B;
+ cimg_library::CImg<unsigned char> image(width, height, 1, 3);
+ for (int y = 0; y < width; y++) {
+ for (int x = 0; x < height; x++) {
+ auto pixel = outBuffer[x + (y * width)];
+ image(x, y, 0) = pixel.r;
+ image(x, y, 1) = pixel.g;
+ image(x, y, 2) = pixel.b;
}
}
image.save("/tmp/file2.bmp");
@@ -1300,56 +1299,56 @@ class AstJpegDecoder {
private:
YuvMode yuvmode{};
- // WIDTH and HEIGHT are the modes your display used
- unsigned long WIDTH{};
- unsigned long HEIGHT{};
- unsigned long USER_WIDTH{};
- unsigned long USER_HEIGHT{};
- unsigned char Y_selector{};
- int SCALEFACTOR;
- int SCALEFACTORUV;
- int ADVANCESCALEFACTOR;
- int ADVANCESCALEFACTORUV;
- int Mapping{};
- unsigned char UV_selector{};
- unsigned char advance_selector{};
- int byte_pos{}; // current byte position
+ // width and height are the modes your display used
+ unsigned long width{};
+ unsigned long height{};
+ unsigned long userWidth{};
+ unsigned long userHeight{};
+ unsigned char ySelector{};
+ int scalefactor;
+ int scalefactoruv;
+ int advancescalefactor;
+ int advancescalefactoruv;
+ int mapping{};
+ unsigned char uvSelector{};
+ unsigned char advanceSelector{};
+ int bytePos{}; // current byte position
// quantization tables, no more than 4 quantization tables
- std::array<std::array<long, 64>, 4> QT{};
+ std::array<std::array<long, 64>, 4> qt{};
// DC huffman tables , no more than 4 (0..3)
- std::array<Huffman_table, 4> HTDC{};
+ std::array<HuffmanTable, 4> htdc{};
// AC huffman tables (0..3)
- std::array<Huffman_table, 4> HTAC{};
- std::array<int, 256> m_CrToR{};
- std::array<int, 256> m_CbToB{};
- std::array<int, 256> m_CrToG{};
- std::array<int, 256> m_CbToG{};
- std::array<int, 256> m_Y{};
- unsigned long buffer_index{};
+ std::array<HuffmanTable, 4> htac{};
+ std::array<int, 256> mCrToR{};
+ std::array<int, 256> mCbToB{};
+ std::array<int, 256> mCrToG{};
+ std::array<int, 256> mCbToG{};
+ std::array<int, 256> mY{};
+ unsigned long bufferIndex{};
uint32_t codebuf{}, newbuf{}, readbuf{};
- const unsigned char *std_luminance_qt{};
- const uint8_t *std_chrominance_qt{};
+ const unsigned char *stdLuminanceQt{};
+ const uint8_t *stdChrominanceQt{};
- signed short int DCY{}, DCCb{}, DCCr{}; // Coeficientii DC pentru Y,Cb,Cr
- signed short int DCT_coeff[384]{};
- // std::vector<signed short int> DCT_coeff; // Current DCT_coefficients
+ signed short int dcy{}, dcCb{}, dcCr{}; // Coeficientii DC pentru Y,Cb,Cr
+ signed short int dctCoeff[384]{};
+ // std::vector<signed short int> dctCoeff; // Current DCT_coefficients
// quantization table number for Y, Cb, Cr
- uint8_t YQ_nr = 0, CbQ_nr = 1, CrQ_nr = 1;
+ uint8_t yqNr = 0, cbQNr = 1, crQNr = 1;
// DC Huffman table number for Y,Cb, Cr
- uint8_t YDC_nr = 0, CbDC_nr = 1, CrDC_nr = 1;
+ uint8_t ydcNr = 0, cbDcNr = 1, crDcNr = 1;
// AC Huffman table number for Y,Cb, Cr
- uint8_t YAC_nr = 0, CbAC_nr = 1, CrAC_nr = 1;
+ uint8_t yacNr = 0, cbAcNr = 1, crAcNr = 1;
int txb = 0;
int tyb = 0;
int newbits{};
- uint8_t *rlimit_table{};
- std::vector<RGB> YUVBuffer;
+ uint8_t *rlimitTable{};
+ std::vector<RGB> yuvBuffer;
// TODO(ed) this shouldn't exist. It is cruft that needs cleaning up
- uint32_t *Buffer{};
+ uint32_t *buffer{};
public:
- std::vector<RGB> OutBuffer;
+ std::vector<RGB> outBuffer;
};
-} // namespace AstVideo \ No newline at end of file
+} // namespace ast_video \ No newline at end of file
diff --git a/include/ast_video_puller.hpp b/include/ast_video_puller.hpp
index 6cd7f37c35..c2ccea27c3 100644
--- a/include/ast_video_puller.hpp
+++ b/include/ast_video_puller.hpp
@@ -1,31 +1,31 @@
#pragma once
-#include <cassert>
#include <ast_video_types.hpp>
+#include <cassert>
#include <iostream>
#include <mutex>
#include <vector>
#include <boost/asio.hpp>
-namespace AstVideo {
+namespace ast_video {
//
// Cursor struct is used in User Mode
//
-struct AST_CUR_ATTRIBUTION_TAG {
+struct AstCurAttributionTag {
unsigned int posX;
unsigned int posY;
- unsigned int cur_width;
- unsigned int cur_height;
- unsigned int cur_type; // 0:mono 1:color 2:disappear cursor
- unsigned int cur_change_flag;
+ unsigned int curWidth;
+ unsigned int curHeight;
+ unsigned int curType; // 0:mono 1:color 2:disappear cursor
+ unsigned int curChangeFlag;
};
//
// For storing Cursor Information
//
-struct AST_CURSOR_TAG {
- AST_CUR_ATTRIBUTION_TAG attr;
+struct AstCursorTag {
+ AstCurAttributionTag attr;
// unsigned char icon[MAX_CUR_OFFSETX*MAX_CUR_OFFSETY*2];
unsigned char *icon; //[64*64*2];
};
@@ -34,11 +34,11 @@ struct AST_CURSOR_TAG {
// For select image format, i.e. 422 JPG420, 444 JPG444, lumin/chrom table, 0
// ~ 11, low to high
//
-struct FEATURES_TAG {
- short jpg_fmt; // 422:JPG420, 444:JPG444
- short lumin_tbl;
- short chrom_tbl;
- short tolerance_noise;
+struct FeaturesTag {
+ short jpgFmt; // 422:JPG420, 444:JPG444
+ short luminTbl;
+ short chromTbl;
+ short toleranceNoise;
int w;
int h;
unsigned char *buf;
@@ -47,48 +47,48 @@ struct FEATURES_TAG {
//
// For configure video engine control registers
//
-struct IMAGE_INFO {
- short do_image_refresh; // Action 0:motion 1:fullframe 2:quick cursor
- char qc_valid; // quick cursor enable/disable
+struct ImageInfo {
+ short doImageRefresh; // Action 0:motion 1:fullframe 2:quick cursor
+ char qcValid; // quick cursor enable/disable
unsigned int len;
int crypttype;
char cryptkey[16];
union {
- FEATURES_TAG features;
- AST_CURSOR_TAG cursor_info;
+ FeaturesTag features;
+ AstCursorTag cursorInfo;
} parameter;
};
class SimpleVideoPuller {
public:
- SimpleVideoPuller() : image_info(){};
+ SimpleVideoPuller() : imageInfo(){};
void initialize() {
std::cout << "Opening /dev/video\n";
- video_fd = open("/dev/video", O_RDWR);
- if (video_fd == 0) {
+ videoFd = open("/dev/video", O_RDWR);
+ if (videoFd == 0) {
std::cout << "Failed to open /dev/video\n";
throw std::runtime_error("Failed to open /dev/video");
}
std::cout << "Opened successfully\n";
}
- RawVideoBuffer read_video() {
- assert(video_fd != 0);
+ RawVideoBuffer readVideo() {
+ assert(videoFd != 0);
RawVideoBuffer raw;
- image_info.do_image_refresh = 1; // full frame refresh
- image_info.qc_valid = 0; // quick cursor disabled
- image_info.parameter.features.buf =
+ imageInfo.doImageRefresh = 1; // full frame refresh
+ imageInfo.qcValid = 0; // quick cursor disabled
+ imageInfo.parameter.features.buf =
reinterpret_cast<unsigned char *>(raw.buffer.data());
- image_info.crypttype = -1;
+ imageInfo.crypttype = -1;
std::cout << "Writing\n";
int status;
/*
- status = write(video_fd, reinterpret_cast<char*>(&image_info),
- sizeof(image_info));
- if (status != sizeof(image_info)) {
+ status = write(videoFd, reinterpret_cast<char*>(&imageInfo),
+ sizeof(imageInfo));
+ if (status != sizeof(imageInfo)) {
std::cout << "Write failed. Return: " << status << "\n";
perror("perror output:");
}
@@ -96,19 +96,19 @@ class SimpleVideoPuller {
std::cout << "Write done\n";
*/
std::cout << "Reading\n";
- status = read(video_fd, reinterpret_cast<char *>(&image_info),
- sizeof(image_info));
+ status =
+ read(videoFd, reinterpret_cast<char *>(&imageInfo), sizeof(imageInfo));
std::cout << "Done reading\n";
if (status != 0) {
std::cerr << "Read failed with status " << status << "\n";
}
- raw.buffer.resize(image_info.len);
+ raw.buffer.resize(imageInfo.len);
- raw.height = image_info.parameter.features.h;
- raw.width = image_info.parameter.features.w;
- if (image_info.parameter.features.jpg_fmt == 422) {
+ raw.height = imageInfo.parameter.features.h;
+ raw.width = imageInfo.parameter.features.w;
+ if (imageInfo.parameter.features.jpgFmt == 422) {
raw.mode = YuvMode::YUV420;
} else {
raw.mode = YuvMode::YUV444;
@@ -117,57 +117,58 @@ class SimpleVideoPuller {
}
private:
- int video_fd{};
- IMAGE_INFO image_info;
+ int videoFd{};
+ ImageInfo imageInfo;
};
#if defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
class AsyncVideoPuller {
public:
- using video_callback = std::function<void (RawVideoBuffer &)>;
+ using video_callback = std::function<void(RawVideoBuffer &)>;
- explicit AsyncVideoPuller(boost::asio::io_service &io_service)
- : image_info(), dev_video(io_service, open("/dev/video", O_RDWR)) {
+ explicit AsyncVideoPuller(boost::asio::io_service &ioService)
+ : imageInfo(), devVideo(ioService, open("/dev/video", O_RDWR)) {
videobuf = std::make_shared<RawVideoBuffer>();
- image_info.do_image_refresh = 1; // full frame refresh
- image_info.qc_valid = 0; // quick cursor disabled
- image_info.parameter.features.buf =
+ imageInfo.doImageRefresh = 1; // full frame refresh
+ imageInfo.qcValid = 0; // quick cursor disabled
+ imageInfo.parameter.features.buf =
reinterpret_cast<unsigned char *>(videobuf->buffer.data());
- image_info.crypttype = -1;
+ imageInfo.crypttype = -1;
};
- void register_callback(video_callback &callback) {
- std::lock_guard<std::mutex> lock(callback_mutex);
+ void registerCallback(video_callback &callback) {
+ std::lock_guard<std::mutex> lock(callbackMutex);
callbacks.push_back(callback);
- start_read();
+ startRead();
}
- void start_read() {
- auto mutable_buffer = boost::asio::buffer(&image_info, sizeof(image_info));
- boost::asio::async_read(
- dev_video, mutable_buffer, [this](const boost::system::error_code &ec,
- std::size_t bytes_transferred) {
- if (ec) {
- std::cerr << "Read failed with status " << ec << "\n";
- } else {
- this->read_done();
- }
- });
+ void startRead() {
+ auto mutableBuffer = boost::asio::buffer(&imageInfo, sizeof(imageInfo));
+ boost::asio::async_read(devVideo, mutableBuffer,
+ [this](const boost::system::error_code &ec,
+ std::size_t bytes_transferred) {
+ if (ec) {
+ std::cerr << "Read failed with status " << ec
+ << "\n";
+ } else {
+ this->readDone();
+ }
+ });
}
- void read_done() {
+ void readDone() {
std::cout << "Done reading\n";
- videobuf->buffer.resize(image_info.len);
+ videobuf->buffer.resize(imageInfo.len);
- videobuf->height = image_info.parameter.features.h;
- videobuf->width = image_info.parameter.features.w;
- if (image_info.parameter.features.jpg_fmt == 422) {
+ videobuf->height = imageInfo.parameter.features.h;
+ videobuf->width = imageInfo.parameter.features.w;
+ if (imageInfo.parameter.features.jpgFmt == 422) {
videobuf->mode = YuvMode::YUV420;
} else {
videobuf->mode = YuvMode::YUV444;
}
- std::lock_guard<std::mutex> lock(callback_mutex);
+ std::lock_guard<std::mutex> lock(callbackMutex);
for (auto &callback : callbacks) {
// TODO(ed) call callbacks async and double buffer frames
callback(*videobuf);
@@ -176,10 +177,10 @@ class AsyncVideoPuller {
private:
std::shared_ptr<RawVideoBuffer> videobuf;
- boost::asio::posix::stream_descriptor dev_video;
- IMAGE_INFO image_info;
- std::mutex callback_mutex;
+ boost::asio::posix::stream_descriptor devVideo;
+ ImageInfo imageInfo;
+ std::mutex callbackMutex;
std::vector<video_callback> callbacks;
};
#endif // defined(BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
-} // namespace AstVideo
+} // namespace ast_video
diff --git a/include/ast_video_types.hpp b/include/ast_video_types.hpp
index f5cfffd1e5..f9801460e6 100644
--- a/include/ast_video_types.hpp
+++ b/include/ast_video_types.hpp
@@ -2,7 +2,7 @@
#include <cstdint>
#include <vector>
-namespace AstVideo {
+namespace ast_video {
enum class YuvMode { YUV444 = 0, YUV420 = 1 };
class RawVideoBuffer {
@@ -10,10 +10,10 @@ class RawVideoBuffer {
RawVideoBuffer() : buffer(1024 * 1024 * 10, 0){};
unsigned long height{};
unsigned long width{};
- int y_selector{};
- int uv_selector{};
+ int ySelector{};
+ int uvSelector{};
YuvMode mode;
// TODO(ed) determine a more appropriate buffer size
std::vector<uint32_t> buffer;
};
-} // namespace AstVideo \ No newline at end of file
+} // namespace ast_video \ No newline at end of file
diff --git a/include/dbus_monitor.hpp b/include/dbus_monitor.hpp
index ab7ebef928..43385e6571 100644
--- a/include/dbus_monitor.hpp
+++ b/include/dbus_monitor.hpp
@@ -11,65 +11,64 @@ struct DbusWebsocketSession {
std::vector<std::unique_ptr<sdbusplus::bus::match::match>> matches;
};
-static boost::container::flat_map<crow::websocket::connection*,
+static boost::container::flat_map<crow::websocket::Connection*,
DbusWebsocketSession>
sessions;
-int on_property_update(sd_bus_message* m, void* userdata,
- sd_bus_error* ret_error) {
+int onPropertyUpdate(sd_bus_message* m, void* userdata,
+ sd_bus_error* ret_error) {
if (ret_error == nullptr || sd_bus_error_is_set(ret_error)) {
- CROW_LOG_ERROR << "Sdbus error in on_property_update";
+ BMCWEB_LOG_ERROR << "Sdbus error in on_property_update";
return 0;
}
sdbusplus::message::message message(m);
- std::string object_name;
+ std::string objectName;
std::vector<
std::pair<std::string, sdbusplus::message::variant<
std::string, bool, int64_t, uint64_t, double>>>
values;
- message.read(object_name, values);
+ message.read(objectName, values);
nlohmann::json j;
const std::string& path = message.get_path();
for (auto& value : values) {
mapbox::util::apply_visitor([&](auto&& val) { j[path] = val; },
value.second);
}
- std::string data_to_send = j.dump();
+ std::string dataToSend = j.dump();
- for (const std::pair<crow::websocket::connection*, DbusWebsocketSession>&
+ for (const std::pair<crow::websocket::Connection*, DbusWebsocketSession>&
session : sessions) {
- session.first->send_text(data_to_send);
+ session.first->sendText(dataToSend);
}
};
template <typename... Middlewares>
-void request_routes(Crow<Middlewares...>& app) {
- CROW_ROUTE(app, "/dbus_monitor")
+void requestRoutes(Crow<Middlewares...>& app) {
+ BMCWEB_ROUTE(app, "/dbus_monitor")
.websocket()
- .onopen([&](crow::websocket::connection& conn) {
- std::string path_namespace(conn.req.url_params.get("path_namespace"));
- if (path_namespace.empty()) {
- conn.send_text(
+ .onopen([&](crow::websocket::Connection& conn) {
+ std::string pathNamespace(conn.req.urlParams.get("path_namespace"));
+ if (pathNamespace.empty()) {
+ conn.sendText(
nlohmann::json({"error", "Did not specify path_namespace"}));
conn.close("error");
}
sessions[&conn] = DbusWebsocketSession();
- std::string match_string(
+ std::string matchString(
"type='signal',"
"interface='org.freedesktop.DBus.Properties',"
"path_namespace='" +
- path_namespace + "'");
+ pathNamespace + "'");
sessions[&conn].matches.emplace_back(
std::make_unique<sdbusplus::bus::match::match>(
- *crow::connections::system_bus, match_string,
- on_property_update));
+ *crow::connections::systemBus, matchString, onPropertyUpdate));
})
- .onclose([&](crow::websocket::connection& conn,
+ .onclose([&](crow::websocket::Connection& conn,
const std::string& reason) { sessions.erase(&conn); })
- .onmessage([&](crow::websocket::connection& conn, const std::string& data,
+ .onmessage([&](crow::websocket::Connection& conn, const std::string& data,
bool is_binary) {
- CROW_LOG_ERROR << "Got unexpected message from client on sensorws";
+ BMCWEB_LOG_ERROR << "Got unexpected message from client on sensorws";
});
}
} // namespace dbus_monitor
diff --git a/include/dbus_singleton.hpp b/include/dbus_singleton.hpp
index e6be81b373..a4a16bb2d1 100644
--- a/include/dbus_singleton.hpp
+++ b/include/dbus_singleton.hpp
@@ -4,7 +4,7 @@
namespace mapbox {
template <typename T, typename... Types>
-const T* get_ptr(const mapbox::util::variant<Types...>& v) {
+const T* getPtr(const mapbox::util::variant<Types...>& v) {
if (v.template is<std::remove_const_t<T>>()) {
return &v.template get_unchecked<std::remove_const_t<T>>();
} else {
@@ -15,7 +15,7 @@ const T* get_ptr(const mapbox::util::variant<Types...>& v) {
namespace crow {
namespace connections {
-static std::shared_ptr<sdbusplus::asio::connection> system_bus;
+static std::shared_ptr<sdbusplus::asio::connection> systemBus;
} // namespace connections
} // namespace crow
diff --git a/include/gzip_helper.hpp b/include/gzip_helper.hpp
index 9b7d253a25..e577c1ffd1 100644
--- a/include/gzip_helper.hpp
+++ b/include/gzip_helper.hpp
@@ -4,8 +4,8 @@
#include <cstring>
#include <string>
-inline bool gzip_inflate(const std::string& compressedBytes,
- std::string& uncompressedBytes) {
+inline bool gzipInflate(const std::string& compressedBytes,
+ std::string& uncompressedBytes) {
if (compressedBytes.empty()) {
uncompressedBytes = compressedBytes;
return true;
diff --git a/include/http_utility.hpp b/include/http_utility.hpp
index 7b04b0f036..f2d317206a 100644
--- a/include/http_utility.hpp
+++ b/include/http_utility.hpp
@@ -2,8 +2,8 @@
#include <boost/algorithm/string.hpp>
namespace http_helpers {
-inline bool request_prefers_html(const crow::request& req) {
- boost::string_view header = req.get_header_value("accept");
+inline bool requestPrefersHtml(const crow::Request& req) {
+ boost::string_view header = req.getHeaderValue("accept");
std::vector<std::string> encodings;
// chrome currently sends 6 accepts headers, firefox sends 4.
encodings.reserve(6);
diff --git a/include/image_upload.hpp b/include/image_upload.hpp
index 2a959677df..df5c1ae491 100644
--- a/include/image_upload.hpp
+++ b/include/image_upload.hpp
@@ -14,17 +14,17 @@ namespace image_upload {
std::unique_ptr<sdbusplus::bus::match::match> fwUpdateMatcher;
-inline void uploadImageHandler(const crow::request& req, crow::response& res,
+inline void uploadImageHandler(const crow::Request& req, crow::Response& res,
const std::string& filename) {
// Only allow one FW update at a time
if (fwUpdateMatcher != nullptr) {
- res.add_header("Retry-After", "30");
+ res.addHeader("Retry-After", "30");
res.result(boost::beast::http::status::service_unavailable);
res.end();
return;
}
// Make this const static so it survives outside this method
- static boost::asio::deadline_timer timeout(*req.io_service,
+ static boost::asio::deadline_timer timeout(*req.ioService,
boost::posix_time::seconds(5));
timeout.expires_from_now(boost::posix_time::seconds(5));
@@ -35,10 +35,10 @@ inline void uploadImageHandler(const crow::request& req, crow::response& res,
// expected, we were canceled before the timer completed.
return;
}
- CROW_LOG_ERROR << "Timed out waiting for log event";
+ BMCWEB_LOG_ERROR << "Timed out waiting for log event";
if (ec) {
- CROW_LOG_ERROR << "Async_wait failed " << ec;
+ BMCWEB_LOG_ERROR << "Async_wait failed " << ec;
return;
}
@@ -48,11 +48,11 @@ inline void uploadImageHandler(const crow::request& req, crow::response& res,
std::function<void(sdbusplus::message::message&)> callback =
[&res](sdbusplus::message::message& m) {
- CROW_LOG_DEBUG << "Match fired";
+ BMCWEB_LOG_DEBUG << "Match fired";
boost::system::error_code ec;
timeout.cancel(ec);
if (ec) {
- CROW_LOG_ERROR << "error canceling timer " << ec;
+ BMCWEB_LOG_ERROR << "error canceling timer " << ec;
}
std::string versionInfo;
m.read(versionInfo); // Read in the object path that was just created
@@ -61,15 +61,15 @@ inline void uploadImageHandler(const crow::request& req, crow::response& res,
if (index != std::string::npos) {
versionInfo.erase(0, index);
}
- res.json_value = {{"data", std::move(versionInfo)},
- {"message", "200 OK"},
- {"status", "ok"}};
- CROW_LOG_DEBUG << "ending response";
+ res.jsonValue = {{"data", std::move(versionInfo)},
+ {"message", "200 OK"},
+ {"status", "ok"}};
+ BMCWEB_LOG_DEBUG << "ending response";
res.end();
fwUpdateMatcher = nullptr;
};
fwUpdateMatcher = std::make_unique<sdbusplus::bus::match::match>(
- *crow::connections::system_bus,
+ *crow::connections::systemBus,
"interface='org.freedesktop.DBus.ObjectManager',type='signal',"
"member='InterfacesAdded',path='/xyz/openbmc_project/logging'",
callback);
@@ -77,7 +77,7 @@ inline void uploadImageHandler(const crow::request& req, crow::response& res,
std::string filepath(
"/tmp/images/" +
boost::uuids::to_string(boost::uuids::random_generator()()));
- CROW_LOG_DEBUG << "Writing file to " << filepath;
+ BMCWEB_LOG_DEBUG << "Writing file to " << filepath;
std::ofstream out(filepath, std::ofstream::out | std::ofstream::binary |
std::ofstream::trunc);
out << req.body;
@@ -86,16 +86,16 @@ inline void uploadImageHandler(const crow::request& req, crow::response& res,
template <typename... Middlewares>
void requestRoutes(Crow<Middlewares...>& app) {
- CROW_ROUTE(app, "/upload/image/<str>")
+ BMCWEB_ROUTE(app, "/upload/image/<str>")
.methods("POST"_method,
- "PUT"_method)([](const crow::request& req, crow::response& res,
+ "PUT"_method)([](const crow::Request& req, crow::Response& res,
const std::string& filename) {
uploadImageHandler(req, res, filename);
});
- CROW_ROUTE(app, "/upload/image")
+ BMCWEB_ROUTE(app, "/upload/image")
.methods("POST"_method,
- "PUT"_method)([](const crow::request& req, crow::response& res) {
+ "PUT"_method)([](const crow::Request& req, crow::Response& res) {
uploadImageHandler(req, res, "");
});
}
diff --git a/include/openbmc_dbus_rest.hpp b/include/openbmc_dbus_rest.hpp
index c10148e783..1f3b9e29bd 100644
--- a/include/openbmc_dbus_rest.hpp
+++ b/include/openbmc_dbus_rest.hpp
@@ -10,41 +10,41 @@
namespace crow {
namespace openbmc_mapper {
-void introspect_objects(crow::response &res, std::string process_name,
- std::string path,
- std::shared_ptr<nlohmann::json> transaction) {
- crow::connections::system_bus->async_method_call(
+void introspectObjects(crow::Response &res, std::string process_name,
+ std::string path,
+ std::shared_ptr<nlohmann::json> transaction) {
+ crow::connections::systemBus->async_method_call(
[
- &res, transaction, process_name{std::move(process_name)},
- object_path{std::move(path)}
+ &res, transaction, processName{std::move(process_name)},
+ objectPath{std::move(path)}
](const boost::system::error_code ec, const std::string &introspect_xml) {
if (ec) {
- CROW_LOG_ERROR << "Introspect call failed with error: "
- << ec.message() << " on process: " << process_name
- << " path: " << object_path << "\n";
+ BMCWEB_LOG_ERROR << "Introspect call failed with error: "
+ << ec.message() << " on process: " << processName
+ << " path: " << objectPath << "\n";
} else {
- transaction->push_back({{"path", object_path}});
+ transaction->push_back({{"path", objectPath}});
tinyxml2::XMLDocument doc;
doc.Parse(introspect_xml.c_str());
tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node");
if (pRoot == nullptr) {
- CROW_LOG_ERROR << "XML document failed to parse " << process_name
- << " " << object_path << "\n";
+ BMCWEB_LOG_ERROR << "XML document failed to parse " << processName
+ << " " << objectPath << "\n";
} else {
tinyxml2::XMLElement *node = pRoot->FirstChildElement("node");
while (node != nullptr) {
- std::string child_path = node->Attribute("name");
+ std::string childPath = node->Attribute("name");
std::string newpath;
- if (object_path != "/") {
- newpath += object_path;
+ if (objectPath != "/") {
+ newpath += objectPath;
}
- newpath += "/" + child_path;
+ newpath += "/" + childPath;
// introspect the subobjects as well
- introspect_objects(res, process_name, newpath, transaction);
+ introspectObjects(res, processName, newpath, transaction);
node = node->NextSiblingElement("node");
}
@@ -52,8 +52,8 @@ void introspect_objects(crow::response &res, std::string process_name,
}
// if we're the last outstanding caller, finish the request
if (transaction.use_count() == 1) {
- res.json_value = {{"status", "ok"},
- {"bus_name", process_name},
+ res.jsonValue = {{"status", "ok"},
+ {"bus_name", processName},
{"objects", std::move(*transaction)}};
res.end();
}
@@ -74,39 +74,38 @@ using ManagedObjectType = std::vector<std::pair<
std::string,
boost::container::flat_map<std::string, DbusRestVariantType>>>>;
-void get_managed_objects_for_enumerate(
+void getManagedObjectsForEnumerate(
const std::string &object_name, const std::string &connection_name,
- crow::response &res, std::shared_ptr<nlohmann::json> transaction) {
- crow::connections::system_bus->async_method_call(
+ crow::Response &res, std::shared_ptr<nlohmann::json> transaction) {
+ crow::connections::systemBus->async_method_call(
[&res, transaction](const boost::system::error_code ec,
const ManagedObjectType &objects) {
if (ec) {
- CROW_LOG_ERROR << ec;
+ BMCWEB_LOG_ERROR << ec;
} else {
- nlohmann::json &data_json = *transaction;
-
- for (auto &object_path : objects) {
- CROW_LOG_DEBUG << "Reading object "
- << static_cast<const std::string &>(
- object_path.first);
- nlohmann::json &object_json =
- data_json[static_cast<const std::string &>(object_path.first)];
- if (object_json.is_null()) {
- object_json = nlohmann::json::object();
+ nlohmann::json &dataJson = *transaction;
+
+ for (auto &objectPath : objects) {
+ BMCWEB_LOG_DEBUG
+ << "Reading object "
+ << static_cast<const std::string &>(objectPath.first);
+ nlohmann::json &objectJson =
+ dataJson[static_cast<const std::string &>(objectPath.first)];
+ if (objectJson.is_null()) {
+ objectJson = nlohmann::json::object();
}
- for (const auto &interface : object_path.second) {
+ for (const auto &interface : objectPath.second) {
for (const auto &property : interface.second) {
- nlohmann::json &property_json = object_json[property.first];
+ nlohmann::json &propertyJson = objectJson[property.first];
mapbox::util::apply_visitor(
- [&property_json](auto &&val) { property_json = val; },
+ [&propertyJson](auto &&val) { propertyJson = val; },
property.second);
// dbus-rest represents booleans as 1 or 0, implement to match
// TODO(ed) see if dbus-rest should be changed
- const bool *property_bool =
- property_json.get_ptr<const bool *>();
- if (property_bool != nullptr) {
- property_json = *property_bool ? 1 : 0;
+ const bool *propertyBool = propertyJson.get_ptr<const bool *>();
+ if (propertyBool != nullptr) {
+ propertyJson = *propertyBool ? 1 : 0;
}
}
}
@@ -114,9 +113,9 @@ void get_managed_objects_for_enumerate(
}
if (transaction.use_count() == 1) {
- res.json_value = {{"message", "200 OK"},
- {"status", "ok"},
- {"data", std::move(*transaction)}};
+ res.jsonValue = {{"message", "200 OK"},
+ {"status", "ok"},
+ {"data", std::move(*transaction)}};
res.end();
}
},
@@ -130,13 +129,13 @@ using GetSubTreeType = std::vector<
// Structure for storing data on an in progress action
struct InProgressActionData {
- InProgressActionData(crow::response &res) : res(res){};
+ InProgressActionData(crow::Response &res) : res(res){};
~InProgressActionData() {
if (res.result() == boost::beast::http::status::internal_server_error) {
// Reset the json object to clear out any data that made it in before the
// error happened
// todo(ed) handle error condition with proper code
- res.json_value = nlohmann::json::object();
+ res.jsonValue = nlohmann::json::object();
}
res.end();
}
@@ -144,7 +143,7 @@ struct InProgressActionData {
void setErrorStatus() {
res.result(boost::beast::http::status::internal_server_error);
}
- crow::response &res;
+ crow::Response &res;
std::string path;
std::string method_name;
nlohmann::json arguments;
@@ -198,7 +197,7 @@ std::vector<std::string> dbus_arg_split(const std::string &string) {
int convert_json_to_dbus(sd_bus_message *m, const std::string &arg_type,
const nlohmann::json &input_json) {
int r = 0;
- CROW_LOG_DEBUG << "Converting " << input_json.dump()
+ BMCWEB_LOG_DEBUG << "Converting " << input_json.dump()
<< " to type: " << arg_type;
const std::vector<std::string> arg_types = dbus_arg_split(arg_type);
@@ -335,7 +334,7 @@ int convert_json_to_dbus(sd_bus_message *m, const std::string &arg_type,
sd_bus_message_close_container(m);
} else if (boost::starts_with(arg_code, "v")) {
std::string contained_type = arg_code.substr(1);
- CROW_LOG_DEBUG << "variant type: " << arg_code
+ BMCWEB_LOG_DEBUG << "variant type: " << arg_code
<< " appending variant of type: " << contained_type;
r = sd_bus_message_open_container(m, SD_BUS_TYPE_VARIANT,
contained_type.c_str());
@@ -408,15 +407,15 @@ int convert_json_to_dbus(sd_bus_message *m, const std::string &arg_type,
void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction,
const std::string &connectionName) {
- CROW_LOG_DEBUG << "find_action_on_interface for connection "
+ BMCWEB_LOG_DEBUG << "find_action_on_interface for connection "
<< connectionName;
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[
transaction, connectionName{std::string(connectionName)}
](const boost::system::error_code ec, const std::string &introspect_xml) {
- CROW_LOG_DEBUG << "got xml:\n " << introspect_xml;
+ BMCWEB_LOG_DEBUG << "got xml:\n " << introspect_xml;
if (ec) {
- CROW_LOG_ERROR << "Introspect call failed with error: "
+ BMCWEB_LOG_ERROR << "Introspect call failed with error: "
<< ec.message() << " on process: " << connectionName
<< "\n";
} else {
@@ -425,7 +424,7 @@ void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction,
doc.Parse(introspect_xml.c_str());
tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node");
if (pRoot == nullptr) {
- CROW_LOG_ERROR << "XML document failed to parse " << connectionName
+ BMCWEB_LOG_ERROR << "XML document failed to parse " << connectionName
<< "\n";
} else {
@@ -438,10 +437,10 @@ void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction,
interface_node->FirstChildElement("method");
while (method_node != nullptr) {
std::string this_method_name = method_node->Attribute("name");
- CROW_LOG_DEBUG << "Found method: " << this_method_name;
+ BMCWEB_LOG_DEBUG << "Found method: " << this_method_name;
if (this_method_name == transaction->method_name) {
sdbusplus::message::message m =
- crow::connections::system_bus->new_method_call(
+ crow::connections::systemBus->new_method_call(
connectionName.c_str(), transaction->path.c_str(),
this_interface_name.c_str(),
transaction->method_name.c_str());
@@ -471,14 +470,14 @@ void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction,
}
argument_node = method_node->NextSiblingElement("arg");
}
- crow::connections::system_bus->async_send(
+ crow::connections::systemBus->async_send(
m, [transaction](boost::system::error_code ec,
sdbusplus::message::message &m) {
if (ec) {
transaction->setErrorStatus();
return;
}
- transaction->res.json_value = {{"status", "ok"},
+ transaction->res.jsonValue = {{"status", "ok"},
{"message", "200 OK"},
{"data", nullptr}};
});
@@ -495,7 +494,7 @@ void find_action_on_interface(std::shared_ptr<InProgressActionData> transaction,
"Introspect");
}
-void handle_action(const crow::request &req, crow::response &res,
+void handle_action(const crow::Request &req, crow::Response &res,
const std::string &object_path,
const std::string &method_name) {
nlohmann::json request_dbus_data =
@@ -516,7 +515,7 @@ void handle_action(const crow::request &req, crow::response &res,
transaction->path = object_path;
transaction->method_name = method_name;
transaction->arguments = std::move(request_dbus_data);
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[transaction](
const boost::system::error_code ec,
const std::vector<std::pair<std::string, std::vector<std::string>>>
@@ -526,7 +525,7 @@ void handle_action(const crow::request &req, crow::response &res,
return;
}
- CROW_LOG_DEBUG << "GetObject returned objects "
+ BMCWEB_LOG_DEBUG << "GetObject returned objects "
<< interface_names.size();
for (const std::pair<std::string, std::vector<std::string>> &object :
@@ -539,31 +538,31 @@ void handle_action(const crow::request &req, crow::response &res,
std::array<std::string, 0>());
}
-void handle_list(crow::response &res, const std::string &object_path) {
- crow::connections::system_bus->async_method_call(
+void handle_list(crow::Response &res, const std::string &objectPath) {
+ crow::connections::systemBus->async_method_call(
[&res](const boost::system::error_code ec,
- std::vector<std::string> &object_paths) {
+ std::vector<std::string> &objectPaths) {
if (ec) {
res.result(boost::beast::http::status::internal_server_error);
} else {
- res.json_value = {{"status", "ok"},
+ res.jsonValue = {{"status", "ok"},
{"message", "200 OK"},
- {"data", std::move(object_paths)}};
+ {"data", std::move(objectPaths)}};
}
res.end();
},
"xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper",
- "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", object_path,
+ "xyz.openbmc_project.ObjectMapper", "GetSubTreePaths", objectPath,
static_cast<int32_t>(99), std::array<std::string, 0>());
}
-void handle_enumerate(crow::response &res, const std::string &object_path) {
- crow::connections::system_bus->async_method_call(
- [&res, object_path{std::string(object_path)} ](
+void handle_enumerate(crow::Response &res, const std::string &objectPath) {
+ crow::connections::systemBus->async_method_call(
+ [&res, objectPath{std::string(objectPath)} ](
const boost::system::error_code ec,
const GetSubTreeType &object_names) {
if (ec) {
- res.json_value = {{"message", "200 OK"},
+ res.jsonValue = {{"message", "200 OK"},
{"status", "ok"},
{"data", nlohmann::json::object()}};
@@ -574,8 +573,8 @@ void handle_enumerate(crow::response &res, const std::string &object_path) {
boost::container::flat_set<std::string> connections;
for (const auto &object : object_names) {
- for (const auto &connection : object.second) {
- connections.insert(connection.first);
+ for (const auto &Connection : object.second) {
+ connections.insert(Connection.first);
}
}
@@ -586,25 +585,26 @@ void handle_enumerate(crow::response &res, const std::string &object_path) {
}
auto transaction =
std::make_shared<nlohmann::json>(nlohmann::json::object());
- for (const std::string &connection : connections) {
- get_managed_objects_for_enumerate(object_path, connection, res,
- transaction);
+ for (const std::string &Connection : connections) {
+ getManagedObjectsForEnumerate(objectPath, Connection, res,
+ transaction);
}
},
"xyz.openbmc_project.ObjectMapper", "/xyz/openbmc_project/object_mapper",
- "xyz.openbmc_project.ObjectMapper", "GetSubTree", object_path, (int32_t)0,
+ "xyz.openbmc_project.ObjectMapper", "GetSubTree", objectPath, (int32_t)0,
std::array<std::string, 0>());
}
-void handle_get(crow::response &res, const std::string &object_path,
- const std::string &dest_property) {
+void handle_get(crow::Response &res, std::string &object_path,
+ std::string &dest_property) {
+ BMCWEB_LOG_DEBUG << "handle_get: " << object_path << " prop:" << dest_property;
std::shared_ptr<std::string> property_name =
std::make_shared<std::string>(dest_property);
using GetObjectType =
std::vector<std::pair<std::string, std::vector<std::string>>>;
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[&res, object_path, property_name](const boost::system::error_code ec,
- const GetObjectType &object_names) {
+ const GetObjectType &object_names) {
if (ec || object_names.size() <= 0) {
res.result(boost::beast::http::status::not_found);
res.end();
@@ -625,13 +625,13 @@ void handle_get(crow::response &res, const std::string &object_path,
}
for (const std::string &interface : interfaceNames) {
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[&res, response, property_name](
const boost::system::error_code ec,
const std::vector<std::pair<
std::string, DbusRestVariantType>> &properties) {
if (ec) {
- CROW_LOG_ERROR << "Bad dbus request error: " << ec;
+ BMCWEB_LOG_ERROR << "Bad dbus request error: " << ec;
} else {
for (const std::pair<std::string, DbusRestVariantType>
&property : properties) {
@@ -652,7 +652,7 @@ void handle_get(crow::response &res, const std::string &object_path,
}
}
if (response.use_count() == 1) {
- res.json_value = {{"status", "ok"},
+ res.jsonValue = {{"status", "ok"},
{"message", "200 OK"},
{"data", *response}};
@@ -670,8 +670,8 @@ void handle_get(crow::response &res, const std::string &object_path,
}
struct AsyncPutRequest {
- AsyncPutRequest(crow::response &res) : res(res) {
- res.json_value = {
+ AsyncPutRequest(crow::Response &res) : res(res) {
+ res.jsonValue = {
{"status", "ok"}, {"message", "200 OK"}, {"data", nullptr}};
}
~AsyncPutRequest() {
@@ -679,12 +679,12 @@ struct AsyncPutRequest {
// Reset the json object to clear out any data that made it in before the
// error happened
// todo(ed) handle error condition with proper code
- res.json_value = nlohmann::json::object();
+ res.jsonValue = nlohmann::json::object();
}
- if (res.json_value.empty()) {
+ if (res.jsonValue.empty()) {
res.result(boost::beast::http::status::forbidden);
- res.json_value = {
+ res.jsonValue = {
{"status", "error"},
{"message", "403 Forbidden"},
{"data",
@@ -699,13 +699,13 @@ struct AsyncPutRequest {
res.result(boost::beast::http::status::internal_server_error);
}
- crow::response &res;
+ crow::Response &res;
std::string objectPath;
std::string propertyName;
nlohmann::json propertyValue;
};
-void handle_put(const crow::request &req, crow::response &res,
+void handle_put(const crow::Request &req, crow::Response &res,
const std::string &objectPath,
const std::string &destProperty) {
nlohmann::json request_dbus_data =
@@ -732,7 +732,7 @@ void handle_put(const crow::request &req, crow::response &res,
using GetObjectType =
std::vector<std::pair<std::string, std::vector<std::string>>>;
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[transaction](const boost::system::error_code ec,
const GetObjectType &object_names) {
if (!ec && object_names.size() <= 0) {
@@ -744,12 +744,12 @@ void handle_put(const crow::request &req, crow::response &res,
object_names) {
const std::string &connectionName = connection.first;
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[ connectionName{std::string(connectionName)}, transaction ](
const boost::system::error_code ec,
const std::string &introspectXml) {
if (ec) {
- CROW_LOG_ERROR
+ BMCWEB_LOG_ERROR
<< "Introspect call failed with error: " << ec.message()
<< " on process: " << connectionName;
transaction->setErrorStatus();
@@ -760,7 +760,7 @@ void handle_put(const crow::request &req, crow::response &res,
doc.Parse(introspectXml.c_str());
tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node");
if (pRoot == nullptr) {
- CROW_LOG_ERROR << "XML document failed to parse: "
+ BMCWEB_LOG_ERROR << "XML document failed to parse: "
<< introspectXml;
transaction->setErrorStatus();
return;
@@ -769,17 +769,17 @@ void handle_put(const crow::request &req, crow::response &res,
pRoot->FirstChildElement("interface");
while (ifaceNode != nullptr) {
const char *interfaceName = ifaceNode->Attribute("name");
- CROW_LOG_DEBUG << "found interface " << interfaceName;
+ BMCWEB_LOG_DEBUG << "found interface " << interfaceName;
tinyxml2::XMLElement *propNode =
ifaceNode->FirstChildElement("property");
while (propNode != nullptr) {
const char *propertyName = propNode->Attribute("name");
- CROW_LOG_DEBUG << "Found property " << propertyName;
+ BMCWEB_LOG_DEBUG << "Found property " << propertyName;
if (propertyName == transaction->propertyName) {
const char *argType = propNode->Attribute("type");
if (argType != nullptr) {
sdbusplus::message::message m =
- crow::connections::system_bus->new_method_call(
+ crow::connections::systemBus->new_method_call(
connectionName.c_str(),
transaction->objectPath.c_str(),
"org.freedesktop.DBus.Properties", "Set");
@@ -802,13 +802,13 @@ void handle_put(const crow::request &req, crow::response &res,
return;
}
- crow::connections::system_bus->async_send(
+ crow::connections::systemBus->async_send(
m, [transaction](boost::system::error_code ec,
sdbusplus::message::message &m) {
- CROW_LOG_DEBUG << "sent";
+ BMCWEB_LOG_DEBUG << "sent";
if (ec) {
- transaction->res.json_value["status"] = "error";
- transaction->res.json_value["message"] =
+ transaction->res.jsonValue["status"] = "error";
+ transaction->res.jsonValue["message"] =
ec.message();
}
});
@@ -829,43 +829,44 @@ void handle_put(const crow::request &req, crow::response &res,
}
template <typename... Middlewares>
-void request_routes(Crow<Middlewares...> &app) {
- CROW_ROUTE(app, "/bus/")
- .methods("GET"_method)([](const crow::request &req, crow::response &res) {
- res.json_value = {{"busses", {{{"name", "system"}}}}, {"status", "ok"}};
+void requestRoutes(Crow<Middlewares...> &app) {
+ BMCWEB_ROUTE(app, "/bus/")
+ .methods("GET"_method)([](const crow::Request &req, crow::Response &res) {
+ res.jsonValue = {{"busses", {{{"name", "system"}}}}, {"status", "ok"}};
});
- CROW_ROUTE(app, "/bus/system/")
- .methods("GET"_method)([](const crow::request &req, crow::response &res) {
+ BMCWEB_ROUTE(app, "/bus/system/")
+ .methods("GET"_method)([](const crow::Request &req, crow::Response &res) {
+
auto myCallback = [&res](const boost::system::error_code ec,
std::vector<std::string> &names) {
if (ec) {
- CROW_LOG_ERROR << "Dbus call failed with code " << ec;
+ BMCWEB_LOG_ERROR << "Dbus call failed with code " << ec;
res.result(boost::beast::http::status::internal_server_error);
} else {
std::sort(names.begin(), names.end());
nlohmann::json j{{"status", "ok"}};
- auto &objects_sub = j["objects"];
+ auto &objectsSub = j["objects"];
for (auto &name : names) {
- objects_sub.push_back({{"name", name}});
+ objectsSub.push_back({{"name", name}});
}
- res.json_value = std::move(j);
+ res.jsonValue = std::move(j);
}
res.end();
};
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
std::move(myCallback), "org.freedesktop.DBus", "/",
"org.freedesktop.DBus", "ListNames");
});
- CROW_ROUTE(app, "/list/")
- .methods("GET"_method)([](const crow::request &req, crow::response &res) {
+ BMCWEB_ROUTE(app, "/list/")
+ .methods("GET"_method)([](const crow::Request &req, crow::Response &res) {
handle_list(res, "/");
});
- CROW_ROUTE(app, "/xyz/<path>")
+ BMCWEB_ROUTE(app, "/xyz/<path>")
.methods("GET"_method, "PUT"_method,
- "POST"_method)([](const crow::request &req, crow::response &res,
+ "POST"_method)([](const crow::Request &req, crow::Response &res,
const std::string &path) {
std::string object_path = "/xyz/" + path;
@@ -915,15 +916,15 @@ void request_routes(Crow<Middlewares...> &app) {
res.end();
});
- CROW_ROUTE(app, "/bus/system/<str>/")
- .methods("GET"_method)([](const crow::request &req, crow::response &res,
- const std::string &connection) {
+ BMCWEB_ROUTE(app, "/bus/system/<str>/")
+ .methods("GET"_method)([](const crow::Request &req, crow::Response &res,
+ const std::string &Connection) {
std::shared_ptr<nlohmann::json> transaction;
- introspect_objects(res, connection, "/", transaction);
+ introspectObjects(res, Connection, "/", transaction);
});
- CROW_ROUTE(app, "/download/dump/<str>/")
- .methods("GET"_method)([](const crow::request &req, crow::response &res,
+ BMCWEB_ROUTE(app, "/download/dump/<str>/")
+ .methods("GET"_method)([](const crow::Request &req, crow::Response &res,
const std::string &dumpId) {
std::regex validFilename("^[\\w\\- ]+(\\.?[\\w\\- ]+)$");
if (!std::regex_match(dumpId, validFilename)) {
@@ -948,7 +949,7 @@ void request_routes(Crow<Middlewares...> &app) {
if (readFile.good()) {
continue;
}
- res.add_header("Content-Type", "application/octet-stream");
+ res.addHeader("Content-Type", "application/octet-stream");
res.body() = {std::istreambuf_iterator<char>(readFile),
std::istreambuf_iterator<char>()};
res.end();
@@ -958,18 +959,18 @@ void request_routes(Crow<Middlewares...> &app) {
return;
});
- CROW_ROUTE(app, "/bus/system/<str>/<path>")
- .methods("GET"_method)([](const crow::request &req, crow::response &res,
- const std::string &process_name,
- const std::string &requested_path) {
+ BMCWEB_ROUTE(app, "/bus/system/<str>/<path>")
+ .methods("GET"_method)([](const crow::Request &req, crow::Response &res,
+ const std::string &processName,
+ const std::string &requestedPath) {
std::vector<std::string> strs;
- boost::split(strs, requested_path, boost::is_any_of("/"));
- std::string object_path;
- std::string interface_name;
- std::string method_name;
+ boost::split(strs, requestedPath, boost::is_any_of("/"));
+ std::string objectPath;
+ std::string interfaceName;
+ std::string methodName;
auto it = strs.begin();
if (it == strs.end()) {
- object_path = "/";
+ objectPath = "/";
}
while (it != strs.end()) {
// Check if segment contains ".". If it does, it must be an
@@ -980,17 +981,17 @@ void request_routes(Crow<Middlewares...> &app) {
// part of our <path> specifier above, which causes the normal
// trailing backslash redirector to fail.
} else if (!it->empty()) {
- object_path += "/" + *it;
+ objectPath += "/" + *it;
}
it++;
}
if (it != strs.end()) {
- interface_name = *it;
+ interfaceName = *it;
it++;
// after interface, we might have a method name
if (it != strs.end()) {
- method_name = *it;
+ methodName = *it;
it++;
}
}
@@ -1001,16 +1002,16 @@ void request_routes(Crow<Middlewares...> &app) {
res.end();
return;
}
- if (interface_name.empty()) {
- crow::connections::system_bus->async_method_call(
- [&, process_name, object_path](
+ if (interfaceName.empty()) {
+ crow::connections::systemBus->async_method_call(
+ [&, processName, objectPath](
const boost::system::error_code ec,
const std::string &introspect_xml) {
if (ec) {
- CROW_LOG_ERROR
+ BMCWEB_LOG_ERROR
<< "Introspect call failed with error: " << ec.message()
- << " on process: " << process_name
- << " path: " << object_path << "\n";
+ << " on process: " << processName
+ << " path: " << objectPath << "\n";
} else {
tinyxml2::XMLDocument doc;
@@ -1018,45 +1019,45 @@ void request_routes(Crow<Middlewares...> &app) {
doc.Parse(introspect_xml.c_str());
tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node");
if (pRoot == nullptr) {
- CROW_LOG_ERROR << "XML document failed to parse "
- << process_name << " " << object_path
- << "\n";
- res.json_value = {{"status", "XML parse error"}};
+ BMCWEB_LOG_ERROR << "XML document failed to parse "
+ << processName << " " << objectPath
+ << "\n";
+ res.jsonValue = {{"status", "XML parse error"}};
res.result(
boost::beast::http::status::internal_server_error);
} else {
- nlohmann::json interfaces_array = nlohmann::json::array();
+ nlohmann::json interfacesArray = nlohmann::json::array();
tinyxml2::XMLElement *interface =
pRoot->FirstChildElement("interface");
while (interface != nullptr) {
- std::string iface_name = interface->Attribute("name");
- interfaces_array.push_back({{"name", iface_name}});
+ std::string ifaceName = interface->Attribute("name");
+ interfacesArray.push_back({{"name", ifaceName}});
interface = interface->NextSiblingElement("interface");
}
- res.json_value = {{"status", "ok"},
- {"bus_name", process_name},
- {"interfaces", interfaces_array},
- {"object_path", object_path}};
+ res.jsonValue = {{"status", "ok"},
+ {"bus_name", processName},
+ {"interfaces", interfacesArray},
+ {"object_path", objectPath}};
}
}
res.end();
},
- process_name, object_path, "org.freedesktop.DBus.Introspectable",
+ processName, objectPath, "org.freedesktop.DBus.Introspectable",
"Introspect");
} else {
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[
- &, process_name, object_path,
- interface_name{std::move(interface_name)}
+ &, processName, objectPath,
+ interface_name{std::move(interfaceName)}
](const boost::system::error_code ec,
const std::string &introspect_xml) {
if (ec) {
- CROW_LOG_ERROR
+ BMCWEB_LOG_ERROR
<< "Introspect call failed with error: " << ec.message()
- << " on process: " << process_name
- << " path: " << object_path << "\n";
+ << " on process: " << processName
+ << " path: " << objectPath << "\n";
} else {
tinyxml2::XMLDocument doc;
@@ -1064,9 +1065,9 @@ void request_routes(Crow<Middlewares...> &app) {
doc.Parse(introspect_xml.c_str());
tinyxml2::XMLNode *pRoot = doc.FirstChildElement("node");
if (pRoot == nullptr) {
- CROW_LOG_ERROR << "XML document failed to parse "
- << process_name << " " << object_path
- << "\n";
+ BMCWEB_LOG_ERROR << "XML document failed to parse "
+ << processName << " " << objectPath
+ << "\n";
res.result(
boost::beast::http::status::internal_server_error);
@@ -1075,66 +1076,66 @@ void request_routes(Crow<Middlewares...> &app) {
pRoot->FirstChildElement("node");
// if we know we're the only call, build the json directly
- nlohmann::json methods_array = nlohmann::json::array();
- nlohmann::json signals_array = nlohmann::json::array();
+ nlohmann::json methodsArray = nlohmann::json::array();
+ nlohmann::json signalsArray = nlohmann::json::array();
tinyxml2::XMLElement *interface =
pRoot->FirstChildElement("interface");
while (interface != nullptr) {
- std::string iface_name = interface->Attribute("name");
+ std::string ifaceName = interface->Attribute("name");
- if (iface_name == interface_name) {
+ if (ifaceName == interfaceName) {
tinyxml2::XMLElement *methods =
interface->FirstChildElement("method");
while (methods != nullptr) {
- nlohmann::json args_array = nlohmann::json::array();
+ nlohmann::json argsArray = nlohmann::json::array();
tinyxml2::XMLElement *arg =
methods->FirstChildElement("arg");
while (arg != nullptr) {
- args_array.push_back(
+ argsArray.push_back(
{{"name", arg->Attribute("name")},
{"type", arg->Attribute("type")},
{"direction", arg->Attribute("direction")}});
arg = arg->NextSiblingElement("arg");
}
- methods_array.push_back(
+ methodsArray.push_back(
{{"name", methods->Attribute("name")},
- {"uri", "/bus/system/" + process_name +
- object_path + "/" + interface_name +
+ {"uri", "/bus/system/" + processName +
+ objectPath + "/" + interfaceName +
"/" + methods->Attribute("name")},
- {"args", args_array}});
+ {"args", argsArray}});
methods = methods->NextSiblingElement("method");
}
tinyxml2::XMLElement *signals =
interface->FirstChildElement("signal");
while (signals != nullptr) {
- nlohmann::json args_array = nlohmann::json::array();
+ nlohmann::json argsArray = nlohmann::json::array();
tinyxml2::XMLElement *arg =
signals->FirstChildElement("arg");
while (arg != nullptr) {
std::string name = arg->Attribute("name");
std::string type = arg->Attribute("type");
- args_array.push_back({
+ argsArray.push_back({
{"name", name},
{"type", type},
});
arg = arg->NextSiblingElement("arg");
}
- signals_array.push_back(
+ signalsArray.push_back(
{{"name", signals->Attribute("name")},
- {"args", args_array}});
+ {"args", argsArray}});
signals = signals->NextSiblingElement("signal");
}
- res.json_value = {
+ res.jsonValue = {
{"status", "ok"},
- {"bus_name", process_name},
- {"interface", interface_name},
- {"methods", methods_array},
- {"object_path", object_path},
+ {"bus_name", processName},
+ {"interface", interfaceName},
+ {"methods", methodsArray},
+ {"object_path", objectPath},
{"properties", nlohmann::json::object()},
- {"signals", signals_array}};
+ {"signals", signalsArray}};
break;
}
@@ -1150,7 +1151,7 @@ void request_routes(Crow<Middlewares...> &app) {
}
res.end();
},
- process_name, object_path, "org.freedesktop.DBus.Introspectable",
+ processName, objectPath, "org.freedesktop.DBus.Introspectable",
"Introspect");
}
});
diff --git a/include/pam_authenticate.hpp b/include/pam_authenticate.hpp
index a66d16b347..65e47402f7 100644
--- a/include/pam_authenticate.hpp
+++ b/include/pam_authenticate.hpp
@@ -6,21 +6,20 @@
#include <boost/utility/string_view.hpp>
// function used to get user input
-inline int pam_function_conversation(int num_msg,
- const struct pam_message** msg,
- struct pam_response** resp,
- void* appdata_ptr) {
- if (appdata_ptr == nullptr) {
+inline int pamFunctionConversation(int numMsg, const struct pam_message** msg,
+ struct pam_response** resp,
+ void* appdataPtr) {
+ if (appdataPtr == nullptr) {
return PAM_AUTH_ERR;
}
auto* pass = reinterpret_cast<char*>(
- malloc(std::strlen(reinterpret_cast<char*>(appdata_ptr)) + 1));
- std::strcpy(pass, reinterpret_cast<char*>(appdata_ptr));
+ malloc(std::strlen(reinterpret_cast<char*>(appdataPtr)) + 1));
+ std::strcpy(pass, reinterpret_cast<char*>(appdataPtr));
*resp = reinterpret_cast<pam_response*>(
- calloc(num_msg, sizeof(struct pam_response)));
+ calloc(numMsg, sizeof(struct pam_response)));
- for (int i = 0; i < num_msg; ++i) {
+ for (int i = 0; i < numMsg; ++i) {
/* Ignore all PAM messages except prompting for hidden input */
if (msg[i]->msg_style != PAM_PROMPT_ECHO_OFF) {
continue;
@@ -33,20 +32,20 @@ inline int pam_function_conversation(int num_msg,
return PAM_SUCCESS;
}
-inline bool pam_authenticate_user(const boost::string_view username,
- const boost::string_view password) {
- std::string user_str(username);
- std::string pass_str(password);
- const struct pam_conv local_conversation = {
- pam_function_conversation, const_cast<char*>(pass_str.c_str())};
- pam_handle_t* local_auth_handle = NULL; // this gets set by pam_start
+inline bool pamAuthenticateUser(const boost::string_view username,
+ const boost::string_view password) {
+ std::string userStr(username);
+ std::string passStr(password);
+ const struct pam_conv localConversation = {
+ pamFunctionConversation, const_cast<char*>(passStr.c_str())};
+ pam_handle_t* localAuthHandle = NULL; // this gets set by pam_start
- if (pam_start("webserver", user_str.c_str(), &local_conversation,
- &local_auth_handle) != PAM_SUCCESS) {
+ if (pam_start("webserver", userStr.c_str(), &localConversation,
+ &localAuthHandle) != PAM_SUCCESS) {
return false;
}
- int retval = pam_authenticate(local_auth_handle,
- PAM_SILENT | PAM_DISALLOW_NULL_AUTHTOK);
+ int retval =
+ pam_authenticate(localAuthHandle, PAM_SILENT | PAM_DISALLOW_NULL_AUTHTOK);
if (retval != PAM_SUCCESS) {
if (retval == PAM_AUTH_ERR) {
@@ -54,18 +53,18 @@ inline bool pam_authenticate_user(const boost::string_view username,
} else {
// printf("pam_authenticate returned %d\n", retval);
}
- pam_end(local_auth_handle, PAM_SUCCESS);
+ pam_end(localAuthHandle, PAM_SUCCESS);
return false;
}
/* check that the account is healthy */
- if (pam_acct_mgmt(local_auth_handle, PAM_DISALLOW_NULL_AUTHTOK) !=
+ if (pam_acct_mgmt(localAuthHandle, PAM_DISALLOW_NULL_AUTHTOK) !=
PAM_SUCCESS) {
- pam_end(local_auth_handle, PAM_SUCCESS);
+ pam_end(localAuthHandle, PAM_SUCCESS);
return false;
}
- if (pam_end(local_auth_handle, PAM_SUCCESS) != PAM_SUCCESS) {
+ if (pam_end(localAuthHandle, PAM_SUCCESS) != PAM_SUCCESS) {
return false;
}
diff --git a/include/persistent_data_middleware.hpp b/include/persistent_data_middleware.hpp
index 334a84de93..d43b4f2f59 100644
--- a/include/persistent_data_middleware.hpp
+++ b/include/persistent_data_middleware.hpp
@@ -15,55 +15,55 @@
namespace crow {
-namespace PersistentData {
+namespace persistent_data {
class Middleware {
// todo(ed) should read this from a fixed location somewhere, not CWD
static constexpr const char* filename = "bmcweb_persistent_data.json";
- int json_revision = 1;
+ int jsonRevision = 1;
public:
- struct context {};
+ struct Context {};
- Middleware() { read_data(); }
+ Middleware() { readData(); }
~Middleware() {
- if (PersistentData::SessionStore::getInstance().needs_write()) {
- write_data();
+ if (persistent_data::SessionStore::getInstance().needsWrite()) {
+ writeData();
}
}
- void before_handle(crow::request& req, response& res, context& ctx) {}
+ void beforeHandle(crow::Request& req, Response& res, Context& ctx) {}
- void after_handle(request& req, response& res, context& ctx) {}
+ void afterHandle(Request& req, Response& res, Context& ctx) {}
// TODO(ed) this should really use protobuf, or some other serialization
// library, but adding another dependency is somewhat outside the scope of
// this application for the moment
- void read_data() {
- std::ifstream persistent_file(filename);
- int file_revision = 0;
- if (persistent_file.is_open()) {
+ void readData() {
+ std::ifstream persistentFile(filename);
+ int fileRevision = 0;
+ if (persistentFile.is_open()) {
// call with exceptions disabled
- auto data = nlohmann::json::parse(persistent_file, nullptr, false);
+ auto data = nlohmann::json::parse(persistentFile, nullptr, false);
if (data.is_discarded()) {
- CROW_LOG_ERROR << "Error parsing persistent data in json file.";
+ BMCWEB_LOG_ERROR << "Error parsing persistent data in json file.";
} else {
for (const auto& item : data.items()) {
if (item.key() == "revision") {
- file_revision = 0;
+ fileRevision = 0;
const uint64_t* uintPtr = item.value().get_ptr<const uint64_t*>();
if (uintPtr == nullptr) {
- CROW_LOG_ERROR << "Failed to read revision flag";
+ BMCWEB_LOG_ERROR << "Failed to read revision flag";
} else {
- file_revision = *uintPtr;
+ fileRevision = *uintPtr;
}
} else if (item.key() == "system_uuid") {
const std::string* jSystemUuid =
item.value().get_ptr<const std::string*>();
if (jSystemUuid != nullptr) {
- system_uuid = *jSystemUuid;
+ systemUuid = *jSystemUuid;
}
} else if (item.key() == "sessions") {
for (const auto& elem : item.value()) {
@@ -71,16 +71,16 @@ class Middleware {
UserSession::fromJson(elem);
if (newSession == nullptr) {
- CROW_LOG_ERROR
+ BMCWEB_LOG_ERROR
<< "Problem reading session from persistent store";
continue;
}
- CROW_LOG_DEBUG << "Restored session: " << newSession->csrf_token
- << " " << newSession->unique_id << " "
- << newSession->session_token;
- SessionStore::getInstance().auth_tokens.emplace(
- newSession->session_token, newSession);
+ BMCWEB_LOG_DEBUG << "Restored session: " << newSession->csrfToken
+ << " " << newSession->uniqueId << " "
+ << newSession->sessionToken;
+ SessionStore::getInstance().authTokens.emplace(
+ newSession->sessionToken, newSession);
}
} else {
// Do nothing in the case of extra fields. We may have cases where
@@ -91,32 +91,32 @@ class Middleware {
}
}
}
- bool need_write = false;
+ bool needWrite = false;
- if (system_uuid.empty()) {
- system_uuid = boost::uuids::to_string(boost::uuids::random_generator()());
- need_write = true;
+ if (systemUuid.empty()) {
+ systemUuid = boost::uuids::to_string(boost::uuids::random_generator()());
+ needWrite = true;
}
- if (file_revision < json_revision) {
- need_write = true;
+ if (fileRevision < jsonRevision) {
+ needWrite = true;
}
// write revision changes or system uuid changes immediately
- if (need_write) {
- write_data();
+ if (needWrite) {
+ writeData();
}
}
- void write_data() {
- std::ofstream persistent_file(filename);
+ void writeData() {
+ std::ofstream persistentFile(filename);
nlohmann::json data{
- {"sessions", PersistentData::SessionStore::getInstance().auth_tokens},
- {"system_uuid", system_uuid},
- {"revision", json_revision}};
- persistent_file << data;
+ {"sessions", SessionStore::getInstance().authTokens},
+ {"system_uuid", systemUuid},
+ {"revision", jsonRevision}};
+ persistentFile << data;
}
- std::string system_uuid{""};
+ std::string systemUuid{""};
};
-} // namespace PersistentData
+} // namespace persistent_data
} // namespace crow
diff --git a/include/redfish_v1.hpp b/include/redfish_v1.hpp
index e8f4d7fd35..b81aa5474a 100644
--- a/include/redfish_v1.hpp
+++ b/include/redfish_v1.hpp
@@ -18,23 +18,23 @@ using ManagedObjectType = std::vector<std::pair<
std::string, sdbusplus::message::variant<bool>>>>>;
template <typename... Middlewares>
-void request_routes(Crow<Middlewares...>& app) {
- CROW_ROUTE(app, "/redfish/")
- .methods("GET"_method)([](const crow::request& req, crow::response& res) {
- res.json_value = {{"v1", "/redfish/v1/"}};
+void requestRoutes(Crow<Middlewares...>& app) {
+ BMCWEB_ROUTE(app, "/redfish/")
+ .methods("GET"_method)([](const crow::Request& req, crow::Response& res) {
+ res.jsonValue = {{"v1", "/redfish/v1/"}};
res.end();
});
- CROW_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
+ BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/")
.methods(
- "GET"_method)([&](const crow::request& req, crow::response& res) {
- crow::connections::system_bus->async_method_call(
+ "GET"_method)([&](const crow::Request& req, crow::Response& res) {
+ crow::connections::systemBus->async_method_call(
[&](const boost::system::error_code ec,
const ManagedObjectType& users) {
if (ec) {
res.result(boost::beast::http::status::internal_server_error);
} else {
- res.json_value = {
+ res.jsonValue = {
{"@odata.context",
"/redfish/v1/"
"$metadata#ManagerAccountCollection."
@@ -45,22 +45,22 @@ void request_routes(Crow<Middlewares...>& app) {
{"Name", "Accounts Collection"},
{"Description", "BMC User Accounts"},
{"Members@odata.count", users.size()}};
- nlohmann::json member_array = nlohmann::json::array();
- int user_index = 0;
+ nlohmann::json memberArray = nlohmann::json::array();
+ int userIndex = 0;
for (auto& user : users) {
const std::string& path =
static_cast<const std::string&>(user.first);
- std::size_t last_index = path.rfind("/");
- if (last_index == std::string::npos) {
- last_index = 0;
+ std::size_t lastIndex = path.rfind("/");
+ if (lastIndex == std::string::npos) {
+ lastIndex = 0;
} else {
- last_index += 1;
+ lastIndex += 1;
}
- member_array.push_back(
+ memberArray.push_back(
{{"@odata.id", "/redfish/v1/AccountService/Accounts/" +
- path.substr(last_index)}});
+ path.substr(lastIndex)}});
}
- res.json_value["Members"] = member_array;
+ res.jsonValue["Members"] = memberArray;
}
res.end();
},
@@ -68,12 +68,12 @@ void request_routes(Crow<Middlewares...>& app) {
"org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
});
- CROW_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
- .methods("GET"_method)([](const crow::request& req, crow::response& res,
+ BMCWEB_ROUTE(app, "/redfish/v1/AccountService/Accounts/<str>/")
+ .methods("GET"_method)([](const crow::Request& req, crow::Response& res,
const std::string& account_name) {
- crow::connections::system_bus->async_method_call(
- [&, account_name{std::move(account_name)} ](
+ crow::connections::systemBus->async_method_call(
+ [&, accountName{std::move(account_name)} ](
const boost::system::error_code ec,
const ManagedObjectType& users) {
if (ec) {
@@ -82,14 +82,14 @@ void request_routes(Crow<Middlewares...>& app) {
for (auto& user : users) {
const std::string& path =
static_cast<const std::string&>(user.first);
- std::size_t last_index = path.rfind("/");
- if (last_index == std::string::npos) {
- last_index = 0;
+ std::size_t lastIndex = path.rfind("/");
+ if (lastIndex == std::string::npos) {
+ lastIndex = 0;
} else {
- last_index += 1;
+ lastIndex += 1;
}
- if (path.substr(last_index) == account_name) {
- res.json_value = {
+ if (path.substr(lastIndex) == accountName) {
+ res.jsonValue = {
{"@odata.context",
"/redfish/v1/$metadata#ManagerAccount.ManagerAccount"},
{"@odata.id", "/redfish/v1/AccountService/Accounts/1"},
@@ -100,7 +100,7 @@ void request_routes(Crow<Middlewares...>& app) {
{"Description", "User Account"},
{"Enabled", false},
{"Password", nullptr},
- {"UserName", account_name},
+ {"UserName", accountName},
{"RoleId", "Administrator"},
{"Links",
{{"Role",
@@ -110,7 +110,7 @@ void request_routes(Crow<Middlewares...>& app) {
break;
}
}
- if (res.json_value.is_null()) {
+ if (res.jsonValue.is_null()) {
res.result(boost::beast::http::status::not_found);
}
}
diff --git a/include/security_headers_middleware.hpp b/include/security_headers_middleware.hpp
index 19369f9711..f7bc478d97 100644
--- a/include/security_headers_middleware.hpp
+++ b/include/security_headers_middleware.hpp
@@ -4,47 +4,46 @@
#include <crow/http_response.h>
namespace crow {
-static const char* strict_transport_security_key = "Strict-Transport-Security";
-static const char* strict_transport_security_value =
+static const char* strictTransportSecurityKey = "Strict-Transport-Security";
+static const char* strictTransportSecurityValue =
"max-age=31536000; includeSubdomains; preload";
-static const char* ua_compatability_key = "X-UA-Compatible";
-static const char* ua_compatability_value = "IE=11";
+static const char* uaCompatabilityKey = "X-UA-Compatible";
+static const char* uaCompatabilityValue = "IE=11";
-static const char* xframe_key = "X-Frame-Options";
-static const char* xframe_value = "DENY";
+static const char* xframeKey = "X-Frame-Options";
+static const char* xframeValue = "DENY";
-static const char* xss_key = "X-XSS-Protection";
-static const char* xss_value = "1; mode=block";
+static const char* xssKey = "X-XSS-Protection";
+static const char* xssValue = "1; mode=block";
-static const char* content_security_key = "X-Content-Security-Policy";
-static const char* content_security_value = "default-src 'self'";
+static const char* contentSecurityKey = "X-Content-Security-Policy";
+static const char* contentSecurityValue = "default-src 'self'";
-static const char* pragma_key = "Pragma";
-static const char* pragma_value = "no-cache";
+static const char* pragmaKey = "Pragma";
+static const char* pragmaValue = "no-cache";
-static const char* cache_control_key = "Cache-Control";
-static const char* cache_control_value = "no-Store,no-Cache";
+static const char* cacheControlKey = "Cache-Control";
+static const char* cacheControlValue = "no-Store,no-Cache";
struct SecurityHeadersMiddleware {
- struct context {};
+ struct Context {};
- void before_handle(crow::request& req, response& res, context& ctx) {}
+ void beforeHandle(crow::Request& req, Response& res, Context& ctx) {}
- void after_handle(request& req, response& res, context& ctx) {
+ void afterHandle(Request& req, Response& res, Context& ctx) {
/*
TODO(ed) these should really check content types. for example,
X-UA-Compatible header doesn't make sense when retrieving a JSON or
javascript file. It doesn't hurt anything, it's just ugly.
*/
- res.add_header(strict_transport_security_key,
- strict_transport_security_value);
- res.add_header(ua_compatability_key, ua_compatability_value);
- res.add_header(xframe_key, xframe_value);
- res.add_header(xss_key, xss_value);
- res.add_header(content_security_key, content_security_value);
- res.add_header(pragma_key, pragma_value);
- res.add_header(cache_control_key, cache_control_value);
+ res.addHeader(strictTransportSecurityKey, strictTransportSecurityValue);
+ res.addHeader(uaCompatabilityKey, uaCompatabilityValue);
+ res.addHeader(xframeKey, xframeValue);
+ res.addHeader(xssKey, xssValue);
+ res.addHeader(contentSecurityKey, contentSecurityValue);
+ res.addHeader(pragmaKey, pragmaValue);
+ res.addHeader(cacheControlKey, cacheControlValue);
}
};
} // namespace crow
diff --git a/include/sessions.hpp b/include/sessions.hpp
index b4e86c721c..f7f937df07 100644
--- a/include/sessions.hpp
+++ b/include/sessions.hpp
@@ -14,7 +14,7 @@
namespace crow {
-namespace PersistentData {
+namespace persistent_data {
enum class PersistenceType {
TIMEOUT, // User session times out after a predetermined amount of time
@@ -22,11 +22,11 @@ enum class PersistenceType {
};
struct UserSession {
- std::string unique_id;
- std::string session_token;
+ std::string uniqueId;
+ std::string sessionToken;
std::string username;
- std::string csrf_token;
- std::chrono::time_point<std::chrono::steady_clock> last_updated;
+ std::string csrfToken;
+ std::chrono::time_point<std::chrono::steady_clock> lastUpdated;
PersistenceType persistence;
/**
@@ -44,20 +44,20 @@ struct UserSession {
const std::string* thisValue =
element.value().get_ptr<const std::string*>();
if (thisValue == nullptr) {
- CROW_LOG_ERROR << "Error reading persistent store. Property "
+ BMCWEB_LOG_ERROR << "Error reading persistent store. Property "
<< element.key() << " was not of type string";
return nullptr;
}
if (element.key() == "unique_id") {
- userSession->unique_id = *thisValue;
+ userSession->uniqueId = *thisValue;
} else if (element.key() == "session_token") {
- userSession->session_token = *thisValue;
+ userSession->sessionToken = *thisValue;
} else if (element.key() == "csrf_token") {
- userSession->csrf_token = *thisValue;
+ userSession->csrfToken = *thisValue;
} else if (element.key() == "username") {
userSession->username = *thisValue;
} else {
- CROW_LOG_ERROR << "Got unexpected property reading persistent file: "
+ BMCWEB_LOG_ERROR << "Got unexpected property reading persistent file: "
<< element.key();
return nullptr;
}
@@ -68,7 +68,7 @@ struct UserSession {
// of wall clock time and steady timer time, possibly persisting values with
// wall clock time instead of steady timer, but the tradeoffs of all the
// corner cases involved are non-trivial, so this is done temporarily
- userSession->last_updated = std::chrono::steady_clock::now();
+ userSession->lastUpdated = std::chrono::steady_clock::now();
userSession->persistence = PersistenceType::TIMEOUT;
return userSession;
@@ -79,100 +79,99 @@ class Middleware;
class SessionStore {
public:
- std::shared_ptr<UserSession> generate_user_session(
+ std::shared_ptr<UserSession> generateUserSession(
const boost::string_view username,
PersistenceType persistence = PersistenceType::TIMEOUT) {
// TODO(ed) find a secure way to not generate session identifiers if
// persistence is set to SINGLE_REQUEST
static constexpr std::array<char, 62> alphanum = {
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
- 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
- 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'b', 'C',
+ 'D', 'E', 'F', 'g', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
+ 'Q', 'r', 'S', 'T', 'U', 'v', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
// entropy: 30 characters, 62 possibilities. log2(62^30) = 178 bits of
// entropy. OWASP recommends at least 60
// https://www.owasp.org/index.php/Session_Management_Cheat_Sheet#Session_ID_Entropy
- std::string session_token;
- session_token.resize(20, '0');
+ std::string sessionToken;
+ sessionToken.resize(20, '0');
std::uniform_int_distribution<int> dist(0, alphanum.size() - 1);
- for (int i = 0; i < session_token.size(); ++i) {
- session_token[i] = alphanum[dist(rd)];
+ for (int i = 0; i < sessionToken.size(); ++i) {
+ sessionToken[i] = alphanum[dist(rd)];
}
// Only need csrf tokens for cookie based auth, token doesn't matter
- std::string csrf_token;
- csrf_token.resize(20, '0');
- for (int i = 0; i < csrf_token.size(); ++i) {
- csrf_token[i] = alphanum[dist(rd)];
+ std::string csrfToken;
+ csrfToken.resize(20, '0');
+ for (int i = 0; i < csrfToken.size(); ++i) {
+ csrfToken[i] = alphanum[dist(rd)];
}
- std::string unique_id;
- unique_id.resize(10, '0');
- for (int i = 0; i < unique_id.size(); ++i) {
- unique_id[i] = alphanum[dist(rd)];
+ std::string uniqueId;
+ uniqueId.resize(10, '0');
+ for (int i = 0; i < uniqueId.size(); ++i) {
+ uniqueId[i] = alphanum[dist(rd)];
}
auto session = std::make_shared<UserSession>(
- UserSession{unique_id, session_token, std::string(username), csrf_token,
+ UserSession{uniqueId, sessionToken, std::string(username), csrfToken,
std::chrono::steady_clock::now(), persistence});
- auto it = auth_tokens.emplace(std::make_pair(session_token, session));
+ auto it = authTokens.emplace(std::make_pair(sessionToken, session));
// Only need to write to disk if session isn't about to be destroyed.
- need_write_ = persistence == PersistenceType::TIMEOUT;
+ needWrite = persistence == PersistenceType::TIMEOUT;
return it.first->second;
}
- std::shared_ptr<UserSession> login_session_by_token(
+ std::shared_ptr<UserSession> loginSessionByToken(
const boost::string_view token) {
- apply_session_timeouts();
- auto session_it = auth_tokens.find(std::string(token));
- if (session_it == auth_tokens.end()) {
+ applySessionTimeouts();
+ auto sessionIt = authTokens.find(std::string(token));
+ if (sessionIt == authTokens.end()) {
return nullptr;
}
- std::shared_ptr<UserSession> user_session = session_it->second;
- user_session->last_updated = std::chrono::steady_clock::now();
- return user_session;
+ std::shared_ptr<UserSession> userSession = sessionIt->second;
+ userSession->lastUpdated = std::chrono::steady_clock::now();
+ return userSession;
}
- std::shared_ptr<UserSession> get_session_by_uid(
- const boost::string_view uid) {
- apply_session_timeouts();
+ std::shared_ptr<UserSession> getSessionByUid(const boost::string_view uid) {
+ applySessionTimeouts();
// TODO(Ed) this is inefficient
- auto session_it = auth_tokens.begin();
- while (session_it != auth_tokens.end()) {
- if (session_it->second->unique_id == uid) {
- return session_it->second;
+ auto sessionIt = authTokens.begin();
+ while (sessionIt != authTokens.end()) {
+ if (sessionIt->second->uniqueId == uid) {
+ return sessionIt->second;
}
- session_it++;
+ sessionIt++;
}
return nullptr;
}
- void remove_session(std::shared_ptr<UserSession> session) {
- auth_tokens.erase(session->session_token);
- need_write_ = true;
+ void removeSession(std::shared_ptr<UserSession> session) {
+ authTokens.erase(session->sessionToken);
+ needWrite = true;
}
- std::vector<const std::string*> get_unique_ids(
+ std::vector<const std::string*> getUniqueIds(
bool getAll = true,
const PersistenceType& type = PersistenceType::SINGLE_REQUEST) {
- apply_session_timeouts();
+ applySessionTimeouts();
std::vector<const std::string*> ret;
- ret.reserve(auth_tokens.size());
- for (auto& session : auth_tokens) {
+ ret.reserve(authTokens.size());
+ for (auto& session : authTokens) {
if (getAll || type == session.second->persistence) {
- ret.push_back(&session.second->unique_id);
+ ret.push_back(&session.second->uniqueId);
}
}
return ret;
}
- bool needs_write() { return need_write_; }
- int get_timeout_in_seconds() const {
- return std::chrono::seconds(timeout_in_minutes).count();
+ bool needsWrite() { return needWrite; }
+ int getTimeoutInSeconds() const {
+ return std::chrono::seconds(timeoutInMinutes).count();
};
- // Persistent data middleware needs to be able to serialize our auth_tokens
+ // Persistent data middleware needs to be able to serialize our authTokens
// structure, which is private
friend Middleware;
@@ -185,48 +184,47 @@ class SessionStore {
SessionStore& operator=(const SessionStore&) = delete;
private:
- SessionStore() : timeout_in_minutes(60) {}
-
- void apply_session_timeouts() {
- auto time_now = std::chrono::steady_clock::now();
- if (time_now - last_timeout_update > std::chrono::minutes(1)) {
- last_timeout_update = time_now;
- auto auth_tokens_it = auth_tokens.begin();
- while (auth_tokens_it != auth_tokens.end()) {
- if (time_now - auth_tokens_it->second->last_updated >=
- timeout_in_minutes) {
- auth_tokens_it = auth_tokens.erase(auth_tokens_it);
- need_write_ = true;
+ SessionStore() : timeoutInMinutes(60) {}
+
+ void applySessionTimeouts() {
+ auto timeNow = std::chrono::steady_clock::now();
+ if (timeNow - lastTimeoutUpdate > std::chrono::minutes(1)) {
+ lastTimeoutUpdate = timeNow;
+ auto authTokensIt = authTokens.begin();
+ while (authTokensIt != authTokens.end()) {
+ if (timeNow - authTokensIt->second->lastUpdated >= timeoutInMinutes) {
+ authTokensIt = authTokens.erase(authTokensIt);
+ needWrite = true;
} else {
- auth_tokens_it++;
+ authTokensIt++;
}
}
}
}
- std::chrono::time_point<std::chrono::steady_clock> last_timeout_update;
+ std::chrono::time_point<std::chrono::steady_clock> lastTimeoutUpdate;
boost::container::flat_map<std::string, std::shared_ptr<UserSession>>
- auth_tokens;
+ authTokens;
std::random_device rd;
- bool need_write_{false};
- std::chrono::minutes timeout_in_minutes;
+ bool needWrite{false};
+ std::chrono::minutes timeoutInMinutes;
};
-} // namespace PersistentData
+} // namespace persistent_data
} // namespace crow
// to_json(...) definition for objects of UserSession type
namespace nlohmann {
template <>
-struct adl_serializer<std::shared_ptr<crow::PersistentData::UserSession>> {
+struct adl_serializer<std::shared_ptr<crow::persistent_data::UserSession>> {
static void to_json(
nlohmann::json& j,
- const std::shared_ptr<crow::PersistentData::UserSession>& p) {
+ const std::shared_ptr<crow::persistent_data::UserSession>& p) {
if (p->persistence !=
- crow::PersistentData::PersistenceType::SINGLE_REQUEST) {
- j = nlohmann::json{{"unique_id", p->unique_id},
- {"session_token", p->session_token},
+ crow::persistent_data::PersistenceType::SINGLE_REQUEST) {
+ j = nlohmann::json{{"unique_id", p->uniqueId},
+ {"session_token", p->sessionToken},
{"username", p->username},
- {"csrf_token", p->csrf_token}};
+ {"csrf_token", p->csrfToken}};
}
}
};
diff --git a/include/ssl_key_handler.hpp b/include/ssl_key_handler.hpp
index 4db4a8fdd5..4eac8035f5 100644
--- a/include/ssl_key_handler.hpp
+++ b/include/ssl_key_handler.hpp
@@ -1,5 +1,5 @@
#pragma once
-#ifdef CROW_ENABLE_SSL
+#ifdef BMCWEB_ENABLE_SSL
#include <openssl/bio.h>
#include <openssl/dh.h>
@@ -14,15 +14,15 @@
#include <boost/asio.hpp>
namespace ensuressl {
-static void init_openssl();
-static void cleanup_openssl();
-static EVP_PKEY *create_rsa_key();
-static EVP_PKEY *create_ec_key();
-static void handle_openssl_error();
+static void initOpenssl();
+static void cleanupOpenssl();
+static EVP_PKEY *createRsaKey();
+static EVP_PKEY *createEcKey();
+static void handleOpensslError();
-inline bool verify_openssl_key_cert(const std::string &filepath) {
- bool private_key_valid = false;
- bool cert_valid = false;
+inline bool verifyOpensslKeyCert(const std::string &filepath) {
+ bool privateKeyValid = false;
+ bool certValid = false;
std::cout << "Checking certs in file " << filepath << "\n";
@@ -45,7 +45,7 @@ inline bool verify_openssl_key_cert(const std::string &filepath) {
if (ec != nullptr) {
std::cout << "Found an EC key\n";
if (EC_KEY_check_key(ec) == 1) {
- private_key_valid = true;
+ privateKeyValid = true;
} else {
std::cerr << "Key not valid error number " << ERR_get_error()
<< "\n";
@@ -54,14 +54,14 @@ inline bool verify_openssl_key_cert(const std::string &filepath) {
}
}
- if (private_key_valid) {
+ if (privateKeyValid) {
X509 *x509 = PEM_read_X509(file, NULL, NULL, NULL);
if (x509 == nullptr) {
std::cout << "error getting x509 cert " << ERR_get_error() << "\n";
} else {
rc = X509_verify(x509, pkey);
if (rc == 1) {
- cert_valid = true;
+ certValid = true;
} else {
std::cerr << "Error in verifying private key signature "
<< ERR_get_error() << "\n";
@@ -73,26 +73,26 @@ inline bool verify_openssl_key_cert(const std::string &filepath) {
}
fclose(file);
}
- return cert_valid;
+ return certValid;
}
-inline void generate_ssl_certificate(const std::string &filepath) {
+inline void generateSslCertificate(const std::string &filepath) {
FILE *pFile = NULL;
std::cout << "Generating new keys\n";
- init_openssl();
+ initOpenssl();
// std::cerr << "Generating RSA key";
// EVP_PKEY *pRsaPrivKey = create_rsa_key();
std::cerr << "Generating EC key\n";
- EVP_PKEY *pRsaPrivKey = create_ec_key();
+ EVP_PKEY *pRsaPrivKey = createEcKey();
if (pRsaPrivKey != nullptr) {
std::cerr << "Generating x509 Certificate\n";
// Use this code to directly generate a certificate
X509 *x509;
x509 = X509_new();
if (x509 != nullptr) {
- // Get a random number from the RNG for the certificate serial number
+ // get a random number from the RNG for the certificate serial number
// If this is not random, regenerating certs throws broswer errors
std::random_device rd;
int serial = rd();
@@ -107,7 +107,7 @@ inline void generate_ssl_certificate(const std::string &filepath) {
// set the public key to the key we just generated
X509_set_pubkey(x509, pRsaPrivKey);
- // Get the subject name
+ // get the subject name
X509_NAME *name;
name = X509_get_subject_name(x509);
@@ -146,7 +146,7 @@ inline void generate_ssl_certificate(const std::string &filepath) {
// cleanup_openssl();
}
-EVP_PKEY *create_rsa_key() {
+EVP_PKEY *createRsaKey() {
RSA *pRSA = NULL;
#if OPENSSL_VERSION_NUMBER < 0x00908000L
pRSA = RSA_generate_key(2048, RSA_3, NULL, NULL);
@@ -160,12 +160,12 @@ EVP_PKEY *create_rsa_key() {
/* pKey owns pRSA from now */
if (RSA_check_key(pRSA) <= 0) {
fprintf(stderr, "RSA_check_key failed.\n");
- handle_openssl_error();
+ handleOpensslError();
EVP_PKEY_free(pKey);
pKey = NULL;
}
} else {
- handle_openssl_error();
+ handleOpensslError();
if (pRSA != nullptr) {
RSA_free(pRSA);
pRSA = NULL;
@@ -178,7 +178,7 @@ EVP_PKEY *create_rsa_key() {
return pKey;
}
-EVP_PKEY *create_ec_key() {
+EVP_PKEY *createEcKey() {
EVP_PKEY *pKey = NULL;
int eccgrp = 0;
eccgrp = OBJ_txt2nid("prime256v1");
@@ -200,7 +200,7 @@ EVP_PKEY *create_ec_key() {
return pKey;
}
-void init_openssl() {
+void initOpenssl() {
#if OPENSSL_VERSION_NUMBER < 0x10100000L
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
@@ -208,7 +208,7 @@ void init_openssl() {
#endif
}
-void cleanup_openssl() {
+void cleanupOpenssl() {
CRYPTO_cleanup_all_ex_data();
ERR_free_strings();
#if OPENSSL_VERSION_NUMBER < 0x10100000L
@@ -217,44 +217,44 @@ void cleanup_openssl() {
EVP_cleanup();
}
-void handle_openssl_error() { ERR_print_errors_fp(stderr); }
-inline void ensure_openssl_key_present_and_valid(const std::string &filepath) {
- bool pem_file_valid = false;
+void handleOpensslError() { ERR_print_errors_fp(stderr); }
+inline void ensureOpensslKeyPresentAndValid(const std::string &filepath) {
+ bool pemFileValid = false;
- pem_file_valid = verify_openssl_key_cert(filepath);
+ pemFileValid = verifyOpensslKeyCert(filepath);
- if (!pem_file_valid) {
+ if (!pemFileValid) {
std::cerr << "Error in verifying signature, regenerating\n";
- generate_ssl_certificate(filepath);
+ generateSslCertificate(filepath);
}
}
-inline boost::asio::ssl::context get_ssl_context(
+inline boost::asio::ssl::context getSslContext(
const std::string &ssl_pem_file) {
- boost::asio::ssl::context m_ssl_context{boost::asio::ssl::context::sslv23};
- m_ssl_context.set_options(boost::asio::ssl::context::default_workarounds |
- boost::asio::ssl::context::no_sslv2 |
- boost::asio::ssl::context::no_sslv3 |
- boost::asio::ssl::context::single_dh_use |
- boost::asio::ssl::context::no_tlsv1 |
- boost::asio::ssl::context::no_tlsv1_1);
+ boost::asio::ssl::context mSslContext{boost::asio::ssl::context::sslv23};
+ mSslContext.set_options(boost::asio::ssl::context::default_workarounds |
+ boost::asio::ssl::context::no_sslv2 |
+ boost::asio::ssl::context::no_sslv3 |
+ boost::asio::ssl::context::single_dh_use |
+ boost::asio::ssl::context::no_tlsv1 |
+ boost::asio::ssl::context::no_tlsv1_1);
// m_ssl_context.set_verify_mode(boost::asio::ssl::verify_peer);
- m_ssl_context.use_certificate_file(ssl_pem_file,
- boost::asio::ssl::context::pem);
- m_ssl_context.use_private_key_file(ssl_pem_file,
- boost::asio::ssl::context::pem);
+ mSslContext.use_certificate_file(ssl_pem_file,
+ boost::asio::ssl::context::pem);
+ mSslContext.use_private_key_file(ssl_pem_file,
+ boost::asio::ssl::context::pem);
// Set up EC curves to auto (boost asio doesn't have a method for this)
// There is a pull request to add this. Once this is included in an asio
// drop, use the right way
// http://stackoverflow.com/questions/18929049/boost-asio-with-ecdsa-certificate-issue
- if (SSL_CTX_set_ecdh_auto(m_ssl_context.native_handle(), 1) != 1) {
- CROW_LOG_ERROR << "Error setting tmp ecdh list\n";
+ if (SSL_CTX_set_ecdh_auto(mSslContext.native_handle(), 1) != 1) {
+ BMCWEB_LOG_ERROR << "Error setting tmp ecdh list\n";
}
// From mozilla "compatibility"
- std::string mozilla_compatibility_ciphers =
+ std::string mozillaCompatibilityCiphers =
"ECDHE-ECDSA-CHACHA20-POLY1305:"
"ECDHE-RSA-CHACHA20-POLY1305:"
"ECDHE-ECDSA-AES128-GCM-SHA256:"
@@ -288,7 +288,7 @@ inline boost::asio::ssl::context get_ssl_context(
"!DSS";
// From mozilla "modern"
- std::string mozilla_modern_ciphers =
+ std::string mozillaModernCiphers =
"ECDHE-ECDSA-AES256-GCM-SHA384:"
"ECDHE-RSA-AES256-GCM-SHA384:"
"ECDHE-ECDSA-CHACHA20-POLY1305:"
@@ -300,13 +300,13 @@ inline boost::asio::ssl::context get_ssl_context(
"ECDHE-ECDSA-AES128-SHA256:"
"ECDHE-RSA-AES128-SHA256";
- std::string aes_only_ciphers = "AES128+EECDH:AES128+EDH:!aNULL:!eNULL";
+ std::string aesOnlyCiphers = "AES128+EECDH:AES128+EDH:!aNULL:!eNULL";
- if (SSL_CTX_set_cipher_list(m_ssl_context.native_handle(),
- mozilla_compatibility_ciphers.c_str()) != 1) {
- CROW_LOG_ERROR << "Error setting cipher list\n";
+ if (SSL_CTX_set_cipher_list(mSslContext.native_handle(),
+ mozillaCompatibilityCiphers.c_str()) != 1) {
+ BMCWEB_LOG_ERROR << "Error setting cipher list\n";
}
- return m_ssl_context;
+ return mSslContext;
}
} // namespace ensuressl
diff --git a/include/token_authorization_middleware.hpp b/include/token_authorization_middleware.hpp
index f151e4ff63..fcc86386fa 100644
--- a/include/token_authorization_middleware.hpp
+++ b/include/token_authorization_middleware.hpp
@@ -12,49 +12,49 @@
namespace crow {
-namespace TokenAuthorization {
+namespace token_authorization {
class Middleware {
public:
- struct context {
- std::shared_ptr<crow::PersistentData::UserSession> session;
+ struct Context {
+ std::shared_ptr<crow::persistent_data::UserSession> session;
};
- void before_handle(crow::request& req, response& res, context& ctx) {
- if (is_on_whitelist(req)) {
+ void beforeHandle(crow::Request& req, Response& res, Context& ctx) {
+ if (isOnWhitelist(req)) {
return;
}
- ctx.session = perform_xtoken_auth(req);
+ ctx.session = performXtokenAuth(req);
if (ctx.session == nullptr) {
- ctx.session = perform_cookie_auth(req);
+ ctx.session = performCookieAuth(req);
}
if (ctx.session == nullptr) {
- boost::string_view auth_header = req.get_header_value("Authorization");
- if (!auth_header.empty()) {
+ boost::string_view authHeader = req.getHeaderValue("Authorization");
+ if (!authHeader.empty()) {
// Reject any kind of auth other than basic or token
- if (boost::starts_with(auth_header, "Token ")) {
- ctx.session = perform_token_auth(auth_header);
- } else if (boost::starts_with(auth_header, "Basic ")) {
- ctx.session = perform_basic_auth(auth_header);
+ if (boost::starts_with(authHeader, "Token ")) {
+ ctx.session = performTokenAuth(authHeader);
+ } else if (boost::starts_with(authHeader, "Basic ")) {
+ ctx.session = performBasicAuth(authHeader);
}
}
}
if (ctx.session == nullptr) {
- CROW_LOG_WARNING << "[AuthMiddleware] authorization failed";
+ BMCWEB_LOG_WARNING << "[AuthMiddleware] authorization failed";
// If it's a browser connecting, don't send the HTTP authenticate header,
// to avoid possible CSRF attacks with basic auth
- if (http_helpers::request_prefers_html(req)) {
+ if (http_helpers::requestPrefersHtml(req)) {
res.result(boost::beast::http::status::temporary_redirect);
- res.add_header("Location", "/#/login");
+ res.addHeader("Location", "/#/login");
} else {
res.result(boost::beast::http::status::unauthorized);
// only send the WWW-authenticate header if this isn't a xhr from the
// browser. most scripts,
- if (req.get_header_value("User-Agent").empty()) {
- res.add_header("WWW-Authenticate", "Basic");
+ if (req.getHeaderValue("User-Agent").empty()) {
+ res.addHeader("WWW-Authenticate", "Basic");
}
}
@@ -62,124 +62,122 @@ class Middleware {
return;
}
- // TODO get user privileges here and propagate it via MW context
+ // TODO get user privileges here and propagate it via MW Context
// else let the request continue unharmed
}
template <typename AllContext>
- void after_handle(request& req, response& res, context& ctx,
- AllContext& allctx) {
+ void afterHandle(Request& req, Response& res, Context& ctx,
+ AllContext& allctx) {
// TODO(ed) THis should really be handled by the persistent data
// middleware, but because it is upstream, it doesn't have access to the
// session information. Should the data middleware persist the current
// user session?
if (ctx.session != nullptr &&
ctx.session->persistence ==
- crow::PersistentData::PersistenceType::SINGLE_REQUEST) {
- PersistentData::SessionStore::getInstance().remove_session(ctx.session);
+ crow::persistent_data::PersistenceType::SINGLE_REQUEST) {
+ persistent_data::SessionStore::getInstance().removeSession(ctx.session);
}
}
private:
- const std::shared_ptr<crow::PersistentData::UserSession> perform_basic_auth(
+ const std::shared_ptr<crow::persistent_data::UserSession> performBasicAuth(
boost::string_view auth_header) const {
- CROW_LOG_DEBUG << "[AuthMiddleware] Basic authentication";
+ BMCWEB_LOG_DEBUG << "[AuthMiddleware] Basic authentication";
- std::string auth_data;
+ std::string authData;
boost::string_view param = auth_header.substr(strlen("Basic "));
- if (!crow::utility::base64_decode(param, auth_data)) {
+ if (!crow::utility::base64Decode(param, authData)) {
return nullptr;
}
- std::size_t separator = auth_data.find(':');
+ std::size_t separator = authData.find(':');
if (separator == std::string::npos) {
return nullptr;
}
- std::string user = auth_data.substr(0, separator);
+ std::string user = authData.substr(0, separator);
separator += 1;
- if (separator > auth_data.size()) {
+ if (separator > authData.size()) {
return nullptr;
}
- std::string pass = auth_data.substr(separator);
+ std::string pass = authData.substr(separator);
- CROW_LOG_DEBUG << "[AuthMiddleware] Authenticating user: " << user;
+ BMCWEB_LOG_DEBUG << "[AuthMiddleware] Authenticating user: " << user;
- if (!pam_authenticate_user(user, pass)) {
+ if (!pamAuthenticateUser(user, pass)) {
return nullptr;
}
- // TODO(ed) generate_user_session is a little expensive for basic
+ // TODO(ed) generateUserSession is a little expensive for basic
// auth, as it generates some random identifiers that will never be
// used. This should have a "fast" path for when user tokens aren't
// needed.
// This whole flow needs to be revisited anyway, as we can't be
// calling directly into pam for every request
- return PersistentData::SessionStore::getInstance().generate_user_session(
- user, crow::PersistentData::PersistenceType::SINGLE_REQUEST);
+ return persistent_data::SessionStore::getInstance().generateUserSession(
+ user, crow::persistent_data::PersistenceType::SINGLE_REQUEST);
}
- const std::shared_ptr<crow::PersistentData::UserSession> perform_token_auth(
+ const std::shared_ptr<crow::persistent_data::UserSession> performTokenAuth(
boost::string_view auth_header) const {
- CROW_LOG_DEBUG << "[AuthMiddleware] Token authentication";
+ BMCWEB_LOG_DEBUG << "[AuthMiddleware] Token authentication";
boost::string_view token = auth_header.substr(strlen("Token "));
auto session =
- PersistentData::SessionStore::getInstance().login_session_by_token(
- token);
+ persistent_data::SessionStore::getInstance().loginSessionByToken(token);
return session;
}
- const std::shared_ptr<crow::PersistentData::UserSession> perform_xtoken_auth(
- const crow::request& req) const {
- CROW_LOG_DEBUG << "[AuthMiddleware] X-Auth-Token authentication";
+ const std::shared_ptr<crow::persistent_data::UserSession> performXtokenAuth(
+ const crow::Request& req) const {
+ BMCWEB_LOG_DEBUG << "[AuthMiddleware] X-Auth-Token authentication";
- boost::string_view token = req.get_header_value("X-Auth-Token");
+ boost::string_view token = req.getHeaderValue("X-Auth-Token");
if (token.empty()) {
return nullptr;
}
auto session =
- PersistentData::SessionStore::getInstance().login_session_by_token(
- token);
+ persistent_data::SessionStore::getInstance().loginSessionByToken(token);
return session;
}
- const std::shared_ptr<crow::PersistentData::UserSession> perform_cookie_auth(
- const crow::request& req) const {
- CROW_LOG_DEBUG << "[AuthMiddleware] Cookie authentication";
+ const std::shared_ptr<crow::persistent_data::UserSession> performCookieAuth(
+ const crow::Request& req) const {
+ BMCWEB_LOG_DEBUG << "[AuthMiddleware] Cookie authentication";
- boost::string_view cookie_value = req.get_header_value("Cookie");
- if (cookie_value.empty()) {
+ boost::string_view cookieValue = req.getHeaderValue("Cookie");
+ if (cookieValue.empty()) {
return nullptr;
}
- auto start_index = cookie_value.find("SESSION=");
- if (start_index == std::string::npos) {
+ auto startIndex = cookieValue.find("SESSION=");
+ if (startIndex == std::string::npos) {
return nullptr;
}
- start_index += sizeof("SESSION=") - 1;
- auto end_index = cookie_value.find(";", start_index);
- if (end_index == std::string::npos) {
- end_index = cookie_value.size();
+ startIndex += sizeof("SESSION=") - 1;
+ auto endIndex = cookieValue.find(";", startIndex);
+ if (endIndex == std::string::npos) {
+ endIndex = cookieValue.size();
}
- boost::string_view auth_key =
- cookie_value.substr(start_index, end_index - start_index);
+ boost::string_view authKey =
+ cookieValue.substr(startIndex, endIndex - startIndex);
- const std::shared_ptr<crow::PersistentData::UserSession> session =
- PersistentData::SessionStore::getInstance().login_session_by_token(
- auth_key);
+ const std::shared_ptr<crow::persistent_data::UserSession> session =
+ persistent_data::SessionStore::getInstance().loginSessionByToken(
+ authKey);
if (session == nullptr) {
return nullptr;
}
#ifndef BMCWEB_INSECURE_DISABLE_CSRF_PREVENTION
// RFC7231 defines methods that need csrf protection
if (req.method() != "GET"_method) {
- boost::string_view csrf = req.get_header_value("X-XSRF-TOKEN");
+ boost::string_view csrf = req.getHeaderValue("X-XSRF-TOKEN");
// Make sure both tokens are filled
- if (csrf.empty() || session->csrf_token.empty()) {
+ if (csrf.empty() || session->csrfToken.empty()) {
return nullptr;
}
// Reject if csrf token not available
- if (csrf != session->csrf_token) {
+ if (csrf != session->csrfToken) {
return nullptr;
}
}
@@ -188,7 +186,7 @@ class Middleware {
}
// checks if request can be forwarded without authentication
- bool is_on_whitelist(const crow::request& req) const {
+ bool isOnWhitelist(const crow::Request& req) const {
// it's allowed to GET root node without authentica tion
if ("GET"_method == req.method()) {
if (req.url == "/redfish/v1" || req.url == "/redfish/v1/") {
@@ -217,27 +215,27 @@ class Middleware {
// routes.
// Possibly an init function on first construction?
template <typename... Middlewares>
-void request_routes(Crow<Middlewares...>& app) {
+void requestRoutes(Crow<Middlewares...>& app) {
static_assert(
- black_magic::contains<PersistentData::Middleware, Middlewares...>::value,
- "TokenAuthorization middleware must be enabled in app to use "
+ black_magic::Contains<persistent_data::Middleware, Middlewares...>::value,
+ "token_authorization middleware must be enabled in app to use "
"auth routes");
- CROW_ROUTE(app, "/login")
+ BMCWEB_ROUTE(app, "/login")
.methods(
- "POST"_method)([&](const crow::request& req, crow::response& res) {
- boost::string_view content_type = req.get_header_value("content-type");
+ "POST"_method)([&](const crow::Request& req, crow::Response& res) {
+ boost::string_view contentType = req.getHeaderValue("content-type");
boost::string_view username;
boost::string_view password;
- bool looks_like_ibm = false;
+ bool looksLikeIbm = false;
// This object needs to be declared at this scope so the strings
// within it are not destroyed before we can use them
- nlohmann::json login_credentials;
+ nlohmann::json loginCredentials;
// Check if auth was provided by a payload
- if (content_type == "application/json") {
- login_credentials = nlohmann::json::parse(req.body, nullptr, false);
- if (login_credentials.is_discarded()) {
+ if (contentType == "application/json") {
+ loginCredentials = nlohmann::json::parse(req.body, nullptr, false);
+ if (loginCredentials.is_discarded()) {
res.result(boost::beast::http::status::bad_request);
res.end();
return;
@@ -245,54 +243,51 @@ void request_routes(Crow<Middlewares...>& app) {
// check for username/password in the root object
// THis method is how intel APIs authenticate
- nlohmann::json::iterator user_it = login_credentials.find("username");
- nlohmann::json::iterator pass_it = login_credentials.find("password");
- if (user_it != login_credentials.end() &&
- pass_it != login_credentials.end()) {
- const std::string* user_str =
- user_it->get_ptr<const std::string*>();
- const std::string* pass_str =
- pass_it->get_ptr<const std::string*>();
- if (user_str != nullptr && pass_str != nullptr) {
- username = *user_str;
- password = *pass_str;
+ nlohmann::json::iterator userIt = loginCredentials.find("username");
+ nlohmann::json::iterator passIt = loginCredentials.find("password");
+ if (userIt != loginCredentials.end() &&
+ passIt != loginCredentials.end()) {
+ const std::string* userStr = userIt->get_ptr<const std::string*>();
+ const std::string* passStr = passIt->get_ptr<const std::string*>();
+ if (userStr != nullptr && passStr != nullptr) {
+ username = *userStr;
+ password = *passStr;
}
} else {
// Openbmc appears to push a data object that contains the same
// keys (username and password), attempt to use that
- auto data_it = login_credentials.find("data");
- if (data_it != login_credentials.end()) {
+ auto dataIt = loginCredentials.find("data");
+ if (dataIt != loginCredentials.end()) {
// Some apis produce an array of value ["username",
// "password"]
- if (data_it->is_array()) {
- if (data_it->size() == 2) {
- nlohmann::json::iterator user_it2 = data_it->begin();
- nlohmann::json::iterator pass_it2 = data_it->begin() + 1;
- looks_like_ibm = true;
- if (user_it2 != data_it->end() &&
- pass_it2 != data_it->end()) {
- const std::string* user_str =
- user_it2->get_ptr<const std::string*>();
- const std::string* pass_str =
- pass_it2->get_ptr<const std::string*>();
- if (user_str != nullptr && pass_str != nullptr) {
- username = *user_str;
- password = *pass_str;
+ if (dataIt->is_array()) {
+ if (dataIt->size() == 2) {
+ nlohmann::json::iterator userIt2 = dataIt->begin();
+ nlohmann::json::iterator passIt2 = dataIt->begin() + 1;
+ looksLikeIbm = true;
+ if (userIt2 != dataIt->end() && passIt2 != dataIt->end()) {
+ const std::string* userStr =
+ userIt2->get_ptr<const std::string*>();
+ const std::string* passStr =
+ passIt2->get_ptr<const std::string*>();
+ if (userStr != nullptr && passStr != nullptr) {
+ username = *userStr;
+ password = *passStr;
}
}
}
- } else if (data_it->is_object()) {
- nlohmann::json::iterator user_it2 = data_it->find("username");
- nlohmann::json::iterator pass_it2 = data_it->find("password");
- if (user_it2 != data_it->end() && pass_it2 != data_it->end()) {
- const std::string* user_str =
- user_it2->get_ptr<const std::string*>();
- const std::string* pass_str =
- pass_it2->get_ptr<const std::string*>();
- if (user_str != nullptr && pass_str != nullptr) {
- username = *user_str;
- password = *pass_str;
+ } else if (dataIt->is_object()) {
+ nlohmann::json::iterator userIt2 = dataIt->find("username");
+ nlohmann::json::iterator passIt2 = dataIt->find("password");
+ if (userIt2 != dataIt->end() && passIt2 != dataIt->end()) {
+ const std::string* userStr =
+ userIt2->get_ptr<const std::string*>();
+ const std::string* passStr =
+ passIt2->get_ptr<const std::string*>();
+ if (userStr != nullptr && passStr != nullptr) {
+ username = *userStr;
+ password = *passStr;
}
}
}
@@ -300,22 +295,22 @@ void request_routes(Crow<Middlewares...>& app) {
}
} else {
// check if auth was provided as a headers
- username = req.get_header_value("username");
- password = req.get_header_value("password");
+ username = req.getHeaderValue("username");
+ password = req.getHeaderValue("password");
}
if (!username.empty() && !password.empty()) {
- if (!pam_authenticate_user(username, password)) {
+ if (!pamAuthenticateUser(username, password)) {
res.result(boost::beast::http::status::unauthorized);
} else {
- auto session = PersistentData::SessionStore::getInstance()
- .generate_user_session(username);
+ auto session = persistent_data::SessionStore::getInstance()
+ .generateUserSession(username);
- if (looks_like_ibm) {
+ if (looksLikeIbm) {
// IBM requires a very specific login structure, and doesn't
// actually look at the status code. TODO(ed).... Fix that
// upstream
- res.json_value = {
+ res.jsonValue = {
{"data", "User '" + std::string(username) + "' logged in"},
{"message", "200 OK"},
{"status", "ok"}};
@@ -329,13 +324,13 @@ void request_routes(Crow<Middlewares...>& app) {
// "set-cookie" string into the value header, and get the result
// we want, even though we are technicaly declaring two headers
// here.
- res.add_header("Set-Cookie",
- "XSRF-TOKEN=" + session->csrf_token +
- "; Secure\r\nSet-Cookie: SESSION=" +
- session->session_token + "; Secure; HttpOnly");
+ res.addHeader("Set-Cookie",
+ "XSRF-TOKEN=" + session->csrfToken +
+ "; Secure\r\nSet-Cookie: SESSION=" +
+ session->sessionToken + "; Secure; HttpOnly");
} else {
// if content type is json, assume json token
- res.json_value = {{"token", session->session_token}};
+ res.jsonValue = {{"token", session->sessionToken}};
}
}
@@ -345,18 +340,18 @@ void request_routes(Crow<Middlewares...>& app) {
res.end();
});
- CROW_ROUTE(app, "/logout")
+ BMCWEB_ROUTE(app, "/logout")
.methods(
- "POST"_method)([&](const crow::request& req, crow::response& res) {
+ "POST"_method)([&](const crow::Request& req, crow::Response& res) {
auto& session =
- app.template get_context<TokenAuthorization::Middleware>(req)
+ app.template getContext<token_authorization::Middleware>(req)
.session;
if (session != nullptr) {
- PersistentData::SessionStore::getInstance().remove_session(session);
+ persistent_data::SessionStore::getInstance().removeSession(session);
}
res.end();
return;
});
}
-} // namespace TokenAuthorization
+} // namespace token_authorization
} // namespace crow
diff --git a/include/web_kvm.hpp b/include/web_kvm.hpp
index 82cb488c5f..ad4b352eb4 100644
--- a/include/web_kvm.hpp
+++ b/include/web_kvm.hpp
@@ -8,9 +8,9 @@
namespace crow {
namespace kvm {
-static const std::string rfb_3_3_version_string = "RFB 003.003\n";
-static const std::string rfb_3_7_version_string = "RFB 003.007\n";
-static const std::string rfb_3_8_version_string = "RFB 003.008\n";
+static const std::string rfb33VersionString = "RFB 003.003\n";
+static const std::string rfb37VersionString = "RFB 003.007\n";
+static const std::string rfb38VersionString = "RFB 003.008\n";
enum class RfbAuthScheme : uint8_t {
connection_failed = 0,
@@ -18,27 +18,27 @@ enum class RfbAuthScheme : uint8_t {
vnc_authentication = 2
};
-struct pixel_format_struct {
- boost::endian::big_uint8_t bits_per_pixel;
+struct PixelFormatStruct {
+ boost::endian::big_uint8_t bitsPerPixel;
boost::endian::big_uint8_t depth;
- boost::endian::big_uint8_t is_big_endian;
- boost::endian::big_uint8_t is_true_color;
- boost::endian::big_uint16_t red_max;
- boost::endian::big_uint16_t green_max;
- boost::endian::big_uint16_t blue_max;
- boost::endian::big_uint8_t red_shift;
- boost::endian::big_uint8_t green_shift;
- boost::endian::big_uint8_t blue_shift;
+ boost::endian::big_uint8_t isBigEndian;
+ boost::endian::big_uint8_t isTrueColor;
+ boost::endian::big_uint16_t redMax;
+ boost::endian::big_uint16_t greenMax;
+ boost::endian::big_uint16_t blueMax;
+ boost::endian::big_uint8_t redShift;
+ boost::endian::big_uint8_t greenShift;
+ boost::endian::big_uint8_t blueShift;
boost::endian::big_uint8_t pad1;
boost::endian::big_uint8_t pad2;
boost::endian::big_uint8_t pad3;
};
-struct server_initialization_msg {
- boost::endian::big_uint16_t framebuffer_width;
- boost::endian::big_uint16_t framebuffer_height;
- pixel_format_struct pixel_format;
- boost::endian::big_uint32_t name_length;
+struct ServerInitializationMsg {
+ boost::endian::big_uint16_t framebufferWidth;
+ boost::endian::big_uint16_t framebufferHeight;
+ PixelFormatStruct pixelFormat;
+ boost::endian::big_uint32_t nameLength;
};
enum class client_to_server_msg_type : uint8_t {
@@ -58,35 +58,35 @@ enum class server_to_client_message_type : uint8_t {
server_cut_text = 3
};
-struct set_pixel_format_msg {
+struct SetPixelFormatMsg {
boost::endian::big_uint8_t pad1;
boost::endian::big_uint8_t pad2;
boost::endian::big_uint8_t pad3;
- pixel_format_struct pixel_format;
+ PixelFormatStruct pixelFormat;
};
-struct frame_buffer_update_req {
+struct FrameBufferUpdateReq {
boost::endian::big_uint8_t incremental;
- boost::endian::big_uint16_t x_position;
- boost::endian::big_uint16_t y_position;
+ boost::endian::big_uint16_t xPosition;
+ boost::endian::big_uint16_t yPosition;
boost::endian::big_uint16_t width;
boost::endian::big_uint16_t height;
};
-struct key_event_msg {
- boost::endian::big_uint8_t down_flag;
+struct KeyEventMsg {
+ boost::endian::big_uint8_t downFlag;
boost::endian::big_uint8_t pad1;
boost::endian::big_uint8_t pad2;
boost::endian::big_uint32_t key;
};
-struct pointer_event_msg {
- boost::endian::big_uint8_t button_mask;
- boost::endian::big_uint16_t x_position;
- boost::endian::big_uint16_t y_position;
+struct PointerEventMsg {
+ boost::endian::big_uint8_t buttonMask;
+ boost::endian::big_uint16_t xPosition;
+ boost::endian::big_uint16_t yPosition;
};
-struct client_cut_text_msg {
+struct ClientCutTextMsg {
std::vector<uint8_t> data;
};
@@ -105,7 +105,7 @@ enum class encoding_type : uint32_t {
cache_enable = 0xFFFF0001,
xor_enable = 0xFFFF0006,
server_state_ultranvc = 0xFFFF8000,
- enable_keep_alive = 0xFFFF8001,
+ enable_keepAlive = 0xFFFF8001,
enableftp_protocol_version = 0xFFFF8002,
tight_compress_level_0 = 0xFFFFFF00,
tight_compress_level_9 = 0xFFFFFF09,
@@ -118,7 +118,7 @@ enum class encoding_type : uint32_t {
tight_quality_level_9 = 0xFFFFFFE9
};
-struct framebuffer_rectangle {
+struct FramebufferRectangle {
boost::endian::big_uint16_t x{};
boost::endian::big_uint16_t y{};
boost::endian::big_uint16_t width{};
@@ -127,35 +127,34 @@ struct framebuffer_rectangle {
std::vector<uint8_t> data;
};
-struct framebuffer_update_msg {
- boost::endian::big_uint8_t message_type{};
- std::vector<framebuffer_rectangle> rectangles;
+struct FramebufferUpdateMsg {
+ boost::endian::big_uint8_t messageType{};
+ std::vector<FramebufferRectangle> rectangles;
};
-inline std::string serialize(const framebuffer_update_msg& msg) {
+inline std::string serialize(const FramebufferUpdateMsg& msg) {
// calculate the size of the needed vector for serialization
- size_t vector_size = 4;
+ size_t vectorSize = 4;
for (const auto& rect : msg.rectangles) {
- vector_size += 12 + rect.data.size();
+ vectorSize += 12 + rect.data.size();
}
- std::string serialized(vector_size, 0);
+ std::string serialized(vectorSize, 0);
size_t i = 0;
serialized[i++] = static_cast<char>(
server_to_client_message_type::framebuffer_update); // Type
serialized[i++] = 0; // Pad byte
- boost::endian::big_uint16_t number_of_rectangles = msg.rectangles.size();
- std::memcpy(&serialized[i], &number_of_rectangles,
- sizeof(number_of_rectangles));
- i += sizeof(number_of_rectangles);
+ boost::endian::big_uint16_t numberOfRectangles = msg.rectangles.size();
+ std::memcpy(&serialized[i], &numberOfRectangles, sizeof(numberOfRectangles));
+ i += sizeof(numberOfRectangles);
for (const auto& rect : msg.rectangles) {
// copy the first part of the struct
- size_t buffer_size =
- sizeof(framebuffer_rectangle) - sizeof(std::vector<uint8_t>);
- std::memcpy(&serialized[i], &rect, buffer_size);
- i += buffer_size;
+ size_t bufferSize =
+ sizeof(FramebufferRectangle) - sizeof(std::vector<uint8_t>);
+ std::memcpy(&serialized[i], &rect, bufferSize);
+ i += bufferSize;
std::memcpy(&serialized[i], rect.data.data(), rect.data.size());
i += rect.data.size();
@@ -172,91 +171,90 @@ enum class VncState {
MAIN_LOOP
};
-class connection_metadata {
+class ConnectionMetadata {
public:
- connection_metadata() {};
+ ConnectionMetadata(){};
- VncState vnc_state{VncState::UNSTARTED};
+ VncState vncState{VncState::UNSTARTED};
};
-using meta_list = std::vector<connection_metadata>;
-meta_list connection_states(10);
+using meta_list = std::vector<ConnectionMetadata>;
+meta_list connectionStates(10);
-connection_metadata meta;
+ConnectionMetadata meta;
template <typename... Middlewares>
-void request_routes(Crow<Middlewares...>& app) {
- CROW_ROUTE(app, "/kvmws")
+void requestRoutes(Crow<Middlewares...>& app) {
+ BMCWEB_ROUTE(app, "/kvmws")
.websocket()
- .onopen([&](crow::websocket::connection& conn) {
- if (meta.vnc_state == VncState::UNSTARTED) {
- meta.vnc_state = VncState::AWAITING_CLIENT_VERSION;
- conn.send_binary(rfb_3_8_version_string);
+ .onopen([&](crow::websocket::Connection& conn) {
+ if (meta.vncState == VncState::UNSTARTED) {
+ meta.vncState = VncState::AWAITING_CLIENT_VERSION;
+ conn.sendBinary(rfb38VersionString);
} else { // SHould never happen
conn.close();
}
})
.onclose(
- [&](crow::websocket::connection& conn, const std::string& reason) {
- meta.vnc_state = VncState::UNSTARTED;
+ [&](crow::websocket::Connection& conn, const std::string& reason) {
+ meta.vncState = VncState::UNSTARTED;
})
- .onmessage([&](crow::websocket::connection& conn, const std::string& data,
+ .onmessage([&](crow::websocket::Connection& conn, const std::string& data,
bool is_binary) {
- switch (meta.vnc_state) {
+ switch (meta.vncState) {
case VncState::AWAITING_CLIENT_VERSION: {
std::cout << "Client sent: " << data;
- if (data == rfb_3_8_version_string ||
- data == rfb_3_7_version_string) {
- std::string auth_types{1,
- (uint8_t)RfbAuthScheme::no_authentication};
- conn.send_binary(auth_types);
- meta.vnc_state = VncState::AWAITING_CLIENT_AUTH_METHOD;
- } else if (data == rfb_3_3_version_string) {
+ if (data == rfb38VersionString || data == rfb37VersionString) {
+ std::string authTypes{1,
+ (uint8_t)RfbAuthScheme::no_authentication};
+ conn.sendBinary(authTypes);
+ meta.vncState = VncState::AWAITING_CLIENT_AUTH_METHOD;
+ } else if (data == rfb33VersionString) {
// TODO(ed) Support older protocols
- meta.vnc_state = VncState::UNSTARTED;
+ meta.vncState = VncState::UNSTARTED;
conn.close();
} else {
// TODO(ed) Support older protocols
- meta.vnc_state = VncState::UNSTARTED;
+ meta.vncState = VncState::UNSTARTED;
conn.close();
}
} break;
case VncState::AWAITING_CLIENT_AUTH_METHOD: {
- std::string security_result{{0, 0, 0, 0}};
+ std::string securityResult{{0, 0, 0, 0}};
if (data[0] == (uint8_t)RfbAuthScheme::no_authentication) {
- meta.vnc_state = VncState::AWAITING_CLIENT_INIT_msg;
+ meta.vncState = VncState::AWAITING_CLIENT_INIT_msg;
} else {
// Mark auth as failed
- security_result[3] = 1;
- meta.vnc_state = VncState::UNSTARTED;
+ securityResult[3] = 1;
+ meta.vncState = VncState::UNSTARTED;
}
- conn.send_binary(security_result);
+ conn.sendBinary(securityResult);
} break;
case VncState::AWAITING_CLIENT_INIT_msg: {
// Now send the server initialization
- server_initialization_msg server_init_msg{};
- server_init_msg.framebuffer_width = 800;
- server_init_msg.framebuffer_height = 600;
- server_init_msg.pixel_format.bits_per_pixel = 32;
- server_init_msg.pixel_format.is_big_endian = 0;
- server_init_msg.pixel_format.is_true_color = 1;
- server_init_msg.pixel_format.red_max = 255;
- server_init_msg.pixel_format.green_max = 255;
- server_init_msg.pixel_format.blue_max = 255;
- server_init_msg.pixel_format.red_shift = 16;
- server_init_msg.pixel_format.green_shift = 8;
- server_init_msg.pixel_format.blue_shift = 0;
- server_init_msg.name_length = 0;
- std::cout << "size: " << sizeof(server_init_msg);
+ ServerInitializationMsg serverInitMsg{};
+ serverInitMsg.framebufferWidth = 800;
+ serverInitMsg.framebufferHeight = 600;
+ serverInitMsg.pixelFormat.bitsPerPixel = 32;
+ serverInitMsg.pixelFormat.isBigEndian = 0;
+ serverInitMsg.pixelFormat.isTrueColor = 1;
+ serverInitMsg.pixelFormat.redMax = 255;
+ serverInitMsg.pixelFormat.greenMax = 255;
+ serverInitMsg.pixelFormat.blueMax = 255;
+ serverInitMsg.pixelFormat.redShift = 16;
+ serverInitMsg.pixelFormat.greenShift = 8;
+ serverInitMsg.pixelFormat.blueShift = 0;
+ serverInitMsg.nameLength = 0;
+ std::cout << "size: " << sizeof(serverInitMsg);
// TODO(ed) this is ugly. Crow should really have a span type
// interface
// to avoid the copy, but alas, today it does not.
- std::string s(reinterpret_cast<char*>(&server_init_msg),
- sizeof(server_init_msg));
+ std::string s(reinterpret_cast<char*>(&serverInitMsg),
+ sizeof(serverInitMsg));
std::cout << "s.size() " << s.size();
- conn.send_binary(s);
- meta.vnc_state = VncState::MAIN_LOOP;
+ conn.sendBinary(s);
+ meta.vncState = VncState::MAIN_LOOP;
} break;
case VncState::MAIN_LOOP: {
if (data.size() >= sizeof(client_to_server_msg_type)) {
@@ -274,55 +272,54 @@ void request_routes(Crow<Middlewares...>& app) {
case client_to_server_msg_type::framebuffer_update_request: {
// Make sure the buffer is long enough to handle what we're
// about to do
- if (data.size() >= sizeof(frame_buffer_update_req) +
+ if (data.size() >= sizeof(FrameBufferUpdateReq) +
sizeof(client_to_server_msg_type)) {
- auto msg = reinterpret_cast<const frame_buffer_update_req*>(
- data.data() + // NOLINT
+ auto msg = reinterpret_cast<const FrameBufferUpdateReq*>(
+ data.data() + // NOLINT
sizeof(client_to_server_msg_type));
// TODO(ed) find a better way to do this deserialization
// Todo(ed) lifecycle of the video puller and decoder
// should be
// with the websocket, not recreated every time
- AstVideo::SimpleVideoPuller p;
+ ast_video::SimpleVideoPuller p;
p.initialize();
- auto out = p.read_video();
- AstVideo::AstJpegDecoder d;
+ auto out = p.readVideo();
+ ast_video::AstJpegDecoder d;
d.decode(out.buffer, out.width, out.height, out.mode,
- out.y_selector, out.uv_selector);
+ out.ySelector, out.uvSelector);
- framebuffer_update_msg buffer_update_msg;
+ FramebufferUpdateMsg bufferUpdateMsg;
// If the viewer is requesting a full update, force write
// of all pixels
- framebuffer_rectangle this_rect;
- this_rect.x = msg->x_position;
- this_rect.y = msg->y_position;
- this_rect.width = out.width;
- this_rect.height = out.height;
- this_rect.encoding =
+ FramebufferRectangle thisRect;
+ thisRect.x = msg->xPosition;
+ thisRect.y = msg->yPosition;
+ thisRect.width = out.width;
+ thisRect.height = out.height;
+ thisRect.encoding =
static_cast<uint8_t>(encoding_type::raw);
- std::cout << "Encoding is " << this_rect.encoding;
- this_rect.data.reserve(
- static_cast<std::size_t>(this_rect.width) *
- static_cast<std::size_t>(this_rect.height) * 4);
+ std::cout << "Encoding is " << thisRect.encoding;
+ thisRect.data.reserve(
+ static_cast<std::size_t>(thisRect.width) *
+ static_cast<std::size_t>(thisRect.height) * 4);
std::cout << "Width " << out.width << " Height "
<< out.height;
for (int i = 0; i < out.width * out.height; i++) {
- auto& pixel = d.OutBuffer[i];
- this_rect.data.push_back(pixel.B);
- this_rect.data.push_back(pixel.G);
- this_rect.data.push_back(pixel.R);
- this_rect.data.push_back(0);
+ auto& pixel = d.outBuffer[i];
+ thisRect.data.push_back(pixel.b);
+ thisRect.data.push_back(pixel.g);
+ thisRect.data.push_back(pixel.r);
+ thisRect.data.push_back(0);
}
- buffer_update_msg.rectangles.push_back(
- std::move(this_rect));
- auto serialized = serialize(buffer_update_msg);
+ bufferUpdateMsg.rectangles.push_back(std::move(thisRect));
+ auto serialized = serialize(bufferUpdateMsg);
- conn.send_binary(serialized);
+ conn.sendBinary(serialized);
} // TODO(Ed) handle error
diff --git a/include/webassets.hpp b/include/webassets.hpp
index 85de3addf4..161fc506f3 100644
--- a/include/webassets.hpp
+++ b/include/webassets.hpp
@@ -15,7 +15,7 @@ namespace webassets {
namespace filesystem = std::experimental::filesystem;
-struct cmp_str {
+struct CmpStr {
bool operator()(const char* a, const char* b) const {
return std::strcmp(a, b) < 0;
}
@@ -24,9 +24,9 @@ struct cmp_str {
static boost::container::flat_set<std::string> routes;
template <typename... Middlewares>
-void request_routes(Crow<Middlewares...>& app) {
- const static boost::container::flat_map<const char*, const char*, cmp_str>
- content_types{
+void requestRoutes(Crow<Middlewares...>& app) {
+ const static boost::container::flat_map<const char*, const char*, CmpStr>
+ contentTypes{
{{".css", "text/css;charset=UTF-8"},
{".html", "text/html;charset=UTF-8"},
{".js", "text/html;charset=UTF-8"},
@@ -46,12 +46,12 @@ void request_routes(Crow<Middlewares...>& app) {
// https://stackoverflow.com/questions/19911929/what-mime-type-should-i-use-for-javascript-source-map-files
{".map", "application/json"}}};
filesystem::path rootpath{"/usr/share/www/"};
- filesystem::recursive_directory_iterator dir_iter(rootpath);
+ filesystem::recursive_directory_iterator dirIter(rootpath);
- for (const filesystem::directory_entry& dir : dir_iter) {
- filesystem::path absolute_path = dir.path();
- filesystem::path relative_path{
- absolute_path.string().substr(rootpath.string().size() - 1)};
+ for (const filesystem::directory_entry& dir : dirIter) {
+ filesystem::path absolutePath = dir.path();
+ filesystem::path relativePath{
+ absolutePath.string().substr(rootpath.string().size() - 1)};
// make sure we don't recurse into certain directories
// note: maybe check for is_directory() here as well...
@@ -59,18 +59,18 @@ void request_routes(Crow<Middlewares...>& app) {
// don't recurse into hidden directories or symlinks
if (boost::starts_with(dir.path().filename().string(), ".") ||
filesystem::is_symlink(dir)) {
- dir_iter.disable_recursion_pending();
+ dirIter.disable_recursion_pending();
}
} else if (filesystem::is_regular_file(dir)) {
- std::string extension = relative_path.extension();
- filesystem::path webpath = relative_path;
- const char* content_encoding = nullptr;
+ std::string extension = relativePath.extension();
+ filesystem::path webpath = relativePath;
+ const char* contentEncoding = nullptr;
if (extension == ".gz") {
webpath = webpath.replace_extension("");
// Use the non-gzip version for determining content type
extension = webpath.extension().string();
- content_encoding = "gzip";
+ contentEncoding = "gzip";
}
if (boost::starts_with(webpath.filename().string(), "index.")) {
@@ -83,38 +83,38 @@ void request_routes(Crow<Middlewares...>& app) {
}
routes.insert(webpath);
- const char* content_type = nullptr;
+ const char* contentType = nullptr;
- auto content_type_it = content_types.find(extension.c_str());
- if (content_type_it == content_types.end()) {
- CROW_LOG_ERROR << "Cannot determine content-type for " << absolute_path
- << " with extension " << extension;
+ auto contentTypeIt = contentTypes.find(extension.c_str());
+ if (contentTypeIt == contentTypes.end()) {
+ BMCWEB_LOG_ERROR << "Cannot determine content-type for " << absolutePath
+ << " with extension " << extension;
} else {
- content_type = content_type_it->second;
+ contentType = contentTypeIt->second;
}
- app.route_dynamic(webpath)(
- [absolute_path, content_type, content_encoding](
- const crow::request& req, crow::response& res) {
- if (content_type != nullptr) {
- res.add_header("Content-Type", content_type);
+ app.routeDynamic(webpath)(
+ [absolutePath, contentType, contentEncoding](const crow::Request& req,
+ crow::Response& res) {
+ if (contentType != nullptr) {
+ res.addHeader("Content-Type", contentType);
}
- if (content_encoding != nullptr) {
- res.add_header("Content-Encoding", content_encoding);
+ if (contentEncoding != nullptr) {
+ res.addHeader("Content-Encoding", contentEncoding);
}
// res.set_header("Cache-Control", "public, max-age=86400");
- std::ifstream inf(absolute_path);
+ std::ifstream inf(absolutePath);
if (!inf) {
- CROW_LOG_DEBUG << "failed to read file";
+ BMCWEB_LOG_DEBUG << "failed to read file";
res.result(boost::beast::http::status::internal_server_error);
res.end();
return;
}
res.body() = {std::istreambuf_iterator<char>(inf),
- std::istreambuf_iterator<char>()};
+ std::istreambuf_iterator<char>()};
res.end();
});
}
diff --git a/include/webserver_common.hpp b/include/webserver_common.hpp
index 4d88629d26..30b567cd66 100644
--- a/include/webserver_common.hpp
+++ b/include/webserver_common.hpp
@@ -20,6 +20,6 @@
#include "security_headers_middleware.hpp"
#include "webserver_common.hpp"
-using CrowApp = crow::App<crow::PersistentData::Middleware,
- crow::TokenAuthorization::Middleware,
+using CrowApp = crow::App<crow::persistent_data::Middleware,
+ crow::token_authorization::Middleware,
crow::SecurityHeadersMiddleware>;
diff --git a/redfish-core/include/error_messages.hpp b/redfish-core/include/error_messages.hpp
index 18ef2af882..4865516b7a 100644
--- a/redfish-core/include/error_messages.hpp
+++ b/redfish-core/include/error_messages.hpp
@@ -28,8 +28,8 @@ namespace redfish {
namespace messages {
-constexpr const char* MESSAGE_VERSION_PREFIX = "Base.1.2.0.";
-constexpr const char* MESSAGE_ANNOTATION = "@Message.ExtendedInfo";
+constexpr const char* messageVersionPrefix = "Base.1.2.0.";
+constexpr const char* messageAnnotation = "@Message.ExtendedInfo";
/**
* @brief Adds Message JSON object to error object
@@ -318,7 +318,7 @@ nlohmann::json resourceNotFound(const std::string& arg1,
/**
* @brief Formats CouldNotEstablishConnection message into JSON
- * Message body: "The service failed to establish a connection with the URI
+ * Message body: "The service failed to establish a Connection with the URI
* <arg0>."
*
* @param[in] arg1 Parameter of message that will replace %1 in its body.
@@ -383,7 +383,7 @@ nlohmann::json actionParameterNotSupported(const std::string& arg1,
/**
* @brief Formats SourceDoesNotSupportProtocol message into JSON
- * Message body: "The other end of the connection at <arg0> does not support the
+ * Message body: "The other end of the Connection at <arg0> does not support the
* specified protocol <arg1>."
*
* @param[in] arg1 Parameter of message that will replace %1 in its body.
@@ -403,7 +403,7 @@ nlohmann::json accountRemoved();
/**
* @brief Formats AccessDenied message into JSON
- * Message body: "While attempting to establish a connection to <arg0>, the
+ * Message body: "While attempting to establish a Connection to <arg0>, the
* service denied access."
*
* @param[in] arg1 Parameter of message that will replace %1 in its body.
@@ -524,7 +524,7 @@ nlohmann::json actionNotSupported(const std::string& arg1);
/**
* @brief Formats InvalidIndex message into JSON
- * Message body: "The Index <arg0> is not a valid offset into the array."
+ * Message body: "The index <arg0> is not a valid offset into the array."
*
* @param[in] arg1 Parameter of message that will replace %1 in its body.
*
diff --git a/redfish-core/include/node.hpp b/redfish-core/include/node.hpp
index 113514a729..ebd8989bea 100644
--- a/redfish-core/include/node.hpp
+++ b/redfish-core/include/node.hpp
@@ -28,11 +28,11 @@ namespace redfish {
*/
class AsyncResp {
public:
- AsyncResp(crow::response& response) : res(response) {}
+ AsyncResp(crow::Response& response) : res(response) {}
~AsyncResp() { res.end(); }
- crow::response& res;
+ crow::Response& res;
};
/**
@@ -43,10 +43,10 @@ class Node {
public:
template <typename... Params>
Node(CrowApp& app, std::string&& entityUrl, Params... params) {
- app.route_dynamic(entityUrl.c_str())
+ app.routeDynamic(entityUrl.c_str())
.methods("GET"_method, "PATCH"_method, "POST"_method,
- "DELETE"_method)([&](const crow::request& req,
- crow::response& res, Params... params) {
+ "DELETE"_method)([&](const crow::Request& req,
+ crow::Response& res, Params... params) {
std::vector<std::string> paramVec = {params...};
dispatchRequest(app, req, res, paramVec);
});
@@ -74,14 +74,14 @@ class Node {
void getSubRoutes(const std::vector<std::unique_ptr<Node>>& allNodes) {
const std::string* url = getUrl();
if (url == nullptr) {
- //CROW_LOG_CRITICAL << "Unable to get url for route";
+ //BMCWEB_LOG_CRITICAL << "Unable to get url for route";
return;
}
for (const auto& node : allNodes) {
const std::string* route = node->getUrl();
if (route == nullptr) {
- //CROW_LOG_CRITICAL << "Unable to get url for route";
+ //BMCWEB_LOG_CRITICAL << "Unable to get url for route";
continue;
}
if (boost::starts_with(*route, *url)) {
@@ -110,25 +110,25 @@ class Node {
protected:
// Node is designed to be an abstract class, so doGet is pure virtual
- virtual void doGet(crow::response& res, const crow::request& req,
+ virtual void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) {
res.result(boost::beast::http::status::method_not_allowed);
res.end();
- };
+ }
- virtual void doPatch(crow::response& res, const crow::request& req,
+ virtual void doPatch(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) {
res.result(boost::beast::http::status::method_not_allowed);
res.end();
}
- virtual void doPost(crow::response& res, const crow::request& req,
+ virtual void doPost(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) {
res.result(boost::beast::http::status::method_not_allowed);
res.end();
}
- virtual void doDelete(crow::response& res, const crow::request& req,
+ virtual void doDelete(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) {
res.result(boost::beast::http::status::method_not_allowed);
res.end();
@@ -137,11 +137,11 @@ class Node {
nlohmann::json json;
private:
- void dispatchRequest(CrowApp& app, const crow::request& req,
- crow::response& res,
+ void dispatchRequest(CrowApp& app, const crow::Request& req,
+ crow::Response& res,
const std::vector<std::string>& params) {
auto ctx =
- app.template get_context<crow::TokenAuthorization::Middleware>(req);
+ app.template getContext<crow::token_authorization::Middleware>(req);
if (!isMethodAllowedForUser(req.method(), entityPrivileges,
ctx.session->username)) {
diff --git a/redfish-core/include/privileges.hpp b/redfish-core/include/privileges.hpp
index e98debbc6a..437bb15e04 100644
--- a/redfish-core/include/privileges.hpp
+++ b/redfish-core/include/privileges.hpp
@@ -34,7 +34,7 @@ constexpr std::array<const char*, 5> basePrivileges{
constexpr const int basePrivilegeCount = basePrivileges.size();
/** @brief Max number of privileges per type */
-constexpr const int MAX_PRIVILEGE_COUNT = 32;
+constexpr const int maxPrivilegeCount = 32;
/** @brief A vector of all privilege names and their indexes */
static const std::vector<std::string> privilegeNames{basePrivileges.begin(),
@@ -45,7 +45,7 @@ static const std::vector<std::string> privilegeNames{basePrivileges.begin(),
*
* Entity privileges and user privileges are represented by this class.
*
- * Each incoming connection requires a comparison between privileges held
+ * Each incoming Connection requires a comparison between privileges held
* by the user issuing a request and the target entity's privileges.
*
* To ensure best runtime performance of this comparison, privileges
@@ -73,8 +73,8 @@ class Privileges {
Privileges(std::initializer_list<const char*> privilegeList) {
for (const char* privilege : privilegeList) {
if (!setSinglePrivilege(privilege)) {
- CROW_LOG_CRITICAL << "Unable to set privilege " << privilege
- << "in constructor";
+ BMCWEB_LOG_CRITICAL << "Unable to set privilege " << privilege
+ << "in constructor";
}
}
}
@@ -88,10 +88,10 @@ class Privileges {
*
*/
bool setSinglePrivilege(const char* privilege) {
- for (int search_index = 0; search_index < privilegeNames.size();
- search_index++) {
- if (privilege == privilegeNames[search_index]) {
- privilegeBitset.set(search_index);
+ for (int searchIndex = 0; searchIndex < privilegeNames.size();
+ searchIndex++) {
+ if (privilege == privilegeNames[searchIndex]) {
+ privilegeBitset.set(searchIndex);
return true;
}
}
@@ -124,16 +124,16 @@ class Privileges {
const PrivilegeType type) const {
std::vector<const std::string*> activePrivileges;
- int search_index = 0;
- int end_index = basePrivilegeCount;
+ int searchIndex = 0;
+ int endIndex = basePrivilegeCount;
if (type == PrivilegeType::OEM) {
- search_index = basePrivilegeCount - 1;
- end_index = privilegeNames.size();
+ searchIndex = basePrivilegeCount - 1;
+ endIndex = privilegeNames.size();
}
- for (; search_index < end_index; search_index++) {
- if (privilegeBitset.test(search_index)) {
- activePrivileges.emplace_back(&privilegeNames[search_index]);
+ for (; searchIndex < endIndex; searchIndex++) {
+ if (privilegeBitset.test(searchIndex)) {
+ activePrivileges.emplace_back(&privilegeNames[searchIndex]);
}
}
@@ -154,7 +154,7 @@ class Privileges {
}
private:
- std::bitset<MAX_PRIVILEGE_COUNT> privilegeBitset = 0;
+ std::bitset<maxPrivilegeCount> privilegeBitset = 0;
};
using OperationMap = boost::container::flat_map<boost::beast::http::verb,
diff --git a/redfish-core/include/utils/json_utils.hpp b/redfish-core/include/utils/json_utils.hpp
index 5651513da7..25ac95417d 100644
--- a/redfish-core/include/utils/json_utils.hpp
+++ b/redfish-core/include/utils/json_utils.hpp
@@ -284,7 +284,7 @@ Result getDouble(const char* fieldName, const nlohmann::json& json,
* @return true if JSON is valid, false when JSON is invalid and response has
* been filled with message and ended.
*/
-bool processJsonFromRequest(crow::response& res, const crow::request& req,
+bool processJsonFromRequest(crow::Response& res, const crow::Request& req,
nlohmann::json& reqJson);
} // namespace json_util
diff --git a/redfish-core/lib/account_service.hpp b/redfish-core/lib/account_service.hpp
index 9071067eb3..47b4c4c7b6 100644
--- a/redfish-core/lib/account_service.hpp
+++ b/redfish-core/lib/account_service.hpp
@@ -46,9 +46,9 @@ class AccountService : public Node {
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
res.end();
}
};
diff --git a/redfish-core/lib/chassis.hpp b/redfish-core/lib/chassis.hpp
index ef3b7afc63..731ea7b69e 100644
--- a/redfish-core/lib/chassis.hpp
+++ b/redfish-core/lib/chassis.hpp
@@ -24,7 +24,7 @@ namespace redfish {
* DBus types primitives for several generic DBus interfaces
* TODO(Pawel) consider move this to separate file into boost::dbus
*/
-// Note, this is not a very useful variant, but because it isn't used to get
+// Note, this is not a very useful Variant, but because it isn't used to get
// values, it should be as simple as possible
// TODO(ed) invent a nullvariant type
using VariantType = sdbusplus::message::variant<bool, std::string>;
@@ -55,38 +55,38 @@ class OnDemandChassisProvider {
* JSON.
*/
template <typename CallbackFunc>
- void get_chassis_list(CallbackFunc &&callback) {
+ void getChassisList(CallbackFunc &&callback) {
const std::array<const char *, 4> interfaces = {
"xyz.openbmc_project.Inventory.Item.Board",
"xyz.openbmc_project.Inventory.Item.Chassis",
"xyz.openbmc_project.Inventory.Item.PowerSupply",
"xyz.openbmc_project.Inventory.Item.System",
};
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[callback{std::move(callback)}](
const boost::system::error_code error_code,
const std::vector<std::string> &resp) {
// Callback requires vector<string> to retrieve all available chassis
// list.
- std::vector<std::string> chassis_list;
+ std::vector<std::string> chassisList;
if (error_code) {
// Something wrong on DBus, the error_code is not important at this
// moment, just return success=false, and empty output. Since size
// of vector may vary depending on information from Entity Manager,
// and empty output could not be treated same way as error.
- callback(false, chassis_list);
+ callback(false, chassisList);
return;
}
// Iterate over all retrieved ObjectPaths.
for (const std::string &objpath : resp) {
- std::size_t last_pos = objpath.rfind("/");
- if (last_pos != std::string::npos) {
+ std::size_t lastPos = objpath.rfind("/");
+ if (lastPos != std::string::npos) {
// and put it into output vector.
- chassis_list.emplace_back(objpath.substr(last_pos + 1));
+ chassisList.emplace_back(objpath.substr(lastPos + 1));
}
}
- // Finally make a callback with useful data
- callback(true, chassis_list);
+ // Finally make a callback with usefull data
+ callback(true, chassisList);
},
"xyz.openbmc_project.ObjectMapper",
"/xyz/openbmc_project/object_mapper",
@@ -120,22 +120,22 @@ class ChassisCollection : public Node {
/**
* Functions triggers appropriate requests on DBus
*/
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
- // Get chassis list, and call the below callback for JSON preparation
- chassis_provider.get_chassis_list(
+ // get chassis list, and call the below callback for JSON preparation
+ chassisProvider.getChassisList(
[&](const bool &success, const std::vector<std::string> &output) {
if (success) {
// ... prepare json array with appropriate @odata.id links
- nlohmann::json chassis_array = nlohmann::json::array();
- for (const std::string &chassis_item : output) {
- chassis_array.push_back(
- {{"@odata.id", "/redfish/v1/Chassis/" + chassis_item}});
+ nlohmann::json chassisArray = nlohmann::json::array();
+ for (const std::string &chassisItem : output) {
+ chassisArray.push_back(
+ {{"@odata.id", "/redfish/v1/Chassis/" + chassisItem}});
}
// Then attach members, count size and return,
- Node::json["Members"] = chassis_array;
- Node::json["Members@odata.count"] = chassis_array.size();
- res.json_value = Node::json;
+ Node::json["Members"] = chassisArray;
+ Node::json["Members@odata.count"] = chassisArray.size();
+ res.jsonValue = Node::json;
} else {
// ... otherwise, return INTERNALL ERROR
res.result(boost::beast::http::status::internal_server_error);
@@ -146,7 +146,7 @@ class ChassisCollection : public Node {
// Chassis Provider object
// TODO(Pawel) consider move it to singleton
- OnDemandChassisProvider chassis_provider;
+ OnDemandChassisProvider chassisProvider;
};
/**
@@ -175,7 +175,7 @@ class Chassis : public Node {
/**
* Functions triggers appropriate requests on DBus
*/
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
// Check if there is required param, truly entering this shall be
// impossible.
@@ -185,17 +185,17 @@ class Chassis : public Node {
return;
}
- res.json_value = Node::json;
- const std::string &chassis_id = params[0];
- crow::connections::system_bus->async_method_call(
- [&res, chassis_id(std::string(chassis_id)) ](
+ res.jsonValue = Node::json;
+ const std::string &chassisId = params[0];
+ crow::connections::systemBus->async_method_call(
+ [&res, chassisId(std::string(chassisId)) ](
const boost::system::error_code error_code,
const std::vector<std::pair<
std::string,
std::vector<std::pair<std::string, std::vector<std::string>>>>>
&subtree) {
if (error_code) {
- res.json_value = {};
+ res.jsonValue = {};
res.result(boost::beast::http::status::internal_server_error);
res.end();
return;
@@ -209,39 +209,39 @@ class Chassis : public Node {
const std::vector<std::pair<std::string, std::vector<std::string>>>
&connectionNames = object.second;
- if (!boost::ends_with(path, chassis_id)) {
+ if (!boost::ends_with(path, chassisId)) {
continue;
}
if (connectionNames.size() < 1) {
- CROW_LOG_ERROR << "Only got " << connectionNames.size()
- << " connection names";
+ BMCWEB_LOG_ERROR << "Only got " << connectionNames.size()
+ << " Connection names";
continue;
}
const std::string connectionName = connectionNames[0].first;
- crow::connections::system_bus->async_method_call(
- [&res, chassis_id(std::string(chassis_id)) ](
+ crow::connections::systemBus->async_method_call(
+ [&res, chassisId(std::string(chassisId)) ](
const boost::system::error_code error_code,
const std::vector<std::pair<std::string, VariantType>>
&propertiesList) {
for (const std::pair<std::string, VariantType> &property :
propertiesList) {
const std::string *value =
- mapbox::get_ptr<const std::string>(property.second);
+ mapbox::getPtr<const std::string>(property.second);
if (value != nullptr) {
- res.json_value[property.first] = *value;
+ res.jsonValue[property.first] = *value;
}
}
- res.json_value["Name"] = chassis_id;
- res.json_value["Id"] = chassis_id;
- res.json_value["Thermal"] = {
+ res.jsonValue["Name"] = chassisId;
+ res.jsonValue["Id"] = chassisId;
+ res.jsonValue["Thermal"] = {
{"@odata.id",
- "/redfish/v1/Chassis/" + chassis_id + "/Thermal"}};
+ "/redfish/v1/Chassis/" + chassisId + "/Thermal"}};
res.end();
},
connectionName, path, "org.freedesktop.DBus.Properties",
"GetAll", "xyz.openbmc_project.Inventory.Decorator.Asset");
- // Found the connection we were looking for, return
+ // Found the Connection we were looking for, return
return;
}
@@ -260,7 +260,7 @@ class Chassis : public Node {
// Chassis Provider object
// TODO(Pawel) consider move it to singleton
- OnDemandChassisProvider chassis_provider;
+ OnDemandChassisProvider chassisProvider;
}; // namespace redfish
} // namespace redfish
diff --git a/redfish-core/lib/ethernet.hpp b/redfish-core/lib/ethernet.hpp
index c008be6b60..293e8020c0 100644
--- a/redfish-core/lib/ethernet.hpp
+++ b/redfish-core/lib/ethernet.hpp
@@ -69,11 +69,11 @@ struct IPv4AddressData {
*/
struct EthernetInterfaceData {
const unsigned int *speed;
- const bool *auto_neg;
+ const bool *autoNeg;
const std::string *hostname;
- const std::string *default_gateway;
- const std::string *mac_address;
- const unsigned int *vlan_id;
+ const std::string *defaultGateway;
+ const std::string *macAddress;
+ const unsigned int *vlanId;
};
/**
@@ -88,17 +88,17 @@ struct EthernetInterfaceData {
class OnDemandEthernetProvider {
private:
// Consts that may have influence on EthernetProvider performance/memory usage
- const size_t MAX_IPV4_ADDRESSES_PER_INTERFACE = 10;
+ const size_t maxIpV4AddressesPerInterface = 10;
// Helper function that allows to extract GetAllPropertiesType from
// GetManagedObjectsType, based on object path, and interface name
const PropertiesMapType *extractInterfaceProperties(
const sdbusplus::message::object_path &objpath,
const std::string &interface, const GetManagedObjectsType &dbus_data) {
- const auto &dbus_obj = dbus_data.find(objpath);
- if (dbus_obj != dbus_data.end()) {
- const auto &iface = dbus_obj->second.find(interface);
- if (iface != dbus_obj->second.end()) {
+ const auto &dbusObj = dbus_data.find(objpath);
+ if (dbusObj != dbus_data.end()) {
+ const auto &iface = dbusObj->second.find(interface);
+ if (iface != dbusObj->second.end()) {
return &iface->second;
}
}
@@ -110,8 +110,8 @@ class OnDemandEthernetProvider {
inline const PropertiesMapType *extractInterfaceProperties(
const std::string &objpath, const std::string &interface,
const GetManagedObjectsType &dbus_data) {
- const auto &dbus_obj = sdbusplus::message::object_path{objpath};
- return extractInterfaceProperties(dbus_obj, interface, dbus_data);
+ const auto &dbusObj = sdbusplus::message::object_path{objpath};
+ return extractInterfaceProperties(dbusObj, interface, dbus_data);
}
// Helper function that allows to get pointer to the property from
@@ -121,7 +121,7 @@ class OnDemandEthernetProvider {
const std::string &name) {
const auto &property = properties.find(name);
if (property != properties.end()) {
- return mapbox::get_ptr<const T>(property->second);
+ return mapbox::getPtr<const T>(property->second);
}
return nullptr;
}
@@ -130,47 +130,47 @@ class OnDemandEthernetProvider {
// Helper function that extracts data from several dbus objects and several
// interfaces required by single ethernet interface instance
- void extractEthernetInterfaceData(const std::string &ethiface_id,
+ void extractEthernetInterfaceData(const std::string &ethifaceId,
const GetManagedObjectsType &dbus_data,
EthernetInterfaceData &eth_data) {
// Extract data that contains MAC Address
- const PropertiesMapType *mac_properties = extractInterfaceProperties(
- "/xyz/openbmc_project/network/" + ethiface_id,
+ const PropertiesMapType *macProperties = extractInterfaceProperties(
+ "/xyz/openbmc_project/network/" + ethifaceId,
"xyz.openbmc_project.Network.MACAddress", dbus_data);
- if (mac_properties != nullptr) {
- eth_data.mac_address =
- extractProperty<std::string>(*mac_properties, "MACAddress");
+ if (macProperties != nullptr) {
+ eth_data.macAddress =
+ extractProperty<std::string>(*macProperties, "MACAddress");
}
- const PropertiesMapType *vlan_properties = extractInterfaceProperties(
- "/xyz/openbmc_project/network/" + ethiface_id,
+ const PropertiesMapType *vlanProperties = extractInterfaceProperties(
+ "/xyz/openbmc_project/network/" + ethifaceId,
"xyz.openbmc_project.Network.VLAN", dbus_data);
- if (vlan_properties != nullptr) {
- eth_data.vlan_id = extractProperty<unsigned int>(*vlan_properties, "Id");
+ if (vlanProperties != nullptr) {
+ eth_data.vlanId = extractProperty<unsigned int>(*vlanProperties, "Id");
}
// Extract data that contains link information (auto negotiation and speed)
- const PropertiesMapType *eth_properties = extractInterfaceProperties(
- "/xyz/openbmc_project/network/" + ethiface_id,
+ const PropertiesMapType *ethProperties = extractInterfaceProperties(
+ "/xyz/openbmc_project/network/" + ethifaceId,
"xyz.openbmc_project.Network.EthernetInterface", dbus_data);
- if (eth_properties != nullptr) {
- eth_data.auto_neg = extractProperty<bool>(*eth_properties, "AutoNeg");
- eth_data.speed = extractProperty<unsigned int>(*eth_properties, "Speed");
+ if (ethProperties != nullptr) {
+ eth_data.autoNeg = extractProperty<bool>(*ethProperties, "AutoNeg");
+ eth_data.speed = extractProperty<unsigned int>(*ethProperties, "Speed");
}
// Extract data that contains network config (HostName and DefaultGW)
- const PropertiesMapType *config_properties = extractInterfaceProperties(
+ const PropertiesMapType *configProperties = extractInterfaceProperties(
"/xyz/openbmc_project/network/config",
"xyz.openbmc_project.Network.SystemConfiguration", dbus_data);
- if (config_properties != nullptr) {
+ if (configProperties != nullptr) {
eth_data.hostname =
- extractProperty<std::string>(*config_properties, "HostName");
- eth_data.default_gateway =
- extractProperty<std::string>(*config_properties, "DefaultGateway");
+ extractProperty<std::string>(*configProperties, "HostName");
+ eth_data.defaultGateway =
+ extractProperty<std::string>(*configProperties, "DefaultGateway");
}
}
@@ -186,11 +186,11 @@ class OnDemandEthernetProvider {
}
// Helper function that extracts data for single ethernet ipv4 address
- void extractIPv4Data(const std::string &ethiface_id,
+ void extractIPv4Data(const std::string &ethifaceId,
const GetManagedObjectsType &dbus_data,
std::vector<IPv4AddressData> &ipv4_config) {
const std::string pathStart =
- "/xyz/openbmc_project/network/" + ethiface_id + "/ipv4/";
+ "/xyz/openbmc_project/network/" + ethifaceId + "/ipv4/";
// Since there might be several IPv4 configurations aligned with
// single ethernet interface, loop over all of them
@@ -198,7 +198,7 @@ class OnDemandEthernetProvider {
// Check if proper patter for object path appears
if (boost::starts_with(
static_cast<const std::string &>(objpath.first),
- "/xyz/openbmc_project/network/" + ethiface_id + "/ipv4/")) {
+ "/xyz/openbmc_project/network/" + ethifaceId + "/ipv4/")) {
// and get approrpiate interface
const auto &interface =
objpath.second.find("xyz.openbmc_project.Network.IP");
@@ -206,23 +206,23 @@ class OnDemandEthernetProvider {
// Make a properties 'shortcut', to make everything more readable
const PropertiesMapType &properties = interface->second;
// Instance IPv4AddressData structure, and set as appropriate
- IPv4AddressData ipv4_address;
+ IPv4AddressData ipv4Address;
- ipv4_address.id = static_cast<const std::string &>(objpath.first)
- .substr(pathStart.size());
+ ipv4Address.id = static_cast<const std::string &>(objpath.first)
+ .substr(pathStart.size());
// IPv4 address
- ipv4_address.address =
+ ipv4Address.address =
extractProperty<std::string>(properties, "Address");
// IPv4 gateway
- ipv4_address.gateway =
+ ipv4Address.gateway =
extractProperty<std::string>(properties, "Gateway");
// Origin is kind of DBus object so fetch pointer...
const std::string *origin =
extractProperty<std::string>(properties, "Origin");
if (origin != nullptr) {
- ipv4_address.origin =
+ ipv4Address.origin =
translateAddressOriginBetweenDBusAndRedfish(origin, true, true);
}
@@ -231,18 +231,18 @@ class OnDemandEthernetProvider {
extractProperty<uint8_t>(properties, "PrefixLength");
if (mask != nullptr) {
// convert it to the string
- ipv4_address.netmask = getNetmask(*mask);
+ ipv4Address.netmask = getNetmask(*mask);
}
// Attach IPv4 only if address is present
- if (ipv4_address.address != nullptr) {
- // Check if given address is local, or global
- if (boost::starts_with(*ipv4_address.address, "169.254")) {
- ipv4_address.global = false;
+ if (ipv4Address.address != nullptr) {
+ // Check if given addres is local, or global
+ if (boost::starts_with(*ipv4Address.address, "169.254")) {
+ ipv4Address.global = false;
} else {
- ipv4_address.global = true;
+ ipv4Address.global = true;
}
- ipv4_config.emplace_back(std::move(ipv4_address));
+ ipv4_config.emplace_back(std::move(ipv4Address));
}
}
}
@@ -270,7 +270,7 @@ class OnDemandEthernetProvider {
template <typename CallbackFunc>
void createVlan(const std::string &ifaceId, const uint64_t &inputVlanId,
CallbackFunc &&callback) {
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
callback, "xyz.openbmc_project.Network", "/xyz/openbmc_project/network",
"xyz.openbmc_project.Network.VLAN.Create", "VLAN", ifaceId,
static_cast<uint32_t>(inputVlanId));
@@ -289,7 +289,7 @@ class OnDemandEthernetProvider {
static void changeVlanId(const std::string &ifaceId,
const uint32_t &inputVlanId,
CallbackFunc &&callback) {
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
callback, "xyz.openbmc_project.Network",
std::string("/xyz/openbmc_project/network/") + ifaceId,
"org.freedesktop.DBus.Properties", "Set",
@@ -377,7 +377,7 @@ class OnDemandEthernetProvider {
* @brief Changes IPv4 address type property (Address, Gateway)
*
* @param[in] ifaceId Id of interface whose IP should be modified
- * @param[in] ipIdx Index of IP in input array that should be modified
+ * @param[in] ipIdx index of IP in input array that should be modified
* @param[in] ipHash DBus Hash id of modified IP
* @param[in] name Name of field in JSON representation
* @param[in] newValue New value that should be written
@@ -397,14 +397,14 @@ class OnDemandEthernetProvider {
](const boost::system::error_code ec) {
if (ec) {
messages::addMessageToJson(
- asyncResp->res.json_value, messages::internalError(),
+ asyncResp->res.jsonValue, messages::internalError(),
"/IPv4Addresses/" + std::to_string(ipIdx) + "/" + name);
} else {
- asyncResp->res.json_value["IPv4Addresses"][ipIdx][name] = newValue;
+ asyncResp->res.jsonValue["IPv4Addresses"][ipIdx][name] = newValue;
}
};
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
std::move(callback), "xyz.openbmc_project.Network",
"/xyz/openbmc_project/network/" + ifaceId + "/ipv4/" + ipHash,
"org.freedesktop.DBus.Properties", "Set",
@@ -416,7 +416,7 @@ class OnDemandEthernetProvider {
* @brief Changes IPv4 address origin property
*
* @param[in] ifaceId Id of interface whose IP should be modified
- * @param[in] ipIdx Index of IP in input array that should be modified
+ * @param[in] ipIdx index of IP in input array that should be modified
* @param[in] ipHash DBus Hash id of modified IP
* @param[in] newValue New value in Redfish format
* @param[in] newValueDbus New value in D-Bus format
@@ -434,15 +434,15 @@ class OnDemandEthernetProvider {
newValue{std::move(newValue)} ](const boost::system::error_code ec) {
if (ec) {
messages::addMessageToJson(
- asyncResp->res.json_value, messages::internalError(),
+ asyncResp->res.jsonValue, messages::internalError(),
"/IPv4Addresses/" + std::to_string(ipIdx) + "/AddressOrigin");
} else {
- asyncResp->res.json_value["IPv4Addresses"][ipIdx]["AddressOrigin"] =
+ asyncResp->res.jsonValue["IPv4Addresses"][ipIdx]["AddressOrigin"] =
newValue;
}
};
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
std::move(callback), "xyz.openbmc_project.Network",
"/xyz/openbmc_project/network/" + ifaceId + "/ipv4/" + ipHash,
"org.freedesktop.DBus.Properties", "Set",
@@ -454,7 +454,7 @@ class OnDemandEthernetProvider {
* @brief Modifies SubnetMask for given IP
*
* @param[in] ifaceId Id of interface whose IP should be modified
- * @param[in] ipIdx Index of IP in input array that should be modified
+ * @param[in] ipIdx index of IP in input array that should be modified
* @param[in] ipHash DBus Hash id of modified IP
* @param[in] newValueStr Mask in dot notation as string
* @param[in] newValue Mask as PrefixLength in bitcount
@@ -471,15 +471,15 @@ class OnDemandEthernetProvider {
](const boost::system::error_code ec) {
if (ec) {
messages::addMessageToJson(
- asyncResp->res.json_value, messages::internalError(),
+ asyncResp->res.jsonValue, messages::internalError(),
"/IPv4Addresses/" + std::to_string(ipIdx) + "/SubnetMask");
} else {
- asyncResp->res.json_value["IPv4Addresses"][ipIdx]["SubnetMask"] =
+ asyncResp->res.jsonValue["IPv4Addresses"][ipIdx]["SubnetMask"] =
newValueStr;
}
};
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
std::move(callback), "xyz.openbmc_project.Network",
"/xyz/openbmc_project/network/" + ifaceId + "/ipv4/" + ipHash,
"org.freedesktop.DBus.Properties", "Set",
@@ -497,7 +497,7 @@ class OnDemandEthernetProvider {
*/
template <typename CallbackFunc>
static void disableVlan(const std::string &ifaceId, CallbackFunc &&callback) {
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
callback, "xyz.openbmc_project.Network",
std::string("/xyz/openbmc_project/network/") + ifaceId,
"xyz.openbmc_project.Object.Delete", "Delete");
@@ -513,7 +513,7 @@ class OnDemandEthernetProvider {
*/
template <typename CallbackFunc>
void setHostName(const std::string &newHostname, CallbackFunc &&callback) {
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
callback, "xyz.openbmc_project.Network",
"/xyz/openbmc_project/network/config",
"org.freedesktop.DBus.Properties", "Set",
@@ -525,7 +525,7 @@ class OnDemandEthernetProvider {
* @brief Deletes given IPv4
*
* @param[in] ifaceId Id of interface whose IP should be deleted
- * @param[in] ipIdx Index of IP in input array that should be deleted
+ * @param[in] ipIdx index of IP in input array that should be deleted
* @param[in] ipHash DBus Hash id of IP that should be deleted
* @param[io] asyncResp Response object that will be returned to client
*
@@ -534,15 +534,15 @@ class OnDemandEthernetProvider {
void deleteIPv4(const std::string &ifaceId, const std::string &ipHash,
unsigned int ipIdx,
const std::shared_ptr<AsyncResp> &asyncResp) {
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[ ipIdx{std::move(ipIdx)}, asyncResp{std::move(asyncResp)} ](
const boost::system::error_code ec) {
if (ec) {
messages::addMessageToJson(
- asyncResp->res.json_value, messages::internalError(),
+ asyncResp->res.jsonValue, messages::internalError(),
"/IPv4Addresses/" + std::to_string(ipIdx) + "/");
} else {
- asyncResp->res.json_value["IPv4Addresses"][ipIdx] = nullptr;
+ asyncResp->res.jsonValue["IPv4Addresses"][ipIdx] = nullptr;
}
},
"xyz.openbmc_project.Network",
@@ -554,7 +554,7 @@ class OnDemandEthernetProvider {
* @brief Creates IPv4 with given data
*
* @param[in] ifaceId Id of interface whose IP should be deleted
- * @param[in] ipIdx Index of IP in input array that should be deleted
+ * @param[in] ipIdx index of IP in input array that should be deleted
* @param[in] ipHash DBus Hash id of IP that should be deleted
* @param[io] asyncResp Response object that will be returned to client
*
@@ -569,12 +569,12 @@ class OnDemandEthernetProvider {
](const boost::system::error_code ec) {
if (ec) {
messages::addMessageToJson(
- asyncResp->res.json_value, messages::internalError(),
+ asyncResp->res.jsonValue, messages::internalError(),
"/IPv4Addresses/" + std::to_string(ipIdx) + "/");
}
};
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
std::move(createIpHandler), "xyz.openbmc_project.Network",
"/xyz/openbmc_project/network/" + ifaceId,
"xyz.openbmc_project.Network.IP.Create", "IP",
@@ -634,23 +634,23 @@ class OnDemandEthernetProvider {
* Function that retrieves all properties for given Ethernet Interface
* Object
* from EntityManager Network Manager
- * @param ethiface_id a eth interface id to query on DBus
+ * @param ethifaceId a eth interface id to query on DBus
* @param callback a function that shall be called to convert Dbus output
* into JSON
*/
template <typename CallbackFunc>
- void getEthernetIfaceData(const std::string &ethiface_id,
+ void getEthernetIfaceData(const std::string &ethifaceId,
CallbackFunc &&callback) {
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[
- this, ethiface_id{std::move(ethiface_id)},
+ this, ethifaceId{std::move(ethifaceId)},
callback{std::move(callback)}
](const boost::system::error_code error_code,
const GetManagedObjectsType &resp) {
- EthernetInterfaceData eth_data{};
- std::vector<IPv4AddressData> ipv4_data;
- ipv4_data.reserve(MAX_IPV4_ADDRESSES_PER_INTERFACE);
+ EthernetInterfaceData ethData{};
+ std::vector<IPv4AddressData> ipv4Data;
+ ipv4Data.reserve(maxIpV4AddressesPerInterface);
if (error_code) {
// Something wrong on DBus, the error_code is not important at
@@ -658,31 +658,31 @@ class OnDemandEthernetProvider {
// size of vector may vary depending on information from Network
// Manager, and empty output could not be treated same way as
// error.
- callback(false, eth_data, ipv4_data);
+ callback(false, ethData, ipv4Data);
return;
}
// Find interface
- if (resp.find("/xyz/openbmc_project/network/" + ethiface_id) ==
+ if (resp.find("/xyz/openbmc_project/network/" + ethifaceId) ==
resp.end()) {
// Interface has not been found
- callback(false, eth_data, ipv4_data);
+ callback(false, ethData, ipv4Data);
return;
}
- extractEthernetInterfaceData(ethiface_id, resp, eth_data);
- extractIPv4Data(ethiface_id, resp, ipv4_data);
+ extractEthernetInterfaceData(ethifaceId, resp, ethData);
+ extractIPv4Data(ethifaceId, resp, ipv4Data);
// Fix global GW
- for (IPv4AddressData &ipv4 : ipv4_data) {
+ for (IPv4AddressData &ipv4 : ipv4Data) {
if ((ipv4.global) &&
((ipv4.gateway == nullptr) || (*ipv4.gateway == "0.0.0.0"))) {
- ipv4.gateway = eth_data.default_gateway;
+ ipv4.gateway = ethData.defaultGateway;
}
}
// Finally make a callback with usefull data
- callback(true, eth_data, ipv4_data);
+ callback(true, ethData, ipv4Data);
},
"xyz.openbmc_project.Network", "/xyz/openbmc_project/network",
"org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
@@ -696,20 +696,20 @@ class OnDemandEthernetProvider {
*/
template <typename CallbackFunc>
void getEthernetIfaceList(CallbackFunc &&callback) {
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[ this, callback{std::move(callback)} ](
const boost::system::error_code error_code,
GetManagedObjectsType &resp) {
// Callback requires vector<string> to retrieve all available ethernet
// interfaces
- std::vector<std::string> iface_list;
- iface_list.reserve(resp.size());
+ std::vector<std::string> ifaceList;
+ ifaceList.reserve(resp.size());
if (error_code) {
// Something wrong on DBus, the error_code is not important at this
// moment, just return success=false, and empty output. Since size
// of vector may vary depending on information from Network Manager,
// and empty output could not be treated same way as error.
- callback(false, iface_list);
+ callback(false, ifaceList);
return;
}
@@ -722,18 +722,18 @@ class OnDemandEthernetProvider {
if (interface.first ==
"xyz.openbmc_project.Network.EthernetInterface") {
// Cut out everyting until last "/", ...
- const std::string &iface_id =
+ const std::string &ifaceId =
static_cast<const std::string &>(objpath.first);
- std::size_t last_pos = iface_id.rfind("/");
- if (last_pos != std::string::npos) {
+ std::size_t lastPos = ifaceId.rfind("/");
+ if (lastPos != std::string::npos) {
// and put it into output vector.
- iface_list.emplace_back(iface_id.substr(last_pos + 1));
+ ifaceList.emplace_back(ifaceId.substr(lastPos + 1));
}
}
}
}
- // Finally make a callback with useful data
- callback(true, iface_list);
+ // Finally make a callback with usefull data
+ callback(true, ifaceList);
},
"xyz.openbmc_project.Network", "/xyz/openbmc_project/network",
"org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
@@ -773,39 +773,38 @@ class EthernetCollection : public Node {
/**
* Functions triggers appropriate requests on DBus
*/
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
// TODO(Pawel) this shall be parametrized call to get EthernetInterfaces for
// any Manager, not only hardcoded 'openbmc'.
- std::string manager_id = "openbmc";
+ std::string managerId = "openbmc";
- // Get eth interface list, and call the below callback for JSON preparation
- ethernet_provider.getEthernetIfaceList(
- [&, manager_id{std::move(manager_id)} ](
- const bool &success, const std::vector<std::string> &iface_list) {
- if (success) {
- nlohmann::json iface_array = nlohmann::json::array();
- for (const std::string &iface_item : iface_list) {
- iface_array.push_back(
- {{"@odata.id", "/redfish/v1/Managers/" + manager_id +
- "/EthernetInterfaces/" + iface_item}});
- }
- Node::json["Members"] = iface_array;
- Node::json["Members@odata.count"] = iface_array.size();
- Node::json["@odata.id"] =
- "/redfish/v1/Managers/" + manager_id + "/EthernetInterfaces";
- res.json_value = Node::json;
- } else {
- // No success, best what we can do is return INTERNALL ERROR
- res.result(boost::beast::http::status::internal_server_error);
- }
- res.end();
- });
+ // get eth interface list, and call the below callback for JSON preparation
+ ethernetProvider.getEthernetIfaceList([&, managerId{std::move(managerId)} ](
+ const bool &success, const std::vector<std::string> &iface_list) {
+ if (success) {
+ nlohmann::json ifaceArray = nlohmann::json::array();
+ for (const std::string &ifaceItem : iface_list) {
+ ifaceArray.push_back(
+ {{"@odata.id", "/redfish/v1/Managers/" + managerId +
+ "/EthernetInterfaces/" + ifaceItem}});
+ }
+ Node::json["Members"] = ifaceArray;
+ Node::json["Members@odata.count"] = ifaceArray.size();
+ Node::json["@odata.id"] =
+ "/redfish/v1/Managers/" + managerId + "/EthernetInterfaces";
+ res.jsonValue = Node::json;
+ } else {
+ // No success, best what we can do is return INTERNALL ERROR
+ res.result(boost::beast::http::status::internal_server_error);
+ }
+ res.end();
+ });
}
// Ethernet Provider object
// TODO(Pawel) consider move it to singleton
- OnDemandEthernetProvider ethernet_provider;
+ OnDemandEthernetProvider ethernetProvider;
};
/**
@@ -845,7 +844,7 @@ class EthernetInterface : public Node {
const std::shared_ptr<AsyncResp> &asyncResp) {
if (!input.is_object()) {
messages::addMessageToJson(
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
messages::propertyValueTypeError(input.dump(), "VLAN"), pathPrefix);
return;
}
@@ -853,8 +852,8 @@ class EthernetInterface : public Node {
const std::string pathStart = (pathPrefix == "/") ? "" : pathPrefix;
nlohmann::json &paramsJson =
(pathPrefix == "/")
- ? asyncResp->res.json_value
- : asyncResp->res.json_value[nlohmann::json_pointer<nlohmann::json>(
+ ? asyncResp->res.jsonValue
+ : asyncResp->res.jsonValue[nlohmann::json_pointer<nlohmann::json>(
pathPrefix)];
bool inputVlanEnabled;
uint64_t inputVlanId;
@@ -862,11 +861,11 @@ class EthernetInterface : public Node {
json_util::Result inputVlanEnabledState = json_util::getBool(
"VLANEnable", input, inputVlanEnabled,
static_cast<int>(json_util::MessageSetting::TYPE_ERROR),
- asyncResp->res.json_value, std::string(pathStart + "/VLANEnable"));
+ asyncResp->res.jsonValue, std::string(pathStart + "/VLANEnable"));
json_util::Result inputVlanIdState = json_util::getUnsigned(
"VLANId", input, inputVlanId,
static_cast<int>(json_util::MessageSetting::TYPE_ERROR),
- asyncResp->res.json_value, std::string(pathStart + "/VLANId"));
+ asyncResp->res.jsonValue, std::string(pathStart + "/VLANId"));
bool inputInvalid = false;
// Do not proceed if fields in VLAN object were of wrong type
@@ -876,10 +875,10 @@ class EthernetInterface : public Node {
}
// Verify input
- if (eth_data.vlan_id == nullptr) {
+ if (eth_data.vlanId == nullptr) {
// This interface is not a VLAN. Cannot do anything with it
// TODO(kkowalsk) Change this message
- messages::addMessageToJson(asyncResp->res.json_value,
+ messages::addMessageToJson(asyncResp->res.jsonValue,
messages::propertyMissing("VLANEnable"),
pathPrefix);
@@ -891,7 +890,7 @@ class EthernetInterface : public Node {
}
if (inputVlanIdState == json_util::Result::NOT_EXIST) {
- inputVlanId = *eth_data.vlan_id;
+ inputVlanId = *eth_data.vlanId;
}
}
@@ -901,7 +900,7 @@ class EthernetInterface : public Node {
}
// VLAN is configured on the interface
- if (inputVlanEnabled == true && inputVlanId != *eth_data.vlan_id) {
+ if (inputVlanEnabled == true && inputVlanId != *eth_data.vlanId) {
// Change VLAN Id
paramsJson["VLANId"] = inputVlanId;
OnDemandEthernetProvider::changeVlanId(
@@ -909,7 +908,7 @@ class EthernetInterface : public Node {
[&, asyncResp, pathPrefx{std::move(pathPrefix)} ](
const boost::system::error_code ec) {
if (ec) {
- messages::addMessageToJson(asyncResp->res.json_value,
+ messages::addMessageToJson(asyncResp->res.jsonValue,
messages::internalError(), pathPrefix);
} else {
paramsJson["VLANEnable"] = true;
@@ -921,7 +920,7 @@ class EthernetInterface : public Node {
ifaceId, [&, asyncResp, pathPrefx{std::move(pathPrefix)} ](
const boost::system::error_code ec) {
if (ec) {
- messages::addMessageToJson(asyncResp->res.json_value,
+ messages::addMessageToJson(asyncResp->res.jsonValue,
messages::internalError(), pathPrefix);
} else {
paramsJson["VLANEnable"] = false;
@@ -939,21 +938,21 @@ class EthernetInterface : public Node {
if (eth_data.hostname == nullptr || newHostname != *eth_data.hostname) {
// Change hostname
- ethernet_provider.setHostName(
+ ethernetProvider.setHostName(
newHostname,
[asyncResp, newHostname](const boost::system::error_code ec) {
if (ec) {
- messages::addMessageToJson(asyncResp->res.json_value,
+ messages::addMessageToJson(asyncResp->res.jsonValue,
messages::internalError(),
"/HostName");
} else {
- asyncResp->res.json_value["HostName"] = newHostname;
+ asyncResp->res.jsonValue["HostName"] = newHostname;
}
});
}
} else {
messages::addMessageToJson(
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
messages::propertyValueTypeError(input.dump(), "HostName"),
"/HostName");
}
@@ -964,7 +963,7 @@ class EthernetInterface : public Node {
const std::shared_ptr<AsyncResp> &asyncResp) {
if (!input.is_array()) {
messages::addMessageToJson(
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
messages::propertyValueTypeError(input.dump(), "IPv4Addresses"),
"/IPv4Addresses");
return;
@@ -974,7 +973,7 @@ class EthernetInterface : public Node {
if (input.size() < ipv4_data.size()) {
// TODO(kkowalsk) This should be a message indicating that not enough
// data has been provided
- messages::addMessageToJson(asyncResp->res.json_value,
+ messages::addMessageToJson(asyncResp->res.jsonValue,
messages::internalError(), "/IPv4Addresses");
return;
}
@@ -996,7 +995,7 @@ class EthernetInterface : public Node {
if (!input[entryIdx].is_object() && !input[entryIdx].is_null()) {
// Invalid object type
messages::addMessageToJson(
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
messages::propertyValueTypeError(input[entryIdx].dump(),
"IPv4Address"),
"/IPv4Addresses/" + std::to_string(entryIdx));
@@ -1008,22 +1007,22 @@ class EthernetInterface : public Node {
addressFieldState = json_util::getString(
"Address", input[entryIdx], addressFieldValue,
static_cast<uint8_t>(json_util::MessageSetting::TYPE_ERROR),
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
"/IPv4Addresses/" + std::to_string(entryIdx) + "/Address");
subnetMaskFieldState = json_util::getString(
"SubnetMask", input[entryIdx], subnetMaskFieldValue,
static_cast<uint8_t>(json_util::MessageSetting::TYPE_ERROR),
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
"/IPv4Addresses/" + std::to_string(entryIdx) + "/SubnetMask");
addressOriginFieldState = json_util::getString(
"AddressOrigin", input[entryIdx], addressOriginFieldValue,
static_cast<uint8_t>(json_util::MessageSetting::TYPE_ERROR),
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
"/IPv4Addresses/" + std::to_string(entryIdx) + "/AddressOrigin");
gatewayFieldState = json_util::getString(
"Gateway", input[entryIdx], gatewayFieldValue,
static_cast<uint8_t>(json_util::MessageSetting::TYPE_ERROR),
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
"/IPv4Addresses/" + std::to_string(entryIdx) + "/Gateway");
if (addressFieldState == json_util::Result::WRONG_TYPE ||
@@ -1034,45 +1033,45 @@ class EthernetInterface : public Node {
}
if (addressFieldState == json_util::Result::SUCCESS &&
- !ethernet_provider.ipv4VerifyIpAndGetBitcount(*addressFieldValue)) {
+ !ethernetProvider.ipv4VerifyIpAndGetBitcount(*addressFieldValue)) {
errorDetected = true;
messages::addMessageToJson(
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
messages::propertyValueFormatError(*addressFieldValue, "Address"),
"/IPv4Addresses/" + std::to_string(entryIdx) + "/Address");
}
if (subnetMaskFieldState == json_util::Result::SUCCESS &&
- !ethernet_provider.ipv4VerifyIpAndGetBitcount(
+ !ethernetProvider.ipv4VerifyIpAndGetBitcount(
*subnetMaskFieldValue, &subnetMaskAsPrefixLength)) {
errorDetected = true;
messages::addMessageToJson(
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
messages::propertyValueFormatError(*subnetMaskFieldValue,
"SubnetMask"),
"/IPv4Addresses/" + std::to_string(entryIdx) + "/SubnetMask");
}
- // Get Address origin in proper format
+ // get Address origin in proper format
addressOriginInDBusFormat =
- ethernet_provider.translateAddressOriginBetweenDBusAndRedfish(
+ ethernetProvider.translateAddressOriginBetweenDBusAndRedfish(
addressOriginFieldValue, true, false);
if (addressOriginFieldState == json_util::Result::SUCCESS &&
addressOriginInDBusFormat.empty()) {
errorDetected = true;
messages::addMessageToJson(
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
messages::propertyValueNotInList(*addressOriginFieldValue,
"AddressOrigin"),
"/IPv4Addresses/" + std::to_string(entryIdx) + "/AddressOrigin");
}
if (gatewayFieldState == json_util::Result::SUCCESS &&
- !ethernet_provider.ipv4VerifyIpAndGetBitcount(*gatewayFieldValue)) {
+ !ethernetProvider.ipv4VerifyIpAndGetBitcount(*gatewayFieldValue)) {
errorDetected = true;
messages::addMessageToJson(
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
messages::propertyValueFormatError(*gatewayFieldValue, "Gateway"),
"/IPv4Addresses/" + std::to_string(entryIdx) + "/Gateway");
}
@@ -1085,28 +1084,27 @@ class EthernetInterface : public Node {
}
if (entryIdx >= ipv4_data.size()) {
- asyncResp->res.json_value["IPv4Addresses"][entryIdx] = input[entryIdx];
+ asyncResp->res.jsonValue["IPv4Addresses"][entryIdx] = input[entryIdx];
// Verify that all field were provided
if (addressFieldState == json_util::Result::NOT_EXIST) {
errorDetected = true;
messages::addMessageToJson(
- asyncResp->res.json_value, messages::propertyMissing("Address"),
+ asyncResp->res.jsonValue, messages::propertyMissing("Address"),
"/IPv4Addresses/" + std::to_string(entryIdx) + "/Address");
}
if (subnetMaskFieldState == json_util::Result::NOT_EXIST) {
errorDetected = true;
messages::addMessageToJson(
- asyncResp->res.json_value,
- messages::propertyMissing("SubnetMask"),
+ asyncResp->res.jsonValue, messages::propertyMissing("SubnetMask"),
"/IPv4Addresses/" + std::to_string(entryIdx) + "/SubnetMask");
}
if (addressOriginFieldState == json_util::Result::NOT_EXIST) {
errorDetected = true;
messages::addMessageToJson(
- asyncResp->res.json_value,
+ asyncResp->res.jsonValue,
messages::propertyMissing("AddressOrigin"),
"/IPv4Addresses/" + std::to_string(entryIdx) + "/AddressOrigin");
}
@@ -1114,7 +1112,7 @@ class EthernetInterface : public Node {
if (gatewayFieldState == json_util::Result::NOT_EXIST) {
errorDetected = true;
messages::addMessageToJson(
- asyncResp->res.json_value, messages::propertyMissing("Gateway"),
+ asyncResp->res.jsonValue, messages::propertyMissing("Gateway"),
"/IPv4Addresses/" + std::to_string(entryIdx) + "/Gateway");
}
@@ -1126,15 +1124,15 @@ class EthernetInterface : public Node {
}
// Create IPv4 with provided data
- ethernet_provider.createIPv4(
- ifaceId, entryIdx, subnetMaskAsPrefixLength, *gatewayFieldValue,
- *addressFieldValue, asyncResp);
+ ethernetProvider.createIPv4(ifaceId, entryIdx, subnetMaskAsPrefixLength,
+ *gatewayFieldValue, *addressFieldValue,
+ asyncResp);
} else {
// Existing object that should be modified/deleted/remain unchanged
if (input[entryIdx].is_null()) {
// Object should be deleted
- ethernet_provider.deleteIPv4(ifaceId, ipv4_data[entryIdx].id,
- entryIdx, asyncResp);
+ ethernetProvider.deleteIPv4(ifaceId, ipv4_data[entryIdx].id, entryIdx,
+ asyncResp);
} else if (input[entryIdx].is_object()) {
if (input[entryIdx].size() == 0) {
// Object shall remain unchanged
@@ -1145,21 +1143,21 @@ class EthernetInterface : public Node {
if (addressFieldState == json_util::Result::SUCCESS &&
ipv4_data[entryIdx].address != nullptr &&
*ipv4_data[entryIdx].address != *addressFieldValue) {
- ethernet_provider.changeIPv4AddressProperty(
+ ethernetProvider.changeIPv4AddressProperty(
ifaceId, entryIdx, ipv4_data[entryIdx].id, "Address",
*addressFieldValue, asyncResp);
}
if (subnetMaskFieldState == json_util::Result::SUCCESS &&
ipv4_data[entryIdx].netmask != *subnetMaskFieldValue) {
- ethernet_provider.changeIPv4SubnetMaskProperty(
+ ethernetProvider.changeIPv4SubnetMaskProperty(
ifaceId, entryIdx, ipv4_data[entryIdx].id,
*subnetMaskFieldValue, subnetMaskAsPrefixLength, asyncResp);
}
if (addressOriginFieldState == json_util::Result::SUCCESS &&
ipv4_data[entryIdx].origin != *addressFieldValue) {
- ethernet_provider.changeIPv4Origin(
+ ethernetProvider.changeIPv4Origin(
ifaceId, entryIdx, ipv4_data[entryIdx].id,
*addressOriginFieldValue, addressOriginInDBusFormat, asyncResp);
}
@@ -1167,7 +1165,7 @@ class EthernetInterface : public Node {
if (gatewayFieldState == json_util::Result::SUCCESS &&
ipv4_data[entryIdx].gateway != nullptr &&
*ipv4_data[entryIdx].gateway != *gatewayFieldValue) {
- ethernet_provider.changeIPv4AddressProperty(
+ ethernetProvider.changeIPv4AddressProperty(
ifaceId, entryIdx, ipv4_data[entryIdx].id, "Gateway",
*gatewayFieldValue, asyncResp);
}
@@ -1177,63 +1175,63 @@ class EthernetInterface : public Node {
}
nlohmann::json parseInterfaceData(
- const std::string &iface_id, const EthernetInterfaceData &eth_data,
+ const std::string &ifaceId, const EthernetInterfaceData &eth_data,
const std::vector<IPv4AddressData> &ipv4_data) {
// Copy JSON object to avoid race condition
- nlohmann::json json_response(Node::json);
+ nlohmann::json jsonResponse(Node::json);
// Fill out obvious data...
- json_response["Id"] = iface_id;
- json_response["@odata.id"] =
- "/redfish/v1/Managers/openbmc/EthernetInterfaces/" + iface_id;
+ jsonResponse["Id"] = ifaceId;
+ jsonResponse["@odata.id"] =
+ "/redfish/v1/Managers/openbmc/EthernetInterfaces/" + ifaceId;
// ... then the one from DBus, regarding eth iface...
- if (eth_data.speed != nullptr) json_response["SpeedMbps"] = *eth_data.speed;
+ if (eth_data.speed != nullptr) jsonResponse["SpeedMbps"] = *eth_data.speed;
- if (eth_data.mac_address != nullptr)
- json_response["MACAddress"] = *eth_data.mac_address;
+ if (eth_data.macAddress != nullptr)
+ jsonResponse["MACAddress"] = *eth_data.macAddress;
if (eth_data.hostname != nullptr)
- json_response["HostName"] = *eth_data.hostname;
+ jsonResponse["HostName"] = *eth_data.hostname;
- if (eth_data.vlan_id != nullptr) {
- nlohmann::json &vlanObj = json_response["VLAN"];
+ if (eth_data.vlanId != nullptr) {
+ nlohmann::json &vlanObj = jsonResponse["VLAN"];
vlanObj["VLANEnable"] = true;
- vlanObj["VLANId"] = *eth_data.vlan_id;
+ vlanObj["VLANId"] = *eth_data.vlanId;
} else {
- nlohmann::json &vlanObj = json_response["VLANs"];
+ nlohmann::json &vlanObj = jsonResponse["VLANs"];
vlanObj["@odata.id"] =
- "/redfish/v1/Managers/openbmc/EthernetInterfaces/" + iface_id +
+ "/redfish/v1/Managers/openbmc/EthernetInterfaces/" + ifaceId +
"/VLANs";
}
// ... at last, check if there are IPv4 data and prepare appropriate
// collection
if (ipv4_data.size() > 0) {
- nlohmann::json ipv4_array = nlohmann::json::array();
- for (auto &ipv4_config : ipv4_data) {
- nlohmann::json json_ipv4;
- if (ipv4_config.address != nullptr) {
- json_ipv4["Address"] = *ipv4_config.address;
- if (ipv4_config.gateway != nullptr)
- json_ipv4["Gateway"] = *ipv4_config.gateway;
-
- json_ipv4["AddressOrigin"] = ipv4_config.origin;
- json_ipv4["SubnetMask"] = ipv4_config.netmask;
-
- ipv4_array.push_back(std::move(json_ipv4));
+ nlohmann::json ipv4Array = nlohmann::json::array();
+ for (auto &ipv4Config : ipv4_data) {
+ nlohmann::json jsonIpv4;
+ if (ipv4Config.address != nullptr) {
+ jsonIpv4["Address"] = *ipv4Config.address;
+ if (ipv4Config.gateway != nullptr)
+ jsonIpv4["Gateway"] = *ipv4Config.gateway;
+
+ jsonIpv4["AddressOrigin"] = ipv4Config.origin;
+ jsonIpv4["SubnetMask"] = ipv4Config.netmask;
+
+ ipv4Array.push_back(std::move(jsonIpv4));
}
}
- json_response["IPv4Addresses"] = std::move(ipv4_array);
+ jsonResponse["IPv4Addresses"] = std::move(ipv4Array);
}
- return json_response;
+ return jsonResponse;
}
/**
* Functions triggers appropriate requests on DBus
*/
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
// TODO(Pawel) this shall be parametrized call (two params) to get
// EthernetInterfaces for any Manager, not only hardcoded 'openbmc'.
@@ -1245,30 +1243,30 @@ class EthernetInterface : public Node {
return;
}
- const std::string &iface_id = params[0];
+ const std::string &ifaceId = params[0];
- // Get single eth interface data, and call the below callback for JSON
+ // get single eth interface data, and call the below callback for JSON
// preparation
- ethernet_provider.getEthernetIfaceData(
- iface_id, [&, iface_id](const bool &success,
- const EthernetInterfaceData &eth_data,
- const std::vector<IPv4AddressData> &ipv4_data) {
+ ethernetProvider.getEthernetIfaceData(
+ ifaceId,
+ [&, ifaceId](const bool &success, const EthernetInterfaceData &eth_data,
+ const std::vector<IPv4AddressData> &ipv4_data) {
if (success) {
- res.json_value = parseInterfaceData(iface_id, eth_data, ipv4_data);
+ res.jsonValue = parseInterfaceData(ifaceId, eth_data, ipv4_data);
} else {
// ... otherwise return error
// TODO(Pawel)consider distinguish between non existing object, and
// other errors
messages::addMessageToErrorJson(
- res.json_value,
- messages::resourceNotFound("EthernetInterface", iface_id));
+ res.jsonValue,
+ messages::resourceNotFound("EthernetInterface", ifaceId));
res.result(boost::beast::http::status::not_found);
}
res.end();
});
}
- void doPatch(crow::response &res, const crow::request &req,
+ void doPatch(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
// TODO(Pawel) this shall be parametrized call (two params) to get
// EthernetInterfaces for any Manager, not only hardcoded 'openbmc'.
@@ -1280,7 +1278,7 @@ class EthernetInterface : public Node {
return;
}
- const std::string &iface_id = params[0];
+ const std::string &ifaceId = params[0];
nlohmann::json patchReq;
@@ -1288,27 +1286,26 @@ class EthernetInterface : public Node {
return;
}
- // Get single eth interface data, and call the below callback for JSON
+ // get single eth interface data, and call the below callback for JSON
// preparation
- ethernet_provider.getEthernetIfaceData(
- iface_id,
- [&, iface_id, patchReq = std::move(patchReq) ](
- const bool &success, const EthernetInterfaceData &eth_data,
- const std::vector<IPv4AddressData> &ipv4_data) {
+ ethernetProvider.getEthernetIfaceData(
+ ifaceId, [&, ifaceId, patchReq = std::move(patchReq) ](
+ const bool &success, const EthernetInterfaceData &eth_data,
+ const std::vector<IPv4AddressData> &ipv4_data) {
if (!success) {
// ... otherwise return error
// TODO(Pawel)consider distinguish between non existing object, and
// other errors
messages::addMessageToErrorJson(
- res.json_value,
- messages::resourceNotFound("VLAN Network Interface", iface_id));
+ res.jsonValue,
+ messages::resourceNotFound("VLAN Network Interface", ifaceId));
res.result(boost::beast::http::status::not_found);
res.end();
return;
}
- res.json_value = parseInterfaceData(iface_id, eth_data, ipv4_data);
+ res.jsonValue = parseInterfaceData(ifaceId, eth_data, ipv4_data);
std::shared_ptr<AsyncResp> asyncResp =
std::make_shared<AsyncResp>(res);
@@ -1316,30 +1313,29 @@ class EthernetInterface : public Node {
for (auto propertyIt = patchReq.begin(); propertyIt != patchReq.end();
++propertyIt) {
if (propertyIt.key() == "VLAN") {
- handleVlanPatch(iface_id, propertyIt.value(), eth_data, "/VLAN",
+ handleVlanPatch(ifaceId, propertyIt.value(), eth_data, "/VLAN",
asyncResp);
} else if (propertyIt.key() == "HostName") {
handleHostnamePatch(propertyIt.value(), eth_data, asyncResp);
} else if (propertyIt.key() == "IPv4Addresses") {
- handleIPv4Patch(iface_id, propertyIt.value(), ipv4_data,
+ handleIPv4Patch(ifaceId, propertyIt.value(), ipv4_data,
asyncResp);
} else if (propertyIt.key() == "IPv6Addresses") {
// TODO(kkowalsk) IPv6 Not supported on D-Bus yet
messages::addMessageToJsonRoot(
- res.json_value,
+ res.jsonValue,
messages::propertyNotWritable(propertyIt.key()));
} else {
- auto fieldInJsonIt = res.json_value.find(propertyIt.key());
+ auto fieldInJsonIt = res.jsonValue.find(propertyIt.key());
- if (fieldInJsonIt == res.json_value.end()) {
+ if (fieldInJsonIt == res.jsonValue.end()) {
// Field not in scope of defined fields
messages::addMessageToJsonRoot(
- res.json_value,
- messages::propertyUnknown(propertyIt.key()));
+ res.jsonValue, messages::propertyUnknown(propertyIt.key()));
} else if (*fieldInJsonIt != *propertyIt) {
// User attempted to modify non-writable field
messages::addMessageToJsonRoot(
- res.json_value,
+ res.jsonValue,
messages::propertyNotWritable(propertyIt.key()));
}
}
@@ -1349,7 +1345,7 @@ class EthernetInterface : public Node {
// Ethernet Provider object
// TODO(Pawel) consider move it to singleton
- OnDemandEthernetProvider ethernet_provider;
+ OnDemandEthernetProvider ethernetProvider;
};
class VlanNetworkInterfaceCollection;
@@ -1388,35 +1384,35 @@ class VlanNetworkInterface : public Node {
private:
nlohmann::json parseInterfaceData(
- const std::string &parent_iface_id, const std::string &iface_id,
+ const std::string &parent_ifaceId, const std::string &ifaceId,
const EthernetInterfaceData &eth_data,
const std::vector<IPv4AddressData> &ipv4_data) {
// Copy JSON object to avoid race condition
- nlohmann::json json_response(Node::json);
+ nlohmann::json jsonResponse(Node::json);
- if (eth_data.vlan_id == nullptr) {
+ if (eth_data.vlanId == nullptr) {
// Interface not a VLAN - abort
- messages::addMessageToErrorJson(json_response, messages::internalError());
- return json_response;
+ messages::addMessageToErrorJson(jsonResponse, messages::internalError());
+ return jsonResponse;
}
// Fill out obvious data...
- json_response["Id"] = iface_id;
- json_response["@odata.id"] =
- "/redfish/v1/Managers/openbmc/EthernetInterfaces/" + parent_iface_id +
- "/VLANs/" + iface_id;
+ jsonResponse["Id"] = ifaceId;
+ jsonResponse["@odata.id"] =
+ "/redfish/v1/Managers/openbmc/EthernetInterfaces/" + parent_ifaceId +
+ "/VLANs/" + ifaceId;
- json_response["VLANEnable"] = true;
- json_response["VLANId"] = *eth_data.vlan_id;
+ jsonResponse["VLANEnable"] = true;
+ jsonResponse["VLANId"] = *eth_data.vlanId;
- return json_response;
+ return jsonResponse;
}
- bool verifyNames(crow::response &res, const std::string &parent,
+ bool verifyNames(crow::Response &res, const std::string &parent,
const std::string &iface) {
if (!boost::starts_with(iface, parent + "_")) {
messages::addMessageToErrorJson(
- res.json_value,
+ res.jsonValue,
messages::resourceNotFound("VLAN Network Interface", iface));
res.result(boost::beast::http::status::not_found);
res.end();
@@ -1430,7 +1426,7 @@ class VlanNetworkInterface : public Node {
/**
* Functions triggers appropriate requests on DBus
*/
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
// TODO(Pawel) this shall be parametrized call (two params) to get
// EthernetInterfaces for any Manager, not only hardcoded 'openbmc'.
@@ -1442,33 +1438,33 @@ class VlanNetworkInterface : public Node {
return;
}
- const std::string &parent_iface_id = params[0];
- const std::string &iface_id = params[1];
+ const std::string &parentIfaceId = params[0];
+ const std::string &ifaceId = params[1];
// Get single eth interface data, and call the below callback for JSON
// preparation
- ethernet_provider.getEthernetIfaceData(
- iface_id,
- [&, parent_iface_id, iface_id](
+ ethernetProvider.getEthernetIfaceData(
+ ifaceId,
+ [&, parentIfaceId, ifaceId](
const bool &success, const EthernetInterfaceData &eth_data,
const std::vector<IPv4AddressData> &ipv4_data) {
- if (success) {
- res.json_value = parseInterfaceData(parent_iface_id, iface_id,
+ if (success && eth_data.vlanId != nullptr) {
+ res.jsonValue = parseInterfaceData(parentIfaceId, ifaceId,
eth_data, ipv4_data);
} else {
// ... otherwise return error
// TODO(Pawel)consider distinguish between non existing object, and
// other errors
messages::addMessageToErrorJson(
- res.json_value,
- messages::resourceNotFound("VLAN Network Interface", iface_id));
+ res.jsonValue,
+ messages::resourceNotFound("VLAN Network Interface", ifaceId));
res.result(boost::beast::http::status::not_found);
}
res.end();
});
}
- void doPatch(crow::response &res, const crow::request &req,
+ void doPatch(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
if (params.size() != 2) {
res.result(boost::beast::http::status::internal_server_error);
@@ -1476,10 +1472,10 @@ class VlanNetworkInterface : public Node {
return;
}
- const std::string &parent_iface_id = params[0];
- const std::string &iface_id = params[1];
+ const std::string &parent_ifaceId = params[0];
+ const std::string &ifaceId = params[1];
- if (!verifyNames(res, parent_iface_id, iface_id)) {
+ if (!verifyNames(res, parent_ifaceId, ifaceId)) {
return;
}
@@ -1491,9 +1487,9 @@ class VlanNetworkInterface : public Node {
// Get single eth interface data, and call the below callback for JSON
// preparation
- ethernet_provider.getEthernetIfaceData(
- iface_id,
- [&, parent_iface_id, iface_id, patchReq = std::move(patchReq) ](
+ ethernetProvider.getEthernetIfaceData(
+ ifaceId,
+ [&, parent_ifaceId, ifaceId, patchReq = std::move(patchReq) ](
const bool &success, const EthernetInterfaceData &eth_data,
const std::vector<IPv4AddressData> &ipv4_data) {
if (!success) {
@@ -1502,15 +1498,15 @@ class VlanNetworkInterface : public Node {
// and
// other errors
messages::addMessageToErrorJson(
- res.json_value,
- messages::resourceNotFound("VLAN Network Interface", iface_id));
+ res.jsonValue,
+ messages::resourceNotFound("VLAN Network Interface", ifaceId));
res.result(boost::beast::http::status::not_found);
res.end();
return;
}
- res.json_value = parseInterfaceData(parent_iface_id, iface_id,
+ res.jsonValue = parseInterfaceData(parent_ifaceId, ifaceId,
eth_data, ipv4_data);
std::shared_ptr<AsyncResp> asyncResp =
@@ -1520,28 +1516,28 @@ class VlanNetworkInterface : public Node {
++propertyIt) {
if (propertyIt.key() != "VLANEnable" &&
propertyIt.key() != "VLANId") {
- auto fieldInJsonIt = res.json_value.find(propertyIt.key());
+ auto fieldInJsonIt = res.jsonValue.find(propertyIt.key());
- if (fieldInJsonIt == res.json_value.end()) {
+ if (fieldInJsonIt == res.jsonValue.end()) {
// Field not in scope of defined fields
messages::addMessageToJsonRoot(
- res.json_value,
+ res.jsonValue,
messages::propertyUnknown(propertyIt.key()));
} else if (*fieldInJsonIt != *propertyIt) {
// User attempted to modify non-writable field
messages::addMessageToJsonRoot(
- res.json_value,
+ res.jsonValue,
messages::propertyNotWritable(propertyIt.key()));
}
}
}
- EthernetInterface::handleVlanPatch(iface_id, patchReq, eth_data, "/",
+ EthernetInterface::handleVlanPatch(ifaceId, patchReq, eth_data, "/",
asyncResp);
});
}
- void doDelete(crow::response &res, const crow::request &req,
+ void doDelete(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
if (params.size() != 2) {
res.result(boost::beast::http::status::internal_server_error);
@@ -1549,30 +1545,30 @@ class VlanNetworkInterface : public Node {
return;
}
- const std::string &parent_iface_id = params[0];
- const std::string &iface_id = params[1];
+ const std::string &parent_ifaceId = params[0];
+ const std::string &ifaceId = params[1];
- if (!verifyNames(res, parent_iface_id, iface_id)) {
+ if (!verifyNames(res, parent_ifaceId, ifaceId)) {
return;
}
// Get single eth interface data, and call the below callback for JSON
// preparation
- ethernet_provider.getEthernetIfaceData(
- iface_id,
- [&, parent_iface_id, iface_id](
+ ethernetProvider.getEthernetIfaceData(
+ ifaceId,
+ [&, parent_ifaceId, ifaceId](
const bool &success, const EthernetInterfaceData &eth_data,
const std::vector<IPv4AddressData> &ipv4_data) {
- if (success && eth_data.vlan_id != nullptr) {
- res.json_value = parseInterfaceData(parent_iface_id, iface_id,
+ if (success && eth_data.vlanId != nullptr) {
+ res.jsonValue = parseInterfaceData(parent_ifaceId, ifaceId,
eth_data, ipv4_data);
// Disable VLAN
OnDemandEthernetProvider::disableVlan(
- iface_id, [&](const boost::system::error_code ec) {
+ ifaceId, [&](const boost::system::error_code ec) {
if (ec) {
- res.json_value = nlohmann::json::object();
- messages::addMessageToErrorJson(res.json_value,
+ res.jsonValue = nlohmann::json::object();
+ messages::addMessageToErrorJson(res.jsonValue,
messages::internalError());
res.result(
boost::beast::http::status::internal_server_error);
@@ -1585,8 +1581,8 @@ class VlanNetworkInterface : public Node {
// and
// other errors
messages::addMessageToErrorJson(
- res.json_value,
- messages::resourceNotFound("VLAN Network Interface", iface_id));
+ res.jsonValue,
+ messages::resourceNotFound("VLAN Network Interface", ifaceId));
res.result(boost::beast::http::status::not_found);
res.end();
}
@@ -1603,7 +1599,7 @@ class VlanNetworkInterface : public Node {
// Ethernet Provider object
// TODO(Pawel) consider move it to singleton
- OnDemandEthernetProvider ethernet_provider;
+ OnDemandEthernetProvider ethernetProvider;
};
/**
@@ -1641,7 +1637,7 @@ class VlanNetworkInterfaceCollection : public Node {
/**
* Functions triggers appropriate requests on DBus
*/
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
if (params.size() != 1) {
// This means there is a problem with the router
@@ -1653,40 +1649,40 @@ class VlanNetworkInterfaceCollection : public Node {
// TODO(Pawel) this shall be parametrized call to get EthernetInterfaces for
// any Manager, not only hardcoded 'openbmc'.
- std::string manager_id = "openbmc";
+ std::string managerId = "openbmc";
std::string rootInterfaceName = params[0];
- // Get eth interface list, and call the below callback for JSON preparation
- ethernet_provider.getEthernetIfaceList([
- &, manager_id{std::move(manager_id)},
+ // get eth interface list, and call the below callback for JSON preparation
+ ethernetProvider.getEthernetIfaceList([
+ &, managerId{std::move(managerId)},
rootInterfaceName{std::move(rootInterfaceName)}
](const bool &success, const std::vector<std::string> &iface_list) {
if (success) {
bool rootInterfaceFound = false;
- nlohmann::json iface_array = nlohmann::json::array();
+ nlohmann::json ifaceArray = nlohmann::json::array();
- for (const std::string &iface_item : iface_list) {
- if (iface_item == rootInterfaceName) {
+ for (const std::string &ifaceItem : iface_list) {
+ if (ifaceItem == rootInterfaceName) {
rootInterfaceFound = true;
- } else if (boost::starts_with(iface_item, rootInterfaceName + "_")) {
- iface_array.push_back(
- {{"@odata.id", "/redfish/v1/Managers/" + manager_id +
+ } else if (boost::starts_with(ifaceItem, rootInterfaceName + "_")) {
+ ifaceArray.push_back(
+ {{"@odata.id", "/redfish/v1/Managers/" + managerId +
"/EthernetInterfaces/" + rootInterfaceName +
- "/VLANs/" + iface_item}});
+ "/VLANs/" + ifaceItem}});
}
}
if (rootInterfaceFound) {
- Node::json["Members"] = iface_array;
- Node::json["Members@odata.count"] = iface_array.size();
- Node::json["@odata.id"] = "/redfish/v1/Managers/" + manager_id +
+ Node::json["Members"] = ifaceArray;
+ Node::json["Members@odata.count"] = ifaceArray.size();
+ Node::json["@odata.id"] = "/redfish/v1/Managers/" + managerId +
"/EthernetInterfaces/" + rootInterfaceName +
"/VLANs";
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
} else {
messages::addMessageToErrorJson(
- res.json_value, messages::resourceNotFound("EthernetInterface",
- rootInterfaceName));
+ res.jsonValue, messages::resourceNotFound("EthernetInterface",
+ rootInterfaceName));
res.result(boost::beast::http::status::not_found);
res.end();
}
@@ -1698,7 +1694,7 @@ class VlanNetworkInterfaceCollection : public Node {
});
}
- void doPost(crow::response &res, const crow::request &req,
+ void doPost(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
if (params.size() != 1) {
// This means there is a problem with the router
@@ -1715,7 +1711,7 @@ class VlanNetworkInterfaceCollection : public Node {
// TODO(Pawel) this shall be parametrized call to get EthernetInterfaces for
// any Manager, not only hardcoded 'openbmc'.
- std::string manager_id = "openbmc";
+ std::string managerId = "openbmc";
std::string rootInterfaceName = params[0];
uint64_t vlanId;
bool errorDetected;
@@ -1724,33 +1720,33 @@ class VlanNetworkInterfaceCollection : public Node {
"VLANId", postReq, vlanId,
static_cast<uint8_t>(json_util::MessageSetting::MISSING) |
static_cast<uint8_t>(json_util::MessageSetting::TYPE_ERROR),
- res.json_value, "/VLANId") != json_util::Result::SUCCESS) {
+ res.jsonValue, "/VLANId") != json_util::Result::SUCCESS) {
res.end();
return;
}
- // Get eth interface list, and call the below callback for JSON preparation
- ethernet_provider.getEthernetIfaceList([
- &, manager_id{std::move(manager_id)},
+ // get eth interface list, and call the below callback for JSON preparation
+ ethernetProvider.getEthernetIfaceList([
+ &, managerId{std::move(managerId)},
rootInterfaceName{std::move(rootInterfaceName)}
](const bool &success, const std::vector<std::string> &iface_list) {
if (success) {
bool rootInterfaceFound = false;
- for (const std::string &iface_item : iface_list) {
- if (iface_item == rootInterfaceName) {
+ for (const std::string &ifaceItem : iface_list) {
+ if (ifaceItem == rootInterfaceName) {
rootInterfaceFound = true;
break;
}
}
if (rootInterfaceFound) {
- ethernet_provider.createVlan(
+ ethernetProvider.createVlan(
rootInterfaceName, vlanId,
[&, vlanId, rootInterfaceName,
req{std::move(req)} ](const boost::system::error_code ec) {
if (ec) {
- messages::addMessageToErrorJson(res.json_value,
+ messages::addMessageToErrorJson(res.jsonValue,
messages::internalError());
res.end();
} else {
@@ -1762,8 +1758,8 @@ class VlanNetworkInterfaceCollection : public Node {
});
} else {
messages::addMessageToErrorJson(
- res.json_value, messages::resourceNotFound("EthernetInterface",
- rootInterfaceName));
+ res.jsonValue, messages::resourceNotFound("EthernetInterface",
+ rootInterfaceName));
res.result(boost::beast::http::status::not_found);
res.end();
}
@@ -1777,7 +1773,7 @@ class VlanNetworkInterfaceCollection : public Node {
// Ethernet Provider object
// TODO(Pawel) consider move it to singleton
- OnDemandEthernetProvider ethernet_provider;
+ OnDemandEthernetProvider ethernetProvider;
VlanNetworkInterface memberVlan;
};
diff --git a/redfish-core/lib/managers.hpp b/redfish-core/lib/managers.hpp
index c8609b441a..daee36a743 100644
--- a/redfish-core/lib/managers.hpp
+++ b/redfish-core/lib/managers.hpp
@@ -30,8 +30,8 @@ class Manager : public Node {
Node::json["Description"] = "Baseboard Management Controller";
Node::json["PowerState"] = "On";
Node::json["UUID"] =
- app.template get_middleware<crow::PersistentData::Middleware>()
- .system_uuid;
+ app.template getMiddleware<crow::persistent_data::Middleware>()
+ .systemUuid;
Node::json["Model"] = "OpenBmc"; // TODO(ed), get model
Node::json["FirmwareVersion"] = "1234456789"; // TODO(ed), get fwversion
Node::json["EthernetInterfaces"] = nlohmann::json(
@@ -52,10 +52,11 @@ class Manager : public Node {
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
Node::json["DateTime"] = getDateTime();
- res.json_value = Node::json;
+ // Copy over the static data to include the entries added by SubRoute
+ res.jsonValue = Node::json;
res.end();
}
@@ -96,9 +97,18 @@ class ManagerCollection : public Node {
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
- res.json_value = Node::json;
+ // Collections don't include the static data added by SubRoute because it
+ // has a duplicate entry for members
+ res.jsonValue["@odata.id"] = "/redfish/v1/Managers";
+ res.jsonValue["@odata.type"] = "#ManagerCollection.ManagerCollection";
+ res.jsonValue["@odata.context"] =
+ "/redfish/v1/$metadata#ManagerCollection.ManagerCollection";
+ res.jsonValue["Name"] = "Manager Collection";
+ res.jsonValue["Members@odata.count"] = 1;
+ res.jsonValue["Members"] = {
+ {{"@odata.id", "/redfish/v1/Managers/openbmc"}}};
res.end();
}
diff --git a/redfish-core/lib/network_protocol.hpp b/redfish-core/lib/network_protocol.hpp
index d7bf1016ad..235b2b8828 100644
--- a/redfish-core/lib/network_protocol.hpp
+++ b/redfish-core/lib/network_protocol.hpp
@@ -45,11 +45,11 @@ class NetworkProtocol : public Node {
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
refreshProtocolsState();
Node::json["HostName"] = getHostName();
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
res.end();
}
diff --git a/redfish-core/lib/redfish_sessions.hpp b/redfish-core/lib/redfish_sessions.hpp
index 9e793df049..a32a660754 100644
--- a/redfish-core/lib/redfish_sessions.hpp
+++ b/redfish-core/lib/redfish_sessions.hpp
@@ -42,52 +42,52 @@ class Sessions : public Node {
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
auto session =
- crow::PersistentData::SessionStore::getInstance().get_session_by_uid(
+ crow::persistent_data::SessionStore::getInstance().getSessionByUid(
params[0]);
if (session == nullptr) {
messages::addMessageToErrorJson(
- res.json_value, messages::resourceNotFound("Session", params[0]));
+ res.jsonValue, messages::resourceNotFound("Session", params[0]));
res.result(boost::beast::http::status::not_found);
res.end();
return;
}
- Node::json["Id"] = session->unique_id;
+ Node::json["Id"] = session->uniqueId;
Node::json["UserName"] = session->username;
Node::json["@odata.id"] =
- "/redfish/v1/SessionService/Sessions/" + session->unique_id;
+ "/redfish/v1/SessionService/Sessions/" + session->uniqueId;
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
res.end();
}
- void doDelete(crow::response& res, const crow::request& req,
+ void doDelete(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
// Need only 1 param which should be id of session to be deleted
if (params.size() != 1) {
// This should be handled by crow and never happen
- CROW_LOG_ERROR
+ BMCWEB_LOG_ERROR
<< "Session DELETE has been called with invalid number of params";
res.result(boost::beast::http::status::bad_request);
- messages::addMessageToErrorJson(res.json_value, messages::generalError());
+ messages::addMessageToErrorJson(res.jsonValue, messages::generalError());
res.end();
return;
}
auto session =
- crow::PersistentData::SessionStore::getInstance().get_session_by_uid(
+ crow::persistent_data::SessionStore::getInstance().getSessionByUid(
params[0]);
if (session == nullptr) {
messages::addMessageToErrorJson(
- res.json_value, messages::resourceNotFound("Session", params[0]));
+ res.jsonValue, messages::resourceNotFound("Session", params[0]));
res.result(boost::beast::http::status::not_found);
res.end();
@@ -97,7 +97,7 @@ class Sessions : public Node {
// DELETE should return representation of object that will be removed
doGet(res, req, params);
- crow::PersistentData::SessionStore::getInstance().remove_session(session);
+ crow::persistent_data::SessionStore::getInstance().removeSession(session);
}
/**
@@ -131,29 +131,29 @@ class SessionCollection : public Node {
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
- std::vector<const std::string*> session_ids =
- crow::PersistentData::SessionStore::getInstance().get_unique_ids(
- false, crow::PersistentData::PersistenceType::TIMEOUT);
+ std::vector<const std::string*> sessionIds =
+ crow::persistent_data::SessionStore::getInstance().getUniqueIds(
+ false, crow::persistent_data::PersistenceType::TIMEOUT);
- Node::json["Members@odata.count"] = session_ids.size();
+ Node::json["Members@odata.count"] = sessionIds.size();
Node::json["Members"] = nlohmann::json::array();
- for (const std::string* uid : session_ids) {
+ for (const std::string* uid : sessionIds) {
Node::json["Members"].push_back(
{{"@odata.id", "/redfish/v1/SessionService/Sessions/" + *uid}});
}
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
res.end();
}
- void doPost(crow::response& res, const crow::request& req,
+ void doPost(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
boost::beast::http::status status;
std::string username;
bool userAuthSuccessful =
- authenticateUser(req, status, username, res.json_value);
+ authenticateUser(req, status, username, res.jsonValue);
res.result(status);
if (!userAuthSuccessful) {
@@ -163,12 +163,12 @@ class SessionCollection : public Node {
// User is authenticated - create session for him
auto session =
- crow::PersistentData::SessionStore::getInstance().generate_user_session(
+ crow::persistent_data::SessionStore::getInstance().generateUserSession(
username);
- res.add_header("X-Auth-Token", session->session_token);
+ res.addHeader("X-Auth-Token", session->sessionToken);
// Return data for created session
- memberSession.doGet(res, req, {session->unique_id});
+ memberSession.doGet(res, req, {session->uniqueId});
// No need for res.end(), as it is called by doGet()
}
@@ -183,15 +183,15 @@ class SessionCollection : public Node {
*
* @return true if authentication was successful, false otherwise
*/
- bool authenticateUser(const crow::request& req,
+ bool authenticateUser(const crow::Request& req,
boost::beast::http::status& httpRespCode,
std::string& user, nlohmann::json& errJson) {
// We need only UserName and Password - nothing more, nothing less
static constexpr const unsigned int numberOfRequiredFieldsInReq = 2;
// call with exceptions disabled
- auto login_credentials = nlohmann::json::parse(req.body, nullptr, false);
- if (login_credentials.is_discarded()) {
+ auto loginCredentials = nlohmann::json::parse(req.body, nullptr, false);
+ if (loginCredentials.is_discarded()) {
httpRespCode = boost::beast::http::status::bad_request;
messages::addMessageToErrorJson(errJson, messages::malformedJSON());
@@ -200,7 +200,7 @@ class SessionCollection : public Node {
}
// Check that there are only as many fields as there should be
- if (login_credentials.size() != numberOfRequiredFieldsInReq) {
+ if (loginCredentials.size() != numberOfRequiredFieldsInReq) {
httpRespCode = boost::beast::http::status::bad_request;
messages::addMessageToErrorJson(errJson, messages::malformedJSON());
@@ -209,18 +209,17 @@ class SessionCollection : public Node {
}
// Find fields that we need - UserName and Password
- auto user_it = login_credentials.find("UserName");
- auto pass_it = login_credentials.find("Password");
- if (user_it == login_credentials.end() ||
- pass_it == login_credentials.end()) {
+ auto userIt = loginCredentials.find("UserName");
+ auto passIt = loginCredentials.find("Password");
+ if (userIt == loginCredentials.end() || passIt == loginCredentials.end()) {
httpRespCode = boost::beast::http::status::bad_request;
- if (user_it == login_credentials.end()) {
+ if (userIt == loginCredentials.end()) {
messages::addMessageToErrorJson(errJson,
messages::propertyMissing("UserName"));
}
- if (pass_it == login_credentials.end()) {
+ if (passIt == loginCredentials.end()) {
messages::addMessageToErrorJson(errJson,
messages::propertyMissing("Password"));
}
@@ -229,27 +228,27 @@ class SessionCollection : public Node {
}
// Check that given data is of valid type (string)
- if (!user_it->is_string() || !pass_it->is_string()) {
+ if (!userIt->is_string() || !passIt->is_string()) {
httpRespCode = boost::beast::http::status::bad_request;
- if (!user_it->is_string()) {
+ if (!userIt->is_string()) {
messages::addMessageToErrorJson(
errJson,
- messages::propertyValueTypeError(user_it->dump(), "UserName"));
+ messages::propertyValueTypeError(userIt->dump(), "UserName"));
}
- if (!pass_it->is_string()) {
+ if (!passIt->is_string()) {
messages::addMessageToErrorJson(
errJson,
- messages::propertyValueTypeError(user_it->dump(), "Password"));
+ messages::propertyValueTypeError(userIt->dump(), "Password"));
}
return false;
}
// Extract username and password
- std::string username = user_it->get<const std::string>();
- std::string password = pass_it->get<const std::string>();
+ std::string username = userIt->get<const std::string>();
+ std::string password = passIt->get<const std::string>();
// Verify that required fields are not empty
if (username.empty() || password.empty()) {
@@ -269,7 +268,7 @@ class SessionCollection : public Node {
}
// Finally - try to authenticate user
- if (!pam_authenticate_user(username, password)) {
+ if (!pamAuthenticateUser(username, password)) {
httpRespCode = boost::beast::http::status::unauthorized;
messages::addMessageToErrorJson(
@@ -304,8 +303,8 @@ class SessionService : public Node {
Node::json["Id"] = "SessionService";
Node::json["Description"] = "Session Service";
Node::json["SessionTimeout"] =
- crow::PersistentData::SessionStore::getInstance()
- .get_timeout_in_seconds();
+ crow::persistent_data::SessionStore::getInstance()
+ .getTimeoutInSeconds();
Node::json["ServiceEnabled"] = true;
entityPrivileges = {
@@ -318,9 +317,9 @@ class SessionService : public Node {
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
res.end();
}
};
diff --git a/redfish-core/lib/roles.hpp b/redfish-core/lib/roles.hpp
index f538c834f5..72d79486bb 100644
--- a/redfish-core/lib/roles.hpp
+++ b/redfish-core/lib/roles.hpp
@@ -34,18 +34,19 @@ class Roles : public Node {
"ConfigureUsers", "ConfigureSelf",
"ConfigureComponents"};
Node::json["OemPrivileges"] = nlohmann::json::array();
- entityPrivileges = {{boost::beast::http::verb::get, {{"Login"}}},
- {boost::beast::http::verb::head, {{"Login"}}},
- {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
- {boost::beast::http::verb::put, {{"ConfigureManager"}}},
- {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
- {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
+ entityPrivileges = {
+ {boost::beast::http::verb::get, {{"Login"}}},
+ {boost::beast::http::verb::head, {{"Login"}}},
+ {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
+ {boost::beast::http::verb::put, {{"ConfigureManager"}}},
+ {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
+ {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
res.end();
}
};
@@ -64,23 +65,24 @@ class RoleCollection : public Node {
Node::json["Members"] = {
{{"@odata.id", "/redfish/v1/AccountService/Roles/Administrator"}}};
- entityPrivileges = {{boost::beast::http::verb::get, {{"Login"}}},
- {boost::beast::http::verb::head, {{"Login"}}},
- {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
- {boost::beast::http::verb::put, {{"ConfigureManager"}}},
- {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
- {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
+ entityPrivileges = {
+ {boost::beast::http::verb::get, {{"Login"}}},
+ {boost::beast::http::verb::head, {{"Login"}}},
+ {boost::beast::http::verb::patch, {{"ConfigureManager"}}},
+ {boost::beast::http::verb::put, {{"ConfigureManager"}}},
+ {boost::beast::http::verb::delete_, {{"ConfigureManager"}}},
+ {boost::beast::http::verb::post, {{"ConfigureManager"}}}};
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
// This is a short term solution to work around a bug. GetSubroutes
// accidentally recognizes the Roles/Administrator route as a subroute
// (because it's hardcoded to a single entity). Remove this line when that
// is resolved
- res.json_value.erase("Administrator");
+ res.jsonValue.erase("Administrator");
res.end();
}
};
diff --git a/redfish-core/lib/sensors.hpp b/redfish-core/lib/sensors.hpp
index 727fa9f2c7..9aa1da4cc8 100644
--- a/redfish-core/lib/sensors.hpp
+++ b/redfish-core/lib/sensors.hpp
@@ -43,10 +43,10 @@ using ManagedObjectsVectorType = std::vector<std::pair<
*/
class SensorsAsyncResp {
public:
- SensorsAsyncResp(crow::response& response, const std::string& chassisId,
+ SensorsAsyncResp(crow::Response& response, const std::string& chassisId,
const std::initializer_list<const char*> types)
: res(response), chassisId(chassisId), types(types) {
- res.json_value["@odata.id"] =
+ res.jsonValue["@odata.id"] =
"/redfish/v1/Chassis/" + chassisId + "/Thermal";
}
@@ -55,7 +55,7 @@ class SensorsAsyncResp {
// Reset the json object to clear out any data that made it in before the
// error happened
// todo(ed) handle error condition with proper code
- res.json_value = nlohmann::json::object();
+ res.jsonValue = nlohmann::json::object();
}
res.end();
}
@@ -64,7 +64,7 @@ class SensorsAsyncResp {
res.result(boost::beast::http::status::internal_server_error);
}
- crow::response& res;
+ crow::Response& res;
std::string chassisId{};
const std::vector<const char*> types;
};
@@ -79,23 +79,23 @@ template <typename Callback>
void getConnections(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp,
const boost::container::flat_set<std::string>& sensorNames,
Callback&& callback) {
- CROW_LOG_DEBUG << "getConnections enter";
+ BMCWEB_LOG_DEBUG << "getConnections enter";
const std::string path = "/xyz/openbmc_project/sensors";
const std::array<std::string, 1> interfaces = {
"xyz.openbmc_project.Sensor.Value"};
// Response handler for parsing objects subtree
- auto resp_handler =
+ auto respHandler =
[ callback{std::move(callback)}, SensorsAsyncResp, sensorNames ](
const boost::system::error_code ec, const GetSubTreeType& subtree) {
- CROW_LOG_DEBUG << "getConnections resp_handler enter";
+ BMCWEB_LOG_DEBUG << "getConnections resp_handler enter";
if (ec) {
SensorsAsyncResp->setErrorStatus();
- CROW_LOG_ERROR << "getConnections resp_handler: Dbus error " << ec;
+ BMCWEB_LOG_ERROR << "getConnections resp_handler: Dbus error " << ec;
return;
}
- CROW_LOG_DEBUG << "Found " << subtree.size() << " subtrees";
+ BMCWEB_LOG_DEBUG << "Found " << subtree.size() << " subtrees";
// Make unique list of connections only for requested sensor types and
// found in the chassis
@@ -103,9 +103,9 @@ void getConnections(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp,
// Intrinsic to avoid malloc. Most systems will have < 8 sensor producers
connections.reserve(8);
- CROW_LOG_DEBUG << "sensorNames list count: " << sensorNames.size();
+ BMCWEB_LOG_DEBUG << "sensorNames list count: " << sensorNames.size();
for (const std::string& tsensor : sensorNames) {
- CROW_LOG_DEBUG << "Sensor to find: " << tsensor;
+ BMCWEB_LOG_DEBUG << "Sensor to find: " << tsensor;
}
for (const std::pair<
@@ -119,10 +119,10 @@ void getConnections(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp,
std::string sensorName = object.first.substr(lastPos + 1);
if (sensorNames.find(sensorName) != sensorNames.end()) {
- // For each connection name
+ // For each Connection name
for (const std::pair<std::string, std::vector<std::string>>&
objData : object.second) {
- CROW_LOG_DEBUG << "Adding connection: " << objData.first;
+ BMCWEB_LOG_DEBUG << "Adding connection: " << objData.first;
connections.insert(objData.first);
}
}
@@ -131,17 +131,17 @@ void getConnections(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp,
}
}
}
- CROW_LOG_DEBUG << "Found " << connections.size() << " connections";
+ BMCWEB_LOG_DEBUG << "Found " << connections.size() << " connections";
callback(std::move(connections));
- CROW_LOG_DEBUG << "getConnections resp_handler exit";
+ BMCWEB_LOG_DEBUG << "getConnections resp_handler exit";
};
// Make call to ObjectMapper to find all sensors objects
- crow::connections::system_bus->async_method_call(
- std::move(resp_handler), "xyz.openbmc_project.ObjectMapper",
+ crow::connections::systemBus->async_method_call(
+ std::move(respHandler), "xyz.openbmc_project.ObjectMapper",
"/xyz/openbmc_project/object_mapper", "xyz.openbmc_project.ObjectMapper",
"GetSubTree", path, 2, interfaces);
- CROW_LOG_DEBUG << "getConnections exit";
+ BMCWEB_LOG_DEBUG << "getConnections exit";
}
/**
@@ -152,13 +152,13 @@ void getConnections(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp,
template <typename Callback>
void getChassis(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp,
Callback&& callback) {
- CROW_LOG_DEBUG << "getChassis enter";
+ BMCWEB_LOG_DEBUG << "getChassis enter";
// Process response from EntityManager and extract chassis data
- auto resp_handler = [ callback{std::move(callback)}, SensorsAsyncResp ](
+ auto respHandler = [ callback{std::move(callback)}, SensorsAsyncResp ](
const boost::system::error_code ec, ManagedObjectsVectorType& resp) {
- CROW_LOG_DEBUG << "getChassis resp_handler enter";
+ BMCWEB_LOG_DEBUG << "getChassis respHandler enter";
if (ec) {
- CROW_LOG_ERROR << "getChassis resp_handler DBUS error: " << ec;
+ BMCWEB_LOG_ERROR << "getChassis respHandler DBUS error: " << ec;
SensorsAsyncResp->setErrorStatus();
return;
}
@@ -176,7 +176,7 @@ void getChassis(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp,
static_cast<const std::string&>(objDictEntry.first);
boost::algorithm::split(split, objectPath, boost::is_any_of("/"));
if (split.size() < 2) {
- CROW_LOG_ERROR << "Got path that isn't long enough " << objectPath;
+ BMCWEB_LOG_ERROR << "Got path that isn't long enough " << objectPath;
split.clear();
continue;
}
@@ -187,28 +187,28 @@ void getChassis(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp,
split.clear();
continue;
}
- CROW_LOG_DEBUG << "New sensor: " << sensorName;
+ BMCWEB_LOG_DEBUG << "New sensor: " << sensorName;
foundChassis = true;
sensorNames.emplace(sensorName);
split.clear();
};
- CROW_LOG_DEBUG << "Found " << sensorNames.size() << " Sensor names";
+ BMCWEB_LOG_DEBUG << "Found " << sensorNames.size() << " Sensor names";
if (!foundChassis) {
- CROW_LOG_INFO << "Unable to find chassis named "
- << SensorsAsyncResp->chassisId;
+ BMCWEB_LOG_INFO << "Unable to find chassis named "
+ << SensorsAsyncResp->chassisId;
SensorsAsyncResp->res.result(boost::beast::http::status::not_found);
} else {
callback(sensorNames);
}
- CROW_LOG_DEBUG << "getChassis resp_handler exit";
+ BMCWEB_LOG_DEBUG << "getChassis respHandler exit";
};
// Make call to EntityManager to find all chassis objects
- crow::connections::system_bus->async_method_call(
- resp_handler, "xyz.openbmc_project.EntityManager", "/",
+ crow::connections::systemBus->async_method_call(
+ respHandler, "xyz.openbmc_project.EntityManager", "/",
"org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
- CROW_LOG_DEBUG << "getChassis exit";
+ BMCWEB_LOG_DEBUG << "getChassis exit";
}
/**
@@ -227,20 +227,19 @@ void objectInterfacesToJson(
interfacesDict,
nlohmann::json& sensor_json) {
// We need a value interface before we can do anything with it
- auto value_it = interfacesDict.find("xyz.openbmc_project.Sensor.Value");
- if (value_it == interfacesDict.end()) {
- CROW_LOG_ERROR << "Sensor doesn't have a value interface";
+ auto valueIt = interfacesDict.find("xyz.openbmc_project.Sensor.Value");
+ if (valueIt == interfacesDict.end()) {
+ BMCWEB_LOG_ERROR << "Sensor doesn't have a value interface";
return;
}
// Assume values exist as is (10^0 == 1) if no scale exists
int64_t scaleMultiplier = 0;
- auto scale_it = value_it->second.find("Scale");
+ auto scaleIt = valueIt->second.find("Scale");
// If a scale exists, pull value as int64, and use the scaling.
- if (scale_it != value_it->second.end()) {
- const int64_t* int64Value =
- mapbox::get_ptr<const int64_t>(scale_it->second);
+ if (scaleIt != valueIt->second.end()) {
+ const int64_t* int64Value = mapbox::getPtr<const int64_t>(scaleIt->second);
if (int64Value != nullptr) {
scaleMultiplier = *int64Value;
}
@@ -271,7 +270,7 @@ void objectInterfacesToJson(
unit = "ReadingVolts";
sensor_json["@odata.type"] = "#Power.v1_0_0.Voltage";
} else {
- CROW_LOG_ERROR << "Redfish cannot map object type for " << sensorName;
+ BMCWEB_LOG_ERROR << "Redfish cannot map object type for " << sensorName;
return;
}
// Map of dbus interface name, dbus property name and redfish property_name
@@ -304,39 +303,38 @@ void objectInterfacesToJson(
properties) {
auto interfaceProperties = interfacesDict.find(std::get<0>(p));
if (interfaceProperties != interfacesDict.end()) {
- auto value_it = interfaceProperties->second.find(std::get<1>(p));
- if (value_it != interfaceProperties->second.end()) {
- const SensorVariant& valueVariant = value_it->second;
- nlohmann::json& value_it = sensor_json[std::get<2>(p)];
+ auto valueIt = interfaceProperties->second.find(std::get<1>(p));
+ if (valueIt != interfaceProperties->second.end()) {
+ const SensorVariant& valueVariant = valueIt->second;
+ nlohmann::json& valueIt = sensor_json[std::get<2>(p)];
// Attempt to pull the int64 directly
- const int64_t* int64Value =
- mapbox::get_ptr<const int64_t>(valueVariant);
+ const int64_t* int64Value = mapbox::getPtr<const int64_t>(valueVariant);
if (int64Value != nullptr) {
if (forceToInt || scaleMultiplier >= 0) {
- value_it = *int64Value * std::pow(10, scaleMultiplier);
+ valueIt = *int64Value * std::pow(10, scaleMultiplier);
} else {
- value_it = *int64Value *
- std::pow(10, static_cast<double>(scaleMultiplier));
+ valueIt = *int64Value *
+ std::pow(10, static_cast<double>(scaleMultiplier));
}
}
// Attempt to pull the float directly
- const double* doubleValue = mapbox::get_ptr<const double>(valueVariant);
+ const double* doubleValue = mapbox::getPtr<const double>(valueVariant);
if (doubleValue != nullptr) {
if (!forceToInt) {
- value_it = *doubleValue *
- std::pow(10, static_cast<double>(scaleMultiplier));
+ valueIt = *doubleValue *
+ std::pow(10, static_cast<double>(scaleMultiplier));
} else {
- value_it = static_cast<int64_t>(*doubleValue *
- std::pow(10, scaleMultiplier));
+ valueIt = static_cast<int64_t>(*doubleValue *
+ std::pow(10, scaleMultiplier));
}
}
}
}
}
- CROW_LOG_DEBUG << "Added sensor " << sensorName;
+ BMCWEB_LOG_DEBUG << "Added sensor " << sensorName;
}
/**
@@ -345,24 +343,24 @@ void objectInterfacesToJson(
* @param SensorsAsyncResp Pointer to object holding response data
*/
void getChassisData(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp) {
- CROW_LOG_DEBUG << "getChassisData enter";
+ BMCWEB_LOG_DEBUG << "getChassisData enter";
auto getChassisCb = [&, SensorsAsyncResp](
boost::container::flat_set<std::string>&
sensorNames) {
- CROW_LOG_DEBUG << "getChassisCb enter";
+ BMCWEB_LOG_DEBUG << "getChassisCb enter";
auto getConnectionCb =
[&, SensorsAsyncResp, sensorNames](
const boost::container::flat_set<std::string>& connections) {
- CROW_LOG_DEBUG << "getConnectionCb enter";
+ BMCWEB_LOG_DEBUG << "getConnectionCb enter";
// Get managed objects from all services exposing sensors
for (const std::string& connection : connections) {
// Response handler to process managed objects
auto getManagedObjectsCb = [&, SensorsAsyncResp, sensorNames](
const boost::system::error_code ec,
ManagedObjectsVectorType& resp) {
- CROW_LOG_DEBUG << "getManagedObjectsCb enter";
+ BMCWEB_LOG_DEBUG << "getManagedObjectsCb enter";
if (ec) {
- CROW_LOG_ERROR << "getManagedObjectsCb DBUS error: " << ec;
+ BMCWEB_LOG_ERROR << "getManagedObjectsCb DBUS error: " << ec;
SensorsAsyncResp->setErrorStatus();
return;
}
@@ -371,8 +369,8 @@ void getChassisData(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp) {
for (const auto& objDictEntry : resp) {
const std::string& objPath =
static_cast<const std::string&>(objDictEntry.first);
- CROW_LOG_DEBUG << "getManagedObjectsCb parsing object "
- << objPath;
+ BMCWEB_LOG_DEBUG << "getManagedObjectsCb parsing object "
+ << objPath;
std::vector<std::string> split;
// Reserve space for
@@ -380,18 +378,18 @@ void getChassisData(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp) {
split.reserve(6);
boost::algorithm::split(split, objPath, boost::is_any_of("/"));
if (split.size() < 6) {
- CROW_LOG_ERROR << "Got path that isn't long enough "
- << objPath;
+ BMCWEB_LOG_ERROR << "Got path that isn't long enough "
+ << objPath;
continue;
}
// These indexes aren't intuitive, as boost::split puts an empty
// string at the beggining
const std::string& sensorType = split[4];
const std::string& sensorName = split[5];
- CROW_LOG_DEBUG << "sensorName " << sensorName << " sensorType "
- << sensorType;
+ BMCWEB_LOG_DEBUG << "sensorName " << sensorName
+ << " sensorType " << sensorType;
if (sensorNames.find(sensorName) == sensorNames.end()) {
- CROW_LOG_ERROR << sensorName << " not in sensor list ";
+ BMCWEB_LOG_ERROR << sensorName << " not in sensor list ";
continue;
}
@@ -407,43 +405,43 @@ void getChassisData(std::shared_ptr<SensorsAsyncResp> SensorsAsyncResp) {
} else if (sensorType == "power") {
fieldName = "PowerSupply";
} else {
- CROW_LOG_ERROR << "Unsure how to handle sensorType "
- << sensorType;
+ BMCWEB_LOG_ERROR << "Unsure how to handle sensorType "
+ << sensorType;
continue;
}
- nlohmann::json& temp_array =
- SensorsAsyncResp->res.json_value[fieldName];
+ nlohmann::json& tempArray =
+ SensorsAsyncResp->res.jsonValue[fieldName];
// Create the array if it doesn't yet exist
- if (temp_array.is_array() == false) {
- temp_array = nlohmann::json::array();
+ if (tempArray.is_array() == false) {
+ tempArray = nlohmann::json::array();
}
- temp_array.push_back(
+ tempArray.push_back(
{{"@odata.id", "/redfish/v1/Chassis/" +
SensorsAsyncResp->chassisId +
"/Thermal#/" + sensorName}});
- nlohmann::json& sensor_json = temp_array.back();
+ nlohmann::json& sensorJson = tempArray.back();
objectInterfacesToJson(sensorName, sensorType,
- objDictEntry.second, sensor_json);
+ objDictEntry.second, sensorJson);
}
- CROW_LOG_DEBUG << "getManagedObjectsCb exit";
+ BMCWEB_LOG_DEBUG << "getManagedObjectsCb exit";
};
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
getManagedObjectsCb, connection, "/",
"org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
};
- CROW_LOG_DEBUG << "getConnectionCb exit";
+ BMCWEB_LOG_DEBUG << "getConnectionCb exit";
};
- // Get connections and then pass it to get sensors
+ // get connections and then pass it to get sensors
getConnections(SensorsAsyncResp, sensorNames, std::move(getConnectionCb));
- CROW_LOG_DEBUG << "getChassisCb exit";
+ BMCWEB_LOG_DEBUG << "getChassisCb exit";
};
- // Get chassis information related to sensors
+ // get chassis information related to sensors
getChassis(SensorsAsyncResp, std::move(getChassisCb));
- CROW_LOG_DEBUG << "getChassisData exit";
+ BMCWEB_LOG_DEBUG << "getChassisData exit";
};
} // namespace redfish
diff --git a/redfish-core/lib/service_root.hpp b/redfish-core/lib/service_root.hpp
index d6cf44e784..6fa9632c9b 100644
--- a/redfish-core/lib/service_root.hpp
+++ b/redfish-core/lib/service_root.hpp
@@ -33,7 +33,7 @@ class ServiceRoot : public Node {
Node::json["Links"]["Sessions"] = {
{"@odata.id", "/redfish/v1/SessionService/Sessions"}};
- Node::json["UUID"] = get_uuid();
+ Node::json["UUID"] = getUuid();
entityPrivileges = {
{boost::beast::http::verb::get, {}},
@@ -45,13 +45,13 @@ class ServiceRoot : public Node {
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
res.end();
}
- const std::string get_uuid() {
+ const std::string getUuid() {
// If we are using a version of systemd that can get the app specific uuid,
// use that
#ifdef sd_id128_get_machine_app_specific
diff --git a/redfish-core/lib/systems.hpp b/redfish-core/lib/systems.hpp
index 7619f14708..668e6a92be 100644
--- a/redfish-core/lib/systems.hpp
+++ b/redfish-core/lib/systems.hpp
@@ -28,14 +28,14 @@ namespace redfish {
*/
class SystemAsyncResp {
public:
- SystemAsyncResp(crow::response &response) : res(response) {}
+ SystemAsyncResp(crow::Response &response) : res(response) {}
~SystemAsyncResp() {
if (res.result() != (boost::beast::http::status::ok)) {
// Reset the json object to clear out any data that made it in before the
// error happened
// todo(ed) handle error condition with proper code
- res.json_value = messages::internalError();
+ res.jsonValue = messages::internalError();
}
res.end();
}
@@ -44,7 +44,7 @@ class SystemAsyncResp {
res.result(boost::beast::http::status::internal_server_error);
}
- crow::response &res;
+ crow::Response &res;
};
/**
@@ -63,8 +63,8 @@ class OnDemandSystemsProvider {
public:
template <typename CallbackFunc>
void getBaseboardList(CallbackFunc &&callback) {
- CROW_LOG_DEBUG << "Get list of available boards.";
- crow::connections::system_bus->async_method_call(
+ BMCWEB_LOG_DEBUG << "Get list of available boards.";
+ crow::connections::systemBus->async_method_call(
[callback{std::move(callback)}](const boost::system::error_code ec,
const std::vector<std::string> &resp) {
// Callback requires vector<string> to retrieve all available board
@@ -78,7 +78,7 @@ class OnDemandSystemsProvider {
callback(false, board_list);
return;
}
- CROW_LOG_DEBUG << "Got " << resp.size() << " boards.";
+ BMCWEB_LOG_DEBUG << "Got " << resp.size() << " boards.";
// Iterate over all retrieved ObjectPaths.
for (const std::string &objpath : resp) {
std::size_t last_pos = objpath.rfind("/");
@@ -114,8 +114,8 @@ class OnDemandSystemsProvider {
"xyz.openbmc_project.Inventory.Item.System",
"xyz.openbmc_project.Common.UUID",
};
- CROW_LOG_DEBUG << "Get available system components.";
- crow::connections::system_bus->async_method_call(
+ BMCWEB_LOG_DEBUG << "Get available system components.";
+ crow::connections::systemBus->async_method_call(
[ name, aResp{std::move(aResp)} ](
const boost::system::error_code ec,
const std::vector<std::pair<
@@ -123,7 +123,7 @@ class OnDemandSystemsProvider {
std::vector<std::pair<std::string, std::vector<std::string>>>>>
&subtree) {
if (ec) {
- CROW_LOG_DEBUG << "DBUS response error";
+ BMCWEB_LOG_DEBUG << "DBUS response error";
aResp->setErrorStatus();
return;
}
@@ -134,7 +134,7 @@ class OnDemandSystemsProvider {
std::vector<std::string>>>>
&object : subtree) {
const std::string &path = object.first;
- CROW_LOG_DEBUG << "Got path: " << path;
+ BMCWEB_LOG_DEBUG << "Got path: " << path;
const std::vector<std::pair<std::string, std::vector<std::string>>>
&connectionNames = object.second;
if (connectionNames.size() < 1) {
@@ -143,31 +143,31 @@ class OnDemandSystemsProvider {
// Check if computer system exist
if (boost::ends_with(path, name)) {
foundName = true;
- CROW_LOG_DEBUG << "Found name: " << name;
+ BMCWEB_LOG_DEBUG << "Found name: " << name;
const std::string connectionName = connectionNames[0].first;
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[ aResp, name(std::string(name)) ](
const boost::system::error_code ec,
const std::vector<std::pair<std::string, VariantType>>
&propertiesList) {
if (ec) {
- CROW_LOG_ERROR << "DBUS response error: " << ec;
+ BMCWEB_LOG_ERROR << "DBUS response error: " << ec;
aResp->setErrorStatus();
return;
}
- CROW_LOG_DEBUG << "Got " << propertiesList.size()
+ BMCWEB_LOG_DEBUG << "Got " << propertiesList.size()
<< "properties for system";
for (const std::pair<std::string, VariantType> &property :
propertiesList) {
const std::string *value =
- mapbox::get_ptr<const std::string>(property.second);
+ mapbox::getPtr<const std::string>(property.second);
if (value != nullptr) {
- aResp->res.json_value[property.first] = *value;
+ aResp->res.jsonValue[property.first] = *value;
}
}
- aResp->res.json_value["Name"] = name;
- aResp->res.json_value["Id"] =
- aResp->res.json_value["SerialNumber"];
+ aResp->res.jsonValue["Name"] = name;
+ aResp->res.jsonValue["Id"] =
+ aResp->res.jsonValue["SerialNumber"];
},
connectionName, path, "org.freedesktop.DBus.Properties",
"GetAll", "xyz.openbmc_project.Inventory.Decorator.Asset");
@@ -176,22 +176,22 @@ class OnDemandSystemsProvider {
for (auto const &s : connectionNames) {
for (auto const &i : s.second) {
if (boost::ends_with(i, "Dimm")) {
- CROW_LOG_DEBUG << "Found Dimm, now get it properties.";
- crow::connections::system_bus->async_method_call(
+ BMCWEB_LOG_DEBUG << "Found Dimm, now get it properties.";
+ crow::connections::systemBus->async_method_call(
[&, aResp](const boost::system::error_code ec,
const std::vector<std::pair<
std::string, VariantType>> &properties) {
if (ec) {
- CROW_LOG_ERROR << "DBUS response error " << ec;
+ BMCWEB_LOG_ERROR << "DBUS response error " << ec;
aResp->setErrorStatus();
return;
}
- CROW_LOG_DEBUG << "Got " << properties.size()
+ BMCWEB_LOG_DEBUG << "Got " << properties.size()
<< "Dimm properties.";
for (const auto &p : properties) {
if (p.first == "MemorySize") {
const std::string *value =
- mapbox::get_ptr<const std::string>(p.second);
+ mapbox::getPtr<const std::string>(p.second);
if ((value != nullptr) && (*value != "NULL")) {
// Remove units char
int32_t unitCoeff;
@@ -200,16 +200,16 @@ class OnDemandSystemsProvider {
} else if (boost::ends_with(*value, "KB")) {
unitCoeff = 1000000;
} else {
- CROW_LOG_ERROR << "Unsupported memory units";
+ BMCWEB_LOG_ERROR << "Unsupported memory units";
aResp->setErrorStatus();
return;
}
auto memSize = boost::lexical_cast<int>(
value->substr(0, value->length() - 2));
- aResp->res.json_value["TotalSystemMemoryGiB"] +=
+ aResp->res.jsonValue["TotalSystemMemoryGiB"] +=
memSize * unitCoeff;
- aResp->res.json_value["MemorySummary"]["Status"]
+ aResp->res.jsonValue["MemorySummary"]["Status"]
["State"] = "Enabled";
}
}
@@ -218,34 +218,34 @@ class OnDemandSystemsProvider {
s.first, path, "org.freedesktop.DBus.Properties",
"GetAll", "xyz.openbmc_project.Inventory.Item.Dimm");
} else if (boost::ends_with(i, "Cpu")) {
- CROW_LOG_DEBUG << "Found Cpu, now get it properties.";
- crow::connections::system_bus->async_method_call(
+ BMCWEB_LOG_DEBUG << "Found Cpu, now get it properties.";
+ crow::connections::systemBus->async_method_call(
[&, aResp](const boost::system::error_code ec,
const std::vector<std::pair<
std::string, VariantType>> &properties) {
if (ec) {
- CROW_LOG_ERROR << "DBUS response error " << ec;
+ BMCWEB_LOG_ERROR << "DBUS response error " << ec;
aResp->setErrorStatus();
return;
}
- CROW_LOG_DEBUG << "Got " << properties.size()
+ BMCWEB_LOG_DEBUG << "Got " << properties.size()
<< "Cpu properties.";
for (const auto &p : properties) {
if (p.first == "ProcessorFamily") {
const std::string *value =
- mapbox::get_ptr<const std::string>(p.second);
+ mapbox::getPtr<const std::string>(p.second);
if (value != nullptr) {
aResp->res
- .json_value["ProcessorSummary"]["Count"] =
+ .jsonValue["ProcessorSummary"]["Count"] =
aResp->res
- .json_value["ProcessorSummary"]["Count"]
+ .jsonValue["ProcessorSummary"]["Count"]
.get<int>() +
1;
- aResp->res.json_value["ProcessorSummary"]
+ aResp->res.jsonValue["ProcessorSummary"]
["Status"]["State"] =
"Enabled";
aResp->res
- .json_value["ProcessorSummary"]["Model"] =
+ .jsonValue["ProcessorSummary"]["Model"] =
*value;
}
}
@@ -254,31 +254,31 @@ class OnDemandSystemsProvider {
s.first, path, "org.freedesktop.DBus.Properties",
"GetAll", "xyz.openbmc_project.Inventory.Item.Cpu");
} else if (boost::ends_with(i, "UUID")) {
- CROW_LOG_DEBUG << "Found UUID, now get it properties.";
- crow::connections::system_bus->async_method_call(
+ BMCWEB_LOG_DEBUG << "Found UUID, now get it properties.";
+ crow::connections::systemBus->async_method_call(
[aResp](const boost::system::error_code ec,
const std::vector<std::pair<
std::string, VariantType>> &properties) {
if (ec) {
- CROW_LOG_DEBUG << "DBUS response error " << ec;
+ BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
aResp->setErrorStatus();
return;
}
- CROW_LOG_DEBUG << "Got " << properties.size()
+ BMCWEB_LOG_DEBUG << "Got " << properties.size()
<< "UUID properties.";
for (const std::pair<std::string, VariantType> &p :
properties) {
if (p.first == "BIOSVer") {
const std::string *value =
- mapbox::get_ptr<const std::string>(p.second);
+ mapbox::getPtr<const std::string>(p.second);
if (value != nullptr) {
- aResp->res.json_value["BiosVersion"] = *value;
+ aResp->res.jsonValue["BiosVersion"] = *value;
}
}
if (p.first == "UUID") {
const std::string *value =
- mapbox::get_ptr<const std::string>(p.second);
- CROW_LOG_DEBUG << "UUID = " << *value
+ mapbox::getPtr<const std::string>(p.second);
+ BMCWEB_LOG_DEBUG << "UUID = " << *value
<< " length " << value->length();
if (value != nullptr) {
// Workaround for to short return str in smbios
@@ -290,7 +290,7 @@ class OnDemandSystemsProvider {
'0');
value = &correctedValue;
} else if (value->length() == 32) {
- aResp->res.json_value["UUID"] =
+ aResp->res.jsonValue["UUID"] =
value->substr(0, 8) + "-" +
value->substr(8, 4) + "-" +
value->substr(12, 4) + "-" +
@@ -329,17 +329,17 @@ class OnDemandSystemsProvider {
template <typename CallbackFunc>
void getLedGroupIdentify(std::shared_ptr<SystemAsyncResp> aResp,
CallbackFunc &&callback) {
- CROW_LOG_DEBUG << "Get led groups";
- crow::connections::system_bus->async_method_call(
+ BMCWEB_LOG_DEBUG << "Get led groups";
+ crow::connections::systemBus->async_method_call(
[
aResp{std::move(aResp)}, &callback
](const boost::system::error_code &ec, const ManagedObjectsType &resp) {
if (ec) {
- CROW_LOG_DEBUG << "DBUS response error " << ec;
+ BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
aResp->setErrorStatus();
return;
}
- CROW_LOG_DEBUG << "Got " << resp.size() << "led group objects.";
+ BMCWEB_LOG_DEBUG << "Got " << resp.size() << "led group objects.";
for (const auto &objPath : resp) {
const std::string &path = objPath.first;
if (path.rfind("enclosure_identify") != std::string::npos) {
@@ -348,7 +348,7 @@ class OnDemandSystemsProvider {
for (const auto &property : interface.second) {
if (property.first == "Asserted") {
const bool *asserted =
- mapbox::get_ptr<const bool>(property.second);
+ mapbox::getPtr<const bool>(property.second);
if (nullptr != asserted) {
callback(*asserted, aResp);
} else {
@@ -369,24 +369,24 @@ class OnDemandSystemsProvider {
template <typename CallbackFunc>
void getLedIdentify(std::shared_ptr<SystemAsyncResp> aResp,
CallbackFunc &&callback) {
- CROW_LOG_DEBUG << "Get identify led properties";
- crow::connections::system_bus->async_method_call(
+ BMCWEB_LOG_DEBUG << "Get identify led properties";
+ crow::connections::systemBus->async_method_call(
[ aResp{std::move(aResp)}, &callback ](
const boost::system::error_code ec,
const PropertiesType &properties) {
if (ec) {
- CROW_LOG_DEBUG << "DBUS response error " << ec;
+ BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
aResp->setErrorStatus();
return;
}
- CROW_LOG_DEBUG << "Got " << properties.size() << "led properties.";
+ BMCWEB_LOG_DEBUG << "Got " << properties.size() << "led properties.";
std::string output;
for (const auto &property : properties) {
if (property.first == "State") {
const std::string *s =
- mapbox::get_ptr<std::string>(property.second);
+ mapbox::getPtr<std::string>(property.second);
if (nullptr != s) {
- CROW_LOG_DEBUG << "Identify Led State: " << *s;
+ BMCWEB_LOG_DEBUG << "Identify Led State: " << *s;
const auto pos = s->rfind('.');
if (pos != std::string::npos) {
auto led = s->substr(pos + 1);
@@ -419,31 +419,31 @@ class OnDemandSystemsProvider {
* @return None.
*/
void getHostState(std::shared_ptr<SystemAsyncResp> aResp) {
- CROW_LOG_DEBUG << "Get host information.";
- crow::connections::system_bus->async_method_call(
+ BMCWEB_LOG_DEBUG << "Get host information.";
+ crow::connections::systemBus->async_method_call(
[aResp{std::move(aResp)}](const boost::system::error_code ec,
const PropertiesType &properties) {
if (ec) {
- CROW_LOG_DEBUG << "DBUS response error " << ec;
+ BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
aResp->setErrorStatus();
return;
}
- CROW_LOG_DEBUG << "Got " << properties.size() << "host properties.";
+ BMCWEB_LOG_DEBUG << "Got " << properties.size() << "host properties.";
for (const auto &property : properties) {
if (property.first == "CurrentHostState") {
const std::string *s =
- mapbox::get_ptr<const std::string>(property.second);
- CROW_LOG_DEBUG << "Host state: " << *s;
+ mapbox::getPtr<const std::string>(property.second);
+ BMCWEB_LOG_DEBUG << "Host state: " << *s;
if (nullptr != s) {
const auto pos = s->rfind('.');
if (pos != std::string::npos) {
// Verify Host State
if (s->substr(pos + 1) == "Running") {
- aResp->res.json_value["PowerState"] = "On";
- aResp->res.json_value["Status"]["State"] = "Enabled";
+ aResp->res.jsonValue["PowerState"] = "On";
+ aResp->res.jsonValue["Status"]["State"] = "Enabled";
} else {
- aResp->res.json_value["PowerState"] = "Off";
- aResp->res.json_value["Status"]["State"] = "Disabled";
+ aResp->res.jsonValue["PowerState"] = "Off";
+ aResp->res.jsonValue["Status"]["State"] = "Disabled";
}
}
}
@@ -484,7 +484,7 @@ class SystemsCollection : public Node {
/**
* Functions triggers appropriate requests on DBus
*/
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
// Get board list, and call the below callback for JSON preparation
provider.getBaseboardList(
@@ -499,7 +499,7 @@ class SystemsCollection : public Node {
// Then attach members, count size and return,
Node::json["Members"] = boardArray;
Node::json["Members@odata.count"] = boardArray.size();
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
} else {
// ... otherwise, return INTERNALL ERROR
res.result(boost::beast::http::status::internal_server_error);
@@ -555,7 +555,7 @@ class Systems : public Node {
/**
* Functions triggers appropriate requests on DBus
*/
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
// Check if there is required param, truly entering this shall be
// impossible
@@ -567,8 +567,8 @@ class Systems : public Node {
const std::string &name = params[0];
- res.json_value = Node::json;
- res.json_value["@odata.id"] = "/redfish/v1/Systems/" + name;
+ res.jsonValue = Node::json;
+ res.jsonValue["@odata.id"] = "/redfish/v1/Systems/" + name;
auto asyncResp = std::make_shared<SystemAsyncResp>(res);
@@ -582,18 +582,18 @@ class Systems : public Node {
aResp, [](const std::string &ledStatus,
const std::shared_ptr<SystemAsyncResp> &aResp) {
if (!ledStatus.empty()) {
- aResp->res.json_value["IndicatorLED"] = ledStatus;
+ aResp->res.jsonValue["IndicatorLED"] = ledStatus;
}
});
} else {
- aResp->res.json_value["IndicatorLED"] = "Off";
+ aResp->res.jsonValue["IndicatorLED"] = "Off";
}
});
provider.getComputerSystem(asyncResp, name);
provider.getHostState(asyncResp);
}
- void doPatch(crow::response &res, const crow::request &req,
+ void doPatch(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
// Check if there is required param, truly entering this shall be
// impossible
@@ -614,7 +614,7 @@ class Systems : public Node {
"IndicatorLED", patch, reqLedState,
static_cast<int>(json_util::MessageSetting::TYPE_ERROR) |
static_cast<int>(json_util::MessageSetting::MISSING),
- res.json_value, std::string("/" + name + "/IndicatorLED"));
+ res.jsonValue, std::string("/" + name + "/IndicatorLED"));
if ((r != json_util::Result::SUCCESS) || (reqLedState == nullptr)) {
res.result(boost::beast::http::status::bad_request);
res.end();
@@ -631,28 +631,28 @@ class Systems : public Node {
// Update led status
auto asyncResp = std::make_shared<SystemAsyncResp>(res);
- res.json_value = Node::json;
- res.json_value["@odata.id"] = "/redfish/v1/Systems/" + name;
+ res.jsonValue = Node::json;
+ res.jsonValue["@odata.id"] = "/redfish/v1/Systems/" + name;
provider.getHostState(asyncResp);
provider.getComputerSystem(asyncResp, name);
if (dbusLedState.empty()) {
messages::addMessageToJsonRoot(
- res.json_value,
+ res.jsonValue,
messages::propertyValueNotInList(*reqLedState, "IndicatorLED"));
} else {
// Update led group
- CROW_LOG_DEBUG << "Update led group.";
- crow::connections::system_bus->async_method_call(
+ BMCWEB_LOG_DEBUG << "Update led group.";
+ crow::connections::systemBus->async_method_call(
[&, asyncResp{std::move(asyncResp)} ](
const boost::system::error_code ec) {
if (ec) {
- CROW_LOG_DEBUG << "DBUS response error " << ec;
+ BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
asyncResp->setErrorStatus();
return;
}
- CROW_LOG_DEBUG << "Led group update done.";
+ BMCWEB_LOG_DEBUG << "Led group update done.";
},
"xyz.openbmc_project.LED.GroupManager",
"/xyz/openbmc_project/led/groups/enclosure_identify",
@@ -661,17 +661,17 @@ class Systems : public Node {
sdbusplus::message::variant<bool>(
(dbusLedState == "Off" ? false : true)));
// Update identify led status
- CROW_LOG_DEBUG << "Update led SoftwareInventoryCollection.";
- crow::connections::system_bus->async_method_call(
+ BMCWEB_LOG_DEBUG << "Update led SoftwareInventoryCollection.";
+ crow::connections::systemBus->async_method_call(
[&, asyncResp{std::move(asyncResp)} ](
const boost::system::error_code ec) {
if (ec) {
- CROW_LOG_DEBUG << "DBUS response error " << ec;
+ BMCWEB_LOG_DEBUG << "DBUS response error " << ec;
asyncResp->setErrorStatus();
return;
}
- CROW_LOG_DEBUG << "Led state update done.";
- res.json_value["IndicatorLED"] = *reqLedState;
+ BMCWEB_LOG_DEBUG << "Led state update done.";
+ res.jsonValue["IndicatorLED"] = *reqLedState;
},
"xyz.openbmc_project.LED.Controller.identify",
"/xyz/openbmc_project/led/physical/identify",
diff --git a/redfish-core/lib/thermal.hpp b/redfish-core/lib/thermal.hpp
index c1b9ada090..8fb291b9bb 100644
--- a/redfish-core/lib/thermal.hpp
+++ b/redfish-core/lib/thermal.hpp
@@ -39,18 +39,18 @@ class Thermal : public Node {
}
private:
- void doGet(crow::response& res, const crow::request& req,
+ void doGet(crow::Response& res, const crow::Request& req,
const std::vector<std::string>& params) override {
if (params.size() != 1) {
res.result(boost::beast::http::status::internal_server_error);
res.end();
return;
}
- const std::string& chassis_name = params[0];
+ const std::string& chassisName = params[0];
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
auto asyncResp = std::make_shared<SensorsAsyncResp>(
- res, chassis_name,
+ res, chassisName,
std::initializer_list<const char*>{
"/xyz/openbmc_project/sensors/fan",
"/xyz/openbmc_project/sensors/temperature"});
diff --git a/redfish-core/lib/update_service.hpp b/redfish-core/lib/update_service.hpp
index de659bcc1e..2ffa82ccef 100644
--- a/redfish-core/lib/update_service.hpp
+++ b/redfish-core/lib/update_service.hpp
@@ -24,14 +24,14 @@ class OnDemandSoftwareInventoryProvider {
public:
template <typename CallbackFunc>
void get_all_software_inventory_object(CallbackFunc &&callback) {
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[callback{std::move(callback)}](
const boost::system::error_code error_code,
const std::vector<std::pair<
std::string,
std::vector<std::pair<std::string, std::vector<std::string>>>>>
&subtree) {
- CROW_LOG_DEBUG << "get all software inventory object callback...";
+ BMCWEB_LOG_DEBUG << "get all software inventory object callback...";
if (error_code) {
// Something wrong on DBus, the error_code is not important at this
// moment, just return success=false, and empty output. Since size
@@ -42,10 +42,10 @@ class OnDemandSoftwareInventoryProvider {
}
if (subtree.empty()) {
- CROW_LOG_DEBUG << "subtree empty";
+ BMCWEB_LOG_DEBUG << "subtree empty";
callback(false, subtree);
} else {
- CROW_LOG_DEBUG << "subtree has something";
+ BMCWEB_LOG_DEBUG << "subtree has something";
callback(true, subtree);
}
},
@@ -81,9 +81,9 @@ class UpdateService : public Node {
}
private:
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
res.end();
}
};
@@ -117,10 +117,10 @@ class SoftwareInventoryCollection : public Node {
/**
* Functions triggers appropriate requests on DBus
*/
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
- res.json_value = Node::json;
- software_inventory_provider.get_all_software_inventory_object(
+ res.jsonValue = Node::json;
+ softwareInventoryProvider.get_all_software_inventory_object(
[&](const bool &success,
const std::vector<std::pair<
std::string,
@@ -133,12 +133,12 @@ class SoftwareInventoryCollection : public Node {
}
if (subtree.empty()) {
- CROW_LOG_DEBUG << "subtree empty!!";
+ BMCWEB_LOG_DEBUG << "subtree empty!!";
res.end();
return;
}
- res.json_value["Members"] = nlohmann::json::array();
+ res.jsonValue["Members"] = nlohmann::json::array();
for (auto &obj : subtree) {
const std::vector<std::pair<std::string, std::vector<std::string>>>
@@ -146,14 +146,14 @@ class SoftwareInventoryCollection : public Node {
for (auto &conn : connections) {
const std::string connectionName = conn.first;
- CROW_LOG_DEBUG << "connectionName = " << connectionName;
- CROW_LOG_DEBUG << "obj.first = " << obj.first;
+ BMCWEB_LOG_DEBUG << "connectionName = " << connectionName;
+ BMCWEB_LOG_DEBUG << "obj.first = " << obj.first;
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[&](const boost::system::error_code error_code,
const boost::container::flat_map<std::string, VariantType>
&propertiesList) {
- CROW_LOG_DEBUG << "safe returned in lambda function";
+ BMCWEB_LOG_DEBUG << "safe returned in lambda function";
if (error_code) {
res.result(
boost::beast::http::status::internal_server_error);
@@ -164,15 +164,15 @@ class SoftwareInventoryCollection : public Node {
VariantType>::const_iterator it =
propertiesList.find("Purpose");
const std::string &sw_inv_purpose =
- *(mapbox::get_ptr<const std::string>(it->second));
+ *(mapbox::getPtr<const std::string>(it->second));
std::size_t last_pos = sw_inv_purpose.rfind(".");
if (last_pos != std::string::npos) {
- res.json_value["Members"].push_back(
+ res.jsonValue["Members"].push_back(
{{"@odata.id",
"/redfish/v1/UpdateService/FirmwareInventory/" +
sw_inv_purpose.substr(last_pos + 1)}});
- res.json_value["Members@odata.count"] =
- res.json_value["Members"].size();
+ res.jsonValue["Members@odata.count"] =
+ res.jsonValue["Members"].size();
res.end();
}
@@ -183,7 +183,7 @@ class SoftwareInventoryCollection : public Node {
}
});
}
- OnDemandSoftwareInventoryProvider software_inventory_provider;
+ OnDemandSoftwareInventoryProvider softwareInventoryProvider;
};
/**
* Chassis override class for delivering Chassis Schema
@@ -217,9 +217,9 @@ class SoftwareInventory : public Node {
/**
* Functions triggers appropriate requests on DBus
*/
- void doGet(crow::response &res, const crow::request &req,
+ void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> &params) override {
- res.json_value = Node::json;
+ res.jsonValue = Node::json;
if (params.size() != 1) {
res.result(boost::beast::http::status::internal_server_error);
@@ -228,16 +228,16 @@ class SoftwareInventory : public Node {
}
const std::string &sw_id = params[0];
- res.json_value["@odata.id"] =
+ res.jsonValue["@odata.id"] =
"/redfish/v1/UpdateService/FirmwareInventory/" + sw_id;
- software_inventory_provider.get_all_software_inventory_object(
+ softwareInventoryProvider.get_all_software_inventory_object(
[&, id{std::string(sw_id)} ](
const bool &success,
const std::vector<std::pair<
std::string,
std::vector<std::pair<std::string, std::vector<std::string>>>>>
&subtree) {
- CROW_LOG_DEBUG << "doGet callback...";
+ BMCWEB_LOG_DEBUG << "doGet callback...";
if (!success) {
res.result(boost::beast::http::status::internal_server_error);
res.end();
@@ -245,7 +245,7 @@ class SoftwareInventory : public Node {
}
if (subtree.empty()) {
- CROW_LOG_DEBUG << "subtree empty!!";
+ BMCWEB_LOG_DEBUG << "subtree empty!!";
res.end();
return;
}
@@ -256,10 +256,10 @@ class SoftwareInventory : public Node {
for (auto &conn : connections) {
const std::string connectionName = conn.first;
- CROW_LOG_DEBUG << "connectionName = " << connectionName;
- CROW_LOG_DEBUG << "obj.first = " << obj.first;
+ BMCWEB_LOG_DEBUG << "connectionName = " << connectionName;
+ BMCWEB_LOG_DEBUG << "obj.first = " << obj.first;
- crow::connections::system_bus->async_method_call(
+ crow::connections::systemBus->async_method_call(
[&, id{std::string(id)} ](
const boost::system::error_code error_code,
const boost::container::flat_map<std::string, VariantType>
@@ -274,21 +274,21 @@ class SoftwareInventory : public Node {
VariantType>::const_iterator it =
propertiesList.find("Purpose");
if (it == propertiesList.end()) {
- CROW_LOG_DEBUG << "Can't find property \"Purpose\"!";
+ BMCWEB_LOG_DEBUG << "Can't find property \"Purpose\"!";
return;
}
const std::string &sw_inv_purpose =
- *(mapbox::get_ptr<const std::string>(it->second));
- CROW_LOG_DEBUG << "sw_inv_purpose = " << sw_inv_purpose;
+ *(mapbox::getPtr<const std::string>(it->second));
+ BMCWEB_LOG_DEBUG << "sw_inv_purpose = " << sw_inv_purpose;
if (boost::ends_with(sw_inv_purpose, "." + id)) {
it = propertiesList.find("Version");
if (it == propertiesList.end()) {
- CROW_LOG_DEBUG << "Can't find property \"Version\"!";
+ BMCWEB_LOG_DEBUG << "Can't find property \"Version\"!";
return;
}
- res.json_value["Version"] =
- *(mapbox::get_ptr<const std::string>(it->second));
- res.json_value["Id"] = id;
+ res.jsonValue["Version"] =
+ *(mapbox::getPtr<const std::string>(it->second));
+ res.jsonValue["Id"] = id;
res.end();
}
@@ -300,7 +300,7 @@ class SoftwareInventory : public Node {
});
}
- OnDemandSoftwareInventoryProvider software_inventory_provider;
+ OnDemandSoftwareInventoryProvider softwareInventoryProvider;
};
} // namespace redfish
diff --git a/redfish-core/scripts/error_messages/error_messages.cpp.in b/redfish-core/scripts/error_messages/error_messages.cpp.in
index a254b08c72..01b82a58ce 100644
--- a/redfish-core/scripts/error_messages/error_messages.cpp.in
+++ b/redfish-core/scripts/error_messages/error_messages.cpp.in
@@ -29,13 +29,13 @@ void addMessageToErrorJson(nlohmann::json& target,
if (!error.is_object()) {
auto message_id_iterator = message.find("MessageId");
if (message_id_iterator == message.end()) {
- CROW_LOG_CRITICAL << "Attempt to add error message without MessageId";
+ BMCWEB_LOG_CRITICAL << "Attempt to add error message without MessageId";
return;
}
auto message_field_iterator = message.find("Message");
if (message_field_iterator == message.end()) {
- CROW_LOG_CRITICAL << "Attempt to add error message without Message";
+ BMCWEB_LOG_CRITICAL << "Attempt to add error message without Message";
return;
}
// clang-format off
@@ -46,7 +46,7 @@ void addMessageToErrorJson(nlohmann::json& target,
// clang-format on
} else {
// More than 1 error occurred, so the message has to be generic
- error["code"] = std::string(MESSAGE_VERSION_PREFIX) + "GeneralError";
+ error["code"] = std::string(messageVersionPrefix) + "GeneralError";
error["message"] = "A general error has occurred. See ExtendedInfo for more"
"information.";
}
@@ -54,7 +54,7 @@ void addMessageToErrorJson(nlohmann::json& target,
// This check could technically be done in in the default construction
// branch above, but because we need the pointer to the extended info field
// anyway, it's more efficient to do it here.
- auto& extended_info = error[messages::MESSAGE_ANNOTATION];
+ auto& extended_info = error[messages::messageAnnotation];
if (!extended_info.is_array()) {
extended_info = nlohmann::json::array();
}
@@ -64,17 +64,17 @@ void addMessageToErrorJson(nlohmann::json& target,
void addMessageToJsonRoot(nlohmann::json& target,
const nlohmann::json& message) {
- if (!target[messages::MESSAGE_ANNOTATION].is_array()) {
+ if (!target[messages::messageAnnotation].is_array()) {
// Force object to be an array
- target[messages::MESSAGE_ANNOTATION] = nlohmann::json::array();
+ target[messages::messageAnnotation] = nlohmann::json::array();
}
- target[messages::MESSAGE_ANNOTATION].push_back(message);
+ target[messages::messageAnnotation].push_back(message);
}
void addMessageToJson(nlohmann::json& target, const nlohmann::json& message,
const std::string& fieldPath) {
- nlohmann::json_pointer extendedInfo(fieldPath + messages::MESSAGE_ANNOTATION);
+ nlohmann::json_pointer extendedInfo(fieldPath + messages::messageAnnotation);
if (!target[extendedInfo].is_array()) {
// Force object to be an array
diff --git a/redfish-core/scripts/error_messages/error_messages.hpp.in b/redfish-core/scripts/error_messages/error_messages.hpp.in
index 287917df97..b0f5c009d9 100644
--- a/redfish-core/scripts/error_messages/error_messages.hpp.in
+++ b/redfish-core/scripts/error_messages/error_messages.hpp.in
@@ -28,8 +28,8 @@ namespace redfish {
namespace messages {
-constexpr const char* MESSAGE_VERSION_PREFIX = "Base.1.2.0.";
-constexpr const char* MESSAGE_ANNOTATION = "@Message.ExtendedInfo";
+constexpr const char* messageVersionPrefix = "Base.1.2.0.";
+constexpr const char* messageAnnotation = "@Message.ExtendedInfo";
/**
* @brief Adds Message JSON object to error object
diff --git a/redfish-core/src/error_messages.cpp b/redfish-core/src/error_messages.cpp
index 18bbac4ed4..4773e3d8a7 100644
--- a/redfish-core/src/error_messages.cpp
+++ b/redfish-core/src/error_messages.cpp
@@ -29,13 +29,13 @@ void addMessageToErrorJson(nlohmann::json& target,
if (!error.is_object()) {
auto message_id_iterator = message.find("MessageId");
if (message_id_iterator == message.end()) {
- CROW_LOG_CRITICAL << "Attempt to add error message without MessageId";
+ BMCWEB_LOG_CRITICAL << "Attempt to add error message without MessageId";
return;
}
auto message_field_iterator = message.find("Message");
if (message_field_iterator == message.end()) {
- CROW_LOG_CRITICAL << "Attempt to add error message without Message";
+ BMCWEB_LOG_CRITICAL << "Attempt to add error message without Message";
return;
}
// clang-format off
@@ -46,7 +46,7 @@ void addMessageToErrorJson(nlohmann::json& target,
// clang-format on
} else {
// More than 1 error occurred, so the message has to be generic
- error["code"] = std::string(MESSAGE_VERSION_PREFIX) + "GeneralError";
+ error["code"] = std::string(messageVersionPrefix) + "GeneralError";
error["message"] =
"A general error has occurred. See ExtendedInfo for more"
"information.";
@@ -55,7 +55,7 @@ void addMessageToErrorJson(nlohmann::json& target,
// This check could technically be done in in the default construction
// branch above, but because we need the pointer to the extended info field
// anyway, it's more efficient to do it here.
- auto& extended_info = error[messages::MESSAGE_ANNOTATION];
+ auto& extended_info = error[messages::messageAnnotation];
if (!extended_info.is_array()) {
extended_info = nlohmann::json::array();
}
@@ -65,18 +65,18 @@ void addMessageToErrorJson(nlohmann::json& target,
void addMessageToJsonRoot(nlohmann::json& target,
const nlohmann::json& message) {
- if (!target[messages::MESSAGE_ANNOTATION].is_array()) {
+ if (!target[messages::messageAnnotation].is_array()) {
// Force object to be an array
- target[messages::MESSAGE_ANNOTATION] = nlohmann::json::array();
+ target[messages::messageAnnotation] = nlohmann::json::array();
}
- target[messages::MESSAGE_ANNOTATION].push_back(message);
+ target[messages::messageAnnotation].push_back(message);
}
void addMessageToJson(nlohmann::json& target, const nlohmann::json& message,
const std::string& fieldPath) {
nlohmann::json_pointer<nlohmann::json> extendedInfo(
- fieldPath + messages::MESSAGE_ANNOTATION);
+ fieldPath + messages::messageAnnotation);
if (!target[extendedInfo].is_array()) {
// Force object to be an array
@@ -553,7 +553,7 @@ nlohmann::json couldNotEstablishConnection(const std::string& arg1) {
return nlohmann::json{
{"@odata.type", "/redfish/v1/$metadata#Message.v1_0_0.Message"},
{"MessageId", "Base.1.2.0.CouldNotEstablishConnection"},
- {"Message", "The service failed to establish a connection with the URI " +
+ {"Message", "The service failed to establish a Connection with the URI " +
arg1 + "."},
{"Severity", "Critical"},
{"Resolution",
@@ -675,7 +675,7 @@ nlohmann::json sourceDoesNotSupportProtocol(const std::string& arg1,
return nlohmann::json{
{"@odata.type", "/redfish/v1/$metadata#Message.v1_0_0.Message"},
{"MessageId", "Base.1.2.0.SourceDoesNotSupportProtocol"},
- {"Message", "The other end of the connection at " + arg1 +
+ {"Message", "The other end of the Connection at " + arg1 +
" does not support the specified protocol " + arg2 + "."},
{"Severity", "Critical"},
{"Resolution", "Change protocols or URIs. "}};
@@ -708,7 +708,7 @@ nlohmann::json accessDenied(const std::string& arg1) {
return nlohmann::json{
{"@odata.type", "/redfish/v1/$metadata#Message.v1_0_0.Message"},
{"MessageId", "Base.1.2.0.AccessDenied"},
- {"Message", "While attempting to establish a connection to " + arg1 +
+ {"Message", "While attempting to establish a Connection to " + arg1 +
", the service denied access."},
{"Severity", "Critical"},
{"Resolution",
@@ -951,7 +951,7 @@ nlohmann::json invalidIndex(const int& arg1) {
return nlohmann::json{
{"@odata.type", "/redfish/v1/$metadata#Message.v1_0_0.Message"},
{"MessageId", "Base.1.2.0.InvalidIndex"},
- {"Message", "The Index " + std::to_string(arg1) +
+ {"Message", "The index " + std::to_string(arg1) +
" is not a valid offset into the array."},
{"Severity", "Warning"},
{"Resolution",
diff --git a/redfish-core/src/utils/json_utils.cpp b/redfish-core/src/utils/json_utils.cpp
index fea4d38964..5d81c21fa9 100644
--- a/redfish-core/src/utils/json_utils.cpp
+++ b/redfish-core/src/utils/json_utils.cpp
@@ -432,12 +432,12 @@ Result getDouble(const char* fieldName, const nlohmann::json& json,
return Result::SUCCESS;
}
-bool processJsonFromRequest(crow::response& res, const crow::request& req,
+bool processJsonFromRequest(crow::Response& res, const crow::Request& req,
nlohmann::json& reqJson) {
reqJson = nlohmann::json::parse(req.body, nullptr, false);
if (reqJson.is_discarded()) {
- messages::addMessageToErrorJson(res.json_value, messages::malformedJSON());
+ messages::addMessageToErrorJson(res.jsonValue, messages::malformedJSON());
res.result(boost::beast::http::status::bad_request);
res.end();
diff --git a/src/ast_jpeg_decoder_test.cpp b/src/ast_jpeg_decoder_test.cpp
index b8faa29330..277ba2cc8b 100644
--- a/src/ast_jpeg_decoder_test.cpp
+++ b/src/ast_jpeg_decoder_test.cpp
@@ -15,7 +15,7 @@ MATCHER_P2(IsBetween, a, b,
};
TEST(AstJpegDecoder, AllBlue) {
- AstVideo::RawVideoBuffer out;
+ ast_video::RawVideoBuffer out;
// This binary blog was created on the aspeed hardware using a blue screen
// consisting of the color 0x8EFFFA in a web browser window
@@ -28,33 +28,33 @@ TEST(AstJpegDecoder, AllBlue) {
ASSERT_GT(bufferlen, 0);
- out.y_selector = 0;
- out.uv_selector = 0;
- out.mode = AstVideo::YuvMode::YUV444;
+ out.ySelector = 0;
+ out.uvSelector = 0;
+ out.mode = ast_video::YuvMode::YUV444;
out.width = 800;
out.height = 600;
- AstVideo::AstJpegDecoder d;
- d.decode(out.buffer, out.width, out.height, out.mode, out.y_selector,
- out.uv_selector);
+ ast_video::AstJpegDecoder d;
+ d.decode(out.buffer, out.width, out.height, out.mode, out.ySelector,
+ out.uvSelector);
int tolerance = 16;
// All pixels should be blue (0x8EFFFA) to within a tolerance (due to jpeg
// compression artifacts and quanitization)
for (int i = 0; i < out.width * out.height; i++) {
- AstVideo::RGB &pixel = d.OutBuffer[i];
- EXPECT_GT(pixel.R, 0x8E - tolerance);
- EXPECT_LT(pixel.R, 0x8E + tolerance);
- EXPECT_GT(pixel.G, 0xFF - tolerance);
- EXPECT_LT(pixel.G, 0xFF + tolerance);
- EXPECT_GT(pixel.B, 0xF1 - tolerance);
- EXPECT_LT(pixel.B, 0xF1 + tolerance);
+ ast_video::RGB &pixel = d.outBuffer[i];
+ EXPECT_GT(pixel.r, 0x8E - tolerance);
+ EXPECT_LT(pixel.r, 0x8E + tolerance);
+ EXPECT_GT(pixel.g, 0xFF - tolerance);
+ EXPECT_LT(pixel.g, 0xFF + tolerance);
+ EXPECT_GT(pixel.b, 0xF1 - tolerance);
+ EXPECT_LT(pixel.b, 0xF1 + tolerance);
}
}
TEST(AstJpegDecoder, AllBlack) {
- AstVideo::RawVideoBuffer out;
+ ast_video::RawVideoBuffer out;
// This binary blog was created on the aspeed hardware using a black screen
FILE *fp = fopen("test_resources/aspeedblackscreen.bin", "rb");
@@ -65,30 +65,30 @@ TEST(AstJpegDecoder, AllBlack) {
ASSERT_GT(bufferlen, 0);
- out.y_selector = 0;
- out.uv_selector = 0;
- out.mode = AstVideo::YuvMode::YUV444;
+ out.ySelector = 0;
+ out.uvSelector = 0;
+ out.mode = ast_video::YuvMode::YUV444;
out.width = 800;
out.height = 600;
- AstVideo::AstJpegDecoder d;
- d.decode(out.buffer, out.width, out.height, out.mode, out.y_selector,
- out.uv_selector);
+ ast_video::AstJpegDecoder d;
+ d.decode(out.buffer, out.width, out.height, out.mode, out.ySelector,
+ out.uvSelector);
// All pixels should be blue (0x8EFFFA) to within a tolerance (due to jpeg
// compression artifacts and quanitization)
for (int x = 0; x < out.width; x++) {
for (int y = 0; y < out.height; y++) {
- AstVideo::RGB pixel = d.OutBuffer[x + (y * out.width)];
- ASSERT_EQ(pixel.R, 0x00) << "X:" << x << " Y: " << y;
- ASSERT_EQ(pixel.G, 0x00) << "X:" << x << " Y: " << y;
- ASSERT_EQ(pixel.B, 0x00) << "X:" << x << " Y: " << y;
+ ast_video::RGB pixel = d.outBuffer[x + (y * out.width)];
+ ASSERT_EQ(pixel.r, 0x00) << "X:" << x << " Y: " << y;
+ ASSERT_EQ(pixel.g, 0x00) << "X:" << x << " Y: " << y;
+ ASSERT_EQ(pixel.b, 0x00) << "X:" << x << " Y: " << y;
}
}
}
TEST(AstJpegDecoder, TestColors) {
- AstVideo::RawVideoBuffer out;
+ ast_video::RawVideoBuffer out;
// This binary blog was created on the aspeed hardware using a blue screen
// consisting of the color 0x8EFFFA in a web browser window
@@ -100,33 +100,33 @@ TEST(AstJpegDecoder, TestColors) {
ASSERT_GT(bufferlen, 0);
- out.y_selector = 0;
- out.uv_selector = 0;
- out.mode = AstVideo::YuvMode::YUV444;
+ out.ySelector = 0;
+ out.uvSelector = 0;
+ out.mode = ast_video::YuvMode::YUV444;
out.width = 800;
out.height = 600;
- AstVideo::AstJpegDecoder d;
- d.decode(out.buffer, out.width, out.height, out.mode, out.y_selector,
- out.uv_selector);
+ ast_video::AstJpegDecoder d;
+ d.decode(out.buffer, out.width, out.height, out.mode, out.ySelector,
+ out.uvSelector);
int tolerance = 16;
/*
for (int i = 0; i < out.width * out.height; i++) {
- AstVideo::RGB &pixel = d.OutBuffer[i];
- EXPECT_GT(pixel.R, 0x8E - tolerance);
- EXPECT_LT(pixel.R, 0x8E + tolerance);
- EXPECT_GT(pixel.G, 0xFF - tolerance);
- EXPECT_LT(pixel.G, 0xFF + tolerance);
- EXPECT_GT(pixel.B, 0xF1 - tolerance);
- EXPECT_LT(pixel.B, 0xF1 + tolerance);
+ ast_video::RGB &pixel = d.outBuffer[i];
+ EXPECT_GT(pixel.r, 0x8E - tolerance);
+ EXPECT_LT(pixel.r, 0x8E + tolerance);
+ EXPECT_GT(pixel.g, 0xFF - tolerance);
+ EXPECT_LT(pixel.g, 0xFF + tolerance);
+ EXPECT_GT(pixel.b, 0xF1 - tolerance);
+ EXPECT_LT(pixel.b, 0xF1 + tolerance);
}
*/
}
// Tests the buffers around the screen aren't written to
TEST(AstJpegDecoder, BufferLimits) {
- AstVideo::RawVideoBuffer out;
+ ast_video::RawVideoBuffer out;
// This binary blog was created on the aspeed hardware using a black screen
FILE *fp = fopen("test_resources/aspeedblackscreen.bin", "rb");
@@ -137,23 +137,23 @@ TEST(AstJpegDecoder, BufferLimits) {
ASSERT_GT(bufferlen, 0);
- out.y_selector = 0;
- out.uv_selector = 0;
- out.mode = AstVideo::YuvMode::YUV444;
+ out.ySelector = 0;
+ out.uvSelector = 0;
+ out.mode = ast_video::YuvMode::YUV444;
out.width = 800;
out.height = 600;
- AstVideo::AstJpegDecoder d;
- d.decode(out.buffer, out.width, out.height, out.mode, out.y_selector,
- out.uv_selector);
- // Reserved pixel should be default value
- for (auto &pixel : d.OutBuffer) {
- EXPECT_EQ(pixel.Reserved, 0xAA);
+ ast_video::AstJpegDecoder d;
+ d.decode(out.buffer, out.width, out.height, out.mode, out.ySelector,
+ out.uvSelector);
+ // reserved pixel should be default value
+ for (auto &pixel : d.outBuffer) {
+ EXPECT_EQ(pixel.reserved, 0xAA);
}
// All pixels beyond the buffer should be zero
- for (int i = out.width * out.height; i < d.OutBuffer.size(); i++) {
- EXPECT_EQ(d.OutBuffer[i].R, 0x00) << "index:" << i;
- EXPECT_EQ(d.OutBuffer[i].B, 0x00) << "index:" << i;
- EXPECT_EQ(d.OutBuffer[i].G, 0x00) << "index:" << i;
+ for (int i = out.width * out.height; i < d.outBuffer.size(); i++) {
+ EXPECT_EQ(d.outBuffer[i].r, 0x00) << "index:" << i;
+ EXPECT_EQ(d.outBuffer[i].b, 0x00) << "index:" << i;
+ EXPECT_EQ(d.outBuffer[i].g, 0x00) << "index:" << i;
}
} \ No newline at end of file
diff --git a/src/ast_video_puller_test.cpp b/src/ast_video_puller_test.cpp
index b1f94e7579..58adda9697 100644
--- a/src/ast_video_puller_test.cpp
+++ b/src/ast_video_puller_test.cpp
@@ -14,12 +14,12 @@
#include <gtest/gtest.h>
TEST(AstvideoPuller, BasicRead) {
- AstVideo::RawVideoBuffer out;
+ ast_video::RawVideoBuffer out;
bool have_hardware = false;
if (access("/dev/video", F_OK) != -1) {
- AstVideo::SimpleVideoPuller p;
+ ast_video::SimpleVideoPuller p;
p.initialize();
- out = p.read_video();
+ out = p.readVideo();
} else {
FILE *fp = fopen("test_resources/ubuntu_444_800x600_0chrom_0lum.bin", "rb");
if (fp) {
@@ -30,18 +30,18 @@ TEST(AstvideoPuller, BasicRead) {
}
fclose(fp);
out.buffer.resize(newLen);
- out.mode = AstVideo::YuvMode::YUV444;
+ out.mode = ast_video::YuvMode::YUV444;
out.width = 800;
out.height = 600;
- out.y_selector = 0;
- out.uv_selector = 0;
+ out.ySelector = 0;
+ out.uvSelector = 0;
}
}
FILE *fp = fopen("/tmp/screendata.bin", "wb");
fwrite(out.buffer.data(), sizeof(char), out.buffer.size(), fp);
- AstVideo::AstJpegDecoder d;
- d.decode(out.buffer, out.width, out.height, out.mode, out.y_selector,
- out.uv_selector);
+ ast_video::AstJpegDecoder d;
+ d.decode(out.buffer, out.width, out.height, out.mode, out.ySelector,
+ out.uvSelector);
}
diff --git a/src/base64.cpp b/src/base64.cpp
index 54a60084cf..0013c28ac3 100644
--- a/src/base64.cpp
+++ b/src/base64.cpp
@@ -109,7 +109,8 @@ bool base64_decode(const std::string &input, std::string &output) {
if (base64code1 == nop) { // non base64 character
return false;
}
- output += static_cast<char>((base64code0 << 2) | ((base64code1 >> 4) & 0x3));
+ output +=
+ static_cast<char>((base64code0 << 2) | ((base64code1 >> 4) & 0x3));
if (++i < input_length) {
char c = input[i];
@@ -120,7 +121,8 @@ bool base64_decode(const std::string &input, std::string &output) {
if (base64code2 == nop) { // non base64 character
return false;
}
- output += static_cast<char>(((base64code1 << 4) & 0xf0) | ((base64code2 >> 2) & 0x0f));
+ output += static_cast<char>(((base64code1 << 4) & 0xf0) |
+ ((base64code2 >> 2) & 0x0f));
}
if (++i < input_length) {
diff --git a/src/crow_getroutes_test.cpp b/src/crow_getroutes_test.cpp
index 4b705b0bdf..29052a9a21 100644
--- a/src/crow_getroutes_test.cpp
+++ b/src/crow_getroutes_test.cpp
@@ -9,16 +9,16 @@ TEST(GetRoutes, TestEmptyRoutes) {
SimpleApp app;
decltype(app)::server_t server(&app, "127.0.0.1", 45451);
- EXPECT_THAT(app.get_routes(), testing::IsEmpty());
+ EXPECT_THAT(app.getRoutes(), testing::IsEmpty());
}
// Tests that static urls are correctly passed
TEST(GetRoutes, TestOneRoute) {
SimpleApp app;
decltype(app)::server_t server(&app, "127.0.0.1", 45451);
- CROW_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
- EXPECT_THAT(app.get_routes(),
+ EXPECT_THAT(app.getRoutes(),
testing::ElementsAre(testing::Pointee(std::string("/"))));
}
@@ -26,18 +26,18 @@ TEST(GetRoutes, TestOneRoute) {
TEST(GetRoutes, TestlotsOfRoutes) {
SimpleApp app;
decltype(app)::server_t server(&app, "127.0.0.1", 45451);
- CROW_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
- CROW_ROUTE(app, "/foo")([]() { return boost::beast::http::status::ok; });
- CROW_ROUTE(app, "/bar")([]() { return boost::beast::http::status::ok; });
- CROW_ROUTE(app, "/baz")([]() { return boost::beast::http::status::ok; });
- CROW_ROUTE(app, "/boo")([]() { return boost::beast::http::status::ok; });
- CROW_ROUTE(app, "/moo")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/foo")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/bar")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/baz")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/boo")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/moo")([]() { return boost::beast::http::status::ok; });
- EXPECT_THAT(app.get_routes(), testing::UnorderedElementsAre(
- testing::Pointee(std::string("/")),
- testing::Pointee(std::string("/foo")),
- testing::Pointee(std::string("/bar")),
- testing::Pointee(std::string("/baz")),
- testing::Pointee(std::string("/boo")),
- testing::Pointee(std::string("/moo"))));
+ EXPECT_THAT(app.getRoutes(), testing::UnorderedElementsAre(
+ testing::Pointee(std::string("/")),
+ testing::Pointee(std::string("/foo")),
+ testing::Pointee(std::string("/bar")),
+ testing::Pointee(std::string("/baz")),
+ testing::Pointee(std::string("/boo")),
+ testing::Pointee(std::string("/moo"))));
} \ No newline at end of file
diff --git a/src/crow_test.cpp b/src/crow_test.cpp
index 20a946dab6..cd668171db 100644
--- a/src/crow_test.cpp
+++ b/src/crow_test.cpp
@@ -3,8 +3,8 @@
#include <sstream>
#include <vector>
#include "gtest/gtest.h"
-#undef CROW_LOG_LEVEL
-#define CROW_LOG_LEVEL 0
+#undef BMCWEB_LOG_LEVEL
+#define BMCWEB_LOG_LEVEL 0
using namespace std;
using namespace crow;
@@ -62,16 +62,16 @@ TEST(Crow, Rule) {
r.validate();
- response res;
+ Response res;
// executing handler
ASSERT_EQUAL(0, x);
boost::beast::http::request<boost::beast::http::string_body> req{};
- r.handle(request(req), res, routing_params());
+ r.handle(Request(req), res, RoutingParams());
ASSERT_EQUAL(1, x);
- // registering handler with request argument
- r([&x](const crow::request&) {
+ // registering handler with Request argument
+ r([&x](const crow::Request&) {
x = 2;
return "";
});
@@ -80,14 +80,14 @@ TEST(Crow, Rule) {
// executing handler
ASSERT_EQUAL(1, x);
- r.handle(request(req), res, routing_params());
+ r.handle(Request(req), res, RoutingParams());
ASSERT_EQUAL(2, x);
}
TEST(Crow, ParameterTagging) {
- static_assert(black_magic::is_valid("<int><int><int>"), "valid url");
- static_assert(!black_magic::is_valid("<int><int<<int>"), "invalid url");
- static_assert(!black_magic::is_valid("nt>"), "invalid url");
+ static_assert(black_magic::isValid("<int><int><int>"), "valid url");
+ static_assert(!black_magic::isValid("<int><int<<int>"), "invalid url");
+ static_assert(!black_magic::isValid("nt>"), "invalid url");
ASSERT_EQUAL(1, black_magic::get_parameter_tag("<int>"));
ASSERT_EQUAL(2, black_magic::get_parameter_tag("<uint>"));
ASSERT_EQUAL(3, black_magic::get_parameter_tag("<float>"));
@@ -106,96 +106,96 @@ TEST(Crow, ParameterTagging) {
// to template argument
static_assert(
std::is_same<black_magic::S<uint64_t, double, int64_t>,
- black_magic::arguments<6 * 6 + 6 * 3 + 2>::type>::value,
+ black_magic::Arguments<6 * 6 + 6 * 3 + 2>::type>::value,
"tag to type container");
}
TEST(Crow, PathRouting) {
SimpleApp app;
- CROW_ROUTE(app, "/file")
+ BMCWEB_ROUTE(app, "/file")
([] { return "file"; });
- CROW_ROUTE(app, "/path/")
+ BMCWEB_ROUTE(app, "/path/")
([] { return "path"; });
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/file";
app.handle(req, res);
- ASSERT_EQUAL(200, res.result_int());
+ ASSERT_EQUAL(200, res.resultInt());
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/file/";
app.handle(req, res);
- ASSERT_EQUAL(404, res.result_int());
+ ASSERT_EQUAL(404, res.resultInt());
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/path";
app.handle(req, res);
- ASSERT_NOTEQUAL(404, res.result_int());
+ ASSERT_NOTEQUAL(404, res.resultInt());
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/path/";
app.handle(req, res);
- ASSERT_EQUAL(200, res.result_int());
+ ASSERT_EQUAL(200, res.resultInt());
}
}
TEST(Crow, RoutingTest) {
SimpleApp app;
int A{};
- uint32_t B{};
+ uint32_t b{};
double C{};
string D{};
string E{};
- CROW_ROUTE(app, "/0/<uint>")
+ BMCWEB_ROUTE(app, "/0/<uint>")
([&](uint32_t b) {
- B = b;
+ b = b;
return "OK";
});
- CROW_ROUTE(app, "/1/<int>/<uint>")
+ BMCWEB_ROUTE(app, "/1/<int>/<uint>")
([&](int a, uint32_t b) {
A = a;
- B = b;
+ b = b;
return "OK";
});
- CROW_ROUTE(app, "/4/<int>/<uint>/<double>/<string>")
+ BMCWEB_ROUTE(app, "/4/<int>/<uint>/<double>/<string>")
([&](int a, uint32_t b, double c, string d) {
A = a;
- B = b;
+ b = b;
C = c;
D = d;
return "OK";
});
- CROW_ROUTE(app, "/5/<int>/<uint>/<double>/<string>/<path>")
+ BMCWEB_ROUTE(app, "/5/<int>/<uint>/<double>/<string>/<path>")
([&](int a, uint32_t b, double c, string d, string e) {
A = a;
- B = b;
+ b = b;
C = c;
D = d;
E = e;
@@ -203,96 +203,96 @@ TEST(Crow, RoutingTest) {
});
app.validate();
- // app.debug_print();
+ // app.debugPrint();
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/-1";
app.handle(req, res);
- ASSERT_EQUAL(404, res.result_int());
+ ASSERT_EQUAL(404, res.resultInt());
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/0/1001999";
app.handle(req, res);
- ASSERT_EQUAL(200, res.result_int());
+ ASSERT_EQUAL(200, res.resultInt());
- ASSERT_EQUAL(1001999, B);
+ ASSERT_EQUAL(1001999, b);
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/1/-100/1999";
app.handle(req, res);
- ASSERT_EQUAL(200, res.result_int());
+ ASSERT_EQUAL(200, res.resultInt());
ASSERT_EQUAL(-100, A);
- ASSERT_EQUAL(1999, B);
+ ASSERT_EQUAL(1999, b);
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/4/5000/3/-2.71828/hellhere";
app.handle(req, res);
- ASSERT_EQUAL(200, res.result_int());
+ ASSERT_EQUAL(200, res.resultInt());
ASSERT_EQUAL(5000, A);
- ASSERT_EQUAL(3, B);
+ ASSERT_EQUAL(3, b);
ASSERT_EQUAL(-2.71828, C);
ASSERT_EQUAL("hellhere", D);
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/5/-5/999/3.141592/hello_there/a/b/c/d";
app.handle(req, res);
- ASSERT_EQUAL(200, res.result_int());
+ ASSERT_EQUAL(200, res.resultInt());
ASSERT_EQUAL(-5, A);
- ASSERT_EQUAL(999, B);
+ ASSERT_EQUAL(999, b);
ASSERT_EQUAL(3.141592, C);
ASSERT_EQUAL("hello_there", D);
ASSERT_EQUAL("a/b/c/d", E);
}
}
-TEST(Crow, simple_response_routing_params) {
+TEST(Crow, simple_response_RoutingParams) {
ASSERT_EQUAL(100,
- response(boost::beast::http::status::continue_).result_int());
- ASSERT_EQUAL(200, response("Hello there").result_int());
- ASSERT_EQUAL(500, response(boost::beast::http::status::internal_server_error,
+ Response(boost::beast::http::status::continue_).resultInt());
+ ASSERT_EQUAL(200, Response("Hello there").resultInt());
+ ASSERT_EQUAL(500, Response(boost::beast::http::status::internal_server_error,
"Internal Error?")
- .result_int());
-
- routing_params rp;
- rp.int_params.push_back(1);
- rp.int_params.push_back(5);
- rp.uint_params.push_back(2);
- rp.double_params.push_back(3);
- rp.string_params.push_back("hello");
+ .resultInt());
+
+ RoutingParams rp;
+ rp.intParams.push_back(1);
+ rp.intParams.push_back(5);
+ rp.uintParams.push_back(2);
+ rp.doubleParams.push_back(3);
+ rp.stringParams.push_back("hello");
ASSERT_EQUAL(1, rp.get<int64_t>(0));
ASSERT_EQUAL(5, rp.get<int64_t>(1));
ASSERT_EQUAL(2, rp.get<uint64_t>(0));
@@ -302,34 +302,34 @@ TEST(Crow, simple_response_routing_params) {
TEST(Crow, handler_with_response) {
SimpleApp app;
- CROW_ROUTE(app, "/")([](const crow::request&, crow::response&) {});
+ BMCWEB_ROUTE(app, "/")([](const crow::Request&, crow::Response&) {});
}
TEST(Crow, http_method) {
SimpleApp app;
- CROW_ROUTE(app, "/").methods("POST"_method,
- "GET"_method)([](const request& req) {
+ BMCWEB_ROUTE(app, "/").methods("POST"_method,
+ "GET"_method)([](const Request& req) {
if (req.method() == "GET"_method)
return "2";
else
return "1";
});
- CROW_ROUTE(app, "/get_only")
- .methods("GET"_method)([](const request& /*req*/) { return "get"; });
- CROW_ROUTE(app, "/post_only")
- .methods("POST"_method)([](const request& /*req*/) { return "post"; });
+ BMCWEB_ROUTE(app, "/get_only")
+ .methods("GET"_method)([](const Request& /*req*/) { return "get"; });
+ BMCWEB_ROUTE(app, "/post_only")
+ .methods("POST"_method)([](const Request& /*req*/) { return "post"; });
// cannot have multiple handlers for the same url
- // CROW_ROUTE(app, "/")
+ // BMCWEB_ROUTE(app, "/")
//.methods("GET"_method)
//([]{ return "2"; });
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/";
app.handle(req, res);
@@ -338,8 +338,8 @@ TEST(Crow, http_method) {
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/";
r.method("POST"_method);
@@ -350,8 +350,8 @@ TEST(Crow, http_method) {
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/get_only";
app.handle(req, res);
@@ -361,8 +361,8 @@ TEST(Crow, http_method) {
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/get_only";
r.method("POST"_method);
@@ -375,7 +375,7 @@ TEST(Crow, http_method) {
TEST(Crow, server_handling_error_request) {
static char buf[2048];
SimpleApp app;
- CROW_ROUTE(app, "/")([] { return "A"; });
+ BMCWEB_ROUTE(app, "/")([] { return "A"; });
Server<SimpleApp> server(&app, LOCALHOST_ADDRESS, 45451);
auto _ = async(launch::async, [&] { server.run(); });
std::string sendmsg = "POX";
@@ -400,10 +400,10 @@ TEST(Crow, server_handling_error_request) {
TEST(Crow, multi_server) {
static char buf[2048];
SimpleApp app1, app2;
- CROW_ROUTE(app1, "/").methods("GET"_method,
- "POST"_method)([] { return "A"; });
- CROW_ROUTE(app2, "/").methods("GET"_method,
- "POST"_method)([] { return "B"; });
+ BMCWEB_ROUTE(app1, "/").methods("GET"_method,
+ "POST"_method)([] { return "A"; });
+ BMCWEB_ROUTE(app2, "/").methods("GET"_method,
+ "POST"_method)([] { return "B"; });
Server<SimpleApp> server1(&app1, LOCALHOST_ADDRESS, 45451);
Server<SimpleApp> server2(&app2, LOCALHOST_ADDRESS, 45452);
@@ -412,7 +412,7 @@ TEST(Crow, multi_server) {
auto _2 = async(launch::async, [&] { server2.run(); });
std::string sendmsg =
- "POST /\r\nContent-Length:3\r\nX-HeaderTest: 123\r\n\r\nA=B\r\n";
+ "POST /\r\nContent-Length:3\r\nX-HeaderTest: 123\r\n\r\nA=b\r\n";
asio::io_service is;
{
asio::ip::tcp::socket c(is);
@@ -436,7 +436,7 @@ TEST(Crow, multi_server) {
}
size_t recved = c.receive(asio::buffer(buf, 2048));
- ASSERT_EQUAL('B', buf[recved - 1]);
+ ASSERT_EQUAL('b', buf[recved - 1]);
}
server1.stop();
@@ -446,58 +446,59 @@ TEST(Crow, multi_server) {
TEST(Crow, black_magic) {
using namespace black_magic;
static_assert(
- std::is_same<void, last_element_type<int, char, void>::type>::value,
- "last_element_type");
- static_assert(std::is_same<char, pop_back<int, char, void>::rebind<
- last_element_type>::type>::value,
- "pop_back");
+ std::is_same<void, LastElementType<int, char, void>::type>::value,
+ "LastElementType");
static_assert(
- std::is_same<int, pop_back<int, char, void>::rebind<pop_back>::rebind<
- last_element_type>::type>::value,
+ std::is_same<
+ char, PopBack<int, char, void>::rebind<LastElementType>::type>::value,
+ "pop_back");
+ static_assert(
+ std::is_same<int, PopBack<int, char, void>::rebind<PopBack>::rebind<
+ LastElementType>::type>::value,
"pop_back");
}
struct NullMiddleware {
- struct context {};
+ struct Context {};
template <typename AllContext>
- void before_handle(request&, response&, context&, AllContext&) {}
+ void beforeHandle(Request&, Response&, Context&, AllContext&) {}
template <typename AllContext>
- void after_handle(request&, response&, context&, AllContext&) {}
+ void afterHandle(Request&, Response&, Context&, AllContext&) {}
};
struct NullSimpleMiddleware {
- struct context {};
+ struct Context {};
- void before_handle(request& /*req*/, response& /*res*/, context& /*ctx*/) {}
+ void beforeHandle(Request& /*req*/, Response& /*res*/, Context& /*ctx*/) {}
- void after_handle(request& /*req*/, response& /*res*/, context& /*ctx*/) {}
+ void afterHandle(Request& /*req*/, Response& /*res*/, Context& /*ctx*/) {}
};
TEST(Crow, middleware_simple) {
App<NullMiddleware, NullSimpleMiddleware> app;
decltype(app)::server_t server(&app, LOCALHOST_ADDRESS, 45451);
- CROW_ROUTE(app, "/")
- ([&](const crow::request& req) {
- app.get_context<NullMiddleware>(req);
- app.get_context<NullSimpleMiddleware>(req);
+ BMCWEB_ROUTE(app, "/")
+ ([&](const crow::Request& req) {
+ app.getContext<NullMiddleware>(req);
+ app.getContext<NullSimpleMiddleware>(req);
return "";
});
}
struct IntSettingMiddleware {
- struct context {
+ struct Context {
int val;
};
template <typename AllContext>
- void before_handle(request&, response&, context& ctx, AllContext&) {
+ void beforeHandle(Request&, Response&, Context& ctx, AllContext&) {
ctx.val = 1;
}
template <typename AllContext>
- void after_handle(request&, response&, context& ctx, AllContext&) {
+ void afterHandle(Request&, Response&, Context& ctx, AllContext&) {
ctx.val = 2;
}
};
@@ -505,49 +506,49 @@ struct IntSettingMiddleware {
std::vector<std::string> test_middleware_context_vector;
struct FirstMW {
- struct context {
+ struct Context {
std::vector<string> v;
};
- void before_handle(request& /*req*/, response& /*res*/, context& ctx) {
+ void beforeHandle(Request& /*req*/, Response& /*res*/, Context& ctx) {
ctx.v.push_back("1 before");
}
- void after_handle(request& /*req*/, response& /*res*/, context& ctx) {
+ void afterHandle(Request& /*req*/, Response& /*res*/, Context& ctx) {
ctx.v.push_back("1 after");
test_middleware_context_vector = ctx.v;
}
};
struct SecondMW {
- struct context {};
+ struct Context {};
template <typename AllContext>
- void before_handle(request& req, response& res, context&,
- AllContext& all_ctx) {
+ void beforeHandle(Request& req, Response& res, Context&,
+ AllContext& all_ctx) {
all_ctx.template get<FirstMW>().v.push_back("2 before");
if (req.url == "/break") res.end();
}
template <typename AllContext>
- void after_handle(request&, response&, context&, AllContext& all_ctx) {
+ void afterHandle(Request&, Response&, Context&, AllContext& all_ctx) {
all_ctx.template get<FirstMW>().v.push_back("2 after");
}
};
struct ThirdMW {
- struct context {};
+ struct Context {};
template <typename AllContext>
- void before_handle(request&, response&, context&, AllContext& all_ctx) {
+ void beforeHandle(Request&, Response&, Context&, AllContext& all_ctx) {
all_ctx.template get<FirstMW>().v.push_back("3 before");
}
template <typename AllContext>
- void after_handle(request&, response&, context&, AllContext& all_ctx) {
+ void afterHandle(Request&, Response&, Context&, AllContext& all_ctx) {
all_ctx.template get<FirstMW>().v.push_back("3 after");
}
};
-TEST(Crow, middleware_context) {
+TEST(Crow, middlewareContext) {
static char buf[2048];
// SecondMW depends on FirstMW (it uses all_ctx.get<FirstMW>)
// so it leads to compile error if we remove FirstMW from definition
@@ -558,23 +559,23 @@ TEST(Crow, middleware_context) {
App<IntSettingMiddleware, FirstMW, SecondMW, ThirdMW> app;
int x{};
- CROW_ROUTE(app, "/")
- ([&](const request& req) {
+ BMCWEB_ROUTE(app, "/")
+ ([&](const Request& req) {
{
- auto& ctx = app.get_context<IntSettingMiddleware>(req);
+ auto& ctx = app.getContext<IntSettingMiddleware>(req);
x = ctx.val;
}
{
- auto& ctx = app.get_context<FirstMW>(req);
+ auto& ctx = app.getContext<FirstMW>(req);
ctx.v.push_back("handle");
}
return "";
});
- CROW_ROUTE(app, "/break")
- ([&](const request& req) {
+ BMCWEB_ROUTE(app, "/break")
+ ([&](const Request& req) {
{
- auto& ctx = app.get_context<FirstMW>(req);
+ auto& ctx = app.getContext<FirstMW>(req);
ctx.v.push_back("handle");
}
@@ -634,7 +635,7 @@ TEST(Crow, bug_quick_repeated_request) {
SimpleApp app;
- CROW_ROUTE(app, "/")([&] { return "hello"; });
+ BMCWEB_ROUTE(app, "/")([&] { return "hello"; });
decltype(app)::server_t server(&app, LOCALHOST_ADDRESS, 45451);
auto _ = async(launch::async, [&] { server.run(); });
@@ -667,11 +668,11 @@ TEST(Crow, simple_url_params) {
SimpleApp app;
- query_string last_url_params;
+ QueryString lastUrlParams;
- CROW_ROUTE(app, "/params")
- ([&last_url_params](const crow::request& req) {
- last_url_params = std::move(req.url_params);
+ BMCWEB_ROUTE(app, "/params")
+ ([&lastUrlParams](const crow::Request& req) {
+ lastUrlParams = std::move(req.urlParams);
return "OK";
});
@@ -693,7 +694,7 @@ TEST(Crow, simple_url_params) {
c.close();
stringstream ss;
- ss << last_url_params;
+ ss << lastUrlParams;
ASSERT_EQUAL("[ ]", ss.str());
}
@@ -707,9 +708,9 @@ TEST(Crow, simple_url_params) {
c.receive(asio::buffer(buf, 2048));
c.close();
- ASSERT_TRUE(last_url_params.get("missing") == nullptr);
- ASSERT_TRUE(last_url_params.get("foobar") != nullptr);
- ASSERT_TRUE(last_url_params.get_list("missing").empty());
+ ASSERT_TRUE(lastUrlParams.get("missing") == nullptr);
+ ASSERT_TRUE(lastUrlParams.get("foobar") != nullptr);
+ ASSERT_TRUE(lastUrlParams.getList("missing").empty());
}
// check multiple presence
sendmsg = "GET /params?foo&bar&baz\r\n\r\n";
@@ -721,10 +722,10 @@ TEST(Crow, simple_url_params) {
c.receive(asio::buffer(buf, 2048));
c.close();
- ASSERT_TRUE(last_url_params.get("missing") == nullptr);
- ASSERT_TRUE(last_url_params.get("foo") != nullptr);
- ASSERT_TRUE(last_url_params.get("bar") != nullptr);
- ASSERT_TRUE(last_url_params.get("baz") != nullptr);
+ ASSERT_TRUE(lastUrlParams.get("missing") == nullptr);
+ ASSERT_TRUE(lastUrlParams.get("foo") != nullptr);
+ ASSERT_TRUE(lastUrlParams.get("bar") != nullptr);
+ ASSERT_TRUE(lastUrlParams.get("baz") != nullptr);
}
// check single value
sendmsg = "GET /params?hello=world\r\n\r\n";
@@ -736,7 +737,7 @@ TEST(Crow, simple_url_params) {
c.receive(asio::buffer(buf, 2048));
c.close();
- ASSERT_EQUAL(string(last_url_params.get("hello")), "world");
+ ASSERT_EQUAL(string(lastUrlParams.get("hello")), "world");
}
// check multiple value
sendmsg = "GET /params?hello=world&left=right&up=down\r\n\r\n";
@@ -748,9 +749,9 @@ TEST(Crow, simple_url_params) {
c.receive(asio::buffer(buf, 2048));
c.close();
- ASSERT_EQUAL(string(last_url_params.get("hello")), "world");
- ASSERT_EQUAL(string(last_url_params.get("left")), "right");
- ASSERT_EQUAL(string(last_url_params.get("up")), "down");
+ ASSERT_EQUAL(string(lastUrlParams.get("hello")), "world");
+ ASSERT_EQUAL(string(lastUrlParams.get("left")), "right");
+ ASSERT_EQUAL(string(lastUrlParams.get("up")), "down");
}
// check multiple value, multiple types
sendmsg = "GET /params?int=100&double=123.45&boolean=1\r\n\r\n";
@@ -762,11 +763,10 @@ TEST(Crow, simple_url_params) {
c.receive(asio::buffer(buf, 2048));
c.close();
- ASSERT_EQUAL(boost::lexical_cast<int>(last_url_params.get("int")), 100);
- ASSERT_EQUAL(boost::lexical_cast<double>(last_url_params.get("double")),
+ ASSERT_EQUAL(boost::lexical_cast<int>(lastUrlParams.get("int")), 100);
+ ASSERT_EQUAL(boost::lexical_cast<double>(lastUrlParams.get("double")),
123.45);
- ASSERT_EQUAL(boost::lexical_cast<bool>(last_url_params.get("boolean")),
- true);
+ ASSERT_EQUAL(boost::lexical_cast<bool>(lastUrlParams.get("boolean")), true);
}
// check single array value
sendmsg = "GET /params?tmnt[]=leonardo\r\n\r\n";
@@ -779,9 +779,9 @@ TEST(Crow, simple_url_params) {
c.receive(asio::buffer(buf, 2048));
c.close();
- ASSERT_TRUE(last_url_params.get("tmnt") == nullptr);
- ASSERT_EQUAL(last_url_params.get_list("tmnt").size(), 1);
- ASSERT_EQUAL(string(last_url_params.get_list("tmnt")[0]), "leonardo");
+ ASSERT_TRUE(lastUrlParams.get("tmnt") == nullptr);
+ ASSERT_EQUAL(lastUrlParams.getList("tmnt").size(), 1);
+ ASSERT_EQUAL(string(lastUrlParams.getList("tmnt")[0]), "leonardo");
}
// check multiple array value
sendmsg =
@@ -795,43 +795,43 @@ TEST(Crow, simple_url_params) {
c.receive(asio::buffer(buf, 2048));
c.close();
- ASSERT_EQUAL(last_url_params.get_list("tmnt").size(), 3);
- ASSERT_EQUAL(string(last_url_params.get_list("tmnt")[0]), "leonardo");
- ASSERT_EQUAL(string(last_url_params.get_list("tmnt")[1]), "donatello");
- ASSERT_EQUAL(string(last_url_params.get_list("tmnt")[2]), "raphael");
+ ASSERT_EQUAL(lastUrlParams.getList("tmnt").size(), 3);
+ ASSERT_EQUAL(string(lastUrlParams.getList("tmnt")[0]), "leonardo");
+ ASSERT_EQUAL(string(lastUrlParams.getList("tmnt")[1]), "donatello");
+ ASSERT_EQUAL(string(lastUrlParams.getList("tmnt")[2]), "raphael");
}
server.stop();
}
-TEST(Crow, route_dynamic) {
+TEST(Crow, routeDynamic) {
SimpleApp app;
int x = 1;
- app.route_dynamic("/")([&] {
+ app.routeDynamic("/")([&] {
x = 2;
return "";
});
- app.route_dynamic("/set4")([&](const request&) {
+ app.routeDynamic("/set4")([&](const Request&) {
x = 4;
return "";
});
- app.route_dynamic("/set5")([&](const request&, response& res) {
+ app.routeDynamic("/set5")([&](const Request&, Response& res) {
x = 5;
res.end();
});
- app.route_dynamic("/set_int/<int>")([&](int y) {
+ app.routeDynamic("/set_int/<int>")([&](int y) {
x = y;
return "";
});
try {
- app.route_dynamic("/invalid_test/<double>/<path>")([]() { return ""; });
+ app.routeDynamic("/invalid_test/<double>/<path>")([]() { return ""; });
fail();
} catch (std::exception&) {
}
- // app is in an invalid state when route_dynamic throws an exception.
+ // app is in an invalid state when routeDynamic throws an exception.
try {
app.validate();
fail();
@@ -840,32 +840,32 @@ TEST(Crow, route_dynamic) {
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/";
app.handle(req, res);
ASSERT_EQUAL(x, 2);
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/set_int/42";
app.handle(req, res);
ASSERT_EQUAL(x, 42);
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/set5";
app.handle(req, res);
ASSERT_EQUAL(x, 5);
}
{
boost::beast::http::request<boost::beast::http::string_body> r{};
- request req{r};
- response res;
+ Request req{r};
+ Response res;
req.url = "/set4";
app.handle(req, res);
ASSERT_EQUAL(x, 4);
diff --git a/src/getvideo_main.cpp b/src/getvideo_main.cpp
index bc4d75b1a4..7055d35dfc 100644
--- a/src/getvideo_main.cpp
+++ b/src/getvideo_main.cpp
@@ -20,12 +20,12 @@
#include <ast_video_puller.hpp>
int main() {
- AstVideo::RawVideoBuffer out;
+ ast_video::RawVideoBuffer out;
bool have_hardware = false;
if (access("/dev/video", F_OK) != -1) {
- AstVideo::SimpleVideoPuller p;
+ ast_video::SimpleVideoPuller p;
p.initialize();
- out = p.read_video();
+ out = p.readVideo();
} else {
FILE *fp = fopen("/home/ed/screendata.bin", "rb");
if (fp != nullptr) {
@@ -36,29 +36,29 @@ int main() {
}
fclose(fp);
out.buffer.resize(newLen);
- out.mode = AstVideo::YuvMode::YUV444;
+ out.mode = ast_video::YuvMode::YUV444;
out.width = 800;
out.height = 600;
- out.y_selector = 0;
- out.uv_selector = 0;
+ out.ySelector = 0;
+ out.uvSelector = 0;
}
}
FILE *fp = fopen("/tmp/screendata.bin", "wb");
fwrite(out.buffer.data(), sizeof(char), out.buffer.size(), fp);
- AstVideo::AstJpegDecoder d;
- d.decode(out.buffer, out.width, out.height, out.mode, out.y_selector,
- out.uv_selector);
+ ast_video::AstJpegDecoder d;
+ d.decode(out.buffer, out.width, out.height, out.mode, out.ySelector,
+ out.uvSelector);
#ifdef BUILD_CIMG
cimg_library::CImg<unsigned char> image(out.width, out.height, 1,
3 /*numchannels*/);
for (int y = 0; y < out.height; y++) {
for (int x = 0; x < out.width; x++) {
- auto pixel = d.OutBuffer[x + (y * out.width)];
- image(x, y, 0) = pixel.R;
- image(x, y, 1) = pixel.G;
- image(x, y, 2) = pixel.B;
+ auto pixel = d.outBuffer[x + (y * out.width)];
+ image(x, y, 0) = pixel.r;
+ image(x, y, 1) = pixel.g;
+ image(x, y, 2) = pixel.b;
}
}
image.save("/tmp/file2.bmp");
diff --git a/src/gtest_main.cpp b/src/gtest_main.cpp
index d70149853d..eec00675a3 100644
--- a/src/gtest_main.cpp
+++ b/src/gtest_main.cpp
@@ -1,5 +1,5 @@
-#include "gtest/gtest.h"
#include "gmock/gmock.h"
+#include "gtest/gtest.h"
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
diff --git a/src/kvm_websocket_test.cpp b/src/kvm_websocket_test.cpp
index 94a9ffc7b5..b5e1bdcffd 100644
--- a/src/kvm_websocket_test.cpp
+++ b/src/kvm_websocket_test.cpp
@@ -15,11 +15,11 @@ TEST(Kvm, BasicRfb) {
return; // TODO(ed) Make hte code below work again
SimpleApp app;
- crow::kvm::request_routes(app);
+ crow::kvm::requestRoutes(app);
app.bindaddr("127.0.0.1").port(45451);
- CROW_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
auto _ = async(std::launch::async, [&] { app.run(); });
- auto routes = app.get_routes();
+ auto routes = app.getRoutes();
asio::io_service is;
{
@@ -56,23 +56,23 @@ TEST(Kvm, BasicRfb) {
asio::ip::address::from_string("127.0.0.1"), 45451));
socket.send(asio::buffer(sendmsg));
- // Read the response status line. The response streambuf will automatically
+ // Read the Response status line. The Response streambuf will automatically
// grow to accommodate the entire line. The growth may be limited by passing
// a maximum size to the streambuf constructor.
boost::asio::streambuf response;
boost::asio::read_until(socket, response, "\r\n");
- // Check that response is OK.
+ // Check that Response is OK.
std::istream response_stream(&response);
std::string http_response;
std::getline(response_stream, http_response);
EXPECT_EQ(http_response, "HTTP/1.1 101 Switching Protocols\r");
- // Read the response headers, which are terminated by a blank line.
+ // Read the Response headers, which are terminated by a blank line.
boost::asio::read_until(socket, response, "\r\n\r\n");
- // Process the response headers.
+ // Process the Response headers.
std::string header;
std::vector<std::string> headers;
while (std::getline(response_stream, header) && header != "\r") {
diff --git a/src/security_headers_middleware_test.cpp b/src/security_headers_middleware_test.cpp
index c435921e50..e7008cb165 100644
--- a/src/security_headers_middleware_test.cpp
+++ b/src/security_headers_middleware_test.cpp
@@ -1,7 +1,7 @@
#include <security_headers_middleware.hpp>
#include <crow/app.h>
-#include <gtest/gtest.h>
#include <gmock/gmock.h>
+#include <gtest/gtest.h>
using namespace crow;
using namespace std;
@@ -10,7 +10,7 @@ using namespace std;
TEST(SecurityHeaders, TestHeadersExist) {
App<SecurityHeadersMiddleware> app;
app.bindaddr("127.0.0.1").port(45451);
- CROW_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
auto _ = async(launch::async, [&] { app.run(); });
asio::io_service is;
diff --git a/src/token_authorization_middleware_test.cpp b/src/token_authorization_middleware_test.cpp
index 47acc857fd..ab735b3a52 100644
--- a/src/token_authorization_middleware_test.cpp
+++ b/src/token_authorization_middleware_test.cpp
@@ -23,8 +23,8 @@ class TokenAuth : public ::testing::Test {
TEST_F(TokenAuth, SpecialResourcesAreAcceptedWithoutAuth) {
CrowApp app(io);
- crow::TokenAuthorization::request_routes(app);
- CROW_ROUTE(app, "/redfish/v1")
+ crow::token_authorization::requestRoutes(app);
+ BMCWEB_ROUTE(app, "/redfish/v1")
([]() { return boost::beast::http::status::ok; });
auto _ = std::async(std::launch::async, [&] {
app.port(testPort).run();
@@ -66,10 +66,10 @@ TEST_F(TokenAuth, SpecialResourcesAreAcceptedWithoutAuth) {
// Tests that Base64 basic strings work
TEST(TokenAuthentication, TestRejectedResource) {
- App<crow::PersistentData::Middleware, crow::TokenAuthorization::Middleware>
+ App<crow::persistent_data::Middleware, crow::token_authorization::Middleware>
app;
app.bindaddr("127.0.0.1").port(45451);
- CROW_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
auto _ = async(std::launch::async, [&] { app.run(); });
asio::io_service is;
@@ -96,10 +96,10 @@ TEST(TokenAuthentication, TestRejectedResource) {
// Tests that Base64 basic strings work
TEST(TokenAuthentication, TestGetLoginUrl) {
- App<crow::PersistentData::Middleware, crow::TokenAuthorization::Middleware>
+ App<crow::persistent_data::Middleware, crow::token_authorization::Middleware>
app;
app.bindaddr("127.0.0.1").port(45451);
- CROW_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
auto _ = async(std::launch::async, [&] { app.run(); });
asio::io_service is;
@@ -126,10 +126,10 @@ TEST(TokenAuthentication, TestGetLoginUrl) {
// Tests boundary conditions on login
TEST(TokenAuthentication, TestPostBadLoginUrl) {
- App<crow::PersistentData::Middleware, crow::TokenAuthorization::Middleware>
+ App<crow::persistent_data::Middleware, crow::token_authorization::Middleware>
app;
app.bindaddr("127.0.0.1").port(45451);
- CROW_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
auto _ = async(std::launch::async, [&] { app.run(); });
asio::io_service is;
@@ -210,10 +210,10 @@ class KnownLoginAuthenticator {
};
TEST(TokenAuthentication, TestSuccessfulLogin) {
- App<crow::PersistentData::Middleware, crow::TokenAuthorization::Middleware>
+ App<crow::persistent_data::Middleware, crow::token_authorization::Middleware>
app;
app.bindaddr("127.0.0.1").port(45451);
- CROW_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
+ BMCWEB_ROUTE(app, "/")([]() { return boost::beast::http::status::ok; });
auto _ = async(std::launch::async, [&] { app.run(); });
asio::io_service is;
diff --git a/src/webassets_test.cpp b/src/webassets_test.cpp
index 4f0844bc6f..2633c9b65b 100644
--- a/src/webassets_test.cpp
+++ b/src/webassets_test.cpp
@@ -16,11 +16,11 @@ using namespace testing;
TEST(Webassets, StaticFilesFixedRoutes) {
std::array<char, 2048> buf;
SimpleApp app;
- webassets::request_routes(app);
+ webassets::requestRoutes(app);
Server<SimpleApp> server(&app, "127.0.0.1", 45451);
auto _ = async(launch::async, [&] { server.run(); });
- // Get the homepage
+ // get the homepage
std::string sendmsg = "GET /\r\n\r\n";
asio::io_service is;
@@ -70,7 +70,7 @@ TEST(Webassets, StaticFilesFixedRoutes) {
// Once this occurs, this line will be obsolete
std::string ungziped_content = http_content;
if (content_encoding == "gzip") {
- EXPECT_TRUE(gzip_inflate(http_content, ungziped_content));
+ EXPECT_TRUE(gzipInflate(http_content, ungziped_content));
}
EXPECT_EQ(headers[0], "HTTP/1.1 200 OK");
@@ -86,11 +86,11 @@ TEST(Webassets, StaticFilesFixedRoutes) {
TEST(Webassets, EtagIsSane) {
std::array<char, 2048> buf;
SimpleApp app;
- webassets::request_routes(app);
+ webassets::requestRoutes(app);
Server<SimpleApp> server(&app, "127.0.0.1", 45451);
auto _ = async(launch::async, [&] { server.run(); });
- // Get the homepage
+ // get the homepage
std::string sendmsg = "GET /\r\n\r\n";
asio::io_service is;
diff --git a/src/webserver_main.cpp b/src/webserver_main.cpp
index 55152d6033..e2a776a7e4 100644
--- a/src/webserver_main.cpp
+++ b/src/webserver_main.cpp
@@ -24,21 +24,21 @@
constexpr int defaultPort = 18080;
template <typename... Middlewares>
-void setup_socket(crow::Crow<Middlewares...>& app) {
- int listen_fd = sd_listen_fds(0);
- if (1 == listen_fd) {
- CROW_LOG_INFO << "attempting systemd socket activation";
+void setupSocket(crow::Crow<Middlewares...>& app) {
+ int listenFd = sd_listen_fds(0);
+ if (1 == listenFd) {
+ BMCWEB_LOG_INFO << "attempting systemd socket activation";
if (sd_is_socket_inet(SD_LISTEN_FDS_START, AF_UNSPEC, SOCK_STREAM, 1, 0)) {
- CROW_LOG_INFO << "Starting webserver on socket handle "
- << SD_LISTEN_FDS_START;
+ BMCWEB_LOG_INFO << "Starting webserver on socket handle "
+ << SD_LISTEN_FDS_START;
app.socket(SD_LISTEN_FDS_START);
} else {
- CROW_LOG_INFO << "bad incoming socket, starting webserver on port "
- << defaultPort;
+ BMCWEB_LOG_INFO << "bad incoming socket, starting webserver on port "
+ << defaultPort;
app.port(defaultPort);
}
} else {
- CROW_LOG_INFO << "Starting webserver on port " << defaultPort;
+ BMCWEB_LOG_INFO << "Starting webserver on port " << defaultPort;
app.port(defaultPort);
}
}
@@ -49,47 +49,47 @@ int main(int argc, char** argv) {
auto io = std::make_shared<boost::asio::io_service>();
CrowApp app(io);
-#ifdef CROW_ENABLE_SSL
- std::string ssl_pem_file("server.pem");
- std::cout << "Building SSL context\n";
+#ifdef BMCWEB_ENABLE_SSL
+ std::string sslPemFile("server.pem");
+ std::cout << "Building SSL Context\n";
- ensuressl::ensure_openssl_key_present_and_valid(ssl_pem_file);
+ ensuressl::ensureOpensslKeyPresentAndValid(sslPemFile);
std::cout << "SSL Enabled\n";
- auto ssl_context = ensuressl::get_ssl_context(ssl_pem_file);
- app.ssl(std::move(ssl_context));
+ auto sslContext = ensuressl::getSslContext(sslPemFile);
+ app.ssl(std::move(sslContext));
#endif
// Static assets need to be initialized before Authorization, because auth
// needs to build the whitelist from the static routes
#ifdef BMCWEB_ENABLE_PHOSPHOR_WEBUI
- crow::webassets::request_routes(app);
+ crow::webassets::requestRoutes(app);
#endif
#ifdef BMCWEB_ENABLE_KVM
- crow::kvm::request_routes(app);
+ crow::kvm::requestRoutes(app);
#endif
#ifdef BMCWEB_ENABLE_REDFISH
- crow::redfish::request_routes(app);
+ crow::redfish::requestRoutes(app);
#endif
#ifdef BMCWEB_ENABLE_DBUS_REST
- crow::dbus_monitor::request_routes(app);
+ crow::dbus_monitor::requestRoutes(app);
crow::image_upload::requestRoutes(app);
- crow::openbmc_mapper::request_routes(app);
+ crow::openbmc_mapper::requestRoutes(app);
#endif
- crow::TokenAuthorization::request_routes(app);
+ crow::token_authorization::requestRoutes(app);
- CROW_LOG_INFO << "bmcweb (" << __DATE__ << ": " << __TIME__ << ')';
- setup_socket(app);
+ BMCWEB_LOG_INFO << "bmcweb (" << __DATE__ << ": " << __TIME__ << ')';
+ setupSocket(app);
- crow::connections::system_bus =
+ crow::connections::systemBus =
std::make_shared<sdbusplus::asio::connection>(*io);
redfish::RedfishService redfish(app);
app.run();
io->run();
- crow::connections::system_bus.reset();
+ crow::connections::systemBus.reset();
}