From 7a67f57be0fcf9609276b2cc0ab4ddb336d37569 Mon Sep 17 00:00:00 2001 From: Alex Hultman Date: Mon, 17 Sep 2018 02:52:10 +0200 Subject: [PATCH] Add static Http server example, fix wildcards --- Makefile | 6 ++++ examples/FileCache.h | 49 +++++++++++++++++++++++++++++++++ examples/Middleware.h | 19 +++++++++++++ examples/static_http_server.cpp | 47 +++++++++++++++++++++++++++++++ src/App.h | 2 +- src/HttpRouter.h | 21 +++++++++++--- 6 files changed, 139 insertions(+), 5 deletions(-) create mode 100644 examples/FileCache.h create mode 100644 examples/Middleware.h create mode 100644 examples/static_http_server.cpp diff --git a/Makefile b/Makefile index 664750d..a4323ea 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,10 @@ default: + rm *.o + clang -flto -O3 -c -IuSockets/src uSockets/src/*.c uSockets/src/eventing/*.c + clang++ -flto -O3 -c -std=c++17 -Isrc -IuSockets/src examples/static_http_server.cpp + clang++ -flto -O3 -s *.o -o static_http_server -lssl -lcrypto -lpthread -lstdc++fs + +main: rm *.o clang -flto -O3 -c -IuSockets/src uSockets/src/*.c uSockets/src/eventing/*.c clang++ -flto -O3 -c -std=c++17 -Isrc -IuSockets/src main.cpp diff --git a/examples/FileCache.h b/examples/FileCache.h new file mode 100644 index 0000000..d78b67e --- /dev/null +++ b/examples/FileCache.h @@ -0,0 +1,49 @@ +#include +#include +#include + +struct FileCache { +private: + std::map cache; + + void cacheFile(std::string file, std::string root) { + std::cout << "Caching file: " << file << std::endl; + + std::ifstream fin(root + file, std::ios::binary); + std::ostringstream oss; + oss << fin.rdbuf(); + + if (file == "/index.html") { + file = "/"; + } + + char *cachedFile = (char *) malloc(oss.str().size()); + memcpy(cachedFile, oss.str().data(), oss.str().size()); + + char *key = (char *) malloc(file.length()); + memcpy(key, file.data(), file.length()); + + std::cout << "Size: " << oss.str().size() << std::endl; + + cache[std::string_view(key, file.length())] = std::string_view(cachedFile, oss.str().size()); + } + +public: + FileCache(std::string root) { + for(auto &p : std::experimental::filesystem::recursive_directory_iterator(root)) { + cacheFile(p.path().string().substr(root.length()), root); + } + } + + std::string_view getFile(std::string_view file) { + auto it = cache.find(file); + + if (it == cache.end()) { +//std::cout << "Did not find file: " << file << std::endl; + return "

Nope!

"; + } else { +//std::cout << "Did find file: " << file << std::endl; + return it->second; + } + } +}; diff --git a/examples/Middleware.h b/examples/Middleware.h new file mode 100644 index 0000000..9e699a9 --- /dev/null +++ b/examples/Middleware.h @@ -0,0 +1,19 @@ +/* Middleware to fill out content-type */ +inline bool hasExt(std::string_view file, std::string_view ext) { + if (ext.size() > file.size()) { + return false; + } + return std::equal(ext.rbegin(), ext.rend(), file.rbegin()); +} + +/* This should be a filter / middleware like app.use(handler) */ +template +uWS::HttpResponse *serveFile(uWS::HttpResponse *res, uWS::HttpRequest *req) { + res->writeStatus(uWS::HTTP_200_OK); + + if (hasExt(req->getUrl(), ".svg")) { + res->writeHeader("Content-Type", "image/svg+xml"); + } + + return res; +} diff --git a/examples/static_http_server.cpp b/examples/static_http_server.cpp new file mode 100644 index 0000000..22ce6e6 --- /dev/null +++ b/examples/static_http_server.cpp @@ -0,0 +1,47 @@ +/* This is a static HTTP(S) server. It caches the files in given root folder and streams them by request */ + +#include + +/* Helpers for this example */ +#include "FileCache.h" +#include "Middleware.h" + +int main(int argc, char **argv) { + + if (argc < 3 || argc > 6) { + std::cout << "Usage: static_http_server root port [ssl_cert ssl_key ssl_passphrase]" << std::endl; + return 0; + } + + int port = atoi(argv[2]); + const char *root = argv[1]; + /* Cache files of root folder */ + FileCache fileCache(root); + + /* Either serve over HTTP or HTTPS */ + if (argc > 4) { + /* HTTPS */ + uWS::SSLApp({ + .cert_file_name = argv[3], + .key_file_name = argv[4], + .passphrase = (argc == 6 ? argv[5] : nullptr) + }).get("/*", [&fileCache](auto *res, auto *req) { + serveFile(res, req)->write(fileCache.getFile(req->getUrl())); + }).listen(port, [port, root](auto *token) { + if (token) { + std::cout << "Serving " << root << " over HTTPS a " << port << std::endl; + } + }).run(); + } else { + /* HTTP */ + uWS::App().get("/*", [&fileCache](auto *res, auto *req) { + serveFile(res, req)->write(fileCache.getFile(req->getUrl())); + }).listen(port, [port, root](auto *token) { + if (token) { + std::cout << "Serving " << root << " over HTTP a " << port << std::endl; + } + }).run(); + } + + std::cout << "Failed to listen to port " << port << std::endl; +} diff --git a/src/App.h b/src/App.h index 7e3cd8b..c09ea38 100644 --- a/src/App.h +++ b/src/App.h @@ -23,7 +23,7 @@ public: httpContext = other.httpContext; } - TemplatedApp(us_ssl_socket_context_options sslOptions) { + TemplatedApp(us_ssl_socket_context_options sslOptions = {}) { httpContext = uWS::HttpContext::create(uWS::Loop::defaultLoop(), &sslOptions); } diff --git a/src/HttpRouter.h b/src/HttpRouter.h index 964e3d5..690ce1c 100644 --- a/src/HttpRouter.h +++ b/src/HttpRouter.h @@ -29,8 +29,11 @@ private: std::string compiled_tree; void add(std::vector route, short handler) { + //std::cout << "add" << std::endl; Node *parent = tree; for (std::string node : route) { + //std::cout << "Node: <" << node << ">" << std::endl; + if (parent->children.find(node) == parent->children.end()) { parent->children[node] = new Node({node, {}, handler}); } @@ -50,13 +53,13 @@ private: compiledNode.append((char *) &nodeLength, sizeof(nodeLength)); compiledNode.append((char *) &nodeNameLength, sizeof(nodeNameLength)); compiledNode.append((char *) &n->handler, sizeof(n->handler)); - compiledNode.append(n->name.data(), n->name.length()); + compiledNode.append(n->name.data(), /*n->name.length()*/ nodeNameLength); compiled_tree = compiledNode + compiled_tree; return nodeLength; } - inline const char *find_node(const char *parent_node, const char *name, int name_length) { + inline const char *find_node(const char *parent_node, const char *name, int name_length, bool *foundWildcard) { unsigned short nodeLength = *(unsigned short *) &parent_node[0]; unsigned short nodeNameLength = *(unsigned short *) &parent_node[2]; @@ -69,7 +72,8 @@ private: unsigned short nodeNameLength = *(unsigned short *) &candidate[2]; // whildcard, parameter, equal - if (nodeNameLength == 0) { + if (nodeNameLength == 1 && candidate[6] == '*') { + *foundWildcard = true; return candidate; } else if (candidate[6] == ':') { // parameter @@ -102,16 +106,23 @@ private: const char *treeStart = (char *) compiled_tree.data(); + bool foundWildcard = false; + const char *stop, *start = url, *end_ptr = url + length; do { stop = getNextSegment(start, end_ptr); //std::cout << "Matching(" << std::string(start, stop - start) << ")" << std::endl; - if(nullptr == (treeStart = find_node(treeStart, start, stop - start))) { + if(nullptr == (treeStart = find_node(treeStart, start, stop - start, &foundWildcard))) { return -1; } + // if the candidate was a wildcard, we do not care for the rest + if (foundWildcard) { + break; + } + start = stop + 1; } while (stop != end_ptr); @@ -165,6 +176,8 @@ public: int index = lookup(url, url_length); if (index != -1) { handlers[index](userData, ¶ms); + } else { + std::cout << "Did not find route for URL: " << std::string_view(url, url_length) << std::endl; } params.clear();