diff --git a/,gitignore b/,gitignore new file mode 100644 index 0000000..582ec45 --- /dev/null +++ b/,gitignore @@ -0,0 +1,2 @@ +bin/* + diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..cb67d39 --- /dev/null +++ b/.clang-format @@ -0,0 +1,128 @@ +# Commented out parameters are those with the same value as base LLVM style +# We can uncomment them if we want to change their value, or enforce the +# chosen value in case the base style changes (last sync: Clang 6.0.1). +--- +### General config, applies to all languages ### +BasedOnStyle: LLVM +AccessModifierOffset: -4 +AlignAfterOpenBracket: DontAlign +# AlignConsecutiveAssignments: false +# AlignConsecutiveDeclarations: false +# AlignEscapedNewlines: Right +# AlignOperands: true +AlignTrailingComments: false +AllowAllParametersOfDeclarationOnNextLine: false +# AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: true +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: true +# AllowShortLoopsOnASingleLine: false +# AlwaysBreakAfterDefinitionReturnType: None +# AlwaysBreakAfterReturnType: None +# AlwaysBreakBeforeMultilineStrings: false +# AlwaysBreakTemplateDeclarations: false +# BinPackArguments: true +# BinPackParameters: true +# BraceWrapping: +# AfterClass: false +# AfterControlStatement: false +# AfterEnum: false +# AfterFunction: false +# AfterNamespace: false +# AfterObjCDeclaration: false +# AfterStruct: false +# AfterUnion: false +# AfterExternBlock: false +# BeforeCatch: false +# BeforeElse: false +# IndentBraces: false +# SplitEmptyFunction: true +# SplitEmptyRecord: true +# SplitEmptyNamespace: true +# BreakBeforeBinaryOperators: None +# BreakBeforeBraces: Attach +# BreakBeforeInheritanceComma: false +BreakBeforeTernaryOperators: false +# BreakConstructorInitializersBeforeComma: false +BreakConstructorInitializers: AfterColon +# BreakStringLiterals: true +ColumnLimit: 0 +# CommentPragmas: '^ IWYU pragma:' +# CompactNamespaces: false +ConstructorInitializerAllOnOneLineOrOnePerLine: true +ConstructorInitializerIndentWidth: 8 +ContinuationIndentWidth: 8 +Cpp11BracedListStyle: false +# DerivePointerAlignment: false +# DisableFormat: false +# ExperimentalAutoDetectBinPacking: false +# FixNamespaceComments: true +# ForEachMacros: +# - foreach +# - Q_FOREACH +# - BOOST_FOREACH +# IncludeBlocks: Preserve +IncludeCategories: + - Regex: '".*"' + Priority: 1 + - Regex: '^<.*\.h>' + Priority: 2 + - Regex: '^<.*' + Priority: 3 +# IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: true +# IndentPPDirectives: None +IndentWidth: 4 +# IndentWrappedFunctionNames: false +# JavaScriptQuotes: Leave +# JavaScriptWrapImports: true +# KeepEmptyLinesAtTheStartOfBlocks: true +# MacroBlockBegin: '' +# MacroBlockEnd: '' +# MaxEmptyLinesToKeep: 1 +# NamespaceIndentation: None +# PenaltyBreakAssignment: 2 +# PenaltyBreakBeforeFirstCallParameter: 19 +# PenaltyBreakComment: 300 +# PenaltyBreakFirstLessLess: 120 +# PenaltyBreakString: 1000 +# PenaltyExcessCharacter: 1000000 +# PenaltyReturnTypeOnItsOwnLine: 60 +# PointerAlignment: Right +# RawStringFormats: +# - Delimiter: pb +# Language: TextProto +# BasedOnStyle: google +# ReflowComments: true +# SortIncludes: true +# SortUsingDeclarations: true +# SpaceAfterCStyleCast: false +# SpaceAfterTemplateKeyword: true +# SpaceBeforeAssignmentOperators: true +# SpaceBeforeParens: ControlStatements +# SpaceInEmptyParentheses: false +# SpacesBeforeTrailingComments: 1 +# SpacesInAngles: false +# SpacesInContainerLiterals: true +# SpacesInCStyleCastParentheses: false +# SpacesInParentheses: false +# SpacesInSquareBrackets: false +TabWidth: 4 +UseTab: Always +--- +### C++ specific config ### +Language: Cpp +Standard: Cpp03 +--- +### ObjC specific config ### +Language: ObjC +Standard: Cpp03 +ObjCBlockIndentWidth: 4 +# ObjCSpaceAfterProperty: false +# ObjCSpaceBeforeProtocolList: true +--- +### Java specific config ### +Language: Java +# BreakAfterJavaFieldAnnotations: false +JavaImportGroups: ['org.godotengine', 'android', 'androidx', 'com.android', 'com.google', 'java', 'javax'] +... diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..16f9b72 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,82 @@ +{ + "files.associations": { + "atomic": "cpp", + "*.ipp": "cpp", + "array": "cpp", + "hash_map": "cpp", + "hash_set": "cpp", + "bitset": "cpp", + "string_view": "cpp", + "initializer_list": "cpp", + "ranges": "cpp", + "regex": "cpp", + "utility": "cpp", + "valarray": "cpp", + "cctype": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "csignal": "cpp", + "cstdarg": "cpp", + "cstddef": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "any": "cpp", + "strstream": "cpp", + "bit": "cpp", + "*.tcc": "cpp", + "chrono": "cpp", + "cinttypes": "cpp", + "codecvt": "cpp", + "compare": "cpp", + "complex": "cpp", + "concepts": "cpp", + "condition_variable": "cpp", + "cstdint": "cpp", + "deque": "cpp", + "forward_list": "cpp", + "list": "cpp", + "map": "cpp", + "set": "cpp", + "unordered_map": "cpp", + "unordered_set": "cpp", + "vector": "cpp", + "exception": "cpp", + "algorithm": "cpp", + "functional": "cpp", + "iterator": "cpp", + "memory": "cpp", + "memory_resource": "cpp", + "numeric": "cpp", + "optional": "cpp", + "random": "cpp", + "ratio": "cpp", + "string": "cpp", + "system_error": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "fstream": "cpp", + "future": "cpp", + "iomanip": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "limits": "cpp", + "mutex": "cpp", + "new": "cpp", + "ostream": "cpp", + "shared_mutex": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "stop_token": "cpp", + "streambuf": "cpp", + "thread": "cpp", + "cfenv": "cpp", + "typeindex": "cpp", + "typeinfo": "cpp", + "variant": "cpp" + } +} \ No newline at end of file diff --git a/bin/server b/bin/server new file mode 100755 index 0000000..bbafdff Binary files /dev/null and b/bin/server differ diff --git a/compile_linux.sh b/compile_linux.sh index 1b1d587..f27a026 100755 --- a/compile_linux.sh +++ b/compile_linux.sh @@ -1 +1 @@ -g++ -o3 cout_server.cpp -o server -Ilibs -lpthread +g++ -o3 -g main.cpp ./framework/settings.cpp ./framework/request.cpp ./framework/http_server.cpp ./framework/file_cache.cpp ./framework/application.cpp ./rdn_application.cpp -o ./bin/server -Ilibs -lpthread -std=c++11 diff --git a/cout_server.cpp b/cout_server.cpp deleted file mode 100644 index 7eb5a65..0000000 --- a/cout_server.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include -#include -#include - -#include -#include -#include -#include - -using namespace brynet; -using namespace brynet::net; - -std::atomic_llong TotalRecvSize = ATOMIC_VAR_INIT(0); -std::atomic_llong total_client_num = ATOMIC_VAR_INIT(0); -std::atomic_llong total_packet_num = ATOMIC_VAR_INIT(0); - -int main(int argc, char **argv) -{ - if (argc != 3) - { - fprintf(stderr, "Usage: \n"); - exit(-1); - } - - auto service = TcpService::Create(); - service->startWorkerThread(atoi(argv[2])); - - auto enterCallback = [](const TcpConnection::Ptr& session) { - total_client_num++; - - session->setDataCallback([session](const char* buffer, size_t len) { - session->send(buffer, len); - TotalRecvSize += len; - total_packet_num++; - - std::cout << "------------------------------------- PACKET -------------------------------------" << std::endl; - std::cout << buffer << std::endl; - std::cout << "------------------------------------------------------------------------------------" << std::endl << std::endl; - - return len; - }); - - session->setDisConnectCallback([](const TcpConnection::Ptr& session) { - (void)session; - total_client_num--; - }); - }; - - wrapper::ListenerBuilder listener; - listener.configureService(service) - .configureSocketOptions({ - [](TcpSocket& socket) { - socket.setNodelay(); - } - }) - .configureConnectionOptions({ - brynet::net::AddSocketOption::WithMaxRecvBufferSize(1024 * 1024), - brynet::net::AddSocketOption::AddEnterCallback(enterCallback) - }) - .configureListen([=](wrapper::BuildListenConfig config) { - config.setAddr(false, "0.0.0.0", atoi(argv[1])); - }) - .asyncRun(); - - EventLoop mainLoop; - while (true) - { - mainLoop.loop(1000); - - total_packet_num = 0; - TotalRecvSize = 0; - - if (brynet::base::app_kbhit()) - { - break; - } - } - - return 0; -} diff --git a/framework/application.cpp b/framework/application.cpp new file mode 100644 index 0000000..5e90be5 --- /dev/null +++ b/framework/application.cpp @@ -0,0 +1,132 @@ +#include "application.h" + +#include +#include + +#include "request.h" + +#include "file_cache.h" + +#include + +#include +#include +#include + +void Application::setup_routes() { + default_error_handler_func = Application::default_fallback_error_handler; + + error_handler_map[404] = Application::default_404_error_handler; +} + +void Application::setup_middleware() { +} + +void Application::default_fallback_error_handler(int error_code, Request *request) { + std::string body = "Internal server error! :("; + request->response->setBody(body); + request->finalized = true; +} + +void Application::default_404_error_handler(int error_code, Request *request) { + std::string body = "404 :("; + request->response->setBody(body); + request->finalized = true; +} + +void Application::handle_request(Request *request) { + + std::string path = request->http_parser->getPath(); + + if (FileCache::get_instance()->has_file(path)) { + send_file(path, request); + + return; + } + + std::function func; + + if (path == "/") { + //quick shortcut + func = index_func; + } else { + std::string main_route = ""; + + uint32_t endpos = 1; + for (; endpos < path.size(); ++endpos) { + if (path[endpos] == '/') { + break; + } + } + + main_route = path.substr(1, endpos - 1); + + func = main_route_map[main_route]; + } + + if (!func) { + send_error(404, request); + + return; + } + + for (uint32_t i; i < middlewares.size(); ++i) { + middlewares[i](request); + + if (request->finalized) + return; + } + + func(request); +} + +void Application::send_error(int error_code, Request *request) { + std::function func = error_handler_map[error_code]; + + if (!func) { + default_error_handler_func(error_code, request); + return; + } + + func(error_code, request); +} + +void Application::send_file(const std::string &path, Request *request) { + std::string fp = FileCache::get_instance()->wwwroot + path; + + FILE *f = fopen(fp.c_str(), "rb"); + fseek(f, 0, SEEK_END); + long fsize = ftell(f); + fseek(f, 0, SEEK_SET); /* same as rewind(f); */ + + std::string body; + body.resize(fsize); + + fread(&body[0], 1, fsize, f); + fclose(f); + + request->response->setBody(body); + request->finalized = true; +} + +Application::Application() { + _instance = this; +} + +Application::~Application() { + main_route_map.clear(); + error_handler_map.clear(); + middlewares.clear(); +} + +Application *Application::get_instance() { + return _instance; +} + +std::function Application::index_func = nullptr; +std::map > Application::main_route_map; +std::map > Application::error_handler_map; +std::function Application::default_error_handler_func = nullptr; +std::vector > Application::middlewares; + +Application *Application::_instance = nullptr; diff --git a/framework/application.h b/framework/application.h new file mode 100644 index 0000000..5b7f770 --- /dev/null +++ b/framework/application.h @@ -0,0 +1,38 @@ +#ifndef APPLICATION_H +#define APPLICATION_H + +#include +#include +#include +#include + +class Request; + +class Application { +public: + static void handle_request(Request *request); + static void send_error(int error_code, Request *request); + static void send_file(const std::string &path, Request *request); + + static void default_fallback_error_handler(int error_code, Request *request); + static void default_404_error_handler(int error_code, Request *request); + + virtual void setup_routes(); + virtual void setup_middleware(); + + Application(); + virtual ~Application(); + + static Application *get_instance(); + + static std::function index_func; + static std::map > main_route_map; + static std::map > error_handler_map; + static std::function default_error_handler_func; + static std::vector > middlewares; + +private: + static Application *_instance; +}; + +#endif \ No newline at end of file diff --git a/framework/file_cache.cpp b/framework/file_cache.cpp new file mode 100644 index 0000000..d119fdb --- /dev/null +++ b/framework/file_cache.cpp @@ -0,0 +1,73 @@ +#include "file_cache.h" + +#include + +#include + +void FileCache::register_file(const std::string &file_path) { + registered_files.insert(file_path); +} + +void FileCache::deregister_file(const std::string &file_path) { + registered_files.erase(file_path); +} + +bool FileCache::has_file(const std::string &file_path) { + return registered_files.find(file_path) != registered_files.end(); +} + +void FileCache::refresh() { + registered_files.clear(); + + evaluate_dir(wwwroot.c_str()); +} + +void FileCache::evaluate_dir(const char *path) { + tinydir_dir dir; + if (tinydir_open(&dir, path) == -1) { + printf("Error opening wwwroot!\n"); + return; + } + + while (dir.has_next) { + tinydir_file file; + if (tinydir_readfile(&dir, &file) == -1) { + tinydir_next(&dir); + continue; + } + + if (!file.is_dir) { + std::string np = file.path; + np = np.substr(wwwroot.size(), np.size() - wwwroot.size()); + + registered_files.insert(np); + } else { + if (file.name[0] == '.' && file.name[1] == '\0' || file.name[0] == '.' && file.name[1] == '.') { + tinydir_next(&dir); + continue; + } + + evaluate_dir(file.path); + } + + tinydir_next(&dir); + } + + tinydir_close(&dir); +} + +FileCache::FileCache() { + _instance = this; +} + +FileCache::~FileCache() { + registered_files.clear(); + + _instance = nullptr; +} + +FileCache *FileCache::get_instance() { + return _instance; +} + +FileCache *FileCache::_instance = nullptr; diff --git a/framework/file_cache.h b/framework/file_cache.h new file mode 100644 index 0000000..cfe97fa --- /dev/null +++ b/framework/file_cache.h @@ -0,0 +1,30 @@ +#ifndef FILE_CACHE_H +#define FILE_CACHE_H + +#include +#include + +class FileCache { +public: + std::string wwwroot; + + void register_file(const std::string &file_path); + void deregister_file(const std::string &file_path); + + bool has_file(const std::string &file_path); + + void refresh(); + void evaluate_dir(const char *path); + + FileCache(); + virtual ~FileCache(); + + static FileCache *get_instance(); + + std::set registered_files; + +private: + static FileCache *_instance; +}; + +#endif \ No newline at end of file diff --git a/framework/http_server.cpp b/framework/http_server.cpp new file mode 100644 index 0000000..60d13c7 --- /dev/null +++ b/framework/http_server.cpp @@ -0,0 +1,111 @@ +#include "http_server.h" + +#include "request.h" +#include "application.h" + +#define LOG_VERBOSE 0 + +void HTTPServer::http_callback_handler(Request *request) { + Application::handle_request(request); +} + +void HTTPServer::httpEnterCallbackDefault(const HTTPParser &httpParser, const HttpSession::Ptr &session) { + //(void)httpParser; needed? + + Request *request = RequestPool::get_request(); + + request->http_parser = &httpParser; + request->session = &session; + +#if LOG_VERBOSE + std::cout << "method:" << http_method_str(static_cast(httpParser.method())) << std::endl; +#endif + + http_callback_handler(request); + + if (httpParser.isKeepAlive()) { + request->response->addHeadValue("Connection", "Keep-Alive"); + + std::string result = request->response->getResult(); + + session->send(result.c_str(), result.size()); + } else { + request->response->addHeadValue("Connection", "Close"); + + std::string result = request->response->getResult(); + + session->send(result.c_str(), result.size(), [session]() { session->postShutdown(); }); + } + + RequestPool::return_request(request); +} + +void HTTPServer::wsEnterCallbackDefault(const HttpSession::Ptr &httpSession, WebSocketFormat::WebSocketFrameType opcode, const std::string &payload) { + + std::cout << "frame enter of type:" << int(opcode) << std::endl; + std::cout << "payload is:" << payload << std::endl; + // echo frame + auto frame = std::make_shared(); + + WebSocketFormat::wsFrameBuild(payload.c_str(), payload.size(), *frame, WebSocketFormat::WebSocketFrameType::TEXT_FRAME, true, false); + + httpSession->send(frame); +} + +void HTTPServer::configure() { +} + +void HTTPServer::initialize() { + if (service) + return; + + configure(); + + service = TcpService::Create(); + service->startWorkerThread(threads); + + int p_port = port; + + if (listenBuilder) + delete listenBuilder; + + listenBuilder = new wrapper::HttpListenerBuilder(); + listenBuilder->configureService(service); + + listenBuilder->configureSocketOptions({ + [](TcpSocket &socket) { + socket.setNodelay(); + }, + }); + + listenBuilder->configureConnectionOptions({ AddSocketOption::WithMaxRecvBufferSize(1024) }); + + listenBuilder->configureListen([p_port](wrapper::BuildListenConfig builder) { + builder.setAddr(false, "0.0.0.0", p_port); + }); + + listenBuilder->configureEnterCallback([](const HttpSession::Ptr &httpSession, HttpSessionHandlers &handlers) { + handlers.setHttpCallback(HTTPServer::httpEnterCallbackDefault); + handlers.setWSCallback(HTTPServer::wsEnterCallbackDefault); + }); + + listenBuilder->asyncRun(); +} + +void HTTPServer::main_loop() { + while (true) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + if (brynet::base::app_kbhit()) { + break; + } + } +} + +HTTPServer::HTTPServer() { + port = 80; + threads = 4; +} + +HTTPServer::~HTTPServer() { + delete listenBuilder; +} \ No newline at end of file diff --git a/framework/http_server.h b/framework/http_server.h new file mode 100644 index 0000000..ec67d63 --- /dev/null +++ b/framework/http_server.h @@ -0,0 +1,42 @@ +#ifndef HTTP_SERVER_H +#define HTTP_SERVER_H + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace brynet; +using namespace brynet::net; +using namespace brynet::net::http; + +class Request; + +class HTTPServer { +public: + int port; + int threads; + std::shared_ptr service; + wrapper::HttpListenerBuilder *listenBuilder; + + static void http_callback_handler(Request *response); + + static void httpEnterCallbackDefault(const HTTPParser &httpParser, const HttpSession::Ptr &session); + static void wsEnterCallbackDefault(const HttpSession::Ptr &httpSession, WebSocketFormat::WebSocketFrameType opcode, const std::string &payload); + + virtual void configure(); + virtual void initialize(); + + void main_loop(); + + HTTPServer(); + virtual ~HTTPServer(); +}; + +#endif \ No newline at end of file diff --git a/framework/request.cpp b/framework/request.cpp new file mode 100644 index 0000000..a0b7255 --- /dev/null +++ b/framework/request.cpp @@ -0,0 +1,65 @@ +#include "request.h" + +void Request::reset() { + http_parser = nullptr; + session = nullptr; + finalized = false; + + if (response) + delete response; + + response = new HttpResponse(); +} + +Request::Request() { + response = nullptr; + + reset(); +} + +Request::~Request() { + delete response; +} + +Request *RequestPool::get_request() { + _mutex.lock(); + + Request *request; + + if (_requests.size() == 0) { + _mutex.unlock(); + + request = new Request(); + + return request; + } + + request = _requests[_requests.size() - 1]; + _requests.pop_back(); + + _mutex.unlock(); + + return request; +} + +void RequestPool::return_request(Request *request) { + request->reset(); + + _mutex.lock(); + _requests.push_back(request); + _mutex.unlock(); +} + +RequestPool::RequestPool() { +} + +RequestPool::~RequestPool() { + for (uint32_t i = 0; i < _requests.size(); ++i) { + delete _requests[i]; + } + + _requests.clear(); +} + +std::mutex RequestPool::_mutex; +std::vector RequestPool::_requests; diff --git a/framework/request.h b/framework/request.h new file mode 100644 index 0000000..e5aa63a --- /dev/null +++ b/framework/request.h @@ -0,0 +1,40 @@ +#ifndef REQUEST_H +#define REQUEST_H + +#include +#include + +#include +#include + +using namespace brynet; +using namespace brynet::net; +using namespace brynet::net::http; + +class Request { +public: + const HTTPParser *http_parser; + const HttpSession::Ptr *session; + HttpResponse *response; + bool finalized; + + void reset(); + + Request(); + ~Request(); +}; + +class RequestPool { +public: + static Request *get_request(); + static void return_request(Request *request); + + RequestPool(); + ~RequestPool(); + +protected: + static std::mutex _mutex; + static std::vector _requests; +}; + +#endif \ No newline at end of file diff --git a/framework/settings.cpp b/framework/settings.cpp index e69de29..6816e88 100644 --- a/framework/settings.cpp +++ b/framework/settings.cpp @@ -0,0 +1,2 @@ +#include "settings.h" + diff --git a/framework/settings.h b/framework/settings.h index e69de29..fd105b9 100644 --- a/framework/settings.h +++ b/framework/settings.h @@ -0,0 +1,10 @@ +#ifndef SETTINGS_H +#define SETTINGS_H + +class Settings { + public: + int i; +}; + + +#endif \ No newline at end of file diff --git a/libs/HEADS b/libs/HEADS index d2c343c..e0f29fe 100644 --- a/libs/HEADS +++ b/libs/HEADS @@ -1,3 +1,3 @@ RapidJSON 0ccdbf364c577803e2a751f5aededce935314313 -brynet 5ddb2cb2b46e5e7730327217932d0d3daf8e5b2a +brynet b0d13e7419628d0f7051a2bb310daaf8a506e08b rapidxml 1.13 \ No newline at end of file diff --git a/libs/brynet/LICENSE b/libs/brynet/LICENSE new file mode 100644 index 0000000..3ac9185 --- /dev/null +++ b/libs/brynet/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 IronsDu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/libs/brynet/base/CPP_VERSION.hpp b/libs/brynet/base/CPP_VERSION.hpp index fb65c91..f32b49d 100644 --- a/libs/brynet/base/CPP_VERSION.hpp +++ b/libs/brynet/base/CPP_VERSION.hpp @@ -11,6 +11,6 @@ #endif #if (__cplusplus >= 201703L || \ - (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)) + (defined(_MSC_VER) && _MSC_VER >= 1910)) #define BRYNET_HAVE_LANG_CXX17 1 #endif \ No newline at end of file diff --git a/libs/brynet/base/Packet.hpp b/libs/brynet/base/Packet.hpp index 8cd451d..7f18d0c 100644 --- a/libs/brynet/base/Packet.hpp +++ b/libs/brynet/base/Packet.hpp @@ -16,7 +16,7 @@ namespace brynet { namespace base { public: BasePacketWriter(char* buffer, size_t len, - bool useBigEndian = false, + bool useBigEndian = true, bool isAutoMalloc = false) : mIsAutoMalloc(isAutoMalloc), @@ -248,85 +248,49 @@ namespace brynet { namespace base { public: BasePacketReader(const char* buffer, size_t len, - bool useBigEndian = false) : - mBigEndian(useBigEndian), - mSize(len) + bool useBigEndian = true) : + mBigEndian(useBigEndian), + mMaxLen(len) { mPos = 0; - mSavedPos = 0; mBuffer = buffer; } virtual ~BasePacketReader() = default; - void useBigEndian() - { - mBigEndian = true; - } - - void useLittleEndian() - { - mBigEndian = false; - } - - void savePos() - { - mSavedPos = mPos; - } - - size_t savedPos() const - { - return mSavedPos; - } - size_t getLeft() const { - if (mPos > mSize) + if (mPos > mMaxLen) { throw std::out_of_range("current pos is greater than max len"); } - return mSize - mPos; + return mMaxLen - mPos; } - bool enough(size_t len) const - { - if (mPos > mSize) - { - return false; - } - return (mSize - mPos) >= len; - } - - const char* begin() const + const char* getBuffer() const { return mBuffer; } - const char* currentBuffer() const + void skipAll() { - return mBuffer+mPos; + mPos = mMaxLen; } - void consumeAll() - { - mPos = mSize; - savePos(); - } - - size_t currentPos() const + size_t getPos() const { return mPos; } - size_t size() const + size_t getMaxPos() const { - return mSize; + return mMaxLen; } void addPos(size_t diff) { const auto tmpPos = mPos + diff; - if (tmpPos > mSize) + if (tmpPos > mMaxLen) { throw std::out_of_range("diff is to big"); } @@ -396,11 +360,11 @@ namespace brynet { namespace base { void read(T& value) { static_assert(std::is_same::type>::value, - "T must a normal type"); + "T must a nomal type"); static_assert(std::is_pod::value, "T must a pod type"); - if ((mPos + sizeof(value)) > mSize) + if ((mPos + sizeof(value)) > mMaxLen) { throw std::out_of_range("T size is to big"); } @@ -410,18 +374,17 @@ namespace brynet { namespace base { } protected: - bool mBigEndian; - const size_t mSize; + const bool mBigEndian; + const size_t mMaxLen; const char* mBuffer; size_t mPos; - size_t mSavedPos; }; template class AutoMallocPacket : public BasePacketWriter { public: - explicit AutoMallocPacket(bool useBigEndian = false, + explicit AutoMallocPacket(bool useBigEndian = true, bool isAutoMalloc = false) : BasePacketWriter(mData, SIZE, useBigEndian, isAutoMalloc) diff --git a/libs/brynet/net/PromiseReceive.hpp b/libs/brynet/net/PromiseReceive.hpp index 2f372f3..b1c0211 100644 --- a/libs/brynet/net/PromiseReceive.hpp +++ b/libs/brynet/net/PromiseReceive.hpp @@ -144,10 +144,9 @@ namespace brynet { namespace net { std::shared_ptr setupPromiseReceive(const TcpConnection::Ptr& session) { auto promiseReceive = std::make_shared(); - session->setDataCallback([promiseReceive](brynet::base::BasePacketReader& reader) { - auto procLen = promiseReceive->process(reader.begin(), reader.size()); - reader.addPos(procLen); - reader.savePos(); + session->setDataCallback([promiseReceive](const char* buffer, + size_t len) { + return promiseReceive->process(buffer, len); }); return promiseReceive; diff --git a/libs/brynet/net/TcpConnection.hpp b/libs/brynet/net/TcpConnection.hpp index 8bed5c2..d8bd605 100644 --- a/libs/brynet/net/TcpConnection.hpp +++ b/libs/brynet/net/TcpConnection.hpp @@ -7,14 +7,12 @@ #include #include #include -#include #include #include #include #include #include -#include #include #include #include @@ -36,17 +34,6 @@ extern "C" { namespace brynet { namespace net { - class SendableMsg - { - public: - using Ptr = std::shared_ptr; - - virtual ~SendableMsg() = default; - - virtual const void * data() = 0; - virtual size_t size() = 0; - }; - class TcpConnection : public Channel, public brynet::base::NonCopyable, public std::enable_shared_from_this @@ -55,10 +42,12 @@ namespace brynet { namespace net { using Ptr = std::shared_ptr; using EnterCallback = std::function; - using DataCallback = std::function; + using DataCallback = std::function; using DisconnectedCallback = std::function; using PacketSendedCallback = std::function; + using PacketPtr = std::shared_ptr; + public: Ptr static Create(TcpSocket::Ptr socket, size_t maxRecvBufferSize, @@ -115,9 +104,9 @@ namespace brynet { namespace net { #endif eventLoop->runAsyncFunctor([session]() - { - session->onEnterEventLoop(); - }); + { + session->onEnterEventLoop(); + }); return session; } @@ -127,102 +116,56 @@ namespace brynet { namespace net { } //TODO::如果所属EventLoop已经没有工作,则可能导致内存无限大,因为所投递的请求都没有得到处理 - void send( - const SendableMsg::Ptr& msg, - PacketSendedCallback&& callback = nullptr - ) - { - auto sharedThis = shared_from_this(); - mEventLoop->runAsyncFunctor([sharedThis, msg, callback]() mutable - { - const auto len = msg->size(); - sharedThis->mSendList.emplace_back(PendingPacket{ - std::move(msg), - len, - std::move(callback) }); - sharedThis->runAfterFlush(); - }); - } void send( const char* buffer, size_t len, PacketSendedCallback&& callback = nullptr) { - send(std::make_shared(buffer, len), std::move(callback)); + send(makePacket(buffer, len), std::move(callback)); } + template void send( - const std::shared_ptr& packet, - PacketSendedCallback&& callback = nullptr) + PacketType&& packet, + PacketSendedCallback&& + callback = nullptr) { - class StringSendMsg : public SendableMsg - { - public: - explicit StringSendMsg(std::shared_ptr&& msg) - : - mMsg(std::move(msg)) - {} - explicit StringSendMsg(const std::shared_ptr& msg) - : - mMsg(msg) - {} - - const void* data() override - { - return static_cast(mMsg->data()); - } - - size_t size() override - { - return mMsg->size(); - } - - private: - std::shared_ptr mMsg; - }; - + auto packetCapture = std::forward(packet); + auto callbackCapture = std::move(callback); auto sharedThis = shared_from_this(); - mEventLoop->runAsyncFunctor([sharedThis, packet, callback]() mutable - { - const auto len = packet->size(); + mEventLoop->runAsyncFunctor( + [sharedThis, packetCapture, callbackCapture]() mutable { + const auto len = packetCapture->size(); sharedThis->mSendList.emplace_back(PendingPacket{ - std::make_shared(std::move(packet)), + std::move(packetCapture), len, - std::move(callback) }); + std::move(callbackCapture) }); sharedThis->runAfterFlush(); - }); + }); } - // setDataCallback(std::function) - template - void setDataCallback(Callback&& cb) + void setDataCallback(DataCallback&& cb) { - verifyArgType(cb, &Callback::operator()); - auto sharedThis = shared_from_this(); - mEventLoop->runAsyncFunctor([sharedThis, cb]() mutable - { - sharedThis->mDataCallback = cb; + mEventLoop->runAsyncFunctor([sharedThis, cb]() mutable { + sharedThis->mDataCallback = std::move(cb); sharedThis->processRecvMessage(); - }); + }); } - void setDisConnectCallback(DisconnectedCallback&& cb) { auto sharedThis = shared_from_this(); - mEventLoop->runAsyncFunctor([sharedThis, cb]() mutable - { + mEventLoop->runAsyncFunctor([sharedThis, cb]() mutable { sharedThis->mDisConnectCallback = std::move(cb); - }); + }); } /* if checkTime is zero, will cancel check heartbeat */ void setHeartBeat(std::chrono::nanoseconds checkTime) { auto sharedThis = shared_from_this(); - mEventLoop->runAsyncFunctor([sharedThis, checkTime]() - { + mEventLoop->runAsyncFunctor([sharedThis, checkTime]() { if (sharedThis->mTimer.lock() != nullptr) { sharedThis->mTimer.lock()->cancel(); @@ -231,28 +174,25 @@ namespace brynet { namespace net { sharedThis->mCheckTime = checkTime; sharedThis->startPingCheckTimer(); - }); + }); } void postDisConnect() { auto sharedThis = shared_from_this(); - mEventLoop->runAsyncFunctor([sharedThis]() - { + mEventLoop->runAsyncFunctor([sharedThis]() { sharedThis->procCloseInLoop(); - }); + }); } void postShutdown() { auto sharedThis = shared_from_this(); - mEventLoop->runAsyncFunctor([sharedThis]() - { - sharedThis->mEventLoop->runFunctorAfterLoop([sharedThis]() - { + mEventLoop->runAsyncFunctor([sharedThis]() { + sharedThis->mEventLoop->runFunctorAfterLoop([sharedThis]() { sharedThis->procShutdownInLoop(); + }); }); - }); } const std::string& getIP() const @@ -260,6 +200,11 @@ namespace brynet { namespace net { return mIP; } + static TcpConnection::PacketPtr makePacket(const char* buffer, size_t len) + { + return std::make_shared(buffer, len); + } + protected: TcpConnection(TcpSocket::Ptr socket, size_t maxRecvBufferSize, @@ -717,7 +662,7 @@ namespace brynet { namespace net { static const int SENDBUF_SIZE = 1024 * 32; if (threadLocalSendBuf == nullptr) { - threadLocalSendBuf = static_cast(malloc(SENDBUF_SIZE)); + threadLocalSendBuf = (char*)malloc(SENDBUF_SIZE); } #ifdef BRYNET_USE_OPENSSL @@ -730,13 +675,13 @@ namespace brynet { namespace net { while (!mSendList.empty() && mCanWrite) { - auto sendptr = threadLocalSendBuf; + char* sendptr = threadLocalSendBuf; size_t wait_send_size = 0; for (auto it = mSendList.begin(); it != mSendList.end(); ++it) { auto& packet = *it; - auto packetLeftBuf = (char*)(packet.data->data()) + packet.data->size() - packet.left; + auto packetLeftBuf = (char*)(packet.data->c_str() + (packet.data->size() - packet.left)); const auto packetLeftLen = packet.left; if ((wait_send_size + packetLeftLen) > SENDBUF_SIZE) @@ -749,7 +694,7 @@ namespace brynet { namespace net { break; } - memcpy(static_cast(sendptr + wait_send_size), static_cast(packetLeftBuf), packetLeftLen); + memcpy(sendptr + wait_send_size, packetLeftBuf, packetLeftLen); wait_send_size += packetLeftLen; } @@ -846,7 +791,7 @@ namespace brynet { namespace net { size_t ready_send_len = 0; for (const auto& p : mSendList) { - iov[num].iov_base = (void*)(static_cast(p.data->data()) + p.data->size() - p.left); + iov[num].iov_base = (void*)(p.data->c_str() + (p.data->size() - p.left)); iov[num].iov_len = p.left; ready_send_len += p.left; @@ -1119,25 +1064,16 @@ namespace brynet { namespace net { { if (mDataCallback != nullptr && buffer_getreadvalidcount(mRecvBuffer.get()) > 0) { - auto reader = brynet::base::BasePacketReader(buffer_getreadptr(mRecvBuffer.get()), - buffer_getreadvalidcount(mRecvBuffer.get()), false); - mDataCallback(reader); - const auto consumedLen = reader.savedPos(); - assert(consumedLen <= reader.size()); - if (consumedLen <= reader.size()) + const auto proclen = mDataCallback(buffer_getreadptr(mRecvBuffer.get()), + buffer_getreadvalidcount(mRecvBuffer.get())); + assert(proclen <= buffer_getreadvalidcount(mRecvBuffer.get())); + if (proclen <= buffer_getreadvalidcount(mRecvBuffer.get())) { - buffer_addreadpos(mRecvBuffer.get(), consumedLen); + buffer_addreadpos(mRecvBuffer.get(), proclen); } } } - template - static void verifyArgType(const CallbackType&, void(CallbackType::*)(Arg&) const) - { - static_assert(std::is_reference::value, "arg must be reference type"); - static_assert(!std::is_const::type>::value, "arg can't be const type"); - } - private: #ifdef BRYNET_PLATFORM_WINDOWS @@ -1169,7 +1105,7 @@ namespace brynet { namespace net { struct PendingPacket { - SendableMsg::Ptr data; + PacketPtr data; size_t left; PacketSendedCallback mCompleteCallback; }; diff --git a/libs/brynet/net/http/HttpService.hpp b/libs/brynet/net/http/HttpService.hpp index fb824ea..a7b46ab 100644 --- a/libs/brynet/net/http/HttpService.hpp +++ b/libs/brynet/net/http/HttpService.hpp @@ -32,7 +32,7 @@ namespace brynet { namespace net { namespace http { void send(PacketType&& packet, TcpConnection::PacketSendedCallback&& callback = nullptr) { - mSession->send(std::forward>(packet), + mSession->send(std::forward(packet), std::move(callback)); } void send(const char* packet, @@ -196,26 +196,25 @@ namespace brynet { namespace net { namespace http { auto httpParser = std::make_shared(HTTP_BOTH); session->setDataCallback([httpSession, httpParser]( - brynet::base::BasePacketReader& reader) { - size_t retLen = 0; + const char* buffer, size_t len) { + size_t retlen = 0; if (httpParser->isWebSocket()) { - retLen = HttpService::ProcessWebSocket( reader.begin(), - reader.size(), - httpParser, - httpSession); + retlen = HttpService::ProcessWebSocket(buffer, + len, + httpParser, + httpSession); } else { - retLen = HttpService::ProcessHttp( reader.begin(), - reader.size(), - httpParser, - httpSession); + retlen = HttpService::ProcessHttp(buffer, + len, + httpParser, + httpSession); } - reader.addPos(retLen); - reader.savePos(); + return retlen; }); } diff --git a/libs/rapidjson/license.txt b/libs/rapidjson/license.txt new file mode 100644 index 0000000..7ccc161 --- /dev/null +++ b/libs/rapidjson/license.txt @@ -0,0 +1,57 @@ +Tencent is pleased to support the open source community by making RapidJSON available. + +Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved. + +If you have downloaded a copy of the RapidJSON binary from Tencent, please note that the RapidJSON binary is licensed under the MIT License. +If you have downloaded a copy of the RapidJSON source code from Tencent, please note that RapidJSON source code is licensed under the MIT License, except for the third-party components listed below which are subject to different license terms. Your integration of RapidJSON into your own projects may require compliance with the MIT License, as well as the other licenses applicable to the third-party components included within RapidJSON. To avoid the problematic JSON license in your own projects, it's sufficient to exclude the bin/jsonchecker/ directory, as it's the only code under the JSON license. +A copy of the MIT License is included in this file. + +Other dependencies and licenses: + +Open Source Software Licensed Under the BSD License: +-------------------------------------------------------------------- + +The msinttypes r29 +Copyright (c) 2006-2013 Alexander Chemeris +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name of copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Open Source Software Licensed Under the JSON License: +-------------------------------------------------------------------- + +json.org +Copyright (c) 2002 JSON.org +All Rights Reserved. + +JSON_checker +Copyright (c) 2002 JSON.org +All Rights Reserved. + + +Terms of the JSON License: +--------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +The Software shall be used for Good, not Evil. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +Terms of the MIT License: +-------------------------------------------------------------------- + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/libs/tinydir/COPYING b/libs/tinydir/COPYING new file mode 100644 index 0000000..0d31329 --- /dev/null +++ b/libs/tinydir/COPYING @@ -0,0 +1,26 @@ +Copyright (c) 2013-2016, tinydir authors: +- Cong Xu +- Lautis Sun +- Baudouin Feildel +- Andargor +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/libs/tinydir/README.md b/libs/tinydir/README.md new file mode 100644 index 0000000..8622c94 --- /dev/null +++ b/libs/tinydir/README.md @@ -0,0 +1,79 @@ +TinyDir +======= +[![Build Status](https://travis-ci.org/cxong/tinydir.svg?branch=master)](https://travis-ci.org/cxong/tinydir) +[![Release](http://img.shields.io/github/release/cxong/tinydir.svg)](https://github.com/cxong/tinydir/releases/latest) + +Lightweight, portable and easy to integrate C directory and file reader. TinyDir wraps dirent for POSIX and FindFirstFile for Windows. + +Windows unicode is supported by defining `UNICODE` and `_UNICODE` before including `tinydir.h`. + +Example +======= + +There are two methods. Error checking omitted: + +```C +tinydir_dir dir; +tinydir_open(&dir, "/path/to/dir"); + +while (dir.has_next) +{ + tinydir_file file; + tinydir_readfile(&dir, &file); + + printf("%s", file.name); + if (file.is_dir) + { + printf("/"); + } + printf("\n"); + + tinydir_next(&dir); +} + +tinydir_close(&dir); +``` + +```C +tinydir_dir dir; +int i; +tinydir_open_sorted(&dir, "/path/to/dir"); + +for (i = 0; i < dir.n_files; i++) +{ + tinydir_file file; + tinydir_readfile_n(&dir, &file, i); + + printf("%s", file.name); + if (file.is_dir) + { + printf("/"); + } + printf("\n"); +} + +tinydir_close(&dir); +``` + +See the `/samples` folder for more examples, including an interactive command-line directory navigator. + +Language +======== + +ANSI C, or C90. + +Platforms +========= + +POSIX and Windows supported. Open to the possibility of supporting other platforms. + +License +======= + +Simplified BSD; if you use tinydir you can comply by including `tinydir.h` or `COPYING` somewhere in your package. + +Known Limitations +================= + +- Limited path and filename sizes +- [Possible race condition bug if folder being read has changing content](https://github.com/cxong/tinydir/issues/13) diff --git a/libs/tinydir/package.json b/libs/tinydir/package.json new file mode 100644 index 0000000..5ad2e9e --- /dev/null +++ b/libs/tinydir/package.json @@ -0,0 +1,17 @@ +{ + "name": "tinydir", + "description": "Lightweight, portable and easy to integrate C directory and file reader", + "license": "BSD-2-Clause", + "keywords": [ + "dir", + "directory", + "file", + "reader", + "filesystem" + ], + "src": [ + "tinydir.h" + ], + "version": "1.2.4", + "repo": "cxong/tinydir" +} diff --git a/libs/tinydir/tinydir.h b/libs/tinydir/tinydir.h new file mode 100644 index 0000000..e08eb84 --- /dev/null +++ b/libs/tinydir/tinydir.h @@ -0,0 +1,831 @@ +/* +Copyright (c) 2013-2019, tinydir authors: +- Cong Xu +- Lautis Sun +- Baudouin Feildel +- Andargor +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef TINYDIR_H +#define TINYDIR_H + +#ifdef __cplusplus +extern "C" { +#endif + +#if ((defined _UNICODE) && !(defined UNICODE)) +#define UNICODE +#endif + +#if ((defined UNICODE) && !(defined _UNICODE)) +#define _UNICODE +#endif + +#include +#include +#include +#ifdef _MSC_VER +# ifndef WIN32_LEAN_AND_MEAN +# define WIN32_LEAN_AND_MEAN +# endif +# include +# include +# pragma warning(push) +# pragma warning (disable : 4996) +#else +# include +# include +# include +# include +#endif +#ifdef __MINGW32__ +# include +#endif + + +/* types */ + +/* Windows UNICODE wide character support */ +#if defined _MSC_VER || defined __MINGW32__ +# define _tinydir_char_t TCHAR +# define TINYDIR_STRING(s) _TEXT(s) +# define _tinydir_strlen _tcslen +# define _tinydir_strcpy _tcscpy +# define _tinydir_strcat _tcscat +# define _tinydir_strcmp _tcscmp +# define _tinydir_strrchr _tcsrchr +# define _tinydir_strncmp _tcsncmp +#else +# define _tinydir_char_t char +# define TINYDIR_STRING(s) s +# define _tinydir_strlen strlen +# define _tinydir_strcpy strcpy +# define _tinydir_strcat strcat +# define _tinydir_strcmp strcmp +# define _tinydir_strrchr strrchr +# define _tinydir_strncmp strncmp +#endif + +#if (defined _MSC_VER || defined __MINGW32__) +# include +# define _TINYDIR_PATH_MAX MAX_PATH +#elif defined __linux__ +# include +# ifdef PATH_MAX +# define _TINYDIR_PATH_MAX PATH_MAX +# endif +#elif defined(__unix__) || (defined(__APPLE__) && defined(__MACH__)) +# include +# if defined(BSD) +# include +# ifdef PATH_MAX +# define _TINYDIR_PATH_MAX PATH_MAX +# endif +# endif +#endif + +#ifndef _TINYDIR_PATH_MAX +#define _TINYDIR_PATH_MAX 4096 +#endif + +#ifdef _MSC_VER +/* extra chars for the "\\*" mask */ +# define _TINYDIR_PATH_EXTRA 2 +#else +# define _TINYDIR_PATH_EXTRA 0 +#endif + +#define _TINYDIR_FILENAME_MAX 256 + +#if (defined _MSC_VER || defined __MINGW32__) +#define _TINYDIR_DRIVE_MAX 3 +#endif + +#ifdef _MSC_VER +# define _TINYDIR_FUNC static __inline +#elif !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L +# define _TINYDIR_FUNC static __inline__ +#else +# define _TINYDIR_FUNC static inline +#endif + +/* readdir_r usage; define TINYDIR_USE_READDIR_R to use it (if supported) */ +#ifdef TINYDIR_USE_READDIR_R + +/* readdir_r is a POSIX-only function, and may not be available under various + * environments/settings, e.g. MinGW. Use readdir fallback */ +#if _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _BSD_SOURCE || _SVID_SOURCE ||\ + _POSIX_SOURCE +# define _TINYDIR_HAS_READDIR_R +#endif +#if _POSIX_C_SOURCE >= 200112L +# define _TINYDIR_HAS_FPATHCONF +# include +#endif +#if _BSD_SOURCE || _SVID_SOURCE || \ + (_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700) +# define _TINYDIR_HAS_DIRFD +# include +#endif +#if defined _TINYDIR_HAS_FPATHCONF && defined _TINYDIR_HAS_DIRFD &&\ + defined _PC_NAME_MAX +# define _TINYDIR_USE_FPATHCONF +#endif +#if defined __MINGW32__ || !defined _TINYDIR_HAS_READDIR_R ||\ + !(defined _TINYDIR_USE_FPATHCONF || defined NAME_MAX) +# define _TINYDIR_USE_READDIR +#endif + +/* Use readdir by default */ +#else +# define _TINYDIR_USE_READDIR +#endif + +/* MINGW32 has two versions of dirent, ASCII and UNICODE*/ +#ifndef _MSC_VER +#if (defined __MINGW32__) && (defined _UNICODE) +#define _TINYDIR_DIR _WDIR +#define _tinydir_dirent _wdirent +#define _tinydir_opendir _wopendir +#define _tinydir_readdir _wreaddir +#define _tinydir_closedir _wclosedir +#else +#define _TINYDIR_DIR DIR +#define _tinydir_dirent dirent +#define _tinydir_opendir opendir +#define _tinydir_readdir readdir +#define _tinydir_closedir closedir +#endif +#endif + +/* Allow user to use a custom allocator by defining _TINYDIR_MALLOC and _TINYDIR_FREE. */ +#if defined(_TINYDIR_MALLOC) && defined(_TINYDIR_FREE) +#elif !defined(_TINYDIR_MALLOC) && !defined(_TINYDIR_FREE) +#else +#error "Either define both alloc and free or none of them!" +#endif + +#if !defined(_TINYDIR_MALLOC) + #define _TINYDIR_MALLOC(_size) malloc(_size) + #define _TINYDIR_FREE(_ptr) free(_ptr) +#endif /* !defined(_TINYDIR_MALLOC) */ + +typedef struct tinydir_file +{ + _tinydir_char_t path[_TINYDIR_PATH_MAX]; + _tinydir_char_t name[_TINYDIR_FILENAME_MAX]; + _tinydir_char_t *extension; + int is_dir; + int is_reg; + +#ifndef _MSC_VER +#ifdef __MINGW32__ + struct _stat _s; +#else + struct stat _s; +#endif +#endif +} tinydir_file; + +typedef struct tinydir_dir +{ + _tinydir_char_t path[_TINYDIR_PATH_MAX]; + int has_next; + size_t n_files; + + tinydir_file *_files; +#ifdef _MSC_VER + HANDLE _h; + WIN32_FIND_DATA _f; +#else + _TINYDIR_DIR *_d; + struct _tinydir_dirent *_e; +#ifndef _TINYDIR_USE_READDIR + struct _tinydir_dirent *_ep; +#endif +#endif +} tinydir_dir; + + +/* declarations */ + +_TINYDIR_FUNC +int tinydir_open(tinydir_dir *dir, const _tinydir_char_t *path); +_TINYDIR_FUNC +int tinydir_open_sorted(tinydir_dir *dir, const _tinydir_char_t *path); +_TINYDIR_FUNC +void tinydir_close(tinydir_dir *dir); + +_TINYDIR_FUNC +int tinydir_next(tinydir_dir *dir); +_TINYDIR_FUNC +int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file); +_TINYDIR_FUNC +int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, size_t i); +_TINYDIR_FUNC +int tinydir_open_subdir_n(tinydir_dir *dir, size_t i); + +_TINYDIR_FUNC +int tinydir_file_open(tinydir_file *file, const _tinydir_char_t *path); +_TINYDIR_FUNC +void _tinydir_get_ext(tinydir_file *file); +_TINYDIR_FUNC +int _tinydir_file_cmp(const void *a, const void *b); +#ifndef _MSC_VER +#ifndef _TINYDIR_USE_READDIR +_TINYDIR_FUNC +size_t _tinydir_dirent_buf_size(_TINYDIR_DIR *dirp); +#endif +#endif + + +/* definitions*/ + +_TINYDIR_FUNC +int tinydir_open(tinydir_dir *dir, const _tinydir_char_t *path) +{ +#ifndef _MSC_VER +#ifndef _TINYDIR_USE_READDIR + int error; + int size; /* using int size */ +#endif +#else + _tinydir_char_t path_buf[_TINYDIR_PATH_MAX]; +#endif + _tinydir_char_t *pathp; + + if (dir == NULL || path == NULL || _tinydir_strlen(path) == 0) + { + errno = EINVAL; + return -1; + } + if (_tinydir_strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) + { + errno = ENAMETOOLONG; + return -1; + } + + /* initialise dir */ + dir->_files = NULL; +#ifdef _MSC_VER + dir->_h = INVALID_HANDLE_VALUE; +#else + dir->_d = NULL; +#ifndef _TINYDIR_USE_READDIR + dir->_ep = NULL; +#endif +#endif + tinydir_close(dir); + + _tinydir_strcpy(dir->path, path); + /* Remove trailing slashes */ + pathp = &dir->path[_tinydir_strlen(dir->path) - 1]; + while (pathp != dir->path && (*pathp == TINYDIR_STRING('\\') || *pathp == TINYDIR_STRING('/'))) + { + *pathp = TINYDIR_STRING('\0'); + pathp++; + } +#ifdef _MSC_VER + _tinydir_strcpy(path_buf, dir->path); + _tinydir_strcat(path_buf, TINYDIR_STRING("\\*")); +#if (defined WINAPI_FAMILY) && (WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP) + dir->_h = FindFirstFileEx(path_buf, FindExInfoStandard, &dir->_f, FindExSearchNameMatch, NULL, 0); +#else + dir->_h = FindFirstFile(path_buf, &dir->_f); +#endif + if (dir->_h == INVALID_HANDLE_VALUE) + { + errno = ENOENT; +#else + dir->_d = _tinydir_opendir(path); + if (dir->_d == NULL) + { +#endif + goto bail; + } + + /* read first file */ + dir->has_next = 1; +#ifndef _MSC_VER +#ifdef _TINYDIR_USE_READDIR + dir->_e = _tinydir_readdir(dir->_d); +#else + /* allocate dirent buffer for readdir_r */ + size = _tinydir_dirent_buf_size(dir->_d); /* conversion to int */ + if (size == -1) return -1; + dir->_ep = (struct _tinydir_dirent*)_TINYDIR_MALLOC(size); + if (dir->_ep == NULL) return -1; + + error = readdir_r(dir->_d, dir->_ep, &dir->_e); + if (error != 0) return -1; +#endif + if (dir->_e == NULL) + { + dir->has_next = 0; + } +#endif + + return 0; + +bail: + tinydir_close(dir); + return -1; +} + +_TINYDIR_FUNC +int tinydir_open_sorted(tinydir_dir *dir, const _tinydir_char_t *path) +{ + /* Count the number of files first, to pre-allocate the files array */ + size_t n_files = 0; + if (tinydir_open(dir, path) == -1) + { + return -1; + } + while (dir->has_next) + { + n_files++; + if (tinydir_next(dir) == -1) + { + goto bail; + } + } + tinydir_close(dir); + + if (n_files == 0 || tinydir_open(dir, path) == -1) + { + return -1; + } + + dir->n_files = 0; + dir->_files = (tinydir_file *)_TINYDIR_MALLOC(sizeof *dir->_files * n_files); + if (dir->_files == NULL) + { + goto bail; + } + while (dir->has_next) + { + tinydir_file *p_file; + dir->n_files++; + + p_file = &dir->_files[dir->n_files - 1]; + if (tinydir_readfile(dir, p_file) == -1) + { + goto bail; + } + + if (tinydir_next(dir) == -1) + { + goto bail; + } + + /* Just in case the number of files has changed between the first and + second reads, terminate without writing into unallocated memory */ + if (dir->n_files == n_files) + { + break; + } + } + + qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp); + + return 0; + +bail: + tinydir_close(dir); + return -1; +} + +_TINYDIR_FUNC +void tinydir_close(tinydir_dir *dir) +{ + if (dir == NULL) + { + return; + } + + memset(dir->path, 0, sizeof(dir->path)); + dir->has_next = 0; + dir->n_files = 0; + _TINYDIR_FREE(dir->_files); + dir->_files = NULL; +#ifdef _MSC_VER + if (dir->_h != INVALID_HANDLE_VALUE) + { + FindClose(dir->_h); + } + dir->_h = INVALID_HANDLE_VALUE; +#else + if (dir->_d) + { + _tinydir_closedir(dir->_d); + } + dir->_d = NULL; + dir->_e = NULL; +#ifndef _TINYDIR_USE_READDIR + _TINYDIR_FREE(dir->_ep); + dir->_ep = NULL; +#endif +#endif +} + +_TINYDIR_FUNC +int tinydir_next(tinydir_dir *dir) +{ + if (dir == NULL) + { + errno = EINVAL; + return -1; + } + if (!dir->has_next) + { + errno = ENOENT; + return -1; + } + +#ifdef _MSC_VER + if (FindNextFile(dir->_h, &dir->_f) == 0) +#else +#ifdef _TINYDIR_USE_READDIR + dir->_e = _tinydir_readdir(dir->_d); +#else + if (dir->_ep == NULL) + { + return -1; + } + if (readdir_r(dir->_d, dir->_ep, &dir->_e) != 0) + { + return -1; + } +#endif + if (dir->_e == NULL) +#endif + { + dir->has_next = 0; +#ifdef _MSC_VER + if (GetLastError() != ERROR_SUCCESS && + GetLastError() != ERROR_NO_MORE_FILES) + { + tinydir_close(dir); + errno = EIO; + return -1; + } +#endif + } + + return 0; +} + +_TINYDIR_FUNC +int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file) +{ + const _tinydir_char_t *filename; + if (dir == NULL || file == NULL) + { + errno = EINVAL; + return -1; + } +#ifdef _MSC_VER + if (dir->_h == INVALID_HANDLE_VALUE) +#else + if (dir->_e == NULL) +#endif + { + errno = ENOENT; + return -1; + } + filename = +#ifdef _MSC_VER + dir->_f.cFileName; +#else + dir->_e->d_name; +#endif + if (_tinydir_strlen(dir->path) + + _tinydir_strlen(filename) + 1 + _TINYDIR_PATH_EXTRA >= + _TINYDIR_PATH_MAX) + { + /* the path for the file will be too long */ + errno = ENAMETOOLONG; + return -1; + } + if (_tinydir_strlen(filename) >= _TINYDIR_FILENAME_MAX) + { + errno = ENAMETOOLONG; + return -1; + } + + _tinydir_strcpy(file->path, dir->path); + if (_tinydir_strcmp(dir->path, TINYDIR_STRING("/")) != 0) + _tinydir_strcat(file->path, TINYDIR_STRING("/")); + _tinydir_strcpy(file->name, filename); + _tinydir_strcat(file->path, filename); +#ifndef _MSC_VER +#ifdef __MINGW32__ + if (_tstat( +#elif (defined _BSD_SOURCE) || (defined _DEFAULT_SOURCE) \ + || ((defined _XOPEN_SOURCE) && (_XOPEN_SOURCE >= 500)) \ + || ((defined _POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 200112L)) + if (lstat( +#else + if (stat( +#endif + file->path, &file->_s) == -1) + { + return -1; + } +#endif + _tinydir_get_ext(file); + + file->is_dir = +#ifdef _MSC_VER + !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); +#else + S_ISDIR(file->_s.st_mode); +#endif + file->is_reg = +#ifdef _MSC_VER + !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || + ( + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) && + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) && +#ifdef FILE_ATTRIBUTE_INTEGRITY_STREAM + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) && +#endif +#ifdef FILE_ATTRIBUTE_NO_SCRUB_DATA + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) && +#endif + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) && + !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY)); +#else + S_ISREG(file->_s.st_mode); +#endif + + return 0; +} + +_TINYDIR_FUNC +int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, size_t i) +{ + if (dir == NULL || file == NULL) + { + errno = EINVAL; + return -1; + } + if (i >= dir->n_files) + { + errno = ENOENT; + return -1; + } + + memcpy(file, &dir->_files[i], sizeof(tinydir_file)); + _tinydir_get_ext(file); + + return 0; +} + +_TINYDIR_FUNC +int tinydir_open_subdir_n(tinydir_dir *dir, size_t i) +{ + _tinydir_char_t path[_TINYDIR_PATH_MAX]; + if (dir == NULL) + { + errno = EINVAL; + return -1; + } + if (i >= dir->n_files || !dir->_files[i].is_dir) + { + errno = ENOENT; + return -1; + } + + _tinydir_strcpy(path, dir->_files[i].path); + tinydir_close(dir); + if (tinydir_open_sorted(dir, path) == -1) + { + return -1; + } + + return 0; +} + +/* Open a single file given its path */ +_TINYDIR_FUNC +int tinydir_file_open(tinydir_file *file, const _tinydir_char_t *path) +{ + tinydir_dir dir; + int result = 0; + int found = 0; + _tinydir_char_t dir_name_buf[_TINYDIR_PATH_MAX]; + _tinydir_char_t file_name_buf[_TINYDIR_FILENAME_MAX]; + _tinydir_char_t *dir_name; + _tinydir_char_t *base_name; +#if (defined _MSC_VER || defined __MINGW32__) + _tinydir_char_t drive_buf[_TINYDIR_PATH_MAX]; + _tinydir_char_t ext_buf[_TINYDIR_FILENAME_MAX]; +#endif + + if (file == NULL || path == NULL || _tinydir_strlen(path) == 0) + { + errno = EINVAL; + return -1; + } + if (_tinydir_strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) + { + errno = ENAMETOOLONG; + return -1; + } + + /* Get the parent path */ +#if (defined _MSC_VER || defined __MINGW32__) +#if ((defined _MSC_VER) && (_MSC_VER >= 1400)) + errno = _tsplitpath_s( + path, + drive_buf, _TINYDIR_DRIVE_MAX, + dir_name_buf, _TINYDIR_FILENAME_MAX, + file_name_buf, _TINYDIR_FILENAME_MAX, + ext_buf, _TINYDIR_FILENAME_MAX); +#else + _tsplitpath( + path, + drive_buf, + dir_name_buf, + file_name_buf, + ext_buf); +#endif + + if (errno) + { + return -1; + } + +/* _splitpath_s not work fine with only filename and widechar support */ +#ifdef _UNICODE + if (drive_buf[0] == L'\xFEFE') + drive_buf[0] = '\0'; + if (dir_name_buf[0] == L'\xFEFE') + dir_name_buf[0] = '\0'; +#endif + + /* Emulate the behavior of dirname by returning "." for dir name if it's + empty */ + if (drive_buf[0] == '\0' && dir_name_buf[0] == '\0') + { + _tinydir_strcpy(dir_name_buf, TINYDIR_STRING(".")); + } + /* Concatenate the drive letter and dir name to form full dir name */ + _tinydir_strcat(drive_buf, dir_name_buf); + dir_name = drive_buf; + /* Concatenate the file name and extension to form base name */ + _tinydir_strcat(file_name_buf, ext_buf); + base_name = file_name_buf; +#else + _tinydir_strcpy(dir_name_buf, path); + dir_name = dirname(dir_name_buf); + _tinydir_strcpy(file_name_buf, path); + base_name = basename(file_name_buf); +#endif + + /* Special case: if the path is a root dir, open the parent dir as the file */ +#if (defined _MSC_VER || defined __MINGW32__) + if (_tinydir_strlen(base_name) == 0) +#else + if ((_tinydir_strcmp(base_name, TINYDIR_STRING("/"))) == 0) +#endif + { + memset(file, 0, sizeof * file); + file->is_dir = 1; + file->is_reg = 0; + _tinydir_strcpy(file->path, dir_name); + file->extension = file->path + _tinydir_strlen(file->path); + return 0; + } + + /* Open the parent directory */ + if (tinydir_open(&dir, dir_name) == -1) + { + return -1; + } + + /* Read through the parent directory and look for the file */ + while (dir.has_next) + { + if (tinydir_readfile(&dir, file) == -1) + { + result = -1; + goto bail; + } + if (_tinydir_strcmp(file->name, base_name) == 0) + { + /* File found */ + found = 1; + break; + } + tinydir_next(&dir); + } + if (!found) + { + result = -1; + errno = ENOENT; + } + +bail: + tinydir_close(&dir); + return result; +} + +_TINYDIR_FUNC +void _tinydir_get_ext(tinydir_file *file) +{ + _tinydir_char_t *period = _tinydir_strrchr(file->name, TINYDIR_STRING('.')); + if (period == NULL) + { + file->extension = &(file->name[_tinydir_strlen(file->name)]); + } + else + { + file->extension = period + 1; + } +} + +_TINYDIR_FUNC +int _tinydir_file_cmp(const void *a, const void *b) +{ + const tinydir_file *fa = (const tinydir_file *)a; + const tinydir_file *fb = (const tinydir_file *)b; + if (fa->is_dir != fb->is_dir) + { + return -(fa->is_dir - fb->is_dir); + } + return _tinydir_strncmp(fa->name, fb->name, _TINYDIR_FILENAME_MAX); +} + +#ifndef _MSC_VER +#ifndef _TINYDIR_USE_READDIR +/* +The following authored by Ben Hutchings +from https://womble.decadent.org.uk/readdir_r-advisory.html +*/ +/* Calculate the required buffer size (in bytes) for directory * +* entries read from the given directory handle. Return -1 if this * +* this cannot be done. * +* * +* This code does not trust values of NAME_MAX that are less than * +* 255, since some systems (including at least HP-UX) incorrectly * +* define it to be a smaller value. */ +_TINYDIR_FUNC +size_t _tinydir_dirent_buf_size(_TINYDIR_DIR *dirp) +{ + long name_max; + size_t name_end; + /* parameter may be unused */ + (void)dirp; + +#if defined _TINYDIR_USE_FPATHCONF + name_max = fpathconf(dirfd(dirp), _PC_NAME_MAX); + if (name_max == -1) +#if defined(NAME_MAX) + name_max = (NAME_MAX > 255) ? NAME_MAX : 255; +#else + return (size_t)(-1); +#endif +#elif defined(NAME_MAX) + name_max = (NAME_MAX > 255) ? NAME_MAX : 255; +#else +#error "buffer size for readdir_r cannot be determined" +#endif + name_end = (size_t)offsetof(struct _tinydir_dirent, d_name) + name_max + 1; + return (name_end > sizeof(struct _tinydir_dirent) ? + name_end : sizeof(struct _tinydir_dirent)); +} +#endif +#endif + +#ifdef __cplusplus +} +#endif + +# if defined (_MSC_VER) +# pragma warning(pop) +# endif + +#endif diff --git a/main.cpp b/main.cpp index f9a2e56..21926fb 100644 --- a/main.cpp +++ b/main.cpp @@ -1,80 +1,32 @@ #include -#include -#include +#include -#include -#include -#include -#include +#include "framework/http_server.h" +#include "framework/application.h" +#include "framework/file_cache.h" -using namespace brynet; -using namespace brynet::net; +#include "rdn_application.h" -std::atomic_llong TotalRecvSize = ATOMIC_VAR_INIT(0); -std::atomic_llong total_client_num = ATOMIC_VAR_INIT(0); -std::atomic_llong total_packet_num = ATOMIC_VAR_INIT(0); +#define MAIN_CLASS RDNApplication -int main(int argc, char **argv) -{ - if (argc != 3) - { - fprintf(stderr, "Usage: \n"); - exit(-1); - } +int main(int argc, char **argv) { + FileCache *file_cache = new FileCache(); + file_cache->wwwroot = "./www"; + file_cache->refresh(); - auto service = TcpService::Create(); - service->startWorkerThread(atoi(argv[2])); + Application *app = new MAIN_CLASS(); - auto enterCallback = [](const TcpConnection::Ptr& session) { - total_client_num++; + app->setup_routes(); - session->setDataCallback([session](const char* buffer, size_t len) { - session->send(buffer, len); - TotalRecvSize += len; - total_packet_num++; + HTTPServer *server = new HTTPServer(); - std::cout << "------------------------------------- PACKET -------------------------------------" << std::endl; - std::cout << buffer << std::endl; - std::cout << "------------------------------------------------------------------------------------" << std::endl << std::endl; + server->port = 8080; + server->initialize(); + server->main_loop(); - return len; - }); + delete server; + delete app; + delete file_cache; - session->setDisConnectCallback([](const TcpConnection::Ptr& session) { - (void)session; - total_client_num--; - }); - }; - - wrapper::ListenerBuilder listener; - listener.configureService(service) - .configureSocketOptions({ - [](TcpSocket& socket) { - socket.setNodelay(); - } - }) - .configureConnectionOptions({ - brynet::net::AddSocketOption::WithMaxRecvBufferSize(1024 * 1024), - brynet::net::AddSocketOption::AddEnterCallback(enterCallback) - }) - .configureListen([=](wrapper::BuildListenConfig config) { - config.setAddr(false, "0.0.0.0", atoi(argv[1])); - }) - .asyncRun(); - - EventLoop mainLoop; - while (true) - { - mainLoop.loop(1000); - - total_packet_num = 0; - TotalRecvSize = 0; - - if (brynet::base::app_kbhit()) - { - break; - } - } - - return 0; -} + return 0; +} \ No newline at end of file diff --git a/rdn_application.cpp b/rdn_application.cpp new file mode 100644 index 0000000..71b088e --- /dev/null +++ b/rdn_application.cpp @@ -0,0 +1,38 @@ +#include "rdn_application.h" + +#include "framework/request.h" + +#include + +void RDNApplication::index(Request *request) { + //std::string body = "hello world aaaaa "; + + std::string body = ""; + + request->response->setBody(body); +} + +void RDNApplication::session_middleware_func(Request *request) { + std::cout << "dddd" << std::endl; +} + +void RDNApplication::setup_routes() { + Application::setup_routes(); + + index_func = index; + + main_route_map["asd"] = index; +} + +void RDNApplication::setup_middleware() { + Application::setup_middleware(); + + middlewares.push_back(RDNApplication::session_middleware_func); +} + +RDNApplication::RDNApplication() : + Application() { +} + +RDNApplication::~RDNApplication() { +} \ No newline at end of file diff --git a/rdn_application.h b/rdn_application.h new file mode 100644 index 0000000..c412906 --- /dev/null +++ b/rdn_application.h @@ -0,0 +1,19 @@ +#ifndef RDN_APPLICATION_H +#define RDN_APPLICATION_H + +#include "framework/application.h" + +class RDNApplication : public Application { +public: + static void index(Request *request); + + static void session_middleware_func(Request *request); + + virtual void setup_routes(); + virtual void setup_middleware(); + + RDNApplication(); + ~RDNApplication(); +}; + +#endif \ No newline at end of file diff --git a/server b/server deleted file mode 100755 index c8b9aac..0000000 Binary files a/server and /dev/null differ diff --git a/www/aaaa/qdeq.html b/www/aaaa/qdeq.html new file mode 100644 index 0000000..133789d --- /dev/null +++ b/www/aaaa/qdeq.html @@ -0,0 +1 @@ +ffqfqfq \ No newline at end of file diff --git a/www/asd.html b/www/asd.html new file mode 100644 index 0000000..e5a49f3 --- /dev/null +++ b/www/asd.html @@ -0,0 +1 @@ +qqq \ No newline at end of file diff --git a/www/index.html b/www/index.html new file mode 100644 index 0000000..fa577b7 --- /dev/null +++ b/www/index.html @@ -0,0 +1,7 @@ + + + +

dadadada

+ + + \ No newline at end of file