incremental
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 9035ee7..d33e4a4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -45,12 +45,16 @@
option(BUILD_SHARED_LIBS "Build as shared library" OFF)
option(BUILD_UT "Enable Unit test" OFF)
+# This needs to be before the crow and other module includes so headers get overriden correctly
+include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
+
# security flags
#SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fstack-protector-strong -fPIE -fPIC -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security" )
#SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -z noexecstack -z relro -z now")
# Boost
#add_definitions(-DBOOST_ASIO_ENABLE_HANDLER_TRACKING)
+#add_definitions(-DBOOST_ERROR_CODE_HEADER_ONLY)
add_definitions(-DBOOST_ALL_NO_LIB)
set(Boost_USE_STATIC_LIBS ON)
hunter_add_package(Boost COMPONENTS system thread)
@@ -60,15 +64,9 @@
hunter_add_package(OpenSSL)
find_package(OpenSSL REQUIRED)
-# Crow
-add_definitions(-DCROW_ENABLE_SSL)
-include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/crow/include)
-#add_subdirectory(crow)
+
#g3 logging
-#option(ADD_FATAL_EXAMPLE "Disable g3 examples" OFF)
-#add_subdirectory(g3log)
-#include_directories(g3log/src)
# G3logger does some unfortunate compile options, so cheat a little bit and copy/paste
set(LOG_SRC ${CMAKE_CURRENT_SOURCE_DIR}/g3log/src)
@@ -84,14 +82,18 @@
# Create the g3log library
include_directories(${LOG_SRC})
-#MESSAGE(" g3logger files: [${SRC_FILES}]")
+
add_library(g3logger ${SRC_FILES})
set_target_properties(g3logger PROPERTIES
LINKER_LANGUAGE CXX
OUTPUT_NAME g3logger
CLEAN_DIRECT_OUTPUT 1)
target_link_libraries(g3logger ${PLATFORM_LINK_LIBRIES})
-SET(G3LOG_LIBRARY g3logger)
+
+
+# Crow
+add_definitions(-DCROW_ENABLE_SSL)
+include_directories( ${CMAKE_CURRENT_SOURCE_DIR}/crow/include)
#Zlib
#hunter_add_package(ZLIB)
@@ -103,7 +105,7 @@
set(WEBSERVER_MAIN src/webserver_main.cpp)
set(HDR_FILES
- include/crow_g3_logger.hpp
+ include/crow/g3_logger.hpp
include/ssl_key_handler.hpp
include/color_cout_g3_sink.hpp
include/webassets.hpp
@@ -124,11 +126,13 @@
set(SRC_FILES
src/token_authorization_middleware.cpp
+ src/security_headers_middleware.cpp
src/base64.cpp
${GENERATED_SRC_FILES}
)
set(UT_FILES
+ src/crowtest/crow_unittest.cpp
src/gtest_main.cpp
src/base64_test.cpp
src/token_authorization_middleware_test.cpp
@@ -149,7 +153,7 @@
add_executable(unittest ${HDR_FILES} ${SRC_FILES} ${UT_FILES})
target_link_libraries(unittest GTest::GTest GTest::Main)
- target_link_libraries(unittest ${BOOST_LIBRARIES} Boost::system Boost::thread)
+ target_link_libraries(unittest Boost::system Boost::thread)
target_link_libraries(unittest ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(unittest OpenSSL::SSL OpenSSL::Crypto)
target_link_libraries(unittest g3logger)
@@ -162,7 +166,7 @@
# bmcweb
add_executable(bmcweb ${WEBSERVER_MAIN} ${HDR_FILES} ${SRC_FILES})
-target_link_libraries(bmcweb ${BOOST_LIBRARIES} Boost::system Boost::thread)
+target_link_libraries(bmcweb Boost::system Boost::thread)
target_link_libraries(bmcweb ${CMAKE_THREAD_LIBS_INIT})
target_link_libraries(bmcweb OpenSSL::SSL OpenSSL::Crypto)
target_link_libraries(bmcweb g3logger)
@@ -170,7 +174,6 @@
add_dependencies(bmcweb packagestaticcpp)
# bmcweb
-#add_definitions(-DBOOST_ALL_NO_LIB)
add_executable(udpclient src/udpclient.cpp)
target_link_libraries(udpclient Boost::system)
@@ -179,9 +182,6 @@
add_executable(getvideo src/getvideo_main.cpp)
-
-include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
-
# Visual Studio Code helper
# this needs to be at the end to make sure all includes are handled correctly
get_property(C_INCLUDE_DIRS DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY INCLUDE_DIRECTORIES)
diff --git a/docs/profile.md b/docs/profile.md
index 3a2156e..b6a0019 100644
--- a/docs/profile.md
+++ b/docs/profile.md
@@ -1,6 +1,6 @@
LD_LIBRARY_PATH=/tmp LD_PRELOAD=libprofiler.so CPUPROFILE=/tmp/profile ./bmcweb
-scp ed@hades.jf.intel.com:/home/ed/webserver/buildarm/bmcweb /tmp
+scp ed@hades.jf.intel.com:/home/ed/webserver/buildarm/bmcweb /tmp -i /nv/.ssh/id_rsa
scp ed@hades.jf.intel.com:/home/ed/webserver/buildarm/getvideo /tmp -i /nv/.ssh/id_rsa
scp ed@hades.jf.intel.com:/home/ed/gperftools/.libs/libprofiler.so /tmp
diff --git a/include/app_type.hpp b/include/app_type.hpp
deleted file mode 100644
index e88d728..0000000
--- a/include/app_type.hpp
+++ /dev/null
@@ -1,6 +0,0 @@
-#pragma once
-
-#include <crow/app.h>
-#include <token_authorization_middleware.hpp>
-
-using BmcAppType = crow::App<crow::TokenAuthorizationMiddleware>;
\ No newline at end of file
diff --git a/include/crow/bmc_app_type.hpp b/include/crow/bmc_app_type.hpp
new file mode 100644
index 0000000..061143b
--- /dev/null
+++ b/include/crow/bmc_app_type.hpp
@@ -0,0 +1,7 @@
+#pragma once
+
+#include <crow/app.h>
+#include <token_authorization_middleware.hpp>
+#include <security_headers_middleware.hpp>
+
+using BmcAppType = crow::App<crow::TokenAuthorizationMiddleware, crow::SecurityHeadersMiddleware>;
\ No newline at end of file
diff --git a/include/crow_g3_logger.hpp b/include/crow/g3_logger.hpp
similarity index 84%
rename from include/crow_g3_logger.hpp
rename to include/crow/g3_logger.hpp
index be84de0..8980207 100644
--- a/include/crow_g3_logger.hpp
+++ b/include/crow/g3_logger.hpp
@@ -34,30 +34,25 @@
class logger {
public:
- logger(std::string prefix, LogLevel level) : level_(level) {
+ logger(std::string prefix, LogLevel level) {
// no op, let g3 handle th log levels
}
//
template <typename T>
logger& operator<<(T const& value) {
-#ifdef CROW_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) { }
static LogLevel get_current_log_level() { return get_log_level_ref(); }
private:
//
static LogLevel& get_log_level_ref() {
- static LogLevel current_level = (LogLevel)CROW_LOG_LEVEL;
+ static LogLevel current_level = LogLevel::DEBUG;
return current_level;
}
diff --git a/include/security_headers_middleware.hpp b/include/security_headers_middleware.hpp
new file mode 100644
index 0000000..7e84543
--- /dev/null
+++ b/include/security_headers_middleware.hpp
@@ -0,0 +1,15 @@
+#pragma once
+
+#include <crow/http_request.h>
+#include <crow/http_response.h>
+
+namespace crow {
+
+struct SecurityHeadersMiddleware {
+ struct context {};
+
+ void before_handle(crow::request& req, response& res, context& ctx);
+
+ void after_handle(request& req, response& res, context& ctx);
+};
+}
\ No newline at end of file
diff --git a/include/token_authorization_middleware.hpp b/include/token_authorization_middleware.hpp
index 1602656..58766b9 100644
--- a/include/token_authorization_middleware.hpp
+++ b/include/token_authorization_middleware.hpp
@@ -17,10 +17,13 @@
std::string auth_token;
};
- std::string auth_token2;
+ TokenAuthorizationMiddleware();
void before_handle(crow::request& req, response& res, context& ctx);
void after_handle(request& req, response& res, context& ctx);
+
+ private:
+ std::string auth_token2;
};
}
\ No newline at end of file
diff --git a/include/web_kvm.hpp b/include/web_kvm.hpp
index 24544fc..65fe812 100644
--- a/include/web_kvm.hpp
+++ b/include/web_kvm.hpp
@@ -1,7 +1,7 @@
#include <boost/endian/arithmetic.hpp>
#include <string>
-#include "app_type.hpp"
+#include <crow/bmc_app_type.hpp>
#include <video.h>
diff --git a/include/webassets.hpp b/include/webassets.hpp
index b5431bc..1994cf5 100644
--- a/include/webassets.hpp
+++ b/include/webassets.hpp
@@ -7,7 +7,7 @@
#include <crow/http_response.h>
#include <crow/routing.h>
-#include <app_type.hpp>
+#include <crow/bmc_app_type.hpp>
namespace crow {
diff --git a/scripts/build_web_assets.py b/scripts/build_web_assets.py
index 8268787..0521bd7 100755
--- a/scripts/build_web_assets.py
+++ b/scripts/build_web_assets.py
@@ -99,7 +99,7 @@
string_content_new = re.sub("((src|href)=[\"'])(" + re.escape(key) + ")([\"'])", "\\1" + replace_name + "\\4", string_content)
if string_content_new != string_content:
print(" Replaced {}".format(key))
- print(" With {}".format(replace_name))
+ print(" With {}".format(replace_name))
string_content = string_content_new
return string_content.encode()
@@ -184,8 +184,8 @@
if match:
depends_on[full_filepath].append(full_replacename)
- elif ext == ".js":
- match = re.search("([\"'])(" + relative_replacename + ")([\"'])", file_content)
+ elif ext == ".js" or ext == ".css":
+ match = re.search("([\"'](\.\./)*)(" + relative_replacename + ")([\"'\?])", file_content)
if match:
depends_on[full_filepath].append(full_replacename)
@@ -206,12 +206,13 @@
with open(full_filepath, 'rb') as input_file:
file_content = input_file.read()
relative_path, relative_path_escaped = get_relative_path(full_filepath)
+ extension = os.path.splitext(relative_path)[1]
print("Including {:<40} size {:>7}".format(relative_path, len(file_content)))
- if relative_path.endswith(".html") or relative_path == "/":
+ if extension == ".html" or relative_path == "/":
new_file_content = filter_html(sha1_list, file_content)
- elif relative_path.endswith(".js"):
+ elif extension == ".js" or extension == ".css":
new_file_content = filter_js(sha1_list, file_content)
else:
new_file_content = file_content
@@ -248,10 +249,6 @@
if relative_path == "static/index.html":
relative_path = "/"
relative_path_sha1 = "/"
- # TODO(ed), handle woff files better. They are referenced in CSS, which at this
- # point isn't scrubbed with a find and replace algorithm
- elif relative_path.endswith(".woff"):
- relative_path_sha1 = relative_path
else:
relative_path_sha1 = "/" + get_sha1_path_from_relative(relative_path, sha1)
@@ -271,7 +268,7 @@
# if we have a valid sha1, and we have a unique path to the resource
# it can be safely cached forever
if sha1 != "" and relative_path != relative_path_sha1:
- environment["CACHE_FOREVER_HEADER"] = CACHE_FOREVER_HEADER
+ environment["CACHE_FOREVER_HEADER"] = CACHE_FOREVER_HEADER
content = CPP_MIDDLE_BUFFER.format(
**environment
diff --git a/src/crowtest/about.txt b/src/crowtest/about.txt
new file mode 100644
index 0000000..bd55fd1
--- /dev/null
+++ b/src/crowtest/about.txt
@@ -0,0 +1 @@
+This folder contains a port of the CROW unit tests, ported to google test to maek them easier to run
\ No newline at end of file
diff --git a/src/crowtest/crow_unittest.cpp b/src/crowtest/crow_unittest.cpp
new file mode 100644
index 0000000..8072c92
--- /dev/null
+++ b/src/crowtest/crow_unittest.cpp
@@ -0,0 +1,1091 @@
+//#define CROW_ENABLE_LOGGING
+#define CROW_ENABLE_DEBUG
+#include <iostream>
+#include <sstream>
+#include <vector>
+#include "crow.h"
+#include "gtest/gtest.h"
+#undef CROW_LOG_LEVEL
+#define CROW_LOG_LEVEL 0
+
+using namespace std;
+using namespace crow;
+
+bool failed__ = false;
+void error_print()
+{
+ cerr << endl;
+}
+
+template <typename A, typename ...Args>
+void error_print(const A& a, Args...args)
+{
+ cerr<<a;
+ error_print(args...);
+}
+
+template <typename ...Args>
+void fail(Args...args) { error_print(args...);failed__ = true; }
+
+#define ASSERT_EQUAL(a, b) if ((a) != (b)) fail(__FILE__ ":", __LINE__, ": Assert fail: expected ", (a), " actual ", (b), ", " #a " == " #b ", at " __FILE__ ":",__LINE__)
+#define ASSERT_NOTEQUAL(a, b) if ((a) == (b)) fail(__FILE__ ":", __LINE__, ": Assert fail: not expected ", (a), ", " #a " != " #b ", at " __FILE__ ":",__LINE__)
+
+#define DISABLE_TEST(x) struct test##x{void test();}x##_; \
+ void test##x::test()
+
+
+#define LOCALHOST_ADDRESS "127.0.0.1"
+
+
+TEST(Crow, Rule)
+{
+ TaggedRule<> r("/http/");
+ r.name("abc");
+
+ // empty handler - fail to validate
+ try
+ {
+ r.validate();
+ fail("empty handler should fail to validate");
+ }
+ catch(runtime_error& e)
+ {
+ }
+
+ int x = 0;
+
+ // registering handler
+ r([&x]{x = 1;return "";});
+
+ r.validate();
+
+ response res;
+
+ // executing handler
+ ASSERT_EQUAL(0, x);
+ r.handle(request(), res, routing_params());
+ ASSERT_EQUAL(1, x);
+
+ // registering handler with request argument
+ r([&x](const crow::request&){x = 2;return "";});
+
+ r.validate();
+
+ // executing handler
+ ASSERT_EQUAL(1, x);
+ r.handle(request(), res, routing_params());
+ 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");
+ 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>"));
+ ASSERT_EQUAL(3, black_magic::get_parameter_tag("<double>"));
+ ASSERT_EQUAL(4, black_magic::get_parameter_tag("<str>"));
+ ASSERT_EQUAL(4, black_magic::get_parameter_tag("<string>"));
+ ASSERT_EQUAL(5, black_magic::get_parameter_tag("<path>"));
+ ASSERT_EQUAL(6*6+6+1, black_magic::get_parameter_tag("<int><int><int>"));
+ ASSERT_EQUAL(6*6+6+2, black_magic::get_parameter_tag("<uint><int><int>"));
+ ASSERT_EQUAL(6*6+6*3+2, black_magic::get_parameter_tag("<uint><double><int>"));
+
+ // url definition parsed in compile time, build into *one number*, and given 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, "tag to type container");
+}
+
+TEST(Crow, PathRouting)
+{
+ SimpleApp app;
+
+ CROW_ROUTE(app, "/file")
+ ([]{
+ return "file";
+ });
+
+ CROW_ROUTE(app, "/path/")
+ ([]{
+ return "path";
+ });
+
+ {
+ request req;
+ response res;
+
+ req.url = "/file";
+
+ app.handle(req, res);
+
+ ASSERT_EQUAL(200, res.code);
+ }
+ {
+ request req;
+ response res;
+
+ req.url = "/file/";
+
+ app.handle(req, res);
+ ASSERT_EQUAL(404, res.code);
+ }
+ {
+ request req;
+ response res;
+
+ req.url = "/path";
+
+ app.handle(req, res);
+ ASSERT_NOTEQUAL(404, res.code);
+ }
+ {
+ request req;
+ response res;
+
+ req.url = "/path/";
+
+ app.handle(req, res);
+ ASSERT_EQUAL(200, res.code);
+ }
+}
+
+TEST(Crow, RoutingTest)
+{
+ SimpleApp app;
+ int A{};
+ uint32_t B{};
+ double C{};
+ string D{};
+ string E{};
+
+ CROW_ROUTE(app, "/0/<uint>")
+ ([&](uint32_t b){
+ B = b;
+ return "OK";
+ });
+
+ CROW_ROUTE(app, "/1/<int>/<uint>")
+ ([&](int a, uint32_t b){
+ A = a; B = b;
+ return "OK";
+ });
+
+ CROW_ROUTE(app, "/4/<int>/<uint>/<double>/<string>")
+ ([&](int a, uint32_t b, double c, string d){
+ A = a; B = b; C = c; D = d;
+ return "OK";
+ });
+
+ CROW_ROUTE(app, "/5/<int>/<uint>/<double>/<string>/<path>")
+ ([&](int a, uint32_t b, double c, string d, string e){
+ A = a; B = b; C = c; D = d; E = e;
+ return "OK";
+ });
+
+ app.validate();
+ //app.debug_print();
+ {
+ request req;
+ response res;
+
+ req.url = "/-1";
+
+ app.handle(req, res);
+
+ ASSERT_EQUAL(404, res.code);
+ }
+
+ {
+ request req;
+ response res;
+
+ req.url = "/0/1001999";
+
+ app.handle(req, res);
+
+ ASSERT_EQUAL(200, res.code);
+
+ ASSERT_EQUAL(1001999, B);
+ }
+
+ {
+ request req;
+ response res;
+
+ req.url = "/1/-100/1999";
+
+ app.handle(req, res);
+
+ ASSERT_EQUAL(200, res.code);
+
+ ASSERT_EQUAL(-100, A);
+ ASSERT_EQUAL(1999, B);
+ }
+ {
+ request req;
+ response res;
+
+ req.url = "/4/5000/3/-2.71828/hellhere";
+ req.add_header("TestHeader", "Value");
+
+ app.handle(req, res);
+
+ ASSERT_EQUAL(200, res.code);
+
+ ASSERT_EQUAL(5000, A);
+ ASSERT_EQUAL(3, B);
+ ASSERT_EQUAL(-2.71828, C);
+ ASSERT_EQUAL("hellhere", D);
+ }
+ {
+ request req;
+ response res;
+
+ req.url = "/5/-5/999/3.141592/hello_there/a/b/c/d";
+ req.add_header("TestHeader", "Value");
+
+ app.handle(req, res);
+
+ ASSERT_EQUAL(200, res.code);
+
+ ASSERT_EQUAL(-5, A);
+ 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)
+{
+ ASSERT_EQUAL(100, response(100).code);
+ ASSERT_EQUAL(200, response("Hello there").code);
+ ASSERT_EQUAL(500, response(500, "Internal Error?").code);
+
+ 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");
+ ASSERT_EQUAL(1, rp.get<int64_t>(0));
+ ASSERT_EQUAL(5, rp.get<int64_t>(1));
+ ASSERT_EQUAL(2, rp.get<uint64_t>(0));
+ ASSERT_EQUAL(3, rp.get<double>(0));
+ ASSERT_EQUAL("hello", rp.get<string>(0));
+}
+
+TEST(Crow, handler_with_response)
+{
+ SimpleApp app;
+ CROW_ROUTE(app, "/")([](const crow::request&, crow::response&)
+ {
+ });
+}
+
+TEST(Crow, http_method)
+{
+ SimpleApp app;
+
+ CROW_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";
+ });
+
+
+ // cannot have multiple handlers for the same url
+ //CROW_ROUTE(app, "/")
+ //.methods("GET"_method)
+ //([]{ return "2"; });
+
+ {
+ request req;
+ response res;
+
+ req.url = "/";
+ app.handle(req, res);
+
+ ASSERT_EQUAL("2", res.body);
+ }
+ {
+ request req;
+ response res;
+
+ req.url = "/";
+ req.method = "POST"_method;
+ app.handle(req, res);
+
+ ASSERT_EQUAL("1", res.body);
+ }
+
+ {
+ request req;
+ response res;
+
+ req.url = "/get_only";
+ app.handle(req, res);
+
+ ASSERT_EQUAL("get", res.body);
+ }
+
+ {
+ request req;
+ response res;
+
+ req.url = "/get_only";
+ req.method = "POST"_method;
+ app.handle(req, res);
+
+ ASSERT_NOTEQUAL("get", res.body);
+ }
+
+}
+
+TEST(Crow, server_handling_error_request)
+{
+ static char buf[2048];
+ SimpleApp app;
+ CROW_ROUTE(app, "/")([]{return "A";});
+ Server<SimpleApp> server(&app, LOCALHOST_ADDRESS, 45451);
+ auto _ = async(launch::async, [&]{server.run();});
+ std::string sendmsg = "POX";
+ asio::io_service is;
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+
+
+ c.send(asio::buffer(sendmsg));
+
+ try
+ {
+ c.receive(asio::buffer(buf, 2048));
+ fail();
+ }
+ catch(std::exception& e)
+ {
+ //std::cerr << e.what() << std::endl;
+ }
+ }
+ server.stop();
+}
+
+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";});
+
+ Server<SimpleApp> server1(&app1, LOCALHOST_ADDRESS, 45451);
+ Server<SimpleApp> server2(&app2, LOCALHOST_ADDRESS, 45452);
+
+ auto _ = async(launch::async, [&]{server1.run();});
+ 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";
+ asio::io_service is;
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+
+ c.send(asio::buffer(sendmsg));
+
+ size_t recved = c.receive(asio::buffer(buf, 2048));
+ ASSERT_EQUAL('A', buf[recved-1]);
+ }
+
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45452));
+
+ for(auto ch:sendmsg)
+ {
+ char buf[1] = {ch};
+ c.send(asio::buffer(buf));
+ }
+
+ size_t recved = c.receive(asio::buffer(buf, 2048));
+ ASSERT_EQUAL('B', buf[recved-1]);
+ }
+
+ server1.stop();
+ server2.stop();
+}
+
+TEST(Crow, json_read)
+{
+ {
+ const char* json_error_tests[] =
+ {
+ "{} 3", "{{}", "{3}",
+ "3.4.5", "+3", "3-2", "00", "03", "1e3e3", "1e+.3",
+ "nll", "f", "t",
+ "{\"x\":3,}",
+ "{\"x\"}",
+ "{\"x\":3 q}",
+ "{\"x\":[3 4]}",
+ "{\"x\":[\"",
+ "{\"x\":[[], 4],\"y\",}",
+ "{\"x\":[3",
+ "{\"x\":[ null, false, true}",
+ };
+ for(auto s:json_error_tests)
+ {
+ auto x = json::load(s);
+ if (x)
+ {
+ fail("should fail to parse ", s);
+ return;
+ }
+ }
+ }
+
+ auto x = json::load(R"({"message":"hello, world"})");
+ if (!x)
+ fail("fail to parse");
+ ASSERT_EQUAL("hello, world", x["message"]);
+ ASSERT_EQUAL(1, x.size());
+ ASSERT_EQUAL(false, x.has("mess"));
+ ASSERT_THROW(x["mess"], std::exception);
+ // TODO returning false is better than exception
+ //ASSERT_THROW(3 == x["message"], std::exception);
+ ASSERT_EQUAL(12, x["message"].size());
+
+ std::string s = R"({"int":3, "ints" :[1,2,3,4,5] })";
+ auto y = json::load(s);
+ ASSERT_EQUAL(3, y["int"]);
+ ASSERT_EQUAL(3.0, y["int"]);
+ ASSERT_NOTEQUAL(3.01, y["int"]);
+ ASSERT_EQUAL(5, y["ints"].size());
+ ASSERT_EQUAL(1, y["ints"][0]);
+ ASSERT_EQUAL(2, y["ints"][1]);
+ ASSERT_EQUAL(3, y["ints"][2]);
+ ASSERT_EQUAL(4, y["ints"][3]);
+ ASSERT_EQUAL(5, y["ints"][4]);
+ ASSERT_EQUAL(1u, y["ints"][0]);
+ ASSERT_EQUAL(1.f, y["ints"][0]);
+
+ int q = (int)y["ints"][1];
+ ASSERT_EQUAL(2, q);
+ q = y["ints"][2].i();
+ ASSERT_EQUAL(3, q);
+
+ std::string s2 = R"({"bools":[true, false], "doubles":[1.2, -3.4]})";
+ auto z = json::load(s2);
+ ASSERT_EQUAL(2, z["bools"].size());
+ ASSERT_EQUAL(2, z["doubles"].size());
+ ASSERT_EQUAL(true, z["bools"][0].b());
+ ASSERT_EQUAL(false, z["bools"][1].b());
+ ASSERT_EQUAL(1.2, z["doubles"][0].d());
+ ASSERT_EQUAL(-3.4, z["doubles"][1].d());
+
+ std::string s3 = R"({"uint64": 18446744073709551615})";
+ auto z1 = json::load(s3);
+ ASSERT_EQUAL(18446744073709551615ull, z1["uint64"].u());
+}
+
+TEST(Crow, json_read_real)
+{
+ vector<std::string> v{"0.036303908355795146", "0.18320417789757412",
+ "0.05319940476190476", "0.15224702380952382", "0", "0.3296201145552561",
+ "0.47921580188679247", "0.05873511904761905", "0.1577827380952381",
+ "0.4996841307277628", "0.6425412735849056", "0.052113095238095236",
+ "0.12830357142857143", "0.7871041105121294", "0.954220013477089",
+ "0.05869047619047619", "0.1625", "0.8144794474393531",
+ "0.9721613881401617", "0.1399404761904762", "0.24470238095238095",
+ "0.04527459568733154", "0.2096950808625337", "0.35267857142857145",
+ "0.42791666666666667", "0.855731974393531", "0.9352467991913747",
+ "0.3816220238095238", "0.4282886904761905", "0.39414167789757415",
+ "0.5316079851752021", "0.3809375", "0.4571279761904762",
+ "0.03522995283018868", "0.1915641846361186", "0.6164136904761904",
+ "0.7192708333333333", "0.05675117924528302", "0.21308541105121293",
+ "0.7045386904761904", "0.8016815476190476"};
+ for(auto x:v)
+ {
+ CROW_LOG_DEBUG << x;
+ ASSERT_EQUAL(json::load(x).d(), boost::lexical_cast<double>(x));
+ }
+
+ auto ret = json::load(R"---({"balloons":[{"mode":"ellipse","left":0.036303908355795146,"right":0.18320417789757412,"top":0.05319940476190476,"bottom":0.15224702380952382,"index":"0"},{"mode":"ellipse","left":0.3296201145552561,"right":0.47921580188679247,"top":0.05873511904761905,"bottom":0.1577827380952381,"index":"1"},{"mode":"ellipse","left":0.4996841307277628,"right":0.6425412735849056,"top":0.052113095238095236,"bottom":0.12830357142857143,"index":"2"},{"mode":"ellipse","left":0.7871041105121294,"right":0.954220013477089,"top":0.05869047619047619,"bottom":0.1625,"index":"3"},{"mode":"ellipse","left":0.8144794474393531,"right":0.9721613881401617,"top":0.1399404761904762,"bottom":0.24470238095238095,"index":"4"},{"mode":"ellipse","left":0.04527459568733154,"right":0.2096950808625337,"top":0.35267857142857145,"bottom":0.42791666666666667,"index":"5"},{"mode":"ellipse","left":0.855731974393531,"right":0.9352467991913747,"top":0.3816220238095238,"bottom":0.4282886904761905,"index":"6"},{"mode":"ellipse","left":0.39414167789757415,"right":0.5316079851752021,"top":0.3809375,"bottom":0.4571279761904762,"index":"7"},{"mode":"ellipse","left":0.03522995283018868,"right":0.1915641846361186,"top":0.6164136904761904,"bottom":0.7192708333333333,"index":"8"},{"mode":"ellipse","left":0.05675117924528302,"right":0.21308541105121293,"top":0.7045386904761904,"bottom":0.8016815476190476,"index":"9"}]})---");
+ ASSERT_TRUE(ret);
+}
+
+TEST(Crow, json_read_unescaping)
+{
+ {
+ auto x = json::load(R"({"data":"\ud55c\n\t\r"})");
+ if (!x)
+ {
+ fail("fail to parse");
+ return;
+ }
+ ASSERT_EQUAL(6, x["data"].size());
+ ASSERT_EQUAL("한\n\t\r", x["data"]);
+ }
+ {
+ // multiple r_string instance
+ auto x = json::load(R"({"data":"\ud55c\n\t\r"})");
+ auto a = x["data"].s();
+ auto b = x["data"].s();
+ ASSERT_EQUAL(6, a.size());
+ ASSERT_EQUAL(6, b.size());
+ ASSERT_EQUAL(6, x["data"].size());
+ }
+}
+
+TEST(Crow, json_write)
+{
+ json::wvalue x;
+ x["message"] = "hello world";
+ ASSERT_EQUAL(R"({"message":"hello world"})", json::dump(x));
+ x["message"] = std::string("string value");
+ ASSERT_EQUAL(R"({"message":"string value"})", json::dump(x));
+ x["message"]["x"] = 3;
+ ASSERT_EQUAL(R"({"message":{"x":3}})", json::dump(x));
+ x["message"]["y"] = 5;
+ ASSERT_TRUE(R"({"message":{"x":3,"y":5}})" == json::dump(x) || R"({"message":{"y":5,"x":3}})" == json::dump(x));
+ x["message"] = 5.5;
+ ASSERT_EQUAL(R"({"message":5.5})", json::dump(x));
+
+ json::wvalue y;
+ y["scores"][0] = 1;
+ y["scores"][1] = "king";
+ y["scores"][2] = 3.5;
+ ASSERT_EQUAL(R"({"scores":[1,"king",3.5]})", json::dump(y));
+
+ y["scores"][2][0] = "real";
+ y["scores"][2][1] = false;
+ y["scores"][2][2] = true;
+ ASSERT_EQUAL(R"({"scores":[1,"king",["real",false,true]]})", json::dump(y));
+
+ y["scores"]["a"]["b"]["c"] = nullptr;
+ ASSERT_EQUAL(R"({"scores":{"a":{"b":{"c":null}}}})", json::dump(y));
+
+ y["scores"] = std::vector<int>{1,2,3};
+ ASSERT_EQUAL(R"({"scores":[1,2,3]})", json::dump(y));
+
+}
+
+TEST(Crow, template_basic)
+{
+ auto t = crow::mustache::compile(R"---(attack of {{name}})---");
+ crow::mustache::context ctx;
+ ctx["name"] = "killer tomatoes";
+ auto result = t.render(ctx);
+ ASSERT_EQUAL("attack of killer tomatoes", result);
+ //crow::mustache::load("basic.mustache");
+}
+
+TEST(Crow, template_load)
+{
+ crow::mustache::set_base(".");
+ ofstream("test.mustache") << R"---(attack of {{name}})---";
+ auto t = crow::mustache::load("test.mustache");
+ crow::mustache::context ctx;
+ ctx["name"] = "killer tomatoes";
+ auto result = t.render(ctx);
+ ASSERT_EQUAL("attack of killer tomatoes", result);
+ unlink("test.mustache");
+}
+
+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");
+ static_assert(std::is_same<int, pop_back<int, char, void>::rebind<pop_back>::rebind<last_element_type>::type>::value, "pop_back");
+}
+
+struct NullMiddleware
+{
+ struct context {};
+
+ template <typename AllContext>
+ void before_handle(request&, response&, context&, AllContext&)
+ {}
+
+ template <typename AllContext>
+ void after_handle(request&, response&, context&, AllContext&)
+ {}
+};
+
+struct NullSimpleMiddleware
+{
+ struct context {};
+
+ void before_handle(request& /*req*/, response& /*res*/, context& /*ctx*/)
+ {}
+
+ void after_handle(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);
+ return "";
+ });
+}
+
+struct IntSettingMiddleware
+{
+ struct context { int val; };
+
+ template <typename AllContext>
+ void before_handle(request&, response&, context& ctx, AllContext& )
+ {
+ ctx.val = 1;
+ }
+
+ template <typename AllContext>
+ void after_handle(request&, response&, context& ctx, AllContext& )
+ {
+ ctx.val = 2;
+ }
+};
+
+std::vector<std::string> test_middleware_context_vector;
+
+struct FirstMW
+{
+ struct context
+ {
+ std::vector<string> v;
+ };
+
+ void before_handle(request& /*req*/, response& /*res*/, context& ctx)
+ {
+ ctx.v.push_back("1 before");
+ }
+
+ void after_handle(request& /*req*/, response& /*res*/, context& ctx)
+ {
+ ctx.v.push_back("1 after");
+ test_middleware_context_vector = ctx.v;
+ }
+};
+
+struct SecondMW
+{
+ struct context {};
+ template <typename AllContext>
+ void before_handle(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)
+ {
+ all_ctx.template get<FirstMW>().v.push_back("2 after");
+ }
+};
+
+struct ThirdMW
+{
+ struct context {};
+ template <typename AllContext>
+ void before_handle(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)
+ {
+ all_ctx.template get<FirstMW>().v.push_back("3 after");
+ }
+};
+
+TEST(Crow, middleware_context)
+{
+
+ 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
+ // App<IntSettingMiddleware, SecondMW> app;
+ // or change the order of FirstMW and SecondMW
+ // App<IntSettingMiddleware, SecondMW, FirstMW> app;
+
+ App<IntSettingMiddleware, FirstMW, SecondMW, ThirdMW> app;
+
+ int x{};
+ CROW_ROUTE(app, "/")([&](const request& req){
+ {
+ auto& ctx = app.get_context<IntSettingMiddleware>(req);
+ x = ctx.val;
+ }
+ {
+ auto& ctx = app.get_context<FirstMW>(req);
+ ctx.v.push_back("handle");
+ }
+
+ return "";
+ });
+ CROW_ROUTE(app, "/break")([&](const request& req){
+ {
+ auto& ctx = app.get_context<FirstMW>(req);
+ ctx.v.push_back("handle");
+ }
+
+ return "";
+ });
+
+ decltype(app)::server_t server(&app, LOCALHOST_ADDRESS, 45451);
+ auto _ = async(launch::async, [&]{server.run();});
+ std::string sendmsg = "GET /\r\n\r\n";
+ asio::io_service is;
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+
+
+ c.send(asio::buffer(sendmsg));
+
+ c.receive(asio::buffer(buf, 2048));
+ c.close();
+ }
+ {
+ auto& out = test_middleware_context_vector;
+ ASSERT_EQUAL(1, x);
+ ASSERT_EQUAL(7, out.size());
+ ASSERT_EQUAL("1 before", out[0]);
+ ASSERT_EQUAL("2 before", out[1]);
+ ASSERT_EQUAL("3 before", out[2]);
+ ASSERT_EQUAL("handle", out[3]);
+ ASSERT_EQUAL("3 after", out[4]);
+ ASSERT_EQUAL("2 after", out[5]);
+ ASSERT_EQUAL("1 after", out[6]);
+ }
+ std::string sendmsg2 = "GET /break\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+
+ c.send(asio::buffer(sendmsg2));
+
+ c.receive(asio::buffer(buf, 2048));
+ c.close();
+ }
+ {
+ auto& out = test_middleware_context_vector;
+ ASSERT_EQUAL(4, out.size());
+ ASSERT_EQUAL("1 before", out[0]);
+ ASSERT_EQUAL("2 before", out[1]);
+ ASSERT_EQUAL("2 after", out[2]);
+ ASSERT_EQUAL("1 after", out[3]);
+ }
+ server.stop();
+}
+
+TEST(Crow, middleware_cookieparser)
+{
+ static char buf[2048];
+
+ App<CookieParser> app;
+
+ std::string value1;
+ std::string value2;
+
+ CROW_ROUTE(app, "/")([&](const request& req){
+ {
+ auto& ctx = app.get_context<CookieParser>(req);
+ value1 = ctx.get_cookie("key1");
+ value2 = ctx.get_cookie("key2");
+ }
+
+ return "";
+ });
+
+ decltype(app)::server_t server(&app, LOCALHOST_ADDRESS, 45451);
+ auto _ = async(launch::async, [&]{server.run();});
+ std::string sendmsg = "GET /\r\nCookie: key1=value1; key2=\"val\\\"ue2\"\r\n\r\n";
+ asio::io_service is;
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+
+ c.send(asio::buffer(sendmsg));
+
+ c.receive(asio::buffer(buf, 2048));
+ c.close();
+ }
+ {
+ ASSERT_EQUAL("value1", value1);
+ ASSERT_EQUAL("val\"ue2", value2);
+ }
+ server.stop();
+}
+
+TEST(Crow, bug_quick_repeated_request)
+{
+ static char buf[2048];
+
+ SimpleApp app;
+
+ CROW_ROUTE(app, "/")([&]{
+ return "hello";
+ });
+
+ decltype(app)::server_t server(&app, LOCALHOST_ADDRESS, 45451);
+ auto _ = async(launch::async, [&]{server.run();});
+ std::string sendmsg = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
+ asio::io_service is;
+ {
+ std::vector<std::future<void>> v;
+ for(int i = 0; i < 5; i++)
+ {
+ v.push_back(async(launch::async,
+ [&]
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+
+ for(int j = 0; j < 5; j ++)
+ {
+ c.send(asio::buffer(sendmsg));
+
+ size_t received = c.receive(asio::buffer(buf, 2048));
+ ASSERT_EQUAL("hello", std::string(buf + received - 5, buf + received));
+ }
+ c.close();
+ }));
+ }
+ }
+ server.stop();
+}
+
+TEST(Crow, simple_url_params)
+{
+ static char buf[2048];
+
+ SimpleApp app;
+
+ query_string last_url_params;
+
+ CROW_ROUTE(app, "/params")
+ ([&last_url_params](const crow::request& req){
+ last_url_params = std::move(req.url_params);
+ return "OK";
+ });
+
+ ///params?h=1&foo=bar&lol&count[]=1&count[]=4&pew=5.2
+
+ decltype(app)::server_t server(&app, LOCALHOST_ADDRESS, 45451);
+ auto _ = async(launch::async, [&]{server.run();});
+ asio::io_service is;
+ std::string sendmsg;
+
+ // check empty params
+ sendmsg = "GET /params\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+ c.send(asio::buffer(sendmsg));
+ c.receive(asio::buffer(buf, 2048));
+ c.close();
+
+ stringstream ss;
+ ss << last_url_params;
+
+ ASSERT_EQUAL("[ ]", ss.str());
+ }
+ // check single presence
+ sendmsg = "GET /params?foobar\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+ c.send(asio::buffer(sendmsg));
+ 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());
+ }
+ // check multiple presence
+ sendmsg = "GET /params?foo&bar&baz\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+ c.send(asio::buffer(sendmsg));
+ 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);
+ }
+ // check single value
+ sendmsg = "GET /params?hello=world\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+ c.send(asio::buffer(sendmsg));
+ c.receive(asio::buffer(buf, 2048));
+ c.close();
+
+ ASSERT_EQUAL(string(last_url_params.get("hello")), "world");
+ }
+ // check multiple value
+ sendmsg = "GET /params?hello=world&left=right&up=down\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+ c.send(asio::buffer(sendmsg));
+ 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");
+ }
+ // check multiple value, multiple types
+ sendmsg = "GET /params?int=100&double=123.45&boolean=1\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+ c.send(asio::buffer(sendmsg));
+ 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")), 123.45);
+ ASSERT_EQUAL(boost::lexical_cast<bool>(last_url_params.get("boolean")), true);
+ }
+ // check single array value
+ sendmsg = "GET /params?tmnt[]=leonardo\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+ c.send(asio::buffer(sendmsg));
+ 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");
+ }
+ // check multiple array value
+ sendmsg = "GET /params?tmnt[]=leonardo&tmnt[]=donatello&tmnt[]=raphael\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string(LOCALHOST_ADDRESS), 45451));
+ c.send(asio::buffer(sendmsg));
+ 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");
+ }
+ server.stop();
+}
+
+TEST(Crow, route_dynamic)
+{
+ SimpleApp app;
+ int x = 1;
+ app.route_dynamic("/")
+ ([&]{
+ x = 2;
+ return "";
+ });
+
+ app.route_dynamic("/set4")
+ ([&](const request&){
+ x = 4;
+ return "";
+ });
+ app.route_dynamic("/set5")
+ ([&](const request&, response& res){
+ x = 5;
+ res.end();
+ });
+
+ app.route_dynamic("/set_int/<int>")
+ ([&](int y){
+ x = y;
+ return "";
+ });
+
+ try
+ {
+ app.route_dynamic("/invalid_test/<double>/<path>")
+ ([](){
+ return "";
+ });
+ fail();
+ }
+ catch(std::exception&)
+ {
+ }
+
+ // app is in an invalid state when route_dynamic throws an exception.
+ try
+ {
+ app.validate();
+ fail();
+ }
+ catch(std::exception&)
+ {
+ }
+
+ {
+ request req;
+ response res;
+ req.url = "/";
+ app.handle(req, res);
+ ASSERT_EQUAL(x, 2);
+ }
+ {
+ request req;
+ response res;
+ req.url = "/set_int/42";
+ app.handle(req, res);
+ ASSERT_EQUAL(x, 42);
+ }
+ {
+ request req;
+ response res;
+ req.url = "/set5";
+ app.handle(req, res);
+ ASSERT_EQUAL(x, 5);
+ }
+ {
+ request req;
+ response res;
+ req.url = "/set4";
+ app.handle(req, res);
+ ASSERT_EQUAL(x, 4);
+ }
+}
diff --git a/src/security_headers_middleware.cpp b/src/security_headers_middleware.cpp
new file mode 100644
index 0000000..bcaa87d
--- /dev/null
+++ b/src/security_headers_middleware.cpp
@@ -0,0 +1,20 @@
+#include <security_headers_middleware.hpp>
+
+namespace crow {
+
+void SecurityHeadersMiddleware::before_handle(crow::request& req, response& res,
+ context& ctx) {}
+
+void SecurityHeadersMiddleware::after_handle(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.set_header("Strict-Transport-Security",
+ "max-age=31536000; includeSubdomains; preload");
+ res.set_header("X-UA-Compatible", "IE=11");
+ res.set_header("X-Frame-Options", "DENY");
+ res.set_header("X-XSS-Protection", "1; mode=block");
+ res.set_header("X-Content-Security-Policy", "default-src 'self'");
+}
+}
diff --git a/src/token_authorization_middleware.cpp b/src/token_authorization_middleware.cpp
index 30d12c5..91feaf1 100644
--- a/src/token_authorization_middleware.cpp
+++ b/src/token_authorization_middleware.cpp
@@ -1,51 +1,58 @@
+#include <boost/algorithm/string/predicate.hpp>
#include <random>
#include <unordered_map>
-#include <boost/algorithm/string/predicate.hpp>
-#include <token_authorization_middleware.hpp>
#include <crow/logging.h>
#include <base64.hpp>
+#include <token_authorization_middleware.hpp>
namespace crow {
-using random_bytes_engine = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, unsigned char>;
+using random_bytes_engine =
+ std::independent_bits_engine<std::default_random_engine, CHAR_BIT,
+ unsigned char>;
+TokenAuthorizationMiddleware::TokenAuthorizationMiddleware()
+ : auth_token2(""){
-void TokenAuthorizationMiddleware::before_handle(crow::request& req, response& res, context& ctx) {
-
+ };
+
+void TokenAuthorizationMiddleware::before_handle(crow::request& req,
+ response& res, context& ctx) {
auto return_unauthorized = [&req, &res]() {
res.code = 401;
res.end();
};
- LOG(DEBUG) << "Got route " << req.url;
+ LOG(DEBUG) << "Token Auth Got route " << req.url;
- if (req.url == "/" || boost::starts_with(req.url, "/static/")){
- //TODO this is total hackery to allow the login page to work before the user
- // is authenticated. Also, it will be quite slow for all pages instead of
- // a one time hit for the whitelist entries.
- // Ideally, this should be done in the url router handler, with tagged routes
- // for the whitelist entries.
+ if (req.url == "/" || boost::starts_with(req.url, "/static/")) {
+ // TODO this is total hackery to allow the login page to work before the
+ // user is authenticated. Also, it will be quite slow for all pages instead
+ // of a one time hit for the whitelist entries. Ideally, this should be
+ // done
+ // in the url router handler, with tagged routes for the whitelist entries.
// Another option would be to whitelist a minimal
return;
}
if (req.url == "/login") {
- if (req.method != HTTPMethod::POST){
+ if (req.method != HTTPMethod::POST) {
return_unauthorized();
return;
} else {
auto login_credentials = crow::json::load(req.body);
- if (!login_credentials){
+ if (!login_credentials) {
return_unauthorized();
return;
}
auto username = login_credentials["username"].s();
auto password = login_credentials["password"].s();
-
+
// TODO(ed) pull real passwords from PAM
- if (username == "dude" && password == "dude"){
- //TODO(ed) the RNG should be initialized at start, not every time we want a token
+ if (username == "dude" && password == "dude") {
+ // TODO(ed) the RNG should be initialized at start, not every time we
+ // want a token
std::random_device rand;
random_bytes_engine rbe;
std::string token('a', 20);
@@ -54,17 +61,25 @@
base64::base64_encode(token, encoded_token);
ctx.auth_token = encoded_token;
this->auth_token2 = encoded_token;
+ crow::json::wvalue x;
+ auto auth_token = ctx.auth_token;
+ x["token"] = auth_token;
+
+ res.write(json::dump(x));
+ res.end();
} else {
return_unauthorized();
return;
}
}
-
+
} else if (req.url == "/logout") {
this->auth_token2 = "";
- } else { // Normal, non login, non static file request
+ res.code = 200;
+ res.end();
+ } else { // Normal, non login, non static file request
// Check to make sure we're logged in
- if (this->auth_token2.empty()){
+ if (this->auth_token2.empty()) {
return_unauthorized();
return;
}
@@ -81,8 +96,8 @@
return;
}
- //todo, use span here instead of constructing a new string
- if (auth_header.substr(6) != this->auth_token2){
+ // TODO(ed), use span here instead of constructing a new string
+ if (auth_header.substr(6) != this->auth_token2) {
return_unauthorized();
return;
}
@@ -90,7 +105,6 @@
}
}
-void TokenAuthorizationMiddleware::after_handle(request& /*req*/, response& res, context& ctx) {
-
-}
+void TokenAuthorizationMiddleware::after_handle(request& req, response& res,
+ context& ctx) {}
}
diff --git a/src/token_authorization_middleware_test.cpp b/src/token_authorization_middleware_test.cpp
index aef33e3..d64cc13 100644
--- a/src/token_authorization_middleware_test.cpp
+++ b/src/token_authorization_middleware_test.cpp
@@ -2,23 +2,76 @@
#include <crow/app.h>
#include "gtest/gtest.h"
+using namespace crow;
+using namespace std;
+
// Tests that Base64 basic strings work
-TEST(Authentication, TestBasicReject) {
- /*
- crow::App<crow::TokenAuthorizationMiddleware> app;
- crow::request req;
- crow::response res;
- app.handle(req, res);
- ASSERT_EQ(res.code, 400);
+TEST(TokenAuthentication, TestBasicReject)
+{
+ App<crow::TokenAuthorizationMiddleware> app;
+ decltype(app)::server_t server(&app, "127.0.0.1", 45451);
+ CROW_ROUTE(app, "/")([]()
+ {
+ return 200;
+ });
+ auto _ = async(launch::async, [&]{server.run();});
+ asio::io_service is;
+ std::string sendmsg;
+ static char buf[2048];
- crow::App<crow::TokenAuthorizationMiddleware> app;
- decltype(app)::server_t server(&app, "127.0.0.1", 45451);
- CROW_ROUTE(app, "/")([&](const crow::request& req)
- {
- app.get_context<NullMiddleware>(req);
- app.get_context<NullSimpleMiddleware>(req);
- return "";
- });
- */
+ // Homepage should be passed with no credentials
+ sendmsg = "GET /\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string("127.0.0.1"), 45451));
+ c.send(asio::buffer(sendmsg));
+ auto received_count = c.receive(asio::buffer(buf, 2048));
+ c.close();
+ ASSERT_EQ("200", std::string(buf + 9, buf + 12));
+ }
+
+ // static should be passed with no credentials
+ sendmsg = "GET /static/index.html\r\n\r\n";
+ {
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string("127.0.0.1"), 45451));
+ c.send(asio::buffer(sendmsg));
+ c.receive(asio::buffer(buf, 2048));
+ c.close();
+ ASSERT_EQ("404", std::string(buf + 9, buf + 12));
+ }
+
+
+ server.stop();
+
}
+
+
+// Tests that Base64 basic strings work
+TEST(TokenAuthentication, TestSuccessfulLogin)
+{
+ App<crow::TokenAuthorizationMiddleware> app;
+ app.bindaddr("127.0.0.1").port(45451);
+ CROW_ROUTE(app, "/")([]()
+ {
+ return 200;
+ });
+ auto _ = async(launch::async, [&]{app.run();});
+
+ asio::io_service is;
+ static char buf[2048];
+ ASSERT_NO_THROW(
+ // Other resources should not be passed
+ std::string sendmsg = "GET /foo\r\n\r\n";
+ asio::ip::tcp::socket c(is);
+ c.connect(asio::ip::tcp::endpoint(asio::ip::address::from_string("127.0.0.1"), 45451));
+ c.send(asio::buffer(sendmsg));
+ auto received_count = c.receive(asio::buffer(buf, 2048));
+ c.close();
+ ASSERT_EQ("401", std::string(buf + 9, buf + 12));
+
+ app.stop();
+ raise;
+
+}
\ No newline at end of file
diff --git a/src/webserver_main.cpp b/src/webserver_main.cpp
index 80354fb..32a1192 100644
--- a/src/webserver_main.cpp
+++ b/src/webserver_main.cpp
@@ -2,7 +2,7 @@
#include <web_kvm.hpp>
#include "ssl_key_handler.hpp"
-#include "app_type.hpp"
+#include <crow/bmc_app_type.hpp>
#include "crow/app.h"
#include "crow/ci_map.h"
@@ -28,7 +28,6 @@
#include "color_cout_g3_sink.hpp"
-#include "token_authorization_middleware.hpp"
#include "webassets.hpp"
@@ -60,33 +59,6 @@
crow::logger::setLogLevel(crow::LogLevel::INFO);
- CROW_ROUTE(app, "/routes")
- ([&app]() {
- crow::json::wvalue routes;
-
- routes["routes"] = app.get_rules();
- return routes;
- });
-
- CROW_ROUTE(app, "/login")
- .methods("POST"_method)([&](const crow::request& req) {
- crow::json::wvalue x;
- auto auth_token =
- app.get_context<crow::TokenAuthorizationMiddleware>(req).auth_token;
-
- x["token"] = auth_token;
-
- return x;
- });
-
- CROW_ROUTE(app, "/logout")
- .methods("GET"_method, "POST"_method)([&](const crow::request& req) {
-
- app.get_context<crow::TokenAuthorizationMiddleware>(req).auth_token = "";
- // Do nothing. Credentials have already been cleared by middleware.
- return 200;
- });
-
CROW_ROUTE(app, "/systeminfo")
([]() {
@@ -140,7 +112,7 @@
size_t len =
socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);
// TODO(ed) THis is ugly. Find a way to not make a copy (ie, use
- // std::string::data())
+ // std::string::data() to
std::string str(std::begin(recv_buf), std::end(recv_buf));
LOG(DEBUG) << "Got " << str << "back \n";
conn.send_binary(str);
diff --git a/static/css/font-awesome.css b/static/css/font-awesome.css
index a992aee..4ce929a 100644
--- a/static/css/font-awesome.css
+++ b/static/css/font-awesome.css
@@ -6,8 +6,8 @@
* -------------------------- */
@font-face {
font-family: 'FontAwesome';
- src: url('../fonts/fontawesome-webfont.eot?v=4.7.0');
- src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');
+ /* WARNING: This line is modified from stock FA, to make cachign work*/
+ src: url('../../static/fonts/fontawesome-webfont.woff?v=4.7.0') format('woff');
font-weight: normal;
font-style: normal;
}
diff --git a/static/js/kvmController.js b/static/js/kvmController.js
index e3dcb14..4f692f1 100644
--- a/static/js/kvmController.js
+++ b/static/js/kvmController.js
@@ -33,8 +33,6 @@
return; // don't continue trying to connect
};
-
-
$scope.$on("$destroy", function() {
if (rfb) {
rfb.disconnect();
@@ -63,6 +61,14 @@
};
function status(text, level) {
+ var status_bar = angular.element(document.querySelector('#noVNC_status_bar'))[0];
+ // Need to check if the status bar still exists. On page change, it gets destroyed
+ // when we swap to a different view. The system will disconnect async
+ if (status_bar){
+ status_bar.textContent = text;
+ }
+
+ var status = angular.element(document.querySelector('#noVNC_status'))[0];
switch (level) {
case 'normal':
case 'warn':
@@ -71,8 +77,9 @@
default:
level = "warn";
}
- angular.element(document.querySelector('#noVNC_status'))[0].textContent = text;
- angular.element(document.querySelector('#noVNC_status_bar'))[0].setAttribute("class", "noVNC_status_" + level);
+ if (status){
+ status.setAttribute("class", "noVNC_status_" + level);
+ }
};
function updateState(rfb, state, oldstate) {