incremental
diff --git a/.server.pem.swp b/.server.pem.swp
deleted file mode 100644
index bff7fa6..0000000
--- a/.server.pem.swp
+++ /dev/null
Binary files differ
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 8d97d92..0a6e3ec 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -33,6 +33,7 @@
option(BUILD_UT "Enable Unit test" OFF)
# Boost
+add_definitions(-DBOOST_ASIO_ENABLE_HANDLER_TRACKING)
add_definitions(-DBOOST_ALL_NO_LIB)
set(Boost_USE_STATIC_LIBS ON)
hunter_add_package(Boost COMPONENTS system thread)
@@ -111,12 +112,13 @@
# This line simply disables the warning, and the compiler does the right thing
# we selectively only disable this warning on this specific file
# http://stackoverflow.com/questions/28094263/create-array-of-chars-avoiding-narrowing
-if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
- if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER "5.0")
+if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set_source_files_properties(${CMAKE_BINARY_DIR}/generated/webassets.cpp PROPERTIES COMPILE_FLAGS -Wno-c++11-narrowing)
- endif()
-elseif(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
- set_source_files_properties(${CMAKE_BINARY_DIR}/generated/webassets.cpp PROPERTIES COMPILE_FLAGS -Wno-c++11-narrowing)
+endif()
+if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
+ if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 5.2)
+ set_source_files_properties(${CMAKE_BINARY_DIR}/generated/webassets.cpp PROPERTIES COMPILE_FLAGS -Wno-narrowing)
+ endif(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 5.2)
endif()
# Unit Tests
diff --git a/docs/profile.md b/docs/profile.md
new file mode 100644
index 0000000..fffc400
--- /dev/null
+++ b/docs/profile.md
@@ -0,0 +1,4 @@
+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/gperftools/.libs/libprofiler.so /tmp
\ No newline at end of file
diff --git a/include/crow_g3_logger.hpp b/include/crow_g3_logger.hpp
index a7e7d9f..be84de0 100644
--- a/include/crow_g3_logger.hpp
+++ b/include/crow_g3_logger.hpp
@@ -72,3 +72,23 @@
#define CROW_LOG_WARNING LOG(WARNING)
#define CROW_LOG_INFO LOG(INFO)
#define CROW_LOG_DEBUG LOG(DEBUG)
+
+
+
+/*
+#define CROW_LOG_CRITICAL \
+ if (false) \
+ crow::logger("CRITICAL", crow::LogLevel::Critical)
+#define CROW_LOG_ERROR \
+ if (false) \
+ crow::logger("ERROR ", crow::LogLevel::Error)
+#define CROW_LOG_WARNING \
+ if (false) \
+ crow::logger("WARNING ", crow::LogLevel::Warning)
+#define CROW_LOG_INFO \
+ if (false) \
+ crow::logger("INFO ", crow::LogLevel::Info)
+#define CROW_LOG_DEBUG \
+ if (false) \
+ crow::logger("DEBUG ", crow::LogLevel::Debug)
+*/
\ No newline at end of file
diff --git a/include/ssl_key_handler.hpp b/include/ssl_key_handler.hpp
index 69987b9..6e09cbe 100644
--- a/include/ssl_key_handler.hpp
+++ b/include/ssl_key_handler.hpp
@@ -11,6 +11,8 @@
#include <openssl/rsa.h>
#include <openssl/ssl.h>
+#include <boost/asio.hpp>
+
#include <g3log/g3log.hpp>
namespace ensuressl {
@@ -40,7 +42,7 @@
RSA *rsa = EVP_PKEY_get1_RSA(pkey);
if (rsa){
if (RSA_check_key(rsa) == 1) {
- private_key_valid = true;
+ //private_key_valid = true;
} else {
LOG(WARNING) << "Key not valid error number " << ERR_get_error();
}
@@ -53,7 +55,7 @@
EC_KEY* ec = EVP_PKEY_get1_EC_KEY(pkey);
if (ec){
if (EC_KEY_check_key(ec) == 1) {
- //private_key_valid = true;
+ private_key_valid = true;
} else {
LOG(WARNING) << "Key not valid error number " << ERR_get_error();
}
@@ -92,11 +94,11 @@
LOG(WARNING) << "Generating new keys";
init_openssl();
- LOG(WARNING) << "Generating RSA key";
- EVP_PKEY *pRsaPrivKey = create_rsa_key();
+ //LOG(WARNING) << "Generating RSA key";
+ //EVP_PKEY *pRsaPrivKey = create_rsa_key();
- //LOG(WARNING) << "Generating EC key";
- //EVP_PKEY *pRsaPrivKey = create_ec_key();
+ LOG(WARNING) << "Generating EC key";
+ EVP_PKEY *pRsaPrivKey = create_ec_key();
LOG(WARNING) << "Generating x509 Certificate";
// Use this code to directly generate a certificate
@@ -149,7 +151,7 @@
EVP_PKEY_free(pRsaPrivKey);
pRsaPrivKey = NULL;
}
-
+
// cleanup_openssl();
}
@@ -241,4 +243,76 @@
generate_ssl_certificate(filepath);
}
}
+
+
+boost::asio::ssl::context get_ssl_context(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);
+
+ // 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);
+
+ // 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";
+ }
+
+ // From mozilla "compatibility"
+ std::string ciphers =
+ "ECDHE-ECDSA-CHACHA20-POLY1305:"
+ "ECDHE-RSA-CHACHA20-POLY1305:"
+ "ECDHE-ECDSA-AES128-GCM-SHA256:"
+ "ECDHE-RSA-AES128-GCM-SHA256:"
+ "ECDHE-ECDSA-AES256-GCM-SHA384:"
+ "ECDHE-RSA-AES256-GCM-SHA384:"
+ "DHE-RSA-AES128-GCM-SHA256:"
+ "DHE-RSA-AES256-GCM-SHA384:"
+ "ECDHE-ECDSA-AES128-SHA256:"
+ "ECDHE-RSA-AES128-SHA256:"
+ "ECDHE-ECDSA-AES128-SHA:"
+ "ECDHE-RSA-AES256-SHA384:"
+ "ECDHE-RSA-AES128-SHA:"
+ "ECDHE-ECDSA-AES256-SHA384:"
+ "ECDHE-ECDSA-AES256-SHA:"
+ "ECDHE-RSA-AES256-SHA:"
+ "DHE-RSA-AES128-SHA256:"
+ "DHE-RSA-AES128-SHA:"
+ "DHE-RSA-AES256-SHA256:"
+ "DHE-RSA-AES256-SHA:"
+ "ECDHE-ECDSA-DES-CBC3-SHA:"
+ "ECDHE-RSA-DES-CBC3-SHA:"
+ "EDH-RSA-DES-CBC3-SHA:"
+ "AES128-GCM-SHA256:"
+ "AES256-GCM-SHA384:"
+ "AES128-SHA256:"
+ "AES256-SHA256:"
+ "AES128-SHA:"
+ "AES256-SHA:"
+ "DES-CBC3-SHA:"
+ "!DSS";
+
+ // From mozilla "modern"
+ std::string modern_ciphers =
+ "ECDHE-ECDSA-AES256-GCM-SHA384:"
+ "ECDHE-RSA-AES256-GCM-SHA384:"
+ "ECDHE-ECDSA-CHACHA20-POLY1305:"
+ "ECDHE-RSA-CHACHA20-POLY1305:"
+ "ECDHE-ECDSA-AES128-GCM-SHA256:"
+ "ECDHE-RSA-AES128-GCM-SHA256:"
+ "ECDHE-ECDSA-AES256-SHA384:"
+ "ECDHE-RSA-AES256-SHA384:"
+ "ECDHE-ECDSA-AES128-SHA256:"
+ "ECDHE-RSA-AES128-SHA256";
+
+ std::string lighttp_ciphers = "AES128+EECDH:AES128+EDH:!aNULL:!eNULL";
+
+ if (SSL_CTX_set_cipher_list(m_ssl_context.native_handle(), ciphers.c_str()) != 1) {
+ CROW_LOG_ERROR << "Error setting cipher list\n";
+ }
+ return m_ssl_context;
+}
}
\ No newline at end of file
diff --git a/include/token_authorization_middleware.hpp b/include/token_authorization_middleware.hpp
index 7e8e503..61c8385 100644
--- a/include/token_authorization_middleware.hpp
+++ b/include/token_authorization_middleware.hpp
@@ -6,14 +6,11 @@
namespace crow {
struct TokenAuthorizationMiddleware {
struct context {
- std::unordered_map<std::string, std::string> cookie_sessions;
- std::unordered_map<std::string, std::string> cookies_to_push_to_client;
-
- std::string get_cookie(const std::string& key);
-
- void set_cookie(const std::string& key, const std::string& value);
+ std::string auth_token;
};
+ std::string auth_token2;
+
void before_handle(crow::request& req, response& res, context& ctx);
void after_handle(request& req, response& res, context& ctx);
diff --git a/scripts/build_web_assets.py b/scripts/build_web_assets.py
index e4d8cab..9cad070 100755
--- a/scripts/build_web_assets.py
+++ b/scripts/build_web_assets.py
@@ -8,35 +8,87 @@
THIS_DIR = os.path.dirname(os.path.realpath(__file__))
-BEGIN_BUFFER = """
+ENABLE_CACHING = False
+# TODO this needs to be better
+CONTENT_TYPES = {
+ '.css': "text/css;charset=UTF-8",
+ '.html': "text/html;charset=UTF-8",
+ '.js': "text/html;charset=UTF-8",
+ '.png': "image/png;charset=UTF-8"
+}
+CPP_BEGIN_BUFFER = """
#include <webassets.hpp>
-void crow::webassets::request_routes(crow::App<crow::TokenAuthorizationMiddleware>& app){
"""
-MIDDLE_BUFFER = """
- CROW_ROUTE(app, "{}")([](const crow::request& req, crow::response& res) {{
+ROUTE_DECLARATION = """void crow::webassets::request_routes(crow::App<crow::TokenAuthorizationMiddleware>& app){
+"""
+
+CPP_MIDDLE_BUFFER = """
+ CROW_ROUTE(app, "{relative_path_sha1}")([](const crow::request& req, crow::response& res) {{
res.code = 200;
// TODO, if you have a browser from the dark ages that doesn't support gzip,
// unzip it before sending based on Accept-Encoding header
res.add_header("Content-Encoding", "gzip");
+ res.add_header("Cache-Control", "{cache_control_value}");
+ res.add_header("Content-Type", "{content_type}");
- res.write({{{}}});
+ res.write({relative_path_escaped});
res.end();
}});
"""
-END_BUFFER = """
-
+CPP_END_BUFFER = """
+}
"""
+CPP_END_BUFFER2 = """const static std::string {relative_path_escaped}{{{file_bytes}}};
+"""
+
+def get_relative_path(full_filepath):
+ pathsplit = full_filepath.split(os.path.sep)
+ relative_path = os.path.sep.join(pathsplit[pathsplit.index("static") + 1:])
+
+ relative_path_escaped = relative_path.replace("/", "_").replace(".", "_").replace("-", "_")
+
+ relative_path = "/static/" + relative_path
+
+ # handle the default routes
+ if relative_path == "/static/index.html":
+ relative_path = "/"
+
+ return relative_path, relative_path_escaped
+
+def get_sha1_path_from_relative(relative_path, sha1):
+ if sha1 != "":
+ path, extension = os.path.splitext(relative_path)
+ return path + "_" + sha1 + extension
+ else:
+ return relative_path
+
+
+def filter_html(sha1_list, file_content):
+ string_content = file_content.decode()
+ for key, value in sha1_list.items():
+ if key != "/":
+ # todo, this is very naive, do it better (parse the html)
+ start = "src=\"" + key.lstrip("/")
+ replace = "src=\"" + get_sha1_path_from_relative(key, value)
+ #print("REplacing {} with {}".format(start, replace))
+ string_content = string_content.replace(start, replace)
+
+ start = "href=\"" + key.lstrip("/")
+ replace = "href=\"" + get_sha1_path_from_relative(key, value)
+ #print("REplacing {} with {}".format(start, replace))
+ string_content = string_content.replace(start, replace)
+ return string_content.encode()
+
def main():
""" Main Function """
- file_list = []
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', nargs='+', type=str)
@@ -45,42 +97,74 @@
file_list = args.input
- with open(args.output, 'w') as output_handle:
+ sha1_list = {}
+ if ENABLE_CACHING:
+ # Sha256 hash everthing
+ for full_filepath in file_list:
+ if not full_filepath.endswith(".html"):
+ with open(full_filepath, 'rb') as input_file:
+ file_content = input_file.read()
+ sha = hashlib.sha256()
+ sha.update(file_content)
- output_handle.write(BEGIN_BUFFER)
+ sha_text = "".join("{:02x}".format(x) for x in sha.digest())[:10]
+ relative_path, relative_path_escaped = get_relative_path(full_filepath)
+ sha1_list[relative_path] = sha_text
+
+ with open(args.output, 'w') as cpp_output:
+ cpp_output.write(CPP_BEGIN_BUFFER)
for full_filepath in file_list:
-
- pathsplit = full_filepath.split(os.path.sep)
- relative_path = os.path.sep.join(pathsplit[pathsplit.index("static") + 1:])
-
- relative_path = "/static/" + relative_path
-
- # handle the default routes
- if relative_path == "/static/index.html":
- relative_path = "/"
-
# make sure none of the files are hidden
with open(full_filepath, 'rb') as input_file:
file_content = input_file.read()
+ relative_path, relative_path_escaped = get_relative_path(full_filepath)
print("Including {:<40} size {:>7}".format(relative_path, len(file_content)))
- sha = hashlib.sha256()
- sha.update(file_content)
+ if relative_path.endswith(".html") or relative_path == "/":
+ print("Fixing {}".format(relative_path))
+ file_content = filter_html(sha1_list, file_content)
- sha_text = "".join("{:02x}".format(x) for x in sha.digest())
- print(sha_text)
file_content = gzip.compress(file_content)
#file_content = file_content[:10]
array_binary_text = ', '.join('0x{:02x}'.format(x) for x in file_content)
- output_handle.write(MIDDLE_BUFFER.format(relative_path, array_binary_text))
+ cpp_output.write(CPP_END_BUFFER2.format(relative_path=relative_path, file_bytes=array_binary_text, relative_path_escaped=relative_path_escaped))
- output_handle.write("};\n")
- output_handle.write(END_BUFFER)
+ cpp_output.write(ROUTE_DECLARATION)
+
+
+ for full_filepath in file_list:
+ relative_path, relative_path_escaped = get_relative_path(full_filepath)
+ sha1 = sha1_list.get(relative_path, '')
+
+ relative_path_sha1 = get_sha1_path_from_relative(relative_path, sha1)
+
+ content_type = CONTENT_TYPES.get(os.path.splitext(relative_path)[1], "")
+ if content_type == "":
+ print("unknown content type for {}".format(relative_path))
+
+ if sha1 == "":
+ cache_control_value = "no-cache"
+ else:
+ cache_control_value = "max-age=31556926"
+
+ content = CPP_MIDDLE_BUFFER.format(
+ relative_path=relative_path,
+ relative_path_escaped=relative_path_escaped,
+ relative_path_sha1=relative_path_sha1,
+ sha1=sha1,
+ content_type=content_type,
+ cache_control_value=cache_control_value
+ )
+ cpp_output.write(content)
+
+ cpp_output.write(CPP_END_BUFFER)
+
+
if __name__ == "__main__":
main()
diff --git a/src/token_authorization_middleware.cpp b/src/token_authorization_middleware.cpp
index 3a92218..40ade75 100644
--- a/src/token_authorization_middleware.cpp
+++ b/src/token_authorization_middleware.cpp
@@ -4,16 +4,14 @@
#include <token_authorization_middleware.hpp>
-namespace crow {
-std::string TokenAuthorizationMiddleware::context::get_cookie(const std::string& key) {
- if (cookie_sessions.count(key)) return cookie_sessions[key];
- return {};
-}
+#include <base64.hpp>
-void TokenAuthorizationMiddleware::context::set_cookie(const std::string& key, const std::string& value) { cookies_to_push_to_client.emplace(key, value); }
+namespace crow {
+
+using random_bytes_engine = std::independent_bits_engine<std::default_random_engine, CHAR_BIT, unsigned char>;
+
void TokenAuthorizationMiddleware::before_handle(crow::request& req, response& res, context& ctx) {
- return;
auto return_unauthorized = [&req, &res]() {
res.code = 401;
@@ -21,32 +19,73 @@
};
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.
+ // 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.
return;
}
- //TODO this
+
if (req.url == "/login") {
- }
- // Check for an authorization header, reject if not present
- if (req.headers.count("Authorization") != 1) {
- return_unauthorized();
- return;
- }
+ if (req.method != HTTPMethod::POST){
+ return_unauthorized();
+ return;
+ } else {
+ auto login_credentials = crow::json::load(req.body);
+ if (!login_credentials){
+ return_unauthorized();
+ return;
+ }
+ auto username = login_credentials["username"].s();
+ auto password = login_credentials["password"].s();
- std::string auth_header = req.get_header_value("Authorization");
- // If the user is attempting any kind of auth other than token, reject
- if (!boost::starts_with(auth_header, "Token ")) {
- return_unauthorized();
- return;
+ if (username == "dude" && password == "dude"){
+ std::random_device rand;
+ random_bytes_engine rbe;
+ std::string token('a', 20);
+ std::generate(begin(token), end(token), std::ref(rbe));
+ std::string encoded_token;
+ base64::base64_encode(token, encoded_token);
+ ctx.auth_token = encoded_token;
+ this->auth_token2 = encoded_token;
+
+ } else {
+ return_unauthorized();
+ return;
+ }
+ }
+
+ } else if (req.url == "/logout") {
+ this->auth_token2 = "";
+ } else { // Normal, non login, non static file request
+ // Check to make sure we're logged in
+ if (this->auth_token2.empty()){
+ return_unauthorized();
+ return;
+ }
+ // Check for an authorization header, reject if not present
+ if (req.headers.count("Authorization") != 1) {
+ return_unauthorized();
+ return;
+ }
+
+ std::string auth_header = req.get_header_value("Authorization");
+ // If the user is attempting any kind of auth other than token, reject
+ if (!boost::starts_with(auth_header, "Token ")) {
+ return_unauthorized();
+ return;
+ }
+
+ //todo, use span here instead of constructing a new string
+ if (auth_header.substr(6) != this->auth_token2){
+ return_unauthorized();
+ return;
+ }
}
}
void TokenAuthorizationMiddleware::after_handle(request& /*req*/, response& res, context& ctx) {
- for (auto& cookie : ctx.cookies_to_push_to_client) {
- res.add_header("Set-Cookie", cookie.first + "=" + cookie.second);
- }
+
}
-}
\ No newline at end of file
+}
diff --git a/src/webserver_main.cpp b/src/webserver_main.cpp
index b89c2a6..c5c3eed 100644
--- a/src/webserver_main.cpp
+++ b/src/webserver_main.cpp
@@ -1,10 +1,9 @@
-#include "crow/ci_map.h"
-#include "crow/http_parser_merged.h"
-#include "crow/query_string.h"
#include "crow/app.h"
+#include "crow/ci_map.h"
#include "crow/common.h"
#include "crow/dumb_timer_queue.h"
#include "crow/http_connection.h"
+#include "crow/http_parser_merged.h"
#include "crow/http_request.h"
#include "crow/http_response.h"
#include "crow/http_server.h"
@@ -14,6 +13,7 @@
#include "crow/middleware_context.h"
#include "crow/mustache.h"
#include "crow/parser.h"
+#include "crow/query_string.h"
#include "crow/routing.h"
#include "crow/settings.h"
#include "crow/socket_adaptors.h"
@@ -25,88 +25,172 @@
#include "webassets.hpp"
#include <iostream>
+#include <memory>
#include <string>
#include "ssl_key_handler.hpp"
+#include <boost/endian/arithmetic.hpp>
+
+#include <boost/asio.hpp>
+
+#include <unordered_set>
#include <webassets.hpp>
-crow::ssl_context_t get_ssl_context(std::string ssl_pem_file){
- crow::ssl_context_t 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);
+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";
- // 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);
+enum class RfbAuthScheme : uint8_t { connection_failed = 0, no_authentication = 1, vnc_authentication = 2 };
- // 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";
+struct pixel_format_struct {
+ boost::endian::big_uint8_t bits_per_pixel;
+ 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 pad1;
+ boost::endian::big_uint8_t pad2;
+ boost::endian::big_uint8_t pad3;
+};
+
+struct server_initialization_message {
+ 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;
+};
+
+enum class client_to_server_message_type : uint8_t {
+ set_pixel_format = 0,
+ fix_color_map_entries = 1,
+ set_encodings = 2,
+ framebuffer_update_request = 3,
+ key_event = 4,
+ pointer_event = 5,
+ client_cut_text = 6
+};
+
+struct set_pixel_format_message {
+ boost::endian::big_uint8_t pad1;
+ boost::endian::big_uint8_t pad2;
+ boost::endian::big_uint8_t pad3;
+ pixel_format_struct pixel_format;
+};
+
+struct frame_buffer_update_request_message {
+ 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 width;
+ boost::endian::big_uint16_t height;
+};
+
+struct key_event_message {
+ boost::endian::big_uint8_t down_flag;
+ boost::endian::big_uint8_t pad1;
+ boost::endian::big_uint8_t pad2;
+ boost::endian::big_uint32_t key;
+};
+
+struct pointer_event_message {
+ boost::endian::big_uint8_t button_mask;
+ boost::endian::big_uint16_t x_position;
+ boost::endian::big_uint16_t y_position;
+};
+
+struct client_cut_text_message {
+ std::vector<uint8_t> data;
+};
+
+enum class encoding_type : uint32_t {
+ raw = 0x00,
+ copy_rectangle = 0x01,
+ rising_rectangle = 0x02,
+ corre = 0x04,
+ hextile = 0x05,
+ zlib = 0x06,
+ tight = 0x07,
+ zlibhex = 0x08,
+ ultra = 0x09,
+ zrle = 0x10,
+ zywrle = 0x011,
+ cache_enable = 0xFFFF0001,
+ xor_enable = 0xFFFF0006,
+ server_state_ultranvc = 0xFFFF8000,
+ enable_keep_alive = 0xFFFF8001,
+ enableftp_protocol_version = 0xFFFF8002,
+ tight_compress_level_0 = 0xFFFFFF00,
+ tight_compress_level_9 = 0xFFFFFF09,
+ x_cursor = 0xFFFFFF10,
+ rich_cursor = 0xFFFFFF11,
+ pointer_pos = 0xFFFFFF18,
+ last_rect = 0xFFFFFF20,
+ new_framebuffer_size = 0xFFFFFF21,
+ tight_quality_level_0 = 0xFFFFFFE0,
+ tight_quality_level_9 = 0xFFFFFFE9
+};
+
+struct framebuffer_rectangle {
+ boost::endian::big_uint16_t x;
+ boost::endian::big_uint16_t y;
+ boost::endian::big_uint16_t width;
+ boost::endian::big_uint16_t height;
+ boost::endian::big_uint32_t encoding;
+ std::vector<uint8_t> data;
+};
+
+struct framebuffer_update_message {
+ boost::endian::big_uint8_t message_type;
+
+ std::vector<framebuffer_rectangle> rectangles;
+};
+
+std::string serialize(const framebuffer_update_message& msg) {
+ // calculate the size of the needed vector for serialization
+ size_t vector_size = 4;
+ for (const auto& rect : msg.rectangles) {
+ vector_size += 12 + rect.data.size();
}
- // From mozilla "compatibility"
- std::string ciphers =
- //"ECDHE-ECDSA-CHACHA20-POLY1305:"
- //"ECDHE-RSA-CHACHA20-POLY1305:"
- //"ECDHE-ECDSA-AES128-GCM-SHA256:"
- //"ECDHE-RSA-AES128-GCM-SHA256:"
- //"ECDHE-ECDSA-AES256-GCM-SHA384:"
- //"ECDHE-RSA-AES256-GCM-SHA384:"
- //"DHE-RSA-AES128-GCM-SHA256:"
- //"DHE-RSA-AES256-GCM-SHA384:"
- //"ECDHE-ECDSA-AES128-SHA256:"
- //"ECDHE-RSA-AES128-SHA256:"
- //"ECDHE-ECDSA-AES128-SHA:"
- //"ECDHE-RSA-AES256-SHA384:"
- //"ECDHE-RSA-AES128-SHA:"
- //"ECDHE-ECDSA-AES256-SHA384:"
- //"ECDHE-ECDSA-AES256-SHA:"
- //"ECDHE-RSA-AES256-SHA:"
- //"DHE-RSA-AES128-SHA256:"
- //"DHE-RSA-AES128-SHA:"
- //"DHE-RSA-AES256-SHA256:"
- //"DHE-RSA-AES256-SHA:"
- //"ECDHE-ECDSA-DES-CBC3-SHA:"
- //"ECDHE-RSA-DES-CBC3-SHA:"
- //"EDH-RSA-DES-CBC3-SHA:"
- "AES128-GCM-SHA256:"
- "AES256-GCM-SHA384:"
- "AES128-SHA256:"
- "AES256-SHA256:"
- "AES128-SHA:"
- "AES256-SHA:"
- "DES-CBC3-SHA:"
- "!DSS";
+ std::string serialized(vector_size, 0);
- // From mozilla "modern"
- std::string modern_ciphers =
- "ECDHE-ECDSA-AES256-GCM-SHA384:"
- "ECDHE-RSA-AES256-GCM-SHA384:"
- "ECDHE-ECDSA-CHACHA20-POLY1305:"
- "ECDHE-RSA-CHACHA20-POLY1305:"
- "ECDHE-ECDSA-AES128-GCM-SHA256:"
- "ECDHE-RSA-AES128-GCM-SHA256:"
- "ECDHE-ECDSA-AES256-SHA384:"
- "ECDHE-RSA-AES256-SHA384:"
- "ECDHE-ECDSA-AES128-SHA256:"
- "ECDHE-RSA-AES128-SHA256";
+ size_t i = 0;
+ serialized[i++] = 0; // Type
+ serialized[i++] = 0; // Pad byte
+ boost::endian::big_uint16_t number_of_rectangles;
+ std::memcpy(&serialized[i], &number_of_rectangles, sizeof(number_of_rectangles));
+ i += sizeof(number_of_rectangles);
- if (SSL_CTX_set_cipher_list(m_ssl_context.native_handle(), ciphers.c_str()) != 1) {
- CROW_LOG_ERROR << "Error setting cipher list\n";
+ 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;
+
+ std::memcpy(&serialized[i], rect.data.data(), rect.data.size());
+ i += rect.data.size();
}
- return m_ssl_context;
+
+ return serialized;
}
+enum class VncState { UNSTARTED, AWAITING_CLIENT_VERSION, AWAITING_CLIENT_AUTH_METHOD, AWAITING_CLIENT_INIT_MESSAGE, MAIN_LOOP };
+
+class connection_metadata {
+ public:
+ connection_metadata(void) : vnc_state(VncState::AWAITING_CLIENT_VERSION){};
+
+ VncState vnc_state;
+};
int main(int argc, char** argv) {
auto worker(g3::LogWorker::createLogWorker());
- //TODO rotating logger isn't working super well
- //auto logger = worker->addSink(std::make_unique<LogRotate>("webserverlog", "/tmp/"),
- // &LogRotate::save);
-
auto handle = worker->addDefaultLogger(argv[0], "/tmp/");
g3::initializeLogging(worker.get());
auto sink_handle = worker->addSink(std::make_unique<crow::ColorCoutSink>(), &crow::ColorCoutSink::ReceiveLogMessage);
@@ -114,17 +198,11 @@
std::string ssl_pem_file("server.pem");
ensuressl::ensure_openssl_key_present_and_valid(ssl_pem_file);
- //crow::App<crow::TokenAuthorizationMiddleware> app;
crow::App<crow::TokenAuthorizationMiddleware> app;
crow::webassets::request_routes(app);
crow::logger::setLogLevel(crow::LogLevel::INFO);
- auto rules = app.get_rules();
- for (auto& rule : rules) {
- LOG(DEBUG) << "Static route: " << rule;
- }
-
CROW_ROUTE(app, "/routes")
([&app]() {
crow::json::wvalue routes;
@@ -133,5 +211,209 @@
return routes;
});
- app.port(18080).ssl(std::move(get_ssl_context(ssl_pem_file))).run();
+ CROW_ROUTE(app, "/login")
+ .methods("POST"_method)([&](const crow::request& req) {
+ auto auth_token = app.get_context<crow::TokenAuthorizationMiddleware>(req).auth_token;
+ crow::json::wvalue x;
+ x["token"] = auth_token;
+
+ return x;
+ });
+
+ CROW_ROUTE(app, "/logout")
+ .methods("GET"_method, "POST"_method)([]() {
+ // Do nothing. Credentials have already been cleared by middleware.
+ return 200;
+ });
+
+ CROW_ROUTE(app, "/systeminfo")
+ ([]() {
+
+ crow::json::wvalue j;
+ j["device_id"] = 0x7B;
+ j["device_provides_sdrs"] = true;
+ j["device_revision"] = true;
+ j["device_available"] = true;
+ j["firmware_revision"] = "0.68";
+
+ j["ipmi_revision"] = "2.0";
+ j["supports_chassis_device"] = true;
+ j["supports_bridge"] = true;
+ j["supports_ipmb_event_generator"] = true;
+ j["supports_ipmb_event_receiver"] = true;
+ j["supports_fru_inventory_device"] = true;
+ j["supports_sel_device"] = true;
+ j["supports_sdr_repository_device"] = true;
+ j["supports_sensor_device"] = true;
+
+ j["firmware_aux_revision"] = "0.60.foobar";
+
+ return j;
+ });
+
+ typedef std::vector<connection_metadata> meta_list;
+ meta_list connection_states(10);
+
+ connection_metadata meta;
+
+ CROW_ROUTE(app, "/kvmws")
+ .websocket()
+ .onopen([&](crow::websocket::connection& conn) {
+ meta.vnc_state = VncState::AWAITING_CLIENT_VERSION;
+ conn.send_binary(rfb_3_8_version_string);
+ })
+ .onclose([&](crow::websocket::connection& conn, const std::string& reason) {
+
+ })
+ .onmessage([&](crow::websocket::connection& conn, const std::string& data, bool is_binary) {
+ switch (meta.vnc_state) {
+ 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) {
+ // TODO(ed)
+ } else {
+ // TODO(ed)
+ }
+ } break;
+ case VncState::AWAITING_CLIENT_AUTH_METHOD: {
+ std::string security_result{{0, 0, 0, 0}};
+ if (data[0] == (uint8_t)RfbAuthScheme::no_authentication) {
+ meta.vnc_state = VncState::AWAITING_CLIENT_INIT_MESSAGE;
+ } else {
+ // Mark auth as failed
+ security_result[3] = 1;
+ meta.vnc_state = VncState::UNSTARTED;
+ }
+ conn.send_binary(security_result);
+ } break;
+ case VncState::AWAITING_CLIENT_INIT_MESSAGE: {
+ // Now send the server initialization
+ server_initialization_message server_init_msg;
+ server_init_msg.framebuffer_width = 640;
+ server_init_msg.framebuffer_height = 480;
+ 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);
+ // 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));
+ LOG(DEBUG) << "s.size() " << s.size();
+ conn.send_binary(s);
+ meta.vnc_state = VncState::MAIN_LOOP;
+ } break;
+ case VncState::MAIN_LOOP: {
+ if (data.size() >= sizeof(client_to_server_message_type)) {
+ auto type = static_cast<client_to_server_message_type>(data[0]);
+ std::cout << "Got type " << (uint32_t)type << "\n";
+ switch (type) {
+ case client_to_server_message_type::set_pixel_format: {
+ } break;
+
+ case client_to_server_message_type::fix_color_map_entries: {
+ } break;
+ case client_to_server_message_type::set_encodings: {
+ } break;
+ case client_to_server_message_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_request_message) + sizeof(client_to_server_message_type)) {
+ auto msg = reinterpret_cast<const frame_buffer_update_request_message*>(data.data() + sizeof(client_to_server_message_type));
+
+ std::cout << "framebuffer_update_request_message\n";
+ std::cout << " incremental=" << msg->incremental << "\n";
+ std::cout << " x=" << msg->x_position;
+ std::cout << " y=" << msg->y_position << "\n";
+ std::cout << " width=" << msg->width;
+ std::cout << " height=" << msg->height << "\n";
+
+ framebuffer_update_message buffer_update_message;
+
+ // 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 = msg->width;
+ this_rect.height = msg->height;
+ this_rect.encoding = static_cast<uint8_t>(encoding_type::raw);
+
+ this_rect.data.reserve(this_rect.width * this_rect.height * 4);
+
+ for (unsigned int x_index = 0; x_index < this_rect.width; x_index++) {
+ for (unsigned int y_index = 0; y_index < this_rect.height; y_index++) {
+ this_rect.data.push_back(static_cast<uint8_t>(0)); // Blue
+ this_rect.data.push_back(static_cast<uint8_t>(0)); // Green
+ this_rect.data.push_back(static_cast<uint8_t>(x_index * 0xFF / msg->width)); // RED
+ this_rect.data.push_back(static_cast<uint8_t>(0)); // UNUSED
+ }
+ }
+
+ buffer_update_message.rectangles.push_back(std::move(this_rect));
+ auto serialized = serialize(buffer_update_message);
+
+ conn.send_binary(serialized);
+ }
+
+ }
+
+ break;
+
+ case client_to_server_message_type::key_event: {
+ } break;
+
+ case client_to_server_message_type::pointer_event: {
+ } break;
+
+ case client_to_server_message_type::client_cut_text: {
+ } break;
+
+ default:
+ break;
+ }
+ }
+
+ } break;
+ case VncState::UNSTARTED:
+ // Error? TODO
+ break;
+ }
+
+ });
+
+ CROW_ROUTE(app, "/ipmiws")
+ .websocket()
+ .onopen([&](crow::websocket::connection& conn) {
+
+ })
+ .onclose([&](crow::websocket::connection& conn, const std::string& reason) {
+
+ })
+ .onmessage([&](crow::websocket::connection& conn, const std::string& data, bool is_binary) {
+ boost::asio::io_service io_service;
+ boost::asio::ip::udp::udp::socket socket(io_service, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 0));
+ boost::asio::ip::udp::resolver resolver(io_service);
+ boost::asio::ip::udp::resolver::query query(boost::asio::ip::udp::v4(), "10.243.48.31", "623");
+ boost::asio::ip::udp::resolver::iterator iter = resolver.resolve(query);
+ socket.send_to(boost::asio::buffer(data), *iter);
+ });
+
+ auto rules = app.get_rules();
+ for (auto& rule : rules) {
+ LOG(DEBUG) << "Static route: " << rule;
+ }
+
+ // app.port(18080).ssl(std::move(get_ssl_context(ssl_pem_file))).concurrency(4).run();
+ app.port(18080).concurrency(4).run();
}
diff --git a/static/CMakeLists.txt b/static/CMakeLists.txt
index 3450531..645db9a 100644
--- a/static/CMakeLists.txt
+++ b/static/CMakeLists.txt
@@ -65,7 +65,7 @@
set(STATIC_ASSETS_OUT "")
foreach(JAVASCRIPT_ASSET ${JAVASCRIPT_ASSETS})
# if it's a debug build, don't minify
- if (CMAKE_BUILD_TYPE STREQUAL "Debug")
+ if (CMAKE_BUILD_TYPE STREQUAL "DEBUG")
list(APPEND STATIC_ASSETS_OUT ${CMAKE_CURRENT_SOURCE_DIR}/${JAVASCRIPT_ASSET})
else()
set(OUTPUT_FILENAME ${CMAKE_CURRENT_BINARY_DIR}/${JAVASCRIPT_ASSET})
@@ -76,17 +76,36 @@
COMMAND closure-compiler --language_in=ECMASCRIPT5
--js "${CMAKE_CURRENT_SOURCE_DIR}/${JAVASCRIPT_ASSET}"
--js_output_file "${CMAKE_CURRENT_BINARY_DIR}/${JAVASCRIPT_ASSET}"
-
+ --compilation_level SIMPLE_OPTIMIZATIONS
+ --angular_pass
DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${JAVASCRIPT_ASSET}"
COMMENT "Minifying ${JAVASCRIPT_ASSET}"
)
list(APPEND STATIC_ASSETS_OUT ${CMAKE_CURRENT_BINARY_DIR}/${JAVASCRIPT_ASSET})
- endif (CMAKE_BUILD_TYPE STREQUAL "Debug")
+ endif (CMAKE_BUILD_TYPE STREQUAL "DEBUG")
endforeach(JAVASCRIPT_ASSET)
# for now CSS is included as is
foreach(CSS_ASSET ${CSS_ASSETS})
- list(APPEND STATIC_ASSETS_OUT ${CMAKE_CURRENT_SOURCE_DIR}/${CSS_ASSET})
+ # if it's a debug build, don't minify
+ if (CMAKE_BUILD_TYPE STREQUAL "DEBUG")
+ list(APPEND STATIC_ASSETS_OUT ${CMAKE_CURRENT_SOURCE_DIR}/${CSS_ASSET})
+ else()
+ set(OUTPUT_FILENAME ${CMAKE_CURRENT_BINARY_DIR}/${CSS_ASSET})
+ get_filename_component(FOLDERNAME ${OUTPUT_FILENAME} DIRECTORY)
+ file(MAKE_DIRECTORY "${FOLDERNAME}")
+ # TODO only minify if not a debug build
+ add_custom_command(OUTPUT ${OUTPUT_FILENAME}
+ COMMAND cssnano
+ "${CMAKE_CURRENT_SOURCE_DIR}/${CSS_ASSET}"
+ "${CMAKE_CURRENT_BINARY_DIR}/${CSS_ASSET}"
+
+ DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/${CSS_ASSET}"
+ COMMENT "Minifying ${CSS_ASSET}"
+ )
+ list(APPEND STATIC_ASSETS_OUT ${CMAKE_CURRENT_BINARY_DIR}/${CSS_ASSET})
+ endif (CMAKE_BUILD_TYPE STREQUAL "DEBUG")
+
endforeach(CSS_ASSET)
# for now HTML is included as is
diff --git a/static/img/logo.png b/static/img/logo.png
index 86f6af7..723e815 100644
--- a/static/img/logo.png
+++ b/static/img/logo.png
Binary files differ
diff --git a/static/index.html b/static/index.html
index e1bb874..0c640d3 100644
--- a/static/index.html
+++ b/static/index.html
@@ -29,6 +29,18 @@
<script src="static/js/angular-websocket.js"></script>
<script src="static/js/kvm-controller.js"></script>
<script src="static/noVNC/include/util.js"></script>
+ <script src="static/noVNC/include/webutil.js"></script>
+ <script src="static/noVNC/include/base64.js"></script>
+ <script src="static/noVNC/include/websock.js"></script>
+ <script src="static/noVNC/include/des.js"></script>
+ <script src="static/noVNC/include/keysymdef.js"></script>
+ <script src="static/noVNC/include/xtscancodes.js"></script>
+ <script src="static/noVNC/include/keyboard.js"></script>
+ <script src="static/noVNC/include/input.js"></script>
+ <script src="static/noVNC/include/display.js"></script>
+ <script src="static/noVNC/include/inflator.js"></script>
+ <script src="static/noVNC/include/rfb.js"></script>
+ <script src="static/noVNC/include/keysym.js"></script>
<script type="text/javascript">
var INCLUDE_URI= "static/noVNC/include/";
diff --git a/static/js/bmcApp.js b/static/js/bmcApp.js
index 1c91e8f..64a480a 100644
--- a/static/js/bmcApp.js
+++ b/static/js/bmcApp.js
@@ -1,8 +1,13 @@
'use strict';
angular.module('Authentication', []);
var app = angular.module('bmcApp', [
- 'Authentication', 'ngCookies', 'ui.bootstrap', 'ui.router',
- 'ngSanitize', 'ngWebSocket', 'ngResource'
+ 'Authentication',
+ 'ngCookies',
+ 'ui.bootstrap',
+ 'ui.router',
+ 'ngSanitize',
+ 'ngWebSocket',
+ 'ngResource'
]);
@@ -10,35 +15,62 @@
});
-app.service('loginInterceptor', function($q, $state) {
+app.service('loginInterceptor', ["$injector",
+ function($injector) {
var service = this;
service.responseError = function(response) {
+ var $state = $injector.get('$state');
+ var AuthenticationService = $injector.get('AuthenticationService');
if (response.status == 401){
console.log("Login required... ");
var invalidate_reason = "Your user was logged out.";
- var continue_promise_chain = false;
// if we're attempting to log in, we need to
// continue the promise chain to make sure the user is informed
if ($state.current.name === "login") {
invalidate_reason = "Your username and password was incorrect";
- continue_promise_chain = true
} else {
$state.after_login_state = $state.current.name;
$state.go('login');
}
AuthenticationService.ClearCredentials(invalidate_reason);
}
- //return $q.reject(response);
+
};
-})
+}])
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('loginInterceptor');
}]);
+app.directive('windowSize', function ($window) {
+ return function (scope, element) {
+ var w = angular.element($window);
+ scope.getWindowDimensions = function () {
+ return {
+ 'h': w.height(),
+ 'w': w.width()
+ };
+ };
+ scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
+ scope.windowHeight = newValue.h;
+ scope.windowWidth = newValue.w;
+ scope.style = function () {
+ return {
+ 'height': (newValue.h - 100) + 'px',
+ 'width': (newValue.w - 100) + 'px'
+ };
+ };
+ }, true);
+
+ w.bind('resize', function () {
+ scope.$apply();
+ });
+ }
+});
+
app.run(['$rootScope', '$cookieStore', '$state', '$resource', 'AuthenticationService',
function($rootScope, $cookieStore, $state, $resource, AuthenticationService) {
if ($rootScope.globals == undefined){
@@ -52,7 +84,8 @@
'$stateChangeStart',
function(event, toState, toParams, fromState, fromParams, options) {
// redirect to login page if not logged in
- if (toState.name !== 'login' && !$rootScope.globals.currentUser) {
+ // unless we're already trying to go to the login page (prevent a loop)
+ if (!$rootScope.globals.currentUser && toState.name !== 'login') {
// If logged out and transitioning to a logged in page:
event.preventDefault();
$state.go('login');
@@ -61,7 +94,8 @@
}
]);
-app.config(function($stateProvider, $urlRouterProvider) {
+app.config(['$stateProvider', '$urlRouterProvider',
+ function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/systeminfo');
@@ -99,9 +133,9 @@
})
-});
+}]);
-app.controller('PaginationDemoCtrl', function($scope, $log) {
+app.controller('PaginationDemoCtrl', ['$scope', '$log', function($scope, $log) {
$scope.totalItems = 64;
$scope.currentPage = 4;
@@ -114,14 +148,12 @@
$scope.maxSize = 5;
$scope.bigTotalItems = 175;
$scope.bigCurrentPage = 1;
-});
+}]);
-angular.module('Authentication')
-
- .factory(
+angular.module('Authentication').factory(
'AuthenticationService',
- ['$cookieStore', '$rootScope', '$timeout', '$resource', '$log',
- function($cookieStore, $rootScope, $timeout, $resource, $log) {
+ ['$cookieStore', '$rootScope', '$timeout', '$resource', '$log', '$http',
+ function($cookieStore, $rootScope, $timeout, $resource, $log, $http) {
var service = {};
service.Login = function(username, password, success_callback, fail_callback) {
@@ -136,8 +168,7 @@
service.SetCredentials = function(username, token) {
$rootScope.globals["currentUser"] = {username: username, authdata: token};
- Restangular.setDefaultHeaders(
- {'Authorization': 'Token ' + token});
+ $http.defaults.headers.common['Authorization'] = 'Token ' + token;
$cookieStore.put('globals', $rootScope.globals);
};
@@ -147,7 +178,7 @@
service.logoutreason = reason;
}
$cookieStore.remove('globals');
- Restangular.setDefaultHeaders({});
+ $http.defaults.headers.common['Authorization'] = '';
};
service.RestoreCredientials = function() {
@@ -163,23 +194,6 @@
}
])
- .factory('Websocket_URI',
- function($rootScope, $http) {
- var loc = window.location, websocket_uri;
- if (loc.protocol === "https:") {
- websocket_uri = "wss:";
- } else {
- websocket_uri = "ws:";
- }
- websocket_uri += "//" + loc.hostname + ":9000";
- // Append the authentication token
- websocket_uri += "?token="
- websocket_uri += $rootScope.globals["currentUser"]["authdata"]
- var methods = {
- uri: websocket_uri
- }
- return methods;
- })
.factory('Base64', function() {
/* jshint ignore:start */
diff --git a/static/js/kvm-controller.js b/static/js/kvm-controller.js
index 3c6af2b..87427b6 100644
--- a/static/js/kvm-controller.js
+++ b/static/js/kvm-controller.js
@@ -1,25 +1,44 @@
-angular.module('bmcApp').controller('KvmController', function($scope, $location) {
+angular.module('bmcApp').controller('KvmController', function($scope, $location, $window) {
/*jslint white: false */
/*global window, $, Util, RFB, */
"use strict";
- var INCLUDE_URI = "noVNC/"
- // Load supporting scripts
- Util.load_scripts(["webutil.js", "base64.js", "websock.js", "des.js",
- "keysymdef.js", "xtscancodes.js", "keyboard.js",
- "input.js", "display.js", "inflator.js", "rfb.js",
- "keysym.js"]);
var rfb;
- var resizeTimeout;
+ var host = $location.host();
+ var port = $location.port();
+ var encrypt = $location.protocol() === 'https:';
+ var password = "";
+ var token = "1234";
+ var path = "kvmws";
+ var target = angular.element(document.querySelector('#noVNC_canvas'))[0];
+ try {
+ rfb = new RFB({'target': target,
+ 'encrypt': encrypt,
+ 'local_cursor': true,
+ 'onUpdateState': updateState,
+ //'onXvpInit': xvpInit,
+ 'onFBUComplete': FBUComplete,
+ 'resize': true});
+ rfb.connect(host, port, password, path);
+ } catch (exc) {
+ updateState(null, 'fatal', null, 'Unable to create RFB client -- ' + exc);
+ return; // don't continue trying to connect
+ }
+
+
+ $scope.$on("$destroy", function() {
+ if (rfb) {
+ rfb.disconnect();
+ }
+ });
function UIresize() {
if (WebUtil.getConfigVar('resize', false)) {
- var innerW = window.innerWidth;
- var innerH = window.innerHeight;
- var controlbarH = $D('noVNC_status_bar').offsetHeight;
+ var innerW = $window.innerWidth;
+ var innerH = $window.innerHeight;
var padding = 5;
if (innerW !== undefined && innerH !== undefined)
rfb.requestDesktopSize(innerW, innerH - controlbarH - padding);
@@ -33,23 +52,11 @@
rfb.sendCtrlAltDel();
return false;
}
- function xvpShutdown() {
- rfb.xvpShutdown();
- return false;
- }
- function xvpReboot() {
- rfb.xvpReboot();
- return false;
- }
- function xvpReset() {
- rfb.xvpReset();
- return false;
- }
+
function updateState(rfb, state, oldstate, msg) {
var s, sb, cad, level;
- s = $D('noVNC_status');
- sb = $D('noVNC_status_bar');
- cad = $D('sendCtrlAltDelButton');
+ s = angular.element(document.querySelector('#noVNC_status'))[0];
+ sb = angular.element(document.querySelector('#noVNC_status_bar'))[0];
switch (state) {
case 'failed': level = "error"; break;
case 'fatal': level = "error"; break;
@@ -59,20 +66,20 @@
default: level = "warn"; break;
}
- if (state === "normal") {
- cad.disabled = false;
- } else {
- cad.disabled = true;
- xvpInit(0);
- }
-
if (typeof(msg) !== 'undefined') {
- sb.setAttribute("class", "noVNC_status_" + level);
- s.innerHTML = msg;
+ // at this point, it's possible the window has already been destroyed, so make sure
+ // the handles exist before writing.
+ if (typeof(sb) !== 'undefined'){
+ sb.setAttribute("class", "noVNC_status_" + level);
+ }
+ if (typeof(sb) !== 'undefined'){
+ s.innerHTML = msg;
+ }
}
}
- window.onresize = function () {
+ var resizeTimeout;
+ $window.onresize = function () {
// When the window has been resized, wait until the size remains
// the same for 0.5 seconds before sending the request for changing
// the resolution of the session
@@ -80,45 +87,5 @@
resizeTimeout = setTimeout(function(){
UIresize();
}, 500);
- };
-
- function xvpInit(ver) {
- var xvpbuttons;
- xvpbuttons = $D('noVNC_xvp_buttons');
- if (ver >= 1) {
- xvpbuttons.style.display = 'inline';
- } else {
- xvpbuttons.style.display = 'none';
- }
- }
-
- window.onscriptsload = function () {
- var host, port, password, path, token;
-
- $D('sendCtrlAltDelButton').style.display = "inline";
- $D('sendCtrlAltDelButton').onclick = sendCtrlAltDel;
- $D('xvpShutdownButton').onclick = xvpShutdown;
- $D('xvpRebootButton').onclick = xvpReboot;
- $D('xvpResetButton').onclick = xvpReset;
-
- host = $location.host();
- port = 9000;
- password = "";
- token = "1234";
- path = "/";
-
- try {
- rfb = new RFB({'target': $D('noVNC_canvas'),
- 'encrypt': true,
- 'local_cursor': true,
- 'onUpdateState': updateState,
- 'onXvpInit': xvpInit,
- 'onFBUComplete': FBUComplete});
- } catch (exc) {
- updateState(null, 'fatal', null, 'Unable to create RFB client -- ' + exc);
- return; // don't continue trying to connect
- }
-
- rfb.connect(host, port, password, path);
- };
+ };
});
\ No newline at end of file
diff --git a/static/js/versionController.js b/static/js/versionController.js
index b77f9b4..c104602 100644
--- a/static/js/versionController.js
+++ b/static/js/versionController.js
@@ -1,16 +1,19 @@
-angular.module('bmcApp').controller('versionController', function($scope) {
+angular.module('bmcApp').controller('versionController', function($scope, $resource) {
- var system_status = Restangular.one('systeminfo').get().then(function(system_status) {
- $scope.system_status = system_status;
+
+ var systeminfo = $resource("/systeminfo");
+ systeminfo.get(function(systeminfo){
+ $scope.host_power_on= true;
+ $scope.rmm_module_installed= true;
+ $scope.bmc_available= true;
+ $scope.bmc_build_date= new Date(2016, 0, 1, 2, 3, 4, 567);
+ $scope.bios_build_number = "D0191";
+ $scope.bmc_build_number = "96.37";
+ $scope.bmc_build_extended = "e04989f7";
+ $scope.bmc_backup_build_number = "96.37";
+ $scope.bmc_backup_build_extended = "e04989f7";
});
- $scope.host_power_on= true;
- $scope.rmm_module_installed= true;
- $scope.bmc_available= true;
- $scope.bmc_build_date= new Date(2016, 0, 1, 2, 3, 4, 567);
- $scope.bios_build_number = "D0191";
- $scope.bmc_build_number = "96.37";
- $scope.bmc_build_extended = "e04989f7";
- $scope.bmc_backup_build_number = "96.37";
- $scope.bmc_backup_build_extended = "e04989f7";
+
+
});
\ No newline at end of file
diff --git a/static/websocket.html b/static/websocket.html
index f21bd6a..5589d14 100644
--- a/static/websocket.html
+++ b/static/websocket.html
@@ -75,7 +75,7 @@
<div id="controls">
<div id="server">
- <input type="text" name="server_url" id="server_url" value="wss://localhost:9000?session_id=foobar" /><br />
+ <input type="text" name="server_url" id="server_url" value="wss://localhost?session_id=foobar" /><br />
<button id="toggle_connect" onclick="toggle_connect();">Connect</button>
</div>
</div>